Yang Yujie [Wed, 6 Aug 2025 10:01:33 +0000 (12:01 +0200)]
bitint: Avoid extending ABI-extended large/huge _BitInts on load
This patch also make casts of ABI-extended large/huge _BitInts
behave the same as the small/middle case, i.e. no-op for casts
to a higher precision _BitInt with the same number of limbs /
extension for casts that turns a full top limb into a partial limb.
This conveniently helps keep some code with implementation-specific
extension semantics (e.g. BEXTC from gcc.dg/bitintext.h) the same
for _BitInts of any precision.
* gimple-lower-bitint.cc (bitint_large_huge::limb_access):
Add a parameter abi_load_p. If set, load a limb directly
in its actual precision without casting from m_limb_type.
(struct bitint_large_huge): Same.
(bitint_large_huge::handle_load): Use.
aarch64 for some strange reason unconditionally enables -Werror for libgcc
building and this particular file for some strange reason contains
a useless static forward declaration of a function only defined in the
#if defined __sun__ && defined __svr4__
block and not otherwise (with __attribute__((constructor))).
And we warn (with -Werror error) in the non-__sun__/__svr4__ case because
it declares a static function that is never defined.
The forward declaration makes no sense to me, for static functions
forward declarations shouldn't be needed even for -Wstrict-prototypes,
and AFAIK we don't warn on static __attribute__((constructor)) void foo (void) {}
being unused. And the function isn't used before being defined.
So, the following patch just removes the forward declaration.
Jakub Jelinek [Wed, 6 Aug 2025 09:30:08 +0000 (11:30 +0200)]
bitint: Fix up INTEGER_CST PHI handling [PR121413]
The following testcase is miscompiled on aarch64-linux.
The problem is in the optimization to shorten large constants
in PHI arguments.
In a couple of places during bitint lowering we compute
minimal precision of constant and if it is significantly
smaller than the precision of the type, store smaller constant
in memory and extend it at runtime (zero or all ones).
Now, in most places that works fine, we handle the stored number
of limbs by loading them from memory and then the rest is
extended. In the PHI INTEGER_CST argument handling we do
it differently, we don't form there any loops (because we
insert stmt sequences on the edges).
The problem is that we copy the whole _BitInt variable from
memory to the PHI VAR_DECL + initialize the rest to = {} or
memset to -1. It has
min_prec = CEIL (min_prec, limb_prec) * limb_prec;
precision, so e.g. on x86_64 there is no padding and it works
just fine. But on aarch64 which has abi_limb_mode TImode
and limb_mode DImode it doesn't in some cases.
In the testcase the constant has 408 bits min precision, rounded up
to limb_prec (64) is 448, i.e. 7 limbs. But aarch64 with TImode
abi_limb_mode will actually allocate 8 limbs and the most significant
limb is solely padding. As we want to extend the constant with all
ones, copying the padding (from memory, so 0s) will result in
64 0 bits where 1 bits were needed.
The following patch fixes it by detecting this case and setting
min_prec to a multiple of abi limb precision so that it has
no padding.
2025-08-06 Jakub Jelinek <jakub@redhat.com>
PR tree-optimization/121413
* gimple-lower-bitint.cc (abi_limb_prec): New variable
(bitint_precision_kind): Initialize it.
(gimple_lower_bitint): Clear it at the start. For
min_prec > limb_prec descreased precision vars for
INTEGER_CST PHI arguments ensure min_prec is either
prec or multiple of abi_limb_prec.
Jakub Jelinek [Wed, 6 Aug 2025 09:28:37 +0000 (11:28 +0200)]
bitint: Fix up handling of uninitialized mul/div/float cast operands [PR121127]
handle_operand_addr (used for the cases where we use libgcc APIs, so
multiplication, division, modulo, casts of _BitInt to float/dfp) when it
sees default definition of an SSA_NAME which is not PARM_DECL (i.e.
uninitialized one) just allocates single uninitialized limb, there is no
need to waste more memory on it, it can just tell libgcc that it has
64-bit precision, not say 1024 bit etc.
Unfortunately, doing this runs into some asserts when we have a narrowing
cast of the uninitialized SSA_NAME (but still large/huge _BitInt).
The following patch fixes that by using a magic value in *prec_stored
for the uninitialized cases (0) and just don't do any *prec tweaks for
narrowing casts from that. precs still needs to be maintained as before,
that one is used for big endian adjustment.
2025-08-06 Jakub Jelinek <jakub@redhat.com>
PR tree-optimization/121127
* gimple-lower-bitint.cc (bitint_large_huge::handle_operand_addr): For
uninitialized SSA_NAME, set *prec_stored to 0 rather than *prec.
Handle that case in narrowing casts. If prec_stored is non-NULL,
set *prec_stored to prec_stored_val.
Jakub Jelinek [Wed, 6 Aug 2025 09:27:00 +0000 (11:27 +0200)]
gengtype: Include system.h earlier in gengtype-lex.cc [PR121386]
OpenBSD headers apparently instead of just
#define SIZE_MAX something
do
#ifndef SIZE_MAX
#define SIZE_MAX something
#endif
This causes problem with gengtype-lex.cc, where the flex generated
code has
#ifndef SIZE_MAX
#define SIZE_MAX (~(size_t)0)
#endif
and system.h is included only after that and since my changes for
host size_t *printf printing SIZE_MAX is used in preprocessor
expressions,
#if SIZE_MAX <= UINT_MAX
etc.
In the preprocessor, identifiers are replaced with 0 and so
it is (~(0)0) <= 0xffffffffU
or so and thus invalid.
Now, normally we want to include system.h early, ideally immediately
after config.h or bconfig.h, but in gengtype-lex.cc case we have
#ifdef HOST_GENERATOR_FILE
#include "config.h"
#define GENERATOR_FILE 1
#else
#include "bconfig.h"
#endif
As I'm not sure what flex we require for building gcc (%top{} which COBOL FE
*.l uses is only in flex from 2003-04-01), the patch keeps using the %top{}
done by hand in Makefile.in, but includes system.h in the top part, with
FLEX_SCANNER temporarily defined (I'm undefining it afterwards because
flex generated code defines it again and I don't want to guarantee it is
defined to the same value) so that malloc/realloc poisoning doesn't happen
and #define malloc xmalloc and realloc xrealloc are done in system.h.
Note, system.h already includes all the 5 headers flex generated code
includes.
2025-08-06 Jakub Jelinek <jakub@redhat.com>
PR bootstrap/121386
* Makefile.in (gengtype-lex.cc): Append #define FLEX_SCANNER,
#include "system.h" and #undef FLEX_SCANNER to the prepended lines.
* gengtype-lex.l: Remove inclusion of config.h or bconfig.h, system.h
and definition of malloc/realloc from %{} section.
Yuao Ma [Mon, 4 Aug 2025 12:19:27 +0000 (20:19 +0800)]
fortran: cleanup duplicate tests for c_f_pointer_shape_driver
tests_2_driver and tests_4_driver are identical, and tests_4_driver is not used
at all. This patch clean this up, and format the driver with gcc style.
gcc/testsuite/ChangeLog:
* gfortran.dg/c_f_pointer_shape_tests_2.f03: Use the new driver.
* gfortran.dg/c_f_pointer_shape_tests_4.f03: Ditto.
* gfortran.dg/c_f_pointer_shape_tests_4_driver.c: Removed.
* gfortran.dg/c_f_pointer_shape_tests_2_driver.c: Renamed to ...
* gfortran.dg/c_f_pointer_shape_tests_driver.c: ... this; format
with gcc style.
Jakub Jelinek [Wed, 6 Aug 2025 08:44:09 +0000 (10:44 +0200)]
c++: Add test for vt/ff in line comments
P2843R3 dropped the
"If there is a form-feed or a vertical-tab character in such a comment, only
whitespace characters shall appear between it and the new-line that terminates
the comment; no diagnostic is required."
sentence from [lex.comment]. AFAIK we've never diagnosed nor checked for
that and C23 doesn't have anything like that, so the following testcase
merely tests that we don't diagnose anything on it.
2025-08-06 Jakub Jelinek <jakub@redhat.com>
PR preprocessor/120778
* c-c++-common/cpp/comment-ff-1.c: New test.
* c-c++-common/cpp/comment-vtab-1.c: New test.
Martin Uecker [Mon, 28 Jul 2025 11:12:14 +0000 (13:12 +0200)]
c: Fix ICE on invalid code involving bit fields [PR121217]
Under some error condition we can end up with NULL_TREEs for
the type of bitfields, which can cause an ICE when testing for
type compatibility. Add the missing check.
Kito Cheng [Thu, 31 Jul 2025 08:25:52 +0000 (16:25 +0800)]
RISC-V: Read extension data from riscv-ext*.def for arch-canonicalize
Previously, arch-canonicalize used hardcoded data to handle IMPLIED_EXT.
But this data often got out of sync with the actual C++ implementation.
Earlier, we introduced riscv-ext.def to keep track of all extension info
and generate docs. Now, arch-canonicalize also uses this same data to handle
extension implication rules directly.
One limitation is that conditional implication rules still need to be written
manually. Luckily, there aren't many of them for now, so it's still manageable.
I really wanted to avoid writing a C++ + Python binding or trying to parse C++
logic in Python...
This version also adds a `--selftest` option to run some unit tests.
gcc/ChangeLog:
* config/riscv/arch-canonicalize: Read extension data from
riscv-ext*.def and adding unittest.
Kito Cheng [Mon, 28 Jul 2025 12:49:39 +0000 (20:49 +0800)]
RISC-V: Support -march=unset
This patch introduces a new `-march=unset` option for RISC-V GCC that
allows users to explicitly ignore previous `-march` options and derive
the architecture string from the `-mcpu` option instead.
This feature is particularly useful for build systems and toolchain
configurations where you want to ensure the architecture is always
derived from the CPU specification rather than relying on potentially
conflicting `-march` options.
* gcc.target/riscv/arch-unset-1.c: New test.
* gcc.target/riscv/arch-unset-2.c: New test.
* gcc.target/riscv/arch-unset-3.c: New test.
* gcc.target/riscv/arch-unset-4.c: New test.
* gcc.target/riscv/arch-unset-5.c: New test.
* gimplify.cc (remove_unused_omp_iterator_vars): Display unused
variable warning for 'to' and 'from' clauses.
(gimplify_scan_omp_clauses): Add argument for iterator loop sequence.
Gimplify the clause decl and size into the iterator loop if iterators
are used.
(gimplify_omp_workshare): Add argument for iterator loops sequence
in call to gimplify_scan_omp_clauses.
(gimplify_omp_target_update): Call remove_unused_omp_iterator_vars and
build_omp_iterators_loops. Add loop sequence as argument when calling
gimplify_scan_omp_clauses, gimplify_adjust_omp_clauses and building
the Gimple statement.
* tree-pretty-print.cc (dump_omp_clause): Call dump_omp_iterators
for to/from clauses with iterators.
* tree.cc (omp_clause_num_ops): Add extra operand for OMP_CLAUSE_FROM
and OMP_CLAUSE_TO.
* tree.h (OMP_CLAUSE_HAS_ITERATORS): Add check for OMP_CLAUSE_TO and
OMP_CLAUSE_FROM.
(OMP_CLAUSE_ITERATORS): Likewise.
openmp: Add support for iterators in map clauses (C/C++)
This adds preliminary support for iterators in map clauses within OpenMP
'target' constructs (which includes constructs such as 'target enter data').
Iterators with non-constant loop bounds are not currently supported.
gcc/c/
* c-parser.cc (c_parser_omp_variable_list): Use location of the
map expression as the clause location.
(c_parser_omp_clause_map): Parse 'iterator' modifier.
* c-typeck.cc (c_finish_omp_clauses): Finish iterators. Apply
iterators to generated clauses.
* gimple-pretty-print.cc (dump_gimple_omp_target): Print expanded
iterator loops.
* gimple.cc (gimple_build_omp_target): Add argument for iterator
loops sequence. Initialize iterator loops field.
* gimple.def (GIMPLE_OMP_TARGET): Set GSS symbol to GSS_OMP_TARGET.
* gimple.h (gomp_target): Set GSS symbol to GSS_OMP_TARGET. Add extra
field for iterator loops.
(gimple_build_omp_target): Add argument for iterator loops sequence.
(gimple_omp_target_iterator_loops): New.
(gimple_omp_target_iterator_loops_ptr): New.
(gimple_omp_target_set_iterator_loops): New.
* gimplify.cc (find_var_decl): New.
(copy_omp_iterator): New.
(remap_omp_iterator_var_1): New.
(remap_omp_iterator_var): New.
(remove_unused_omp_iterator_vars): New.
(struct iterator_loop_info_t): New type.
(iterator_loop_info_map_t): New type.
(build_omp_iterators_loops): New.
(enter_omp_iterator_loop_context_1): New.
(enter_omp_iterator_loop_context): New.
(enter_omp_iterator_loop_context): New.
(exit_omp_iterator_loop_context): New.
(gimplify_adjust_omp_clauses): Add argument for iterator loop
sequence. Gimplify the clause decl and size into the iterator
loop if iterators are used.
(gimplify_omp_workshare): Call remove_unused_omp_iterator_vars and
build_omp_iterators_loops for OpenMP target expressions. Add
loop sequence as argument when calling gimplify_adjust_omp_clauses
and building the Gimple statement.
* gimplify.h (enter_omp_iterator_loop_context): New prototype.
(exit_omp_iterator_loop_context): New prototype.
* gsstruct.def (GSS_OMP_TARGET): New.
* omp-low.cc (lower_omp_map_iterator_expr): New.
(lower_omp_map_iterator_size): New.
(finish_omp_map_iterators): New.
(lower_omp_target): Add sorry if iterators used with deep mapping.
Call lower_omp_map_iterator_expr before assigning to sender ref.
Call lower_omp_map_iterator_size before setting the size. Insert
iterator loop sequence before the statements for the target clause.
* tree-nested.cc (convert_nonlocal_reference_stmt): Walk the iterator
loop sequence of OpenMP target statements.
(convert_local_reference_stmt): Likewise.
(convert_tramp_reference_stmt): Likewise.
* tree-pretty-print.cc (dump_omp_iterators): Dump extra iterator
information if present.
(dump_omp_clause): Call dump_omp_iterators for iterators in map
clauses.
* tree.cc (omp_clause_num_ops): Add operand for OMP_CLAUSE_MAP.
(walk_tree_1): Do not walk last operand of OMP_CLAUSE_MAP.
* tree.h (OMP_CLAUSE_HAS_ITERATORS): New.
(OMP_CLAUSE_ITERATORS): New.
Jason Merrill [Tue, 5 Aug 2025 22:16:50 +0000 (15:16 -0700)]
c++: clobber object on placement new [PR121068]
My r16-2432 patch addressed the original testcase involving an array of
scalars, but not this additional testcase involving an array of classes.
This patch addresses the issue more thoroughly, by having placement new
first clobber the new object, and improving cxx_eval_store_expression to
implement initial clobbers as well.
My earlier attempt to do this clobbered the array as a whole, which broke
construct_at after the resolution of LWG3436 due to trying to create a
multidimensional array over the top of a single-dimensional array. To
side-step that issue, this patch instead clobbers the individual elements of
an array, taking advantage of the earlier change to let that activate the
array member of a union.
PR c++/121068
gcc/cp/ChangeLog:
* constexpr.cc (cxx_eval_store_expression): Handle clobbers.
(potential_constant_expression_1): Handle clobbers more.
* decl.cc (build_clobber_this): Use INIT_EXPR for initial clobber.
* init.cc (build_new_1): Clobber on placement new.
(build_vec_init): Don't clean up after clobber.
Mikael Morin [Tue, 5 Aug 2025 12:58:02 +0000 (14:58 +0200)]
fortran: Remove array bound update after constructor expansion
The array constructor expansion extends the size of the array
dynamically, and sets the upper bound appropriately every time it
does. There is no need to do it again at the end of expansion.
gcc/fortran/ChangeLog:
* trans-array.cc (trans_array_constructor): Remove the update of
the array descriptor upper bound after array constructor
expansion.
Mikael Morin [Tue, 5 Aug 2025 12:58:01 +0000 (14:58 +0200)]
fortran: Remove premature initialization of a function result's span
Setting just the span in an otherwise uninitialized array descriptor to
pass to a function that will use the descriptor for its result (thus do
the initialization) doesn't seem to be useful.
gcc/fortran/ChangeLog:
* trans-array.cc (gfc_conv_expr_descriptor): Remove
isolated initialization of the span field before passing to
the function that will do the initialization.
Mikael Morin [Tue, 5 Aug 2025 12:58:00 +0000 (14:58 +0200)]
fortran: Remove default initialization of local pointers's span
A pointer has no default initialization; it is invalid to use it before
it is associated to a target. We can just as well leave its span field
uninitialized, and wait for the first pointer association to define a
span value. The value of zero was an invalid span value anyway.
gcc/fortran/ChangeLog:
* trans-decl.cc (gfc_trans_deferred_vars): Don't default
initialize the span of local pointer arrays.
Mikael Morin [Tue, 5 Aug 2025 12:57:59 +0000 (14:57 +0200)]
fortran: Remove redundant initialisation of associate variable span
In the initialization of associate variable array descriptors, remove
an overwrite of the span field. The descriptor that is returned by
gfc_conv_expr_descriptor should already be usable without it.
The range of cases where the code was in effect is not completely
clear. The span overwrite looks redundant, and the conditional guarding
it seems to make it dead. However, the conditions governing
gfc_conv_expr_descriptor, gfc_get_array_span and trans_associate_var
make it difficult to track what is possible and what isn't. Trying to
investigate the case where the target is an array subreference wrapped
in parenthesis, I encountered a wrong-code issue, PR121384. Let's
remove all this and see what happens.
gcc/fortran/ChangeLog:
* trans-stmt.cc (trans_associate_var): Remove overwrite of the
span field of the associate variable's array descriptor.
Mikael Morin [Tue, 5 Aug 2025 12:57:58 +0000 (14:57 +0200)]
fortran: Remove span overwrite with pointer assignments
Remove an overwrite of the array descriptor span field when pointer-
assigning from a polymorphic function result to a non-polymorphic
pointer. That overwrite doesn't make sense because the span is
determined by the memory layout of the array; we can't change it
without also changing the data pointer.
gcc/fortran/ChangeLog:
* trans-expr.cc (gfc_trans_pointer_assignment): Remove overwrite
of the span after assignment of the array descriptor in the
polymorphic function result to non-polymorphic pointer case.
gets the widest vector mode from MOVE_MAX. But for memset, it should
use STORE_MAX_PIECES.
gcc/
PR target/121410
* config/i386/i386-expand.cc (ix86_expand_set_or_cpymem): Use
STORE_MAX_PIECES to get the widest vector mode in vector loop
for memset.
gcc/testsuite/
PR target/121410
* gcc.target/i386/pr121410.c: New test.
AVR: Allow combination of sign_extend with ashift.
gcc/
* config/avr/avr.cc (avr_rtx_costs_1) [SIGN_EXTEND]: Adjust cost.
* config/avr/avr.md (*sext.ashift<QIPSI:mode><HISI:mode>2): New
insn and a cc split.
* Make-lang.in (rust-readonly-check2.cc):
Add read-only check on HIR
* checks/errors/rust-readonly-check2.cc (ReadonlyChecker):
Add read-only check on HIR
* checks/errors/rust-readonly-check2.h (ReadonlyChecker):
Add read-only check on HIR
* expand/rust-macro-builtins-helpers.cc
(try_extract_string_literal_from_fragment): Perform static_cast
to AST::LiteralExpr only after it's verified that an AST::Expr
is a literal.
This doesn't handle rustc_args_required_const, but it does allow us to
recognize it as a valid attribute.
gcc/rust/ChangeLog:
* util/rust-attribute-values.h
(Attributes::RUSTC_ARGS_REQUIRED_CONST): New constexpr variable.
* util/rust-attributes.cc (__definitions): New entry for
RUSTC_ARGS_REQUIRED_CONST.
Philip Herron [Fri, 1 Aug 2025 10:54:52 +0000 (11:54 +0100)]
gccrs: Remove more calls to the old TyTy::BaseType::can_eq interface
This old can_eq interface was an old method to try and check if types can match up
by taking into account generics but its not maintained properly and we already have
a new wrapper Resolver::types_compatable (type, type, locus, emit_errors) which
just calls unify_site_and infer with commit false. There are only a few places left
to update.
One minor downside is that i need to remove const in some places because the unify
interface is non const. Ideally we would want to avoid writing a seperate const unify
anyway so i think this is not ideal but fine for us.
gccrs: Add rest pattern support for AST::SlicePattern
The main change can be found in ast/rust-pattern.h, which introduces 2 item types for
AST::SlicePattern - one without rest pattern (SlicePatternItemsNoRest) & the other with
it (SlicePatternItemsHasRest). This led to a number of cascading changes as seen in the
changelog.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc: Add support for the 2 new classes.
* ast/rust-ast-collector.h: Header file update for above.
* ast/rust-ast-full-decls.h: Add forward decls for the 2 new classes.
* ast/rust-ast-visitor.cc: Add visit support for the 2 new classes.
* ast/rust-ast-visitor.h: Header file update for above.
* ast/rust-pattern.cc: Implementation of certain methods for the 2 new classes.
* ast/rust-pattern.h: Define the 2 new classes. Update SlicePattern to be able to hold
2 kinds of items - SlicePatternItemsNoRest or SlicePatternItemsRest.
* expand/rust-cfg-strip.cc: Add support for the 2 new classes.
* expand/rust-cfg-strip.h: Header file update for above.
* expand/rust-derive.h: Add visits for the 2 new classes.
* hir/rust-ast-lower-base.cc: Add visits for the 2 new classes.
* hir/rust-ast-lower-base.h: Header file update for above.
* hir/rust-ast-lower-pattern.cc: Update lowering of SlicePattern to support
SlicePatternItemsNoRest.
* parse/rust-parse-impl.h (parse_slice_pattern()): Add support for parsing DOT_DOT into
respective SlicePatternItems.
* resolve/rust-ast-resolve-base.cc: Add visits for the 2 new classes.
* resolve/rust-ast-resolve-base.h: Header file update for above.
* resolve/rust-ast-resolve-pattern.cc: Update SlicePattern resolution to support new
classes.
Philip Herron [Thu, 31 Jul 2025 20:18:56 +0000 (21:18 +0100)]
gccrs: Support const generic inference variables
We already support const infer so this just creates a fresh tyty::infer_var
for the const element type and then a ConstKind::Infer type for the const
type wrapper and the existing plumbing handles this.
Philip Herron [Sun, 27 Jul 2025 20:47:54 +0000 (21:47 +0100)]
gccrs: Add initial support for const generics
In order to support const generics we map the declarations to a ConstType this
means we reuse all our existing type coercion, unification code and generic
substitutions code to support this with minimal impact.
This patch adds support for:
1. Default const generics
2. Infer const generics
3. ADTType suport
4. unconstrained checks
5. ensure types of the const generic and default
6. validation if passing a const argument to a type argument
Lots of test cases now work and new ones added. More work is needed to support this
on functions and method resolution of impls like Foo<1> vs Foo<2> once thats in we
can look to support some of the const generic array impls next.
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc: useful debug
* backend/rust-compile-stmt.cc (CompileStmt::visit): likewise
* backend/rust-compile-type.cc (TyTyResolveCompile::visit): fold the capacity into ConstType
* hir/tree/rust-hir-generic-param.h: make const
* hir/tree/rust-hir-path.h: take into account const arguments now
* typecheck/rust-hir-type-check-base.cc (TypeCheckBase::resolve_literal): needs const
* typecheck/rust-hir-type-check-base.h: add error handling for const supported locations
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): const type the arrays
* typecheck/rust-hir-type-check-implitem.cc (TypeCheckTopLevelExternItem::visit): update
(TypeCheckImplItem::visit): likewise
* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::visit): likewise
(TypeCheckItem::resolve_impl_block_substitutions): likewise
* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit): wrap up const type
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::visit): likewise
(TypeResolveGenericParam::visit): likewise
(TypeResolveGenericParam::apply_trait_bounds): remove HIR::Generic from Param
* typecheck/rust-hir-type-check.cc (TraitItemReference::get_type_from_fn): cleanup
* typecheck/rust-tyty-subst.cc (SubstitutionParamMapping::SubstitutionParamMapping):
handle const generics
(SubstitutionParamMapping::get_type_representation): likewise
(SubstitutionParamMapping::param_has_default_ty): likewise
(SubstitutionParamMapping::get_default_ty): likewise
(SubstitutionRef::infer_substitions): likewise
* typecheck/rust-tyty-subst.h: likewise
* typecheck/rust-tyty-util.cc (TyVar::get_implicit_const_infer_var): new helper
* typecheck/rust-tyty-util.h (class ConstType): likewise
* typecheck/rust-tyty.cc (BaseType::is_concrete): check for array const concrete
(ArrayType::as_string): update to const
(ArrayType::handle_substitions): likewise
(ParamType::ParamType): likewise
(ParamType::get_generic_param): likewise
(ParamType::clone): likewise
(ConstType::ConstType): likewise
(ConstType::set_value): likewise
(ConstType::clone): likewise
(ConstType::get_generic_param): likewise
(generate_tree_str): new helper to pretty print gimple
(ConstType::get_name): uses the generate_tree_str
(ConstType::handle_substitions): handle const infer's
* typecheck/rust-tyty.h (RUST_TYTY): likewise
* typecheck/rust-unify.cc (UnifyRules::expect_array): likewise
(UnifyRules::expect_const): likewise
gcc/testsuite/ChangeLog:
* rust/compile/const_generics_3.rs: this works now
* rust/compile/const_generics_5.rs: likewise
* rust/compile/const_generics_8.rs: move the failure to another test case
* rust/compile/const_generics_10.rs: New test.
* rust/compile/const_generics_11.rs: New test.
* rust/compile/const_generics_12.rs: New test.
* rust/compile/const_generics_13.rs: New test.
* rust/compile/const_generics_14.rs: New test.
* rust/compile/const_generics_15.rs: New test.
* rust/compile/const_generics_16.rs: New test.
* rust/compile/const_generics_9.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Philip Herron [Sun, 27 Jul 2025 19:19:41 +0000 (20:19 +0100)]
gccrs: Add ConstType boiler plate to handle const generics
This patch is all about just putting in the boiler plate for the new
BaseGeneric TyTy::ConstType. Nothing is really change but just the
nessecary cogs added to the machine.
Philip Herron [Fri, 25 Jul 2025 16:49:15 +0000 (17:49 +0100)]
gccrs: Refactor the ParamType to a BaseGeneric base-type
In order to support const generics we need to abstract away some of the specific
ParamType to a BaseGeneric type so we can easily reuse our existing substitution
bits for const generics which will mean creating a TyTy::ConstType to wrap up
the gcc tree but also represent a const inference and the const decl.
Philip Herron [Fri, 25 Jul 2025 15:56:17 +0000 (16:56 +0100)]
gccrs: Refactor substitution param mapping to be more abstract
This is an initial patch required to refactor our generics code to be
simpler and more abstract so we return the HIR::GenericParam in ParamMappings
instead of assuming its a TypeParam so we can slowly introduce ConstGenericParam
into this same flow.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-base.cc: check for type param
* typecheck/rust-tyty-subst.cc (SubstitutionParamMapping::SubstitutionParamMapping):
return HIR::GenericParam base class
(SubstitutionParamMapping::get_generic_param): likewise
(SubstitutionParamMapping::get_type_representation): new helper
(SubstitutionParamMapping::param_has_default_ty): check for param type
(SubstitutionParamMapping::get_default_ty): likewise
* typecheck/rust-tyty-subst.h: get the locus from the subst HIR::GenericParam now
* typecheck/rust-tyty-variance-analysis.cc (GenericTyPerCrateCtx::debug_print_solutions):
likwise
(GenericTyVisitorCtx::process_type): likewise
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Philip Herron [Thu, 31 Jul 2025 20:46:42 +0000 (21:46 +0100)]
gccrs: Fix ICE during const eval of const capacity
We assert that struct expressions during code-gen must be of TyTy::ADTType
but we can simply just check for this and return error_mark_node to make
this safe.
Fixes Rust-GCC#3960
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::visit): check for ADTType instead of assert
gcc/testsuite/ChangeLog:
* rust/compile/issue-3960.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gccrs: Add input/output from inout and split in out
Inline assembly was incomplete and input/output from inout or split in
out were not handled.
gcc/rust/ChangeLog:
* backend/rust-compile-asm.cc (get_out_expr): Return valid output from
an operand.
(CompileAsm::asm_construct_outputs): Handle every output
(get_in_expr): Return valid input from an operand.
(CompileAsm::asm_construct_inputs): Handle every input
* hir/rust-hir-dump.cc (Dump::visit): Dump inline assembly fields
* hir/tree/rust-hir-expr.h: Add non const getter and avoid operand copy
from getters.
* hir/tree/rust-hir-visitor.cc (DefaultHIRVisitor::walk): Use non const
reference.
* rust-backend.h: New slice_index_expression function.
* rust-gcc.cc: Implementation of slice_index_expression to generate tree node for
accessing slice elements.
* backend/rust-compile-pattern.cc: Implement SlicePattern check expression & binding
compilation against SliceType scrutinee.
gccrs: Update SlicePattern typechecking against slice reference parents
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit(SlicePattern)):
Add new type check case for SliceType wrapped in ReferenceType.
* backend/rust-compile-pattern.cc: Adjusted the asserts accordingly for
CompilePatternCheckExpr(SlicePattern) & CompilePatternBindings(SlicePattern).
Arthur Cohen [Tue, 22 Jul 2025 11:30:11 +0000 (13:30 +0200)]
gccrs: desugar: Handle try-blocks
gcc/rust/ChangeLog:
* Make-lang.in: Compile it.
* ast/rust-expression-yeast.cc (ExpressionYeast::dispatch): Dispatch to try-block
desugar.
* ast/rust-desugar-try-block.cc: New file.
* ast/rust-desugar-try-block.h: New file.
gccrs: Handle IfLetExprConseqElse in DefaultResolver
This relies on the DefaultASTVisitor visitor for IfLetExprConseqElse
performing a virtual call of the visitor for IfLetExpr, which doesn't
hold when DefaultASTVisitor is generated by the X-macro-DSL-system I
have in another patch.
Arthur Cohen [Mon, 21 Jul 2025 09:27:01 +0000 (11:27 +0200)]
gccrs: desugar: Add desugar dispatch for all desugars
Since we are doing more and more "external" desugars, as in desugars
that take a pointer and replace it with another one, rather than
modifying it from within, having an external visitor dispatch to the
proper desugar helps with code clarity.
gcc/rust/ChangeLog:
* Make-lang.in: Compile it.
* rust-session-manager.cc: Call the expression desugar dispatcher.
* ast/rust-desugar-question-mark.cc: Rework class API.
* ast/rust-desugar-question-mark.h: Likewise.
* ast/rust-expression-yeast.cc: New file.
* ast/rust-expression-yeast.h: New file.
TopLevel would ignore just-loaded modules but Early and ExpandVisitor
wouldn't. The latter would produce errors when it hit attributes which
should have been indirectly CfgStrip'd away.
gcc/rust/ChangeLog:
* expand/rust-cfg-strip.cc (CfgStrip::visit): Load unloaded
modules.
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit):
Assume modules have been loaded by CfgStrip.
* expand/rust-expand-visitor.cc
(ExpandVisitor::expand_inner_items): Adjust call to
expand_macro_children.
(ExpandVisitor::expand_inner_stmts): Likewise.
(ExpandVisitor::visit): Likewise.
* expand/rust-expand-visitor.h
(ExpandVisitor::expand_macro_children): Take a pointer to member
function instead of a std::function.
Philip Herron [Sun, 20 Jul 2025 20:48:18 +0000 (21:48 +0100)]
gccrs: fix bad monomophization of generic paths
When we have generic paths like T::foobar during codegen sometimes we need
to enforce an extra lookup for this generic parameter type to the mono
morphized underlying type.
Fixes Rust-GCC#3915
Fixes Rust-GCC#1247
gcc/rust/ChangeLog:
* backend/rust-compile-resolve-path.cc (HIRCompileBase::query_compile): do another lookup
gcc/testsuite/ChangeLog:
* rust/compile/issue-3915.rs: New test.
* rust/execute/torture/sip-hasher.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This should make it easier for us to handle attribute meta items of the
form <SimplePath> '=' <Expression> where the expression isn't a literal.
Some low hanging fruit remains here, but I think I should keep this
patch small as I had some trouble debugging it as-is (see:
Rust::Token::as_string vs Rust::Token::get_str vs
Rust::AST::Token::as_string).
gcc/rust/ChangeLog:
* ast/rust-ast.cc: Include "rust-macro-invoc-lexer.h".
(AttributeParser::~AttributeParser): Move function definition
here.
(AttributeParser::AttributeParser): Likewise and adjust member
initialization.
(AttributeParser::parse_meta_item_inner): Handle changes to
peek_token.
(AttributeParser::parse_literal): Likewise.
(AttributeParser::parse_simple_path_segment): Likewise.
(AttributeParser::parse_meta_item_seq): Handle changes to
AttributeParser fields.
(AttributeParser::peek_token): Move function definition here and
wrap MacroInvocLexer.
(AttributeParser::skip_token): Likewise.
* ast/rust-macro.h (class MacroInvocLexer): Forward declare.
(class Parser): Likewise.
(AttributeParser::token_stream): Remove field.
(AttributeParser::stream_pos): Likewise.
(AttributeParser::lexer): New field.
(AttributeParser::parser): Likewise.
(AttributeParser::AttributeParser): Move definition to
"rust-ast.cc".
(AttributeParser::~AttributeParser): Likewise.
(AttributeParser::peek_token): Likewise.
(AttributeParser::skip_token): Likewise.
Philip Herron [Fri, 18 Jul 2025 14:46:59 +0000 (15:46 +0100)]
gccrs: Add initial support for deffered operator overload resolution
In the test case:
fn test (len: usize) -> u64 {
let mut i = 0;
let mut out = 0;
if i + 3 < len {
out = 123;
}
out
}
The issue is to determine the correct type of 'i', out is simple because it hits a
coercion site in the resturn position for u64. But 'i + 3', 'i' is an integer infer
variable and the same for the literal '3'. So when it comes to resolving the type for
the Add expression we hit the resolve the operator overload code and because of this:
macro_rules! add_impl {
($($t:ty)*) => ($(
impl Add for $t {
type Output = $t;
This means the resolution for 'i + 3' is ambigious because it could be any of these Add
implementations. But because we unify against the '< len' where len is defined as usize
later in the resolution we determine 'i' is actually a usize. Which means if we defer the
resolution of this operator overload in the ambigious case we can simply resolve it at the
end.
Fixes Rust-GCC#3916
gcc/rust/ChangeLog:
* hir/tree/rust-hir-expr.cc (OperatorExprMeta::OperatorExprMeta): track the rhs
* hir/tree/rust-hir-expr.h: likewise
* hir/tree/rust-hir-path.h: get rid of old comments
* typecheck/rust-hir-trait-reference.cc (TraitReference::get_trait_substs): return
references instead of copy
* typecheck/rust-hir-trait-reference.h: update header
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::ResolveOpOverload): write ambigious
operator overloads to a table and try to resolve it at the end
* typecheck/rust-hir-type-check-expr.h: new static helper
* typecheck/rust-hir-type-check.h (struct DeferredOpOverload): new model to defer resolution
* typecheck/rust-typecheck-context.cc (TypeCheckContext::lookup_operator_overload): new
(TypeCheckContext::compute_ambigious_op_overload): likewise
(TypeCheckContext::compute_inference_variables): likewise
gcc/testsuite/ChangeLog:
* rust/compile/issue-3916.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Philip Herron [Fri, 18 Jul 2025 15:22:44 +0000 (16:22 +0100)]
gccrs: Fix ICE with duplicate root item main function
Rust seems to allow duplicate HIR::Item 'main' functions but it needs
to be a root item to be the true main entry point. This means we can
use the canonical path to determine if this is a root one where
its CrateName::main or CrateName::Module::main.
Fixes Rust-GCC#3978
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc: check the canonical path
gcc/testsuite/ChangeLog:
* rust/compile/issue-3978.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
* parse/rust-parse-impl.h (Parser::parse_simple_path): Be more
careful about skipping SCOPE_RESOLUTION tokens.
(Parser::parse_simple_path_segment): Allow parsing from a
starting offset.
(Parser::parse_use_tree): Handle a non-skipped SCOPE_RESOLUTION
token.
* parse/rust-parse.h (Parser::parse_simple_path_segment): Add
parameter for parsing from a starting offset.
gcc/testsuite/ChangeLog:
* rust/compile/parse_simple_path_fail_1.rs: New test.
* rust/compile/parse_simple_path_fail_2.rs: New test.
* rust-backend.h: New size_constant_expression function.
* rust-gcc.cc: Implementation of size_constant_expression function to generate tree node
for array access.
* backend/rust-compile-pattern.h: Remove empty visits for SlicePattern.
* backend/rust-compile-pattern.cc: Implement SlicePattern check expression & binding
compilation against ArrayType scrutinee.
* typecheck/rust-hir-type-check-pattern.cc(TypeCheckPattern::visit(SlicePattern)):
Implement size checking for SlicePattern when type checking against array parent