[PATCH] [x86] Fix ICE due to condition mismatch between expander and define_insn.

2022-12-06 Thread liuhongt via Gcc-patches
ice.i:7:1: error: unrecognizable insn:
7 | }
  | ^
(insn 7 6 8 2 (set (reg:V2SF 84 [ vect__3.8 ])
(unspec:V2SF [
(reg:V2SF 86 [ vect__1.7 ])
(const_int 11 [0xb])
] UNSPEC_ROUND)) "ice.i":5:14 -1
 (nil))
during RTL pass: vregs

Bootstrapped and regtested on x86_64-pc-linux-gnu{-m32,}.
I checked other round patterns are ok, just typo in this one.
Ready push to trunk as obvious patch.

gcc/ChangeLog:

PR target/107970
* config/i386/mmx.md (btruncv2sf2): Add TARGET_MMX_WITH_SSE to
the condition.

gcc/testsuite/ChangeLog:

* gcc.target/i386/pr107970.c: New test.
---
 gcc/config/i386/mmx.md   |  3 ++-
 gcc/testsuite/gcc.target/i386/pr107970.c | 10 ++
 2 files changed, 12 insertions(+), 1 deletion(-)
 create mode 100644 gcc/testsuite/gcc.target/i386/pr107970.c

diff --git a/gcc/config/i386/mmx.md b/gcc/config/i386/mmx.md
index 63aff287795..c3afc6b5846 100644
--- a/gcc/config/i386/mmx.md
+++ b/gcc/config/i386/mmx.md
@@ -1709,7 +1709,8 @@ (define_expand "btruncv2sf2"
  [(match_operand:V2SF 1 "register_operand")
   (match_dup 2)]
  UNSPEC_ROUND))]
-  "TARGET_SSE4_1 && !flag_trapping_math"
+  "TARGET_SSE4_1 && !flag_trapping_math
+  && TARGET_MMX_WITH_SSE"
   "operands[2] = GEN_INT (ROUND_TRUNC | ROUND_NO_EXC);")
 
 (define_insn "*mmx_roundv2sf2"
diff --git a/gcc/testsuite/gcc.target/i386/pr107970.c 
b/gcc/testsuite/gcc.target/i386/pr107970.c
new file mode 100644
index 000..1fbbb14ee72
--- /dev/null
+++ b/gcc/testsuite/gcc.target/i386/pr107970.c
@@ -0,0 +1,10 @@
+/* { dg-do compile { target ia32 } } */
+/* { dg-options "-Ofast -m3dnow -msse4.1" } */
+
+float *foo_p;
+
+void
+foo(float *__restrict q) {
+  foo_p[0] = __builtin_truncf(q[0]);
+  foo_p[1] = __builtin_truncf(q[1]);
+}
-- 
2.27.0



[committed] libgomp.texi: Fix a OpenMP 5.2 and a TR11 impl-status item

2022-12-06 Thread Tobias Burnus

Found when updating the wwwdocs files.

Committed as obvious as https://gcc.gnu.org/r13-4500

Tobias
-
Siemens Electronic Design Automation GmbH; Anschrift: Arnulfstraße 201, 80634 
München; Gesellschaft mit beschränkter Haftung; Geschäftsführer: Thomas 
Heurung, Frank Thürauf; Sitz der Gesellschaft: München; Registergericht 
München, HRB 106955
commit 9f80367e539839fff1df2c85fc2640638199fc9e
Author: Tobias Burnus 
Date:   Tue Dec 6 09:49:30 2022 +0100

libgomp.texi: Fix a OpenMP 5.2 and a TR11 impl-status item

libgomp/
* libgomp.texi (OpenMP 5.2): Add missing 'the'.
(TR11): Add missing '@tab N @tab'.
---
 libgomp/libgomp.texi | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/libgomp/libgomp.texi b/libgomp/libgomp.texi
index 4caac497506..efa7d956a33 100644
--- a/libgomp/libgomp.texi
+++ b/libgomp/libgomp.texi
@@ -406,7 +406,7 @@ to address of matching mapped list item per 5.1, Sect. 2.21.7.2 @tab N @tab
 @item @code{allocate} and @code{firstprivate} clauses on @code{scope}
   @tab Y @tab
 @item @code{ompt_callback_work} @tab N @tab
-@item Default map-type for @code{map} clause in @code{target enter/exit data}
+@item Default map-type for the @code{map} clause in @code{target enter/exit data}
   @tab Y @tab
 @item New @code{doacross} clause as alias for @code{depend} with
   @code{source}/@code{sink} modifier @tab Y @tab
@@ -463,6 +463,7 @@ Technical Report (TR) 11 is the first preview for OpenMP 6.0.
 @item @code{access} allocator trait changes @tab N @tab
 @item Extension of @code{interop} operation of @code{append_args}, allowing all
   modifiers of the @code{init} clause
+  @tab N @tab
 @item @code{interop} clause to @code{dispatch} @tab N @tab
 @item @code{apply} code to loop-transforming constructs @tab N @tab
 @item @code{omp_curr_progress_width} identifier @tab N @tab


[wwwdocs] gcc-13/changes.html + projects/gomp: OpenMP GCC 13 update

2022-12-06 Thread Tobias Burnus

This patch updates the OpenMP implementation status, based on libgomp.texi.
For the release notes, it also moves 'non-rectangular loop nests' up as that's
a 5.0 not a 5.1 feature.
And in line with libgomp.texi, it adds to projects/gomp/ the items for TR11,
a OpenMP 6.0 preview. (Hence, the id="omp6.0" to have a fixed id even when
the list is updated to TR12 and later OpenMP 6.0.)

Comments? Suggestions? OK?

Tobias

PS: There will be surely more updates before GCC 13 is released; I hope/assume
the next change will be for nvptx reverse offload...
-
Siemens Electronic Design Automation GmbH; Anschrift: Arnulfstraße 201, 80634 
München; Gesellschaft mit beschränkter Haftung; Geschäftsführer: Thomas 
Heurung, Frank Thürauf; Sitz der Gesellschaft: München; Registergericht 
München, HRB 106955
commit 9f80367e539839fff1df2c85fc2640638199fc9e
Author: Tobias Burnus 
Date:   Tue Dec 6 09:49:30 2022 +0100

libgomp.texi: Fix a OpenMP 5.2 and a TR11 impl-status item

libgomp/
* libgomp.texi (OpenMP 5.2): Add missing 'the'.
(TR11): Add missing '@tab N @tab'.
---
 libgomp/libgomp.texi | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/libgomp/libgomp.texi b/libgomp/libgomp.texi
index 4caac497506..efa7d956a33 100644
--- a/libgomp/libgomp.texi
+++ b/libgomp/libgomp.texi
@@ -406,7 +406,7 @@ to address of matching mapped list item per 5.1, Sect. 2.21.7.2 @tab N @tab
 @item @code{allocate} and @code{firstprivate} clauses on @code{scope}
   @tab Y @tab
 @item @code{ompt_callback_work} @tab N @tab
-@item Default map-type for @code{map} clause in @code{target enter/exit data}
+@item Default map-type for the @code{map} clause in @code{target enter/exit data}
   @tab Y @tab
 @item New @code{doacross} clause as alias for @code{depend} with
   @code{source}/@code{sink} modifier @tab Y @tab
@@ -463,6 +463,7 @@ Technical Report (TR) 11 is the first preview for OpenMP 6.0.
 @item @code{access} allocator trait changes @tab N @tab
 @item Extension of @code{interop} operation of @code{append_args}, allowing all
   modifiers of the @code{init} clause
+  @tab N @tab
 @item @code{interop} clause to @code{dispatch} @tab N @tab
 @item @code{apply} code to loop-transforming constructs @tab N @tab
 @item @code{omp_curr_progress_width} identifier @tab N @tab


[PATCH v2 0/1] RISC-V: Optimze the reverse conditions of rotate shift

2022-12-06 Thread Feng Wang
The first patch is 
https://gcc.gnu.org/pipermail/gcc-patches/2022-November/607332.html.
Accroding to Jeff's suggestion I added some conditions when reverse the rotate
shift during RTL expansion and RTL optimization.

wangfeng (1):
  RISC-V: Optimze the reverse conditions of rotate shift

 gcc/config/riscv/bitmanip.md  |  4 +-
 gcc/expmed.cc | 14 ++--
 gcc/rtl.h |  1 +
 gcc/simplify-rtx.cc   | 49 ++
 .../gcc.target/riscv/zbb-rol-ror-04.c | 52 +++
 .../gcc.target/riscv/zbb-rol-ror-05.c | 24 +++
 .../gcc.target/riscv/zbb-rol-ror-06.c | 36 +++
 .../gcc.target/riscv/zbb-rol-ror-07.c | 64 +++
 8 files changed, 219 insertions(+), 25 deletions(-)
 create mode 100644 gcc/testsuite/gcc.target/riscv/zbb-rol-ror-04.c
 create mode 100644 gcc/testsuite/gcc.target/riscv/zbb-rol-ror-05.c
 create mode 100644 gcc/testsuite/gcc.target/riscv/zbb-rol-ror-06.c
 create mode 100644 gcc/testsuite/gcc.target/riscv/zbb-rol-ror-07.c

-- 
2.17.1



[PATCH v2 1/1] RISC-V: Optimze the reverse conditions of rotate shift

2022-12-06 Thread Feng Wang
From: wangfeng 

There is no Immediate operand of ins "rol" according to the B-ext,
so the immediate operand should be loaded into register at first.
But we can convert it to the ins "rori" or "roriw", and then one
immediate load ins can be reduced.
So I added some conditions when reverse the rotate shift during RTL
expansion and RTL optimization.Reverse if the below two conditions
are met at the same time,
1. The current insn_code doesn't exist or it's operand doesn't match,
   or the shift amount is beyond the half size of the machine mode;
2. The reversed insn_code exists and it's operand matches.

Please refer to the following use cases:
unsigned long foo2(unsigned long rs1)
{
return (rs1 << 10) | (rs1 >> 54);
}

The compiler result is:
li  a1,10
rol a0,a0,a1

This patch will generate one ins
rori a0,a0,54

At the same time I add the missing "roriw" ins RTL pattern

Pass the linux-rv32imafdc-ilp32d-medany,linux-rv64imafdc-lp64d-medany,
newlib-rv32imafc-ilp32f-medany and newlib-rv64imafdc-lp64d-medany regression.

gcc/ChangeLog:

* config/riscv/bitmanip.md:  Add "roriw" insn output
* expmed.cc (expand_shift_1):Call reverse_rotate_by_imm_p to judge
   whether reverse the rotate direction when GIMPLE to RTL.
* rtl.h (reverse_rotate_by_imm_p): Add function declartion
* simplify-rtx.cc (reverse_rotate_by_imm_p): Add a function to judge
   whether reverse rotate shift direction when simplify rtx.
   Reverse if the below two conditions are met at the same time,
   1. The current insn_code doesn't exist or it's operand doesn't 
match,
  or the shift amount is beyond the half size of the machine 
mode;
   2. The reversed insn_code exists and it's operand matches.

gcc/testsuite/ChangeLog:

* gcc.target/riscv/zbb-rol-ror-04.c: New test.
* gcc.target/riscv/zbb-rol-ror-05.c: New test.
* gcc.target/riscv/zbb-rol-ror-06.c: New test.
* gcc.target/riscv/zbb-rol-ror-07.c: New test.
---
 gcc/config/riscv/bitmanip.md  |  4 +-
 gcc/expmed.cc | 14 ++--
 gcc/rtl.h |  1 +
 gcc/simplify-rtx.cc   | 49 ++
 .../gcc.target/riscv/zbb-rol-ror-04.c | 52 +++
 .../gcc.target/riscv/zbb-rol-ror-05.c | 24 +++
 .../gcc.target/riscv/zbb-rol-ror-06.c | 36 +++
 .../gcc.target/riscv/zbb-rol-ror-07.c | 64 +++
 8 files changed, 219 insertions(+), 25 deletions(-)
 create mode 100644 gcc/testsuite/gcc.target/riscv/zbb-rol-ror-04.c
 create mode 100644 gcc/testsuite/gcc.target/riscv/zbb-rol-ror-05.c
 create mode 100644 gcc/testsuite/gcc.target/riscv/zbb-rol-ror-06.c
 create mode 100644 gcc/testsuite/gcc.target/riscv/zbb-rol-ror-07.c

diff --git a/gcc/config/riscv/bitmanip.md b/gcc/config/riscv/bitmanip.md
index d17133d58c1..ba69d0134b2 100644
--- a/gcc/config/riscv/bitmanip.md
+++ b/gcc/config/riscv/bitmanip.md
@@ -292,9 +292,9 @@
 (define_insn "rotrsi3_sext"
   [(set (match_operand:DI 0 "register_operand" "=r")
(sign_extend:DI (rotatert:SI (match_operand:SI 1 "register_operand" "r")
-(match_operand:QI 2 "register_operand" 
"r"]
+(match_operand:QI 2 "arith_operand" 
"rI"]
   "TARGET_64BIT && TARGET_ZBB"
-  "rorw\t%0,%1,%2"
+  "ror%i2%~\t%0,%1,%2"
   [(set_attr "type" "bitmanip")])
 
 (define_insn "rotlsi3"
diff --git a/gcc/expmed.cc b/gcc/expmed.cc
index b12b0e000c2..907c259c624 100644
--- a/gcc/expmed.cc
+++ b/gcc/expmed.cc
@@ -2475,7 +2475,7 @@ expand_dec (rtx target, rtx dec)
   if (value != target)
 emit_move_insn (target, value);
 }
-
+
 /* Output a shift instruction for expression code CODE,
with SHIFTED being the rtx for the value to shift,
and AMOUNT the rtx for the amount to shift by.
@@ -2535,17 +2535,13 @@ expand_shift_1 (enum tree_code code, machine_mode mode, 
rtx shifted,
op1 = SUBREG_REG (op1);
 }
 
-  /* Canonicalize rotates by constant amount.  If op1 is bitsize / 2,
- prefer left rotation, if op1 is from bitsize / 2 + 1 to
- bitsize - 1, use other direction of rotate with 1 .. bitsize / 2 - 1
- amount instead.  */
+  /* Canonicalize rotates by constant amount.  If the condition of
+ reversing direction is met, then reverse the direction. */
   if (rotate
-  && CONST_INT_P (op1)
-  && IN_RANGE (INTVAL (op1), GET_MODE_BITSIZE (scalar_mode) / 2 + left,
-  GET_MODE_BITSIZE (scalar_mode) - 1))
+  && reverse_rotate_by_imm_p (scalar_mode, left, op1))
 {
   op1 = gen_int_shift_amount (mode, (GET_MODE_BITSIZE (scalar_mode)
-- INTVAL (op1)));
+  - INTVAL (op1)));
   left = !left;
   code = left ? LROTATE_EXPR : RROTATE_EXPR;
 }
diff --git a/gcc/rt

Re: [wwwdocs] gcc-13/changes.html + projects/gomp: OpenMP GCC 13 update

2022-12-06 Thread Jakub Jelinek via Gcc-patches
On Tue, Dec 06, 2022 at 09:59:17AM +0100, Tobias Burnus wrote:
> This patch updates the OpenMP implementation status, based on libgomp.texi.
> For the release notes, it also moves 'non-rectangular loop nests' up as that's
> a 5.0 not a 5.1 feature.
> And in line with libgomp.texi, it adds to projects/gomp/ the items for TR11,
> a OpenMP 6.0 preview. (Hence, the id="omp6.0" to have a fixed id even when
> the list is updated to TR12 and later OpenMP 6.0.)

The posted patch is certainly good, but doesn't do what you wrote above.

> PS: There will be surely more updates before GCC 13 is released; I hope/assume
> the next change will be for nvptx reverse offload...
> -
> Siemens Electronic Design Automation GmbH; Anschrift: Arnulfstraße 201, 80634 
> München; Gesellschaft mit beschränkter Haftung; Geschäftsführer: Thomas 
> Heurung, Frank Thürauf; Sitz der Gesellschaft: München; Registergericht 
> München, HRB 106955

> commit 9f80367e539839fff1df2c85fc2640638199fc9e
> Author: Tobias Burnus 
> Date:   Tue Dec 6 09:49:30 2022 +0100
> 
> libgomp.texi: Fix a OpenMP 5.2 and a TR11 impl-status item
> 
> libgomp/
> * libgomp.texi (OpenMP 5.2): Add missing 'the'.
> (TR11): Add missing '@tab N @tab'.
> ---
>  libgomp/libgomp.texi | 3 ++-
>  1 file changed, 2 insertions(+), 1 deletion(-)
> 
> diff --git a/libgomp/libgomp.texi b/libgomp/libgomp.texi
> index 4caac497506..efa7d956a33 100644
> --- a/libgomp/libgomp.texi
> +++ b/libgomp/libgomp.texi
> @@ -406,7 +406,7 @@ to address of matching mapped list item per 5.1, Sect. 
> 2.21.7.2 @tab N @tab
>  @item @code{allocate} and @code{firstprivate} clauses on @code{scope}
>@tab Y @tab
>  @item @code{ompt_callback_work} @tab N @tab
> -@item Default map-type for @code{map} clause in @code{target enter/exit data}
> +@item Default map-type for the @code{map} clause in @code{target enter/exit 
> data}
>@tab Y @tab
>  @item New @code{doacross} clause as alias for @code{depend} with
>@code{source}/@code{sink} modifier @tab Y @tab
> @@ -463,6 +463,7 @@ Technical Report (TR) 11 is the first preview for OpenMP 
> 6.0.
>  @item @code{access} allocator trait changes @tab N @tab
>  @item Extension of @code{interop} operation of @code{append_args}, allowing 
> all
>modifiers of the @code{init} clause
> +  @tab N @tab
>  @item @code{interop} clause to @code{dispatch} @tab N @tab
>  @item @code{apply} code to loop-transforming constructs @tab N @tab
>  @item @code{omp_curr_progress_width} identifier @tab N @tab


Jakub



Re: [PATCH v2] Add pattern to convert vector shift + bitwise and + multiply to vector compare in some cases.

2022-12-06 Thread Manolis Tsamis
On Wed, Nov 30, 2022 at 9:44 AM Richard Biener
 wrote:
>
> On Tue, Nov 29, 2022 at 11:05 AM Manolis Tsamis  
> wrote:
> >
> > When using SWAR (SIMD in a register) techniques a comparison operation 
> > within
> > such a register can be made by using a combination of shifts, bitwise and 
> > and
> > multiplication. If code using this scheme is vectorized then there is 
> > potential
> > to replace all these operations with a single vector comparison, by 
> > reinterpreting
> > the vector types to match the width of the SWAR register.
> >
> > For example, for the test function packed_cmp_16_32, the original generated 
> > code is:
> >
> > ldr q0, [x0]
> > add w1, w1, 1
> > ushrv0.4s, v0.4s, 15
> > and v0.16b, v0.16b, v2.16b
> > shl v1.4s, v0.4s, 16
> > sub v0.4s, v1.4s, v0.4s
> > str q0, [x0], 16
> > cmp w2, w1
> > bhi .L20
> >
> > with this pattern the above can be optimized to:
> >
> > ldr q0, [x0]
> > add w1, w1, 1
> > cmltv0.8h, v0.8h, #0
> > str q0, [x0], 16
> > cmp w2, w1
> > bhi .L20
> >
> > The effect is similar for x86-64.
> >
> > Signed-off-by: Manolis Tsamis 
> >
> > gcc/ChangeLog:
> >
> > * match.pd: Simplify vector shift + bit_and + multiply in some 
> > cases.
> >
> > gcc/testsuite/ChangeLog:
> >
> > * gcc.target/aarch64/swar_to_vec_cmp.c: New test.
> >
> > ---
> >
> > Changes in v2:
> > - Changed pattern to use vec_cond_expr.
> > - Changed pattern to work with VLA vector.
> > - Added more checks and comments.
> >
> >  gcc/match.pd  | 60 
> >  .../gcc.target/aarch64/swar_to_vec_cmp.c  | 72 +++
> >  2 files changed, 132 insertions(+)
> >  create mode 100644 gcc/testsuite/gcc.target/aarch64/swar_to_vec_cmp.c
> >
> > diff --git a/gcc/match.pd b/gcc/match.pd
> > index 67a0a682f31..05e7fc79ba8 100644
> > --- a/gcc/match.pd
> > +++ b/gcc/match.pd
> > @@ -301,6 +301,66 @@ DEFINE_INT_AND_FLOAT_ROUND_FN (RINT)
> >  (view_convert (bit_and:itype (view_convert @0)
> >  (ne @1 { build_zero_cst (type); })))
> >
> > +/* In SWAR (SIMD in a register) code a signed comparison of packed data can
> > +   be constructed with a particular combination of shift, bitwise and,
> > +   and multiplication by constants.  If that code is vectorized we can
> > +   convert this pattern into a more efficient vector comparison.  */
> > +(simplify
> > + (mult (bit_and (rshift @0 uniform_integer_cst_p@1)
> > +   uniform_integer_cst_p@2)
> > +uniform_integer_cst_p@3)
>
> Please use VECTOR_CST in the match instead of uniform_integer_cst_p
> and instead ...
>
> > + (with {
> > +   tree rshift_cst = uniform_integer_cst_p (@1);
> > +   tree bit_and_cst = uniform_integer_cst_p (@2);
> > +   tree mult_cst = uniform_integer_cst_p (@3);
> > +  }
> > +  /* Make sure we're working with vectors and uniform vector constants.  */
> > +  (if (VECTOR_TYPE_P (type)
>
> ... test for non-NULL *_cst here where you can use uniform_vector_p instead
> of uniform_integer_cst_p.  You can elide the VECTOR_TYPE_P check then
> and instead do INTEGRAL_TYPE_P (TREE_TYPE (type)).
>

I implemented this solution but it didn't match the pattern and after
re-examining the GIMPLE code I remembered that it looks like this:

  vect__5.151_72 = MEM  [(uint32_tD.4389 *)_58];
  vect__38.152_73 = vect__5.151_72 >> 15;
  vect__39.153_74 = vect__38.152_73 & { 65537, 65537, 65537, 65537 };
  vect__40.154_75 = vect__39.153_74 * { 65535, 65535, 65535, 65535 };

Even if all the operations are on vectors the shift is not a VECTOR_CST.
I don't know if this is guaranteed to be the case, i.e. vector shifts are always
a single constant? I used uniform_integer_cst_p to handle this difference in
the constants involved without making an assumption about the shift being
a single constant.

Is there a better way to deal with this subtlety?

Manolis

>
> > +   && tree_fits_uhwi_p (rshift_cst)
> > +   && tree_fits_uhwi_p (mult_cst)
> > +   && tree_fits_uhwi_p (bit_and_cst))
> > +   /* Compute what constants would be needed for this to represent a packed
> > +  comparison based on the shift amount denoted by RSHIFT_CST.  */
> > +   (with {
> > + HOST_WIDE_INT vec_elem_bits = vector_element_bits (type);
> > + poly_int64 vec_nelts = TYPE_VECTOR_SUBPARTS (type);
> > + poly_int64 vec_bits = vec_elem_bits * vec_nelts;
> > +
> > + unsigned HOST_WIDE_INT cmp_bits_i, bit_and_i, mult_i;
> > + unsigned HOST_WIDE_INT target_mult_i, target_bit_and_i;
> > + cmp_bits_i = tree_to_uhwi (rshift_cst) + 1;
> > + target_mult_i = (HOST_WIDE_INT_1U << cmp_bits_i) - 1;
> > +
> > + mult_i = tree_to_uhwi (mult_cst);
> > + bit_and_i = tree_to_uhwi (bit_and_cst);
> > + target_bit_and_i = 0;
> > +
> > + /* The bit pattern in

Re: [wwwdocs] gcc-13/changes.html + projects/gomp: OpenMP GCC 13 update

2022-12-06 Thread Tobias Burnus

On 06.12.22 10:15, Jakub Jelinek wrote:

On Tue, Dec 06, 2022 at 09:59:17AM +0100, Tobias Burnus wrote:

This patch updates the OpenMP implementation status, based on libgomp.texi.
For the release notes, it also moves 'non-rectangular loop nests' up as that's
a 5.0 not a 5.1 feature.
And in line with libgomp.texi, it adds to projects/gomp/ the items for TR11,
a OpenMP 6.0 preview. (Hence, the id="omp6.0" to have a fixed id even when
the list is updated to TR12 and later OpenMP 6.0.)

The posted patch is certainly good, but doesn't do what you wrote above.


Next try  – how about this one?

Tobias


PS: There will be surely more updates before GCC 13 is released; I hope/assume
the next change will be for nvptx reverse offload...

-
Siemens Electronic Design Automation GmbH; Anschrift: Arnulfstraße 201, 80634 
München; Gesellschaft mit beschränkter Haftung; Geschäftsführer: Thomas 
Heurung, Frank Thürauf; Sitz der Gesellschaft: München; Registergericht 
München, HRB 106955
gcc-13/changes.html + projects/gomp: OpenMP GCC 13 update

 htdocs/gcc-13/changes.html  |  21 ++--
 htdocs/projects/gomp/index.html | 227 
 2 files changed, 223 insertions(+), 25 deletions(-)

diff --git a/htdocs/gcc-13/changes.html b/htdocs/gcc-13/changes.html
index 689178f9..59cb7a8d 100644
--- a/htdocs/gcc-13/changes.html
+++ b/htdocs/gcc-13/changes.html
@@ -46,14 +46,15 @@ a work-in-progress.
 General Improvements
 
 
-  https://gcc.gnu.org/projects/gomp/";>OpenMP
+  https://gcc.gnu.org/projects/gomp/";>OpenMP
   
 
   Reverse offload is now supported and the all clauses to the
   requires directive are now accepted; however, the
   requires_offload, unified_address
   and unified_shared_memory clauses cause that the
-  only available device is the initial device (the host).
+  only available device is the initial device (the host). Fortran now
+  supports non-rectangular loop nests, which were added for C/C++ in GCC 11.
 
 
   The following OpenMP 5.1 features have been added: the
@@ -62,9 +63,10 @@ a work-in-progress.
   clause for the taskwait directive and the
   omp_target_is_accessible, omp_target_memcpy_async,
   omp_target_memcpy_rect_async and
-  omp_get_mapped_ptr API routines. Fortran now supports
-  non-rectangular loop nests, which were added for C/C++ in GCC 11.
-
+  omp_get_mapped_ptr API routines. The assume and assumes
+  directives, the begin/end declare target syntax in C/C++
+  and device-specific ICV settings with environment variables are now
+  supported.
 
   Initial support for OpenMP 5.2 features have been added: Support for
   firstprivate and allocate clauses on the
@@ -73,7 +75,14 @@ a work-in-progress.
   omp_initial_device and omp_invalid_device; and
   optionally omitting the map-type in target enter/exit data.
   The enter clause (as alias for to) has been added
-  to the declare target directive.
+  to the declare target directive. Also added has been the
+  omp_in_explicit_task routine and the doacross
+  clause as alias for depend with source/sink
+  modifier.
+
+
+  The _ALL suffix to the device-scope environment variables,
+  added in Technical Report (TR11) is already handled.
 
 
   For user defined allocators requesting high bandwidth or large capacity
diff --git a/htdocs/projects/gomp/index.html b/htdocs/projects/gomp/index.html
index 87903289..114bcde6 100644
--- a/htdocs/projects/gomp/index.html
+++ b/htdocs/projects/gomp/index.html
@@ -28,7 +28,8 @@ OpenMP and OpenACC are supported with GCC's C, C++ and Fortran compilers.
   2.5 · 3.0 ·
   3.1 · 4.0 ·
   4.5 · 5.0 ·
-  5.1 · 5.2
+  5.1 · 5.2 ·
+  TR 11
   OpenMP Releases and Status
 
 
@@ -620,6 +621,16 @@ than listed, depending on resolved corner cases and optimizations.
 GCC 12
 
   
+  
+device-specific ICV settings with environment variables
+GCC 13
+
+  
+  
+assume directive
+GCC 13
+
+  
   
 inoutset argument to the depend clause
 GCC 13
@@ -650,6 +661,11 @@ than listed, depending on resolved corner cases and optimizations.
 GCC 13
 
   
+  
+Support begin/end declare target syntax in C/C++
+GCC 13
+
+  
   
 target_device trait in OpenMP Context
 No
@@ -675,16 +691,6 @@ than listed, depending on resolved corner cases and optimizations.
 No
 
   
-  
-device-specific ICV settings with environment variables
-GCC 13
-
-  
-  
-assume directive
-No
-
-  
   
 Loop transformation constructs
 No
@@ -727,27 +733,28 @@ than listed, depending on resolved corner cases and optimizations.
 
   
   
-ompt_sync_region_t enum additions
+For Fortran, diagnose placing declarative before/between USE,
+  IMPORT, and IMPLICIT as invalid
 No
 
   
   
-ompt_state_t enum: ompt_state_wait_barrier_implementati

Re: [PATCH] Add a new conversion for conditional ternary set into ifcvt [PR106536]

2022-12-06 Thread Richard Sandiford via Gcc-patches
Richard Biener via Gcc-patches  writes:
> On Thu, Nov 24, 2022 at 8:25 AM HAO CHEN GUI  wrote:
>>
>> Hi Richard,
>>
>>
>> 在 2022/11/24 4:06, Richard Biener 写道:
>> > Wouldn't we usually either add an optab or try to recog a canonical
>> > RTL form instead of adding a new target hook for things like this?
>>
>> Thanks so much for your comments. Please let me make it clear.
>>
>> Do you mean we should create an optab for "setb" pattern (the nested
>> if-then-else insn) and detect candidate insns in ifcvt pass? Then
>> generate the insn with the new optab?
>
> Yes, that would be one way to do it.  Another way would be to
> generate a (to be defined) canonical form of such instruction and
> see whether it can be recognized (whether there's a define_insn
> for it).
>
> Note that were just things that came into my mind here, I'm not too
> familiar with how we handle such situations but at least I'm not
> aware of dozens of target hooks to handle instruction availability.

Yeah, this was my reaction too.  The patch does use recog for the
conditional set itself, which is good, but I'm not sure from the patch
what the target hook is supposed to do in preparation for the recog.

I think it'd be better to avoid having too many hooks that take
noce_if_info parameters.  It's really just a bunch of internal
pass state, rather than something that was designed to be a public
interface.

Currently we have one hook that takes noce_if_info parameters,
for costing.  That's still one more than I'd like, but at least there
are no correctness concerns and, if someone changes noce_if_info
in future, just rebuilding cc1 for the affected targets should be
good enough as far as testing goes.  If we start using hooks for code
generation too, we're effectively distributing the ifcvt pass across
targets, which makes the pass harder to maintain.

Thanks,
Richard


Re: [PATCH 1/3] Rework 128-bit complex multiply and divide, PR target/107299

2022-12-06 Thread Kewen.Lin via Gcc-patches
Hi Mike,

Thanks for fixing this!

on 2022/11/2 10:40, Michael Meissner wrote:
> This function reworks how the complex multiply and divide built-in functions 
> are
> done.  Previously we created built-in declarations for doing long double 
> complex
> multiply and divide when long double is IEEE 128-bit.  The old code also did 
> not
> support __ibm128 complex multiply and divide if long double is IEEE 128-bit.
> 
> In terms of history, I wrote the original code just as I was starting to test
> GCC on systems where IEEE 128-bit long double was the default.  At the time, 
> we
> had not yet started mangling the built-in function names as a way to bridge
> going from a system with 128-bit IBM long double to 128-bin IEEE long double.
 ~~~ bit
> 
> The original code depends on there only being two 128-bit types invovled.  
> With
  ~~ 
involved.
> the next patch in this series, this assumption will no longer be true.  When
> long double is IEEE 128-bit, there will be 2 IEEE 128-bit types (one for the
> explicit __float128/_Float128 type and one for long double).
> 
> The problem is we cannot create two separate built-in functions that resolve 
> to
> the same name.  This is a requirement of add_builtin_function and the C front
> end.  That means for the 3 possible modes (IFmode, KFmode, and TFmode), you 
> can
> only use 2 of them.
> 
> This code does not create the built-in declaration with the changed name.
> Instead, it uses the TARGET_MANGLE_DECL_ASSEMBLER_NAME hook to change the name
> before it is written out to the assembler file like it now does for all of the
> other long double built-in functions.
> 
> We need to disable using this mapping when we are building libgcc, 
> specifically
> when it is building the floating point 128-bit multiply and divide functions.
> The flag that is used when libgcc is built (-fbuilding-libcc) is only 
> available
> in the C/C++ front ends.  We need to remember that we are building libgcc in 
> the
> rs6000-c.cc support to be able to use this later to decided whether to mangle
> the decl assembler name or not.

IIUC, for the building of floating point 128-bit multiply and divide functions,
the mapping seems still to work fine.  Using the multiply as example here, when
compiling _multc3.o, it's with -mabi=ibmlongdouble, it maps the name with "tc"
which is consistent with what we need.  While compiling _mulkc3*.o, we would
check the macro __LONG_DOUBLE_IEEE128__ and use either KCmode or TCmode, either
of the mapping result would be "kc".

Could you help to elaborate why we need to disable it during libgcc building?

BR,
Kewen

> 
> When I wrote these patches, I discovered that __ibm128 complex multiply and
> divide had originally not been supported if long double is IEEE 128-bit as it
> would generate calls to __mulic3 and __divic3.  I added tests in the testsuite
> to verify that the correct name (i.e. __multc3 and __divtc3) is used in this
> case.
> 
> I tested all 3 patchs for PR target/107299 on:
> 
> 1)LE Power10 using --with-cpu=power10 
> --with-long-double-format=ieee
> 2)LE Power10 using --with-cpu=power10 
> --with-long-double-format=ibm
> 3)LE Power9  using --with-cpu=power9  
> --with-long-double-format=ibm
> 4)BE Power8  using --with-cpu=power8  
> --with-long-double-format=ibm
> 
> Once all 3 patches have been applied, we can once again build GCC when long
> double is IEEE 128-bit.  There were no other regressions with these patches.
> Can I check these patches into the trunk?
> 
> 2022-11-01   Michael Meissner  
> 
> gcc/
> 
>   PR target/107299
>   * config/rs6000/rs6000-c.cc (rs6000_cpu_cpp_builtins): Set
>   building_libgcc.
>   * config/rs6000/rs6000.cc (create_complex_muldiv): Delete.
>   (init_float128_ieee): Delete code to switch complex multiply and divide
>   for long double.
>   (complex_multiply_builtin_code): New helper function.
>   (complex_divide_builtin_code): Likewise.
>   (rs6000_mangle_decl_assembler_name): Add support for mangling the name
>   of complex 128-bit multiply and divide built-in functions.
>   * config/rs6000/rs6000.opt (building_libgcc): New target variable.
> 
> gcc/testsuite/
> 
>   PR target/107299
>   * gcc.target/powerpc/divic3-1.c: New test.
>   * gcc.target/powerpc/divic3-2.c: Likewise.
>   * gcc.target/powerpc/mulic3-1.c: Likewise.
>   * gcc.target/powerpc/mulic3-2.c: Likewise.
> ---
>  gcc/config/rs6000/rs6000-c.cc   |   8 ++
>  gcc/config/rs6000/rs6000.cc | 110 +++-
>  gcc/config/rs6000/rs6000.opt|   4 +
>  gcc/testsuite/gcc.target/powerpc/divic3-1.c |  18 
>  gcc/testsuite/gcc.target/powerpc/divic3-2.c |  17 +++
>  gcc/testsuite/gcc.target/powerpc/mulic3-1.c |  18 
>  gcc/testsuite/gcc.target/powerpc/mulic3-2.c | 

Re: [wwwdocs] gcc-13/changes.html + projects/gomp: OpenMP GCC 13 update

2022-12-06 Thread Jakub Jelinek via Gcc-patches
On Tue, Dec 06, 2022 at 10:32:40AM +0100, Tobias Burnus wrote:
> +  omp_get_mapped_ptr API routines. The assume and assumes

assume and assumes please

> +  directives, the begin/end declare target syntax in C/C++
> +  and device-specific ICV settings with environment variables are now
> +  supported.
>  
>Initial support for OpenMP 5.2 features have been added: Support for
>firstprivate and allocate clauses on the
> @@ -73,7 +75,14 @@ a work-in-progress.
>omp_initial_device and omp_invalid_device; 
> and
>optionally omitting the map-type in target enter/exit 
> data.
>The enter clause (as alias for to) has been 
> added
> -  to the declare target directive.
> +  to the declare target directive. Also added has been the
> +  omp_in_explicit_task routine and the doacross
> +  clause as alias for depend with source/sink

source/sink

Otherwise LGTM.

Jakub



[PATCH] tree-optimization/104475 - improve access diagnostics

2022-12-06 Thread Richard Biener via Gcc-patches
When we end up isolating a nullptr path it happens we diagnose
accesses to offsetted nullptr objects.  The current diagnostics
have no good indication that this happens so the following records
the fact that our heuristic detected a nullptr based access in
the access_ref structure and sets up diagnostics to inform
of that detail.  The diagnostic itself could probably be
improved here but its API is twisted and the necessary object
isn't passed around.

Instead of just

...bits/atomic_base.h:655:34: warning: 'unsigned int 
__atomic_fetch_and_4(volatile void*, unsigned int, int)' writing 4 bytes into a 
region of size 0 overflows the destination [-Wstringop-overflow=]

we now add

In member function 'void QFutureInterfaceBase::setThrottled(bool)':
cc1plus: note: destination object is likely at address zero

Bootstrapped on x86_64-unknown-linux-gnu, testing in progress.

I think it's an improvement - do you agree that it's enough of it?

Thanks,
Richard.

PR tree-optimization/104475
* pointer-query.h (access_ref::ref_nullptr_p): New flag.
* pointer-query.cc (access_ref::access_ref): Initialize
ref_nullptr_p.
(compute_objsize_r): Set ref_nullptr_p if we treat it that way.
(access_ref::inform_access): If ref was treated as nullptr
based, indicate that.
---
 gcc/pointer-query.cc | 20 
 gcc/pointer-query.h  |  5 -
 2 files changed, 20 insertions(+), 5 deletions(-)

diff --git a/gcc/pointer-query.cc b/gcc/pointer-query.cc
index 95565fd6005..ea6ca684d93 100644
--- a/gcc/pointer-query.cc
+++ b/gcc/pointer-query.cc
@@ -600,8 +600,8 @@ gimple_parm_array_size (tree ptr, wide_int rng[2],
 /* Initialize the object.  */
 
 access_ref::access_ref ()
-  : ref (), eval ([](tree x){ return x; }), deref (), trail1special (true),
-base0 (true), parmarray ()
+  : ref (), eval ([](tree x){ return x; }), deref (), ref_nullptr_p (false),
+trail1special (true), base0 (true), parmarray ()
 {
   /* Set to valid.  */
   offrng[0] = offrng[1] = 0;
@@ -1193,7 +1193,16 @@ access_ref::inform_access (access_mode mode, int ostype 
/* = 1 */) const
 loc = EXPR_LOCATION (ref);
   else if (TREE_CODE (ref) != IDENTIFIER_NODE
   && TREE_CODE (ref) != SSA_NAME)
-return;
+{
+  if (TREE_CODE (ref) == INTEGER_CST && ref_nullptr_p)
+   {
+ if (mode == access_read_write || mode == access_write_only)
+   inform (loc, "destination object is likely at address zero");
+ else
+   inform (loc, "source object is likely at address zero");
+   }
+  return;
+}
 
   if (mode == access_read_write || mode == access_write_only)
 {
@@ -2280,7 +2289,10 @@ compute_objsize_r (tree ptr, gimple *stmt, bool addr, 
int ostype,
  if (targetm.addr_space.zero_address_valid (as))
pref->set_max_size_range ();
  else
-   pref->sizrng[0] = pref->sizrng[1] = 0;
+   {
+ pref->sizrng[0] = pref->sizrng[1] = 0;
+ pref->ref_nullptr_p = true;
+   }
}
   else
pref->sizrng[0] = pref->sizrng[1] = 0;
diff --git a/gcc/pointer-query.h b/gcc/pointer-query.h
index 801a240c38d..19a6f15aab2 100644
--- a/gcc/pointer-query.h
+++ b/gcc/pointer-query.h
@@ -88,7 +88,7 @@ struct access_ref
  argument to the minimum.  */
   offset_int size_remaining (offset_int * = nullptr) const;
 
-/* Return true if the offset and object size are in range for SIZE.  */
+  /* Return true if the offset and object size are in range for SIZE.  */
   bool offset_in_range (const offset_int &) const;
 
   /* Return true if *THIS is an access to a declared object.  */
@@ -141,6 +141,9 @@ struct access_ref
   /* Positive when REF is dereferenced, negative when its address is
  taken.  */
   int deref;
+  /* The following indicates if heuristics interpreted 'ref' is interpreted
+ as (offsetted) nullptr.  */
+  bool ref_nullptr_p;
   /* Set if trailing one-element arrays should be treated as flexible
  array members.  */
   bool trail1special;
-- 
2.35.3


Zen4 tuning part 1 - cost tables

2022-12-06 Thread Jan Hubicka via Gcc-patches
Hi
this patch updates cost of znver4 mostly based on data measued by Agner Fog.
Compared to previous generations x87 became bit slower which is probably not
big deal (and we have minimal benchmarking coverage for it).  One interesting
improvement is reducation of FMA cost.  I also updated costs of AVX256
loads/stores  based on latencies (not throughput which is twice of avx256).
Overall AVX512 vectorization seems to improve noticeably some of TSVC
benchmarks but since internally 512 vectors are split to 256 vectors it is
somewhat risky and does not win in SPEC scores (mostly by regressing benchmarks
with loop that have small trip count like x264 and exchange), so for now I am
going to set AVX256_OPTIMAL tune but I am still playing with it.  We improved
since ZNVER1 on choosing vectorization size and also have vectorized
prologues/epilogues so it may be possible to make avx512 small win overall.

In general I would like to keep cost tables latency based unless we have
a good reason to not do so.  There are some interesting diferences in
znver3 tables that I also patched and seems performance neutral.  I will
send that separately.

Bootstrapped/regtested x86_64-linux, also benchmarked on SPEC2017 along
with AVX512 tuning.  I plan to commit it tomorrow unless there are some
comments.

Honza

* x86-tune-costs.h (znver4_cost): Upate costs of FP and SSE moves,
division multiplication, gathers, L2 cache size, and more complex
FP instrutions.
diff --git a/gcc/config/i386/x86-tune-costs.h b/gcc/config/i386/x86-tune-costs.h
index f01b8ee9eef..3a6ce02f093 100644
--- a/gcc/config/i386/x86-tune-costs.h
+++ b/gcc/config/i386/x86-tune-costs.h
@@ -1867,9 +1868,9 @@ struct processor_costs znver4_cost = {
   {8, 8, 8},   /* cost of storing integer
   registers.  */
   2,   /* cost of reg,reg fld/fst.  */
-  {6, 6, 16},  /* cost of loading fp registers
+  {14, 14, 17},/* cost of loading fp registers
   in SFmode, DFmode and XFmode.  */
-  {8, 8, 16},  /* cost of storing fp registers
+  {12, 12, 16},/* cost of storing fp registers
   in SFmode, DFmode and XFmode.  */
   2,   /* cost of moving MMX register.  */
   {6, 6},  /* cost of loading MMX registers
@@ -1878,13 +1879,13 @@ struct processor_costs znver4_cost = {
   in SImode and DImode.  */
   2, 2, 3, /* cost of moving XMM,YMM,ZMM
   register.  */
-  {6, 6, 6, 6, 12},/* cost of loading SSE registers
+  {6, 6, 10, 10, 12},  /* cost of loading SSE registers
   in 32,64,128,256 and 512-bit.  */
-  {8, 8, 8, 8, 16},/* cost of storing SSE registers
+  {8, 8, 8, 12, 12},   /* cost of storing SSE registers
   in 32,64,128,256 and 512-bit.  */
-  6, 6,/* SSE->integer and integer->SSE
+  6, 8,/* SSE->integer and integer->SSE
   moves.  */
-  8, 8,/* mask->integer and integer->mask 
moves */
+  8, 8,/* mask->integer and 
integer->mask moves */
   {6, 6, 6},   /* cost of loading mask register
   in QImode, HImode, SImode.  */
   {8, 8, 8},   /* cost if storing mask register
@@ -1894,6 +1895,7 @@ struct processor_costs znver4_cost = {
   },
 
   COSTS_N_INSNS (1),   /* cost of an add instruction.  */
+  /* TODO: Lea with 3 components has cost 2.  */
   COSTS_N_INSNS (1),   /* cost of a lea instruction.  */
   COSTS_N_INSNS (1),   /* variable shift costs.  */
   COSTS_N_INSNS (1),   /* constant shift costs.  */
@@ -1904,11 +1906,11 @@ struct processor_costs znver4_cost = {
COSTS_N_INSNS (3)}, /*  other.  */
   0,   /* cost of multiply per each bit
   set.  */
-  {COSTS_N_INSNS (9),  /* cost of a divide/mod for QI.  */
-   COSTS_N_INSNS (10), /*  HI.  */
-   COSTS_N_INSNS (12), /*  SI.  */
-   COSTS_N_INSNS (17), /*  DI.  */
-   COSTS_N_INSNS (17)},/*  
other.  */
+  {COSTS_N_INSNS (12), /* cost of a divide/mod for QI.  *

Re: [PATCH] tree-optimization/104475 - improve access diagnostics

2022-12-06 Thread Jakub Jelinek via Gcc-patches
On Tue, Dec 06, 2022 at 10:50:20AM +0100, Richard Biener wrote:
> When we end up isolating a nullptr path it happens we diagnose
> accesses to offsetted nullptr objects.  The current diagnostics
> have no good indication that this happens so the following records
> the fact that our heuristic detected a nullptr based access in
> the access_ref structure and sets up diagnostics to inform
> of that detail.  The diagnostic itself could probably be
> improved here but its API is twisted and the necessary object
> isn't passed around.
> 
> Instead of just
> 
> ...bits/atomic_base.h:655:34: warning: 'unsigned int 
> __atomic_fetch_and_4(volatile void*, unsigned int, int)' writing 4 bytes into 
> a region of size 0 overflows the destination [-Wstringop-overflow=]
> 
> we now add
> 
> In member function 'void QFutureInterfaceBase::setThrottled(bool)':
> cc1plus: note: destination object is likely at address zero
> 
> Bootstrapped on x86_64-unknown-linux-gnu, testing in progress.
> 
> I think it's an improvement - do you agree that it's enough of it?
> 
> Thanks,
> Richard.
> 
>   PR tree-optimization/104475
>   * pointer-query.h (access_ref::ref_nullptr_p): New flag.
>   * pointer-query.cc (access_ref::access_ref): Initialize
>   ref_nullptr_p.
>   (compute_objsize_r): Set ref_nullptr_p if we treat it that way.
>   (access_ref::inform_access): If ref was treated as nullptr
>   based, indicate that.

LGTM.

Jakub



Rust front-end patches v4

2022-12-06 Thread arthur . cohen
This patchset contains the fixed version of our most recent patchset. We
have fixed most of the issues noted in the previous round of reviews, and are
keeping some for later as they would otherwise create too many conflicts with
our updated development branch.

Similarly to the previous round of patches, this patchset does not contain any
new features - only fixes for the reviews of the v3. New features will follow
shortly once that first patchset is merged.

Once again, thank you to all the contributors who made this possible and
especially to Philip Herron for his dedication to the project.

You can see the current status of our work on our branch:
https://gcc.gnu.org/git/?p=gcc.git;a=shortlog;h=refs/heads/devel/rust/master

Patch status table:

An 'x' in the first column indicates a patch has been reviewed.
One in the second column indicates that a patch has been approved.

|0001-Use-DW_ATE_UTF-for-the-Rust-char-type.patch   |x|x|
|0002-gccrs-Add-necessary-hooks-for-a-Rust-front-end-tests.patch|x|x|
|0003-gccrs-Add-Debug-info-testsuite.patch  | | |
|0004-gccrs-Add-link-cases-testsuite.patch  | | |
|0005-gccrs-Add-general-compilation-test-cases.patch| | |
|0006-gccrs-Add-execution-test-cases.patch  | | |
|0007-gccrs-Add-gcc-check-target-check-rust.patch   |x| |
|0008-gccrs-Add-Rust-front-end-base-AST-data-structures.patch   | | |
|0009-gccrs-Add-definitions-of-Rust-Items-in-AST-data-stru.patch| | |
|0010-gccrs-Add-full-definitions-of-Rust-AST-data-structur.patch| | |
|0011-gccrs-Add-Rust-AST-visitors.patch | | |
|0012-gccrs-Add-Lexer-for-Rust-front-end.patch  |x| |
|0013-gccrs-Add-Parser-for-Rust-front-end-pt.1.patch| | |
|0014-gccrs-Add-Parser-for-Rust-front-end-pt.2.patch| | |
|0015-gccrs-Add-expansion-pass-for-the-Rust-front-end.patch | | |
|0016-gccrs-Add-name-resolution-pass-to-the-Rust-front-end.patch| | |
|0017-gccrs-Add-declarations-for-Rust-HIR.patch | | |
|0018-gccrs-Add-HIR-definitions-and-visitor-framework.patch | | |
|0019-gccrs-Add-AST-to-HIR-lowering-pass.patch  | | |
|0020-gccrs-Add-wrapper-for-make_unique.patch   | | |
|0021-gccrs-Add-port-of-FNV-hash-used-during-legacy-symbol.patch| | |
|0022-gccrs-Add-Rust-ABI-enum-helpers.patch | | |
|0023-gccrs-Add-Base62-implementation.patch | | |
|0024-gccrs-Add-implementation-of-Optional.patch| | |
|0025-gccrs-Add-attributes-checker.patch| | |
|0026-gccrs-Add-helpers-mappings-canonical-path-and-lang-i.patch| | |
|0027-gccrs-Add-type-resolution-and-trait-solving-pass.patch| | |
|0028-gccrs-Add-Rust-type-information.patch | | |
|0029-gccrs-Add-remaining-type-system-transformations.patch | | |
|0030-gccrs-Add-unsafe-checks-for-Rust.patch| | |
|0031-gccrs-Add-const-checker.patch | | |
|0032-gccrs-Add-privacy-checks.patch| | |
|0033-gccrs-Add-dead-code-scan-on-HIR.patch | | |
|0034-gccrs-Add-unused-variable-scan.patch  | | |
|0035-gccrs-Add-metadata-output-pass.patch  | | |
|0036-gccrs-Add-base-for-HIR-to-GCC-GENERIC-lowering.patch  | | |
|0037-gccrs-Add-HIR-to-GCC-GENERIC-lowering-for-all-nodes.patch |x|x|
|0038-gccrs-Add-HIR-to-GCC-GENERIC-lowering-entry-point.patch   |x|x|
|0039-gccrs-These-are-wrappers-ported-from-reusing-gccgo.patch  | | |
|0040-gccrs-Add-GCC-Rust-front-end-Make-lang.in.patch   |x| |
|0041-gccrs-Add-config-lang.in.patch|x|x|
|0042-gccrs-Add-lang-spec.h.patch   | | |
|0043-gccrs-Add-lang.opt.patch  |x| |
|0044-gccrs-Add-compiler-driver.patch   | | |
|0045-gccrs-Compiler-proper-interface-kicks-off-the-pipeli.patch| | |
|0046-gccrs-Add-README-CONTRIBUTING-and-compiler-logo.patch | | |

Patches 34 to 39 and 44 to 45 interact with common GCC APIs:

0034-gccrs-Add-unused-variable-scan.patch
0035-gccrs-Add-metadata-output-pass.patch
0036-gccrs-Add-base-for-HIR-to-GCC-GENERIC-lowering.patch
0037-gccrs-Add-HIR-to-GCC-GENERIC-lowering-for-all-nodes.patch 
0038-gccrs-Add-HIR-to-GCC-GENERIC-lowering-entry-point.patch 
0039-gccrs-These-are-wrappers-ported-from-reusing-gccgo.patch
0044-gccrs-Add-compiler-driver.patch 
0045-gccrs-Compiler-proper-interface-kicks-off-the-pipeli.patch

Patch 02 and 07 contain test infrastructure changes:

0002-gccrs-Add-necessary-hooks-for-a-Rust-front-end-tests.patch
0007-gccrs-Add-gcc-check-target-check-rust.patch

Patch 03 to 06 contain Rust test cases:

0003-gccrs-Add-Debug-info-testsuite.patch
0004-gccrs-Add-link-cases-testsuite.patch
0005-gccrs-Add-general-compilation-test-cases.patch
0006-gccrs-Add-execution-test-cases.patch

Patch

[PATCH Rust front-end v4 01/46] Use DW_ATE_UTF for the Rust 'char' type

2022-12-06 Thread arthur . cohen
From: Tom Tromey 

The Rust 'char' type should use the DWARF DW_ATE_UTF encoding.

Co-authored-by: Mark Wielaard 
Co-authored-by: Marc Poulhiès 
---
 gcc/dwarf2out.cc | 19 ++-
 1 file changed, 18 insertions(+), 1 deletion(-)

diff --git a/gcc/dwarf2out.cc b/gcc/dwarf2out.cc
index e3920c898f5..0d8dd4f1767 100644
--- a/gcc/dwarf2out.cc
+++ b/gcc/dwarf2out.cc
@@ -5600,6 +5600,17 @@ is_fortran (const_tree decl)
   return is_fortran ();
 }
 
+/* Return TRUE if the language is Rust.
+   Note, returns FALSE for dwarf_version < 5 && dwarf_strict. */
+
+static inline bool
+is_rust ()
+{
+  unsigned int lang = get_AT_unsigned (comp_unit_die (), DW_AT_language);
+
+  return lang == DW_LANG_Rust;
+}
+
 /* Return TRUE if the language is Ada.  */
 
 static inline bool
@@ -13231,7 +13242,11 @@ base_type_die (tree type, bool reverse)
}
   if (TYPE_STRING_FLAG (type))
{
- if (TYPE_UNSIGNED (type))
+ if ((dwarf_version >= 4 || !dwarf_strict)
+ && is_rust ()
+ && int_size_in_bytes (type) == 4)
+   encoding = DW_ATE_UTF;
+ else if (TYPE_UNSIGNED (type))
encoding = DW_ATE_unsigned_char;
  else
encoding = DW_ATE_signed_char;
@@ -25226,6 +25241,8 @@ gen_compile_unit_die (const char *filename)
{
  if (strcmp (language_string, "GNU Go") == 0)
language = DW_LANG_Go;
+ else if (strcmp (language_string, "GNU Rust") == 0)
+   language = DW_LANG_Rust;
}
 }
   /* Use a degraded Fortran setting in strict DWARF2 so is_fortran works.  */
-- 
2.38.1



[PATCH Rust front-end v4 03/46] gccrs: Add Debug info testsuite

2022-12-06 Thread arthur . cohen
From: Philip Herron 

This testsuite is specifically about testcases which scan the asm debug
info for results.

Co-authored-by: Tom Tromey 
Co-authored-by: Mark Wielaard 
Co-authored-by: Marc Poulhiès 
---
 gcc/testsuite/rust/debug/chartype.rs  | 10 ++
 .../rust/debug/custom_link_section.rs | 13 
 gcc/testsuite/rust/debug/debug.exp| 33 +++
 gcc/testsuite/rust/debug/i8u8.rs  | 12 +++
 gcc/testsuite/rust/debug/lang.rs  |  6 
 gcc/testsuite/rust/debug/no_mangle.rs | 17 ++
 gcc/testsuite/rust/debug/oldlang.rs   |  6 
 gcc/testsuite/rust/debug/tuple.rs |  8 +
 gcc/testsuite/rust/debug/win64-abi.rs | 11 +++
 9 files changed, 116 insertions(+)
 create mode 100644 gcc/testsuite/rust/debug/chartype.rs
 create mode 100644 gcc/testsuite/rust/debug/custom_link_section.rs
 create mode 100644 gcc/testsuite/rust/debug/debug.exp
 create mode 100644 gcc/testsuite/rust/debug/i8u8.rs
 create mode 100644 gcc/testsuite/rust/debug/lang.rs
 create mode 100644 gcc/testsuite/rust/debug/no_mangle.rs
 create mode 100644 gcc/testsuite/rust/debug/oldlang.rs
 create mode 100644 gcc/testsuite/rust/debug/tuple.rs
 create mode 100644 gcc/testsuite/rust/debug/win64-abi.rs

diff --git a/gcc/testsuite/rust/debug/chartype.rs 
b/gcc/testsuite/rust/debug/chartype.rs
new file mode 100644
index 000..69e7ab0b17f
--- /dev/null
+++ b/gcc/testsuite/rust/debug/chartype.rs
@@ -0,0 +1,10 @@
+// 'char' should use DW_ATE_UTF
+fn main () {
+let c = 'x';
+// { dg-do compile }
+// Use -w to avoid warnings about the unused variables
+// DW_ATE_UTF entered in DWARF 4.
+// { dg-options "-w -gdwarf-4 -dA" }
+// DW_ATE_UTF = 0x10
+// { dg-final { scan-assembler "0x10\[ \t]\[^\n\r]* DW_AT_encoding" } } */
+}
diff --git a/gcc/testsuite/rust/debug/custom_link_section.rs 
b/gcc/testsuite/rust/debug/custom_link_section.rs
new file mode 100644
index 000..142f3513136
--- /dev/null
+++ b/gcc/testsuite/rust/debug/custom_link_section.rs
@@ -0,0 +1,13 @@
+#[link_section = ".universe"]
+fn not_in_text() -> i32 {
+42
+}
+
+fn main() -> i32 {
+// { dg-do compile }
+// { dg-options "-gdwarf-5 -dA -w" }
+not_in_text();
+// { dg-final { scan-assembler ".universe" } } */
+
+0
+}
diff --git a/gcc/testsuite/rust/debug/debug.exp 
b/gcc/testsuite/rust/debug/debug.exp
new file mode 100644
index 000..c71b5930d90
--- /dev/null
+++ b/gcc/testsuite/rust/debug/debug.exp
@@ -0,0 +1,33 @@
+# Copyright (C) 2021-2022 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+# 
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+# 
+# You should have received a copy of the GNU General Public License
+# along with GCC; see the file COPYING3.  If not see
+# .
+
+# Debugging tests.
+
+# Load support procs.
+load_lib rust-dg.exp
+
+# Initialize `dg'.
+dg-init
+
+# Main loop.
+set saved-dg-do-what-default ${dg-do-what-default}
+
+set dg-do-what-default "compile"
+dg-runtest [lsort [glob -nocomplain $srcdir/$subdir/*.rs]] "" ""
+set dg-do-what-default ${saved-dg-do-what-default}
+
+# All done.
+dg-finish
diff --git a/gcc/testsuite/rust/debug/i8u8.rs b/gcc/testsuite/rust/debug/i8u8.rs
new file mode 100644
index 000..1cd21a4a8ff
--- /dev/null
+++ b/gcc/testsuite/rust/debug/i8u8.rs
@@ -0,0 +1,12 @@
+// i8 and u8 types should not have the DWARF 'char' encoding.
+fn main () {
+let x : i8 = 5;
+let y : u8 = 7;
+// { dg-do compile }
+// Use -w to avoid warnings about the unused variables
+// { dg-options "-w -g -dA" }
+// DW_ATE_signed_char = 6
+// { dg-final { scan-assembler-not "0x6\[ \t]\[^\n\r]* DW_AT_encoding" } } */
+// DW_ATE_unsigned_char = 8
+// { dg-final { scan-assembler-not "0x8\[ \t]\[^\n\r]* DW_AT_encoding" } } */
+}
diff --git a/gcc/testsuite/rust/debug/lang.rs b/gcc/testsuite/rust/debug/lang.rs
new file mode 100644
index 000..12e0b587a02
--- /dev/null
+++ b/gcc/testsuite/rust/debug/lang.rs
@@ -0,0 +1,6 @@
+fn main () {
+// { dg-do compile }
+// { dg-options "-gdwarf-5 -dA" }
+// DW_LANG_Rust is 0x1c
+// { dg-final { scan-assembler "0x1c\[ \t]\[^\n\r]* DW_AT_language" } } */
+}
diff --git a/gcc/testsuite/rust/debug/no_mangle.rs 
b/gcc/testsuite/rust/debug/no_mangle.rs
new file mode 100644
index 000..0cef40482f4
--- /dev/null
+++ b/gcc/testsuite/rust/debug/no_mangle.rs
@@ -0,0 +1,17 @@
+#[no_mangle]
+fn do_not_mangle() -> i32 {
+0 
+}
+
+fn please_mangle() {}
+
+fn main() {
+// { dg-do compile }
+// { dg-options "-gdwarf-5 -dA" }
+  

[PATCH Rust front-end v4 02/46] gccrs: Add necessary hooks for a Rust front-end testsuite

2022-12-06 Thread arthur . cohen
From: Philip Herron 

This copies over code from other front-end testsuites to enable testing
for the rust front-end specifically.

Co-authored-by: Marc Poulhiès 
Co-authored-by: Thomas Schwinge 
---
 gcc/testsuite/lib/rust-dg.exp |  49 +
 gcc/testsuite/lib/rust.exp| 186 ++
 2 files changed, 235 insertions(+)
 create mode 100644 gcc/testsuite/lib/rust-dg.exp
 create mode 100644 gcc/testsuite/lib/rust.exp

diff --git a/gcc/testsuite/lib/rust-dg.exp b/gcc/testsuite/lib/rust-dg.exp
new file mode 100644
index 000..a8a2ac0c8eb
--- /dev/null
+++ b/gcc/testsuite/lib/rust-dg.exp
@@ -0,0 +1,49 @@
+# Copyright (C) 1997-2022 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with GCC; see the file COPYING3.  If not see
+# .
+
+load_lib gcc-dg.exp
+
+# Define rust callbacks for dg.exp.
+
+proc rust-dg-test { prog do_what extra_tool_flags } {
+return [gcc-dg-test-1 rust_target_compile $prog $do_what $extra_tool_flags]
+}
+
+proc rust-dg-prune { system text } {
+return [gcc-dg-prune $system $text]
+}
+
+# Utility routines.
+
+#
+# rust_load -- wrapper around default rust_load to handle tests that
+# require program arguments passed to them.
+#
+
+if { [info procs rust_load] != [list] \
+  && [info procs prev_rust_load] == [list] } {
+rename rust_load prev_rust_load
+
+proc rust_load { program args } {
+   global RUST_EXECUTE_ARGS
+   if [info exists RUST_EXECUTE_ARGS] then {
+   set args [concat "{$RUST_EXECUTE_ARGS}"]
+   }
+   set result [eval [list prev_rust_load $program] $args ]
+   return $result
+}
+}
+
diff --git a/gcc/testsuite/lib/rust.exp b/gcc/testsuite/lib/rust.exp
new file mode 100644
index 000..6993c976304
--- /dev/null
+++ b/gcc/testsuite/lib/rust.exp
@@ -0,0 +1,186 @@
+# Copyright (C) 2012-2022 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with GCC; see the file COPYING3.  If not see
+# .
+
+#
+# rust support library routines
+#
+
+load_lib prune.exp
+load_lib gcc-defs.exp
+load_lib timeout.exp
+load_lib target-libpath.exp
+
+#
+# RUST_UNDER_TEST is the compiler under test.
+#
+
+set rust_compile_options ""
+
+
+#
+# rust_include_flags -- include flags for the gcc tree structure
+#
+
+proc rust_include_flags { paths } {
+global srcdir
+global TESTING_IN_BUILD_TREE
+
+set flags ""
+
+if { [is_remote host] || ![info exists TESTING_IN_BUILD_TREE] } {
+   return "${flags}"
+}
+
+set gccpath ${paths}
+
+return "$flags"
+}
+
+#
+# rust_link_flags -- linker flags for the gcc tree structure
+#
+
+proc rust_link_flags { paths } {
+global srcdir
+global ld_library_path
+global RUST_UNDER_TEST
+global shlib_ext
+global SHARED_OPTION
+
+set gccpath ${paths}
+set libio_dir ""
+set flags ""
+set ld_library_path "."
+set shlib_ext [get_shlib_extension]
+set SHARED_OPTION ""
+verbose "shared lib extension: $shlib_ext"
+
+set_ld_library_path_env_vars
+
+return "$flags"
+}
+
+#
+# rust_init -- called at the start of each subdir of tests
+#
+
+proc rust_init { args } {
+global subdir
+global rust_initialized
+global base_dir
+global tmpdir
+global libdir
+global gluefile wrap_flags
+global objdir srcdir
+global ALWAYS_RUSTFLAGS
+global TOOL_EXECUTABLE TOOL_OPTIONS
+global RUST_UNDER_TEST
+global TESTING_IN_BUILD_TREE
+global TEST_ALWAYS_FLAGS
+global gcc_warning_prefix
+global gcc_error_prefix
+
+# We set LC_ALL and LANG to C so that we get the same error messages as 
expected.
+setenv LC_ALL C
+setenv LANG C
+
+if ![info exists RUST_UNDER_TEST] then {
+   if [info exists TOOL_EXECUTABLE] {
+   set RUST_UNDER_TEST $TOOL_EXECUTABLE
+   } else {
+   if { [is_remot

[PATCH Rust front-end v4 04/46] gccrs: Add link cases testsuite

2022-12-06 Thread arthur . cohen
From: Philip Herron 

This testsuite is heavily inspired from the LTO testsuite that uses a
pattern where each file is compiled to an object file and finally linked
together. Since Rust does not have headers/prototypes, we rely on the
ordering here so that all files numbered greater than zero get compiled to
object files first. This leaves the _0 file free to test the 'extern crate' and
'use' keywords to force testing of the compiler to read metadata from the
other 'crates'.
---
 gcc/testsuite/rust/link/generic_function_0.rs |   7 +
 gcc/testsuite/rust/link/generic_function_1.rs |   3 +
 gcc/testsuite/rust/link/link.exp  | 172 ++
 gcc/testsuite/rust/link/simple_function_0.rs  |   8 +
 gcc/testsuite/rust/link/simple_function_1.rs  |   3 +
 gcc/testsuite/rust/link/trait_import_0.rs |  19 ++
 gcc/testsuite/rust/link/trait_import_1.rs |   6 +
 7 files changed, 218 insertions(+)
 create mode 100644 gcc/testsuite/rust/link/generic_function_0.rs
 create mode 100644 gcc/testsuite/rust/link/generic_function_1.rs
 create mode 100644 gcc/testsuite/rust/link/link.exp
 create mode 100644 gcc/testsuite/rust/link/simple_function_0.rs
 create mode 100644 gcc/testsuite/rust/link/simple_function_1.rs
 create mode 100644 gcc/testsuite/rust/link/trait_import_0.rs
 create mode 100644 gcc/testsuite/rust/link/trait_import_1.rs

diff --git a/gcc/testsuite/rust/link/generic_function_0.rs 
b/gcc/testsuite/rust/link/generic_function_0.rs
new file mode 100644
index 000..58b8eb13db6
--- /dev/null
+++ b/gcc/testsuite/rust/link/generic_function_0.rs
@@ -0,0 +1,7 @@
+extern crate generic_function_1;
+use generic_function_1::generic_function;
+
+fn main() -> i32 {
+let a = generic_function(123);
+a - 123
+}
diff --git a/gcc/testsuite/rust/link/generic_function_1.rs 
b/gcc/testsuite/rust/link/generic_function_1.rs
new file mode 100644
index 000..8fb0788e388
--- /dev/null
+++ b/gcc/testsuite/rust/link/generic_function_1.rs
@@ -0,0 +1,3 @@
+pub fn generic_function(a: X) -> X {
+a
+}
diff --git a/gcc/testsuite/rust/link/link.exp b/gcc/testsuite/rust/link/link.exp
new file mode 100644
index 000..8b2e93ceab6
--- /dev/null
+++ b/gcc/testsuite/rust/link/link.exp
@@ -0,0 +1,172 @@
+# Copyright (C) 2021-2022 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+# 
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+# 
+# You should have received a copy of the GNU General Public License
+# along with GCC; see the file COPYING3.  If not see
+# .
+
+# Execute tests, torture testing.
+
+# Load support procs.
+load_lib rust-dg.exp
+
+# Initialize `dg'.
+dg-init
+
+# Main loop.
+set saved-dg-do-what-default ${dg-do-what-default}
+
+set dg-do-what-default "assemble"
+
+# rs-obj -- compile to an object file
+#
+# SOURCE is the source file
+# DEST is the object file
+# OPTALL is the list of compiler options to use with all tests
+# OPTFILE is the list of compiler options to use with this file
+# OPTSTR is the options to print with test messages
+# XFAILDATA is the xfail data to be passed to the compiler
+proc rs-obj { source dest optall optfile optstr xfaildata } {
+global tool
+global compiler_conditional_xfail_data
+
+# Set up the options for compiling this file.
+set options ""
+lappend options "additional_flags=$optall $optfile"
+
+set compiler_conditional_xfail_data $xfaildata
+set comp_output [${tool}_target_compile "$source" "$dest" object $options]
+}
+
+# rs-execute -- compile multi-file tests
+#
+# SRC1 is the full pathname of the main file of the testcase.
+# SID identifies a test suite in the names of temporary files.
+proc rs-execute-1 { src1 } {
+global srcdir tmpdir
+
+# Get extra flags for this test from the primary source file, and
+# process other dg-* options that this suite supports.  Warn about
+# unsupported flags.
+verbose "rs-execute: $src1" 1
+set compile_type "run"
+set compile_xfail(0) "" 
+
+# Set up the names of the other source files.
+set dir [file dirname $src1]
+set base [file rootname $src1]
+set base [string range $base [string length $dir] end]
+regsub "_0" $base "" base
+regsub "/" $base "" base
+set src_list $src1
+set i 1
+set done 0
+while { !$done } {
+   set names [glob -nocomplain -types f -- "${dir}/${base}_${i}.*"]
+   if { [llength ${names}] > 1 } {
+   warning "rs-link-execute: more than one file matched 
${dir}/${base}_${i}.*"
+   }
+   if { [llength ${names}] == 1 } {

[PATCH Rust front-end v4 06/46] gccrs: Add execution test cases

2022-12-06 Thread arthur . cohen
From: Philip Herron 

This is similar to the compile/torture/*.rs test cases, but all of these are
dg-execute testcases. They are compiled, linked and executed by default. These
testcases are also compiled with the matrix of torture options.

The only caveat here is that gccrs does not currently support the main shim,
so we have a C-style main function here returning zero which is not proper Rust
code.

Co-authored-by: Arthur Cohen 
Co-authored-by: Thomas Schwinge 
Co-authored-by: Mark Wielaard 
Co-authored-by: Marc Poulhiès 
---
 .../rust/execute/torture/block_expr1.rs   |   8 +
 .../rust/execute/torture/builtin_macro_cfg.rs |  32 
 .../execute/torture/builtin_macro_concat.rs   |  29 +++
 .../rust/execute/torture/builtin_macro_env.rs |  31 
 .../torture/builtin_macro_include_bytes.rs|  46 +
 .../torture/builtin_macro_include_str.rs  |  27 +++
 .../execute/torture/builtin_macro_line.rs |  25 +++
 .../rust/execute/torture/builtin_macros1.rs   |  21 +++
 .../rust/execute/torture/builtin_macros3.rs   |  28 +++
 gcc/testsuite/rust/execute/torture/cfg1.rs|  32 
 gcc/testsuite/rust/execute/torture/cfg2.rs|  31 
 gcc/testsuite/rust/execute/torture/cfg3.rs|  37 
 gcc/testsuite/rust/execute/torture/cfg4.rs|  38 
 gcc/testsuite/rust/execute/torture/cfg5.rs|  13 ++
 .../rust/execute/torture/coercion1.rs |  41 +
 .../rust/execute/torture/coercion2.rs |  39 
 .../rust/execute/torture/const_fold1.rs   |  13 ++
 .../rust/execute/torture/const_fold2.rs   |  16 ++
 .../execute/torture/copy_nonoverlapping1.rs   |  17 ++
 .../rust/execute/torture/empty_main.rs|   3 +
 .../rust/execute/torture/execute.exp  |  33 
 .../rust/execute/torture/exit_error.rs|   5 +
 .../rust/execute/torture/extern_mod4.rs   |  19 ++
 gcc/testsuite/rust/execute/torture/func1.rs   |   5 +
 .../rust/execute/torture/helloworld1.rs   |  15 ++
 .../rust/execute/torture/helloworld2.rs   |  15 ++
 .../rust/execute/torture/include.txt  |   1 +
 gcc/testsuite/rust/execute/torture/index1.rs  |  28 +++
 .../rust/execute/torture/issue-1120.rs| 123 +
 .../rust/execute/torture/issue-1133.rs| 146 +++
 .../rust/execute/torture/issue-1198.rs|  75 
 .../rust/execute/torture/issue-1231.rs|  36 
 .../rust/execute/torture/issue-1232.rs| 159 
 .../rust/execute/torture/issue-1249.rs|  39 
 .../rust/execute/torture/issue-1436.rs| 172 ++
 .../rust/execute/torture/issue-1496.rs|  75 
 .../rust/execute/torture/issue-647.rs |  33 
 .../rust/execute/torture/issue-845.rs |  47 +
 .../rust/execute/torture/issue-851.rs |  35 
 .../rust/execute/torture/issue-858.rs |  32 
 .../rust/execute/torture/issue-976.rs |  14 ++
 .../rust/execute/torture/issue-995.rs |   9 +
 gcc/testsuite/rust/execute/torture/macros1.rs |  13 ++
 .../rust/execute/torture/macros10.rs  |  22 +++
 .../rust/execute/torture/macros11.rs  |  25 +++
 .../rust/execute/torture/macros12.rs  |  22 +++
 .../rust/execute/torture/macros13.rs  |  22 +++
 .../rust/execute/torture/macros14.rs  |  22 +++
 .../rust/execute/torture/macros16.rs  |  14 ++
 .../rust/execute/torture/macros17.rs  |  17 ++
 .../rust/execute/torture/macros18.rs  |  14 ++
 .../rust/execute/torture/macros19.rs  |  14 ++
 gcc/testsuite/rust/execute/torture/macros2.rs |  40 
 .../rust/execute/torture/macros20.rs  |  14 ++
 .../rust/execute/torture/macros21.rs  |  15 ++
 .../rust/execute/torture/macros22.rs  |  27 +++
 .../rust/execute/torture/macros23.rs  |  19 ++
 .../rust/execute/torture/macros24.rs  |   9 +
 .../rust/execute/torture/macros25.rs  |  13 ++
 .../rust/execute/torture/macros26.rs  |  12 ++
 .../rust/execute/torture/macros27.rs  |  24 +++
 .../rust/execute/torture/macros28.rs  |  13 ++
 .../rust/execute/torture/macros29.rs  |  24 +++
 gcc/testsuite/rust/execute/torture/macros3.rs |  61 +++
 .../rust/execute/torture/macros30.rs  |  25 +++
 .../rust/execute/torture/macros31.rs  |  32 
 gcc/testsuite/rust/execute/torture/macros4.rs |  15 ++
 gcc/testsuite/rust/execute/torture/macros5.rs |  13 ++
 gcc/testsuite/rust/execute/torture/macros6.rs |  12 ++
 gcc/testsuite/rust/execute/torture/macros7.rs |  28 +++
 gcc/testsuite/rust/execute/torture/macros8.rs |  27 +++
 gcc/testsuite/rust/execute/torture/macros9.rs |  28 +++
 gcc/testsuite/rust/execute/torture/match1.rs  |  58 ++
 gcc/testsuite/rust/execute/torture/match2.rs  |  41 +
 gcc/testsuite/rust/execute/torture/match3.rs  |  51 ++
 .../rust/execute/torture/match_bool1.rs   |  49 +
 .../rust/execute/torture/match_byte1.rs   |  56 ++
 .../rust/ex

[PATCH Rust front-end v4 07/46] gccrs: Add gcc-check-target check-rust

2022-12-06 Thread arthur . cohen
From: Philip Herron 

This allows us to invoke the rust testsuite.

ChangeLog:
* Makefile.def: Add Rust language.
* Makefile.in: Regenerate via autogen.
---
 Makefile.def | 1 +
 Makefile.in  | 8 
 2 files changed, 9 insertions(+)

diff --git a/Makefile.def b/Makefile.def
index 3291b126b26..821016af3a2 100644
--- a/Makefile.def
+++ b/Makefile.def
@@ -681,6 +681,7 @@ languages = { language=go;  gcc-check-target=check-go;
 languages = { language=d;  gcc-check-target=check-d;
lib-check-target=check-target-libphobos; };
 languages = { language=jit;gcc-check-target=check-jit; };
+languages = { language=rust;   gcc-check-target=check-rust; };
 
 // Toplevel bootstrap
 bootstrap_stage = { id=1 ; };
diff --git a/Makefile.in b/Makefile.in
index 1919dfee829..9ed2c0dec52 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -60583,6 +60583,14 @@ check-gcc-jit:
(cd gcc && $(MAKE) $(GCC_FLAGS_TO_PASS) check-jit);
 check-jit: check-gcc-jit
 
+.PHONY: check-gcc-rust check-rust
+check-gcc-rust:
+   r=`${PWD_COMMAND}`; export r; \
+   s=`cd $(srcdir); ${PWD_COMMAND}`; export s; \
+   $(HOST_EXPORTS) \
+   (cd gcc && $(MAKE) $(GCC_FLAGS_TO_PASS) check-rust);
+check-rust: check-gcc-rust
+
 
 # The gcc part of install-no-fixedincludes, which relies on an intimate
 # knowledge of how a number of gcc internal targets (inter)operate.  Delegate.
-- 
2.38.1



[PATCH Rust front-end v4 11/46] gccrs: Add Rust AST visitors

2022-12-06 Thread arthur . cohen
From: The Other 

This patch contains the basic framework of our AST visitors, as well as
one aimed at pretty-printing and exporting these AST nodes.

Co-authored-by: Philip Herron 
Co-authored-by: Arthur Cohen 
---
 gcc/rust/ast/rust-ast-dump.cc| 1089 ++
 gcc/rust/ast/rust-ast-dump.h |  246 ++
 gcc/rust/ast/rust-ast-visitor.h  |  234 ++
 gcc/rust/ast/rust-cond-compilation.h |  249 ++
 4 files changed, 1818 insertions(+)
 create mode 100644 gcc/rust/ast/rust-ast-dump.cc
 create mode 100644 gcc/rust/ast/rust-ast-dump.h
 create mode 100644 gcc/rust/ast/rust-ast-visitor.h
 create mode 100644 gcc/rust/ast/rust-cond-compilation.h

diff --git a/gcc/rust/ast/rust-ast-dump.cc b/gcc/rust/ast/rust-ast-dump.cc
new file mode 100644
index 000..ad9ad0b7de7
--- /dev/null
+++ b/gcc/rust/ast/rust-ast-dump.cc
@@ -0,0 +1,1089 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#include "rust-ast-dump.h"
+
+namespace Rust {
+namespace AST {
+
+Indent::Indent () : tabs (0) {}
+
+std::ostream &
+operator<< (std::ostream &stream, const Indent &indent)
+{
+  return stream << std::string (indent.tabs, '\t');
+}
+
+void
+Indent::increment ()
+{
+  tabs++;
+}
+
+void
+Indent::decrement ()
+{
+  rust_assert (tabs != 0);
+  tabs--;
+}
+
+Dump::Dump (std::ostream &stream) : stream (stream), indentation (Indent ()) {}
+
+void
+Dump::go (AST::Crate &crate)
+{
+  for (auto &item : crate.items)
+{
+  stream << indentation;
+  item->accept_vis (*this);
+  stream << "\n";
+}
+}
+
+void
+Dump::go (AST::Item &item)
+{
+  item.accept_vis (*this);
+}
+
+void
+Dump::format_function_param (FunctionParam ¶m)
+{
+  param.get_pattern ()->accept_vis (*this);
+  stream << ": ";
+  param.get_type ()->accept_vis (*this);
+}
+
+void
+Dump::emit_attrib (const Attribute &attrib)
+{
+  stream << "#";
+  stream << "[";
+
+  for (size_t i = 0; i < attrib.get_path ().get_segments ().size (); i++)
+{
+  const auto &seg = attrib.get_path ().get_segments ().at (i);
+  bool has_next = (i + 1) < attrib.get_path ().get_segments ().size ();
+
+  stream << seg.get_segment_name ();
+  if (has_next)
+   stream << "::";
+}
+
+  if (attrib.has_attr_input ())
+{
+  stream << " = ";
+
+  bool is_literal = attrib.get_attr_input ().get_attr_input_type ()
+   == AST::AttrInput::AttrInputType::LITERAL;
+  if (is_literal)
+   {
+ auto &literal
+   = static_cast (attrib.get_attr_input ());
+ const auto &value = literal.get_literal ().as_string ();
+
+ stream << "\"" << value << "\"";
+   }
+  else
+   {
+ stream << "FIXME";
+   }
+}
+
+  stream << "]";
+}
+
+void
+Dump::visit (Token &tok)
+{}
+
+void
+Dump::visit (DelimTokenTree &delim_tok_tree)
+{}
+
+void
+Dump::visit (AttrInputMetaItemContainer &input)
+{}
+
+void
+Dump::visit (IdentifierExpr &ident_expr)
+{
+  stream << ident_expr.get_ident ();
+}
+
+void
+Dump::visit (Lifetime &lifetime)
+{}
+
+void
+Dump::visit (LifetimeParam &lifetime_param)
+{}
+
+void
+Dump::visit (ConstGenericParam &lifetime_param)
+{}
+
+// rust-path.h
+void
+Dump::visit (PathInExpression &path)
+{}
+
+void
+Dump::visit (TypePathSegment &segment)
+{}
+
+void
+Dump::visit (TypePathSegmentGeneric &segment)
+{}
+
+void
+Dump::visit (TypePathSegmentFunction &segment)
+{}
+
+void
+Dump::visit (TypePath &path)
+{
+  stream << path.as_string ();
+}
+
+void
+Dump::visit (QualifiedPathInExpression &path)
+{}
+
+void
+Dump::visit (QualifiedPathInType &path)
+{}
+
+// rust-expr.h
+void
+Dump::visit (LiteralExpr &expr)
+{
+  stream << expr.as_string ();
+}
+
+void
+Dump::visit (AttrInputLiteral &attr_input)
+{}
+
+void
+Dump::visit (MetaItemLitExpr &meta_item)
+{}
+
+void
+Dump::visit (MetaItemPathLit &meta_item)
+{}
+
+void
+Dump::visit (BorrowExpr &expr)
+{}
+
+void
+Dump::visit (DereferenceExpr &expr)
+{}
+
+void
+Dump::visit (ErrorPropagationExpr &expr)
+{}
+
+void
+Dump::visit (NegationExpr &expr)
+{}
+
+void
+Dump::visit (ArithmeticOrLogicalExpr &expr)
+{
+  expr.get_left_expr ()->accept_vis (*this);
+  stream << " ";
+
+  switch (expr.get_expr_type ())
+{
+case ArithmeticOrLogicalOperator::ADD:
+  stream << "+";
+  break;
+
+case ArithmeticOrLogicalOperator::

[PATCH Rust front-end v4 12/46] gccrs: Add Lexer for Rust front-end

2022-12-06 Thread arthur . cohen
From: The Other 

The lexer is referred to as a ManagedTokenSource within the parser. This
lexer does not currently support Unicode, but serves as a starting point
to do so.

Co-authored-by: Philip Herron 
Co-authored-by: Arthur Cohen 
Co-authored-by: Mark Wielaard 
---
 gcc/rust/lex/rust-codepoint.h  |   46 +
 gcc/rust/lex/rust-lex.cc   | 2728 
 gcc/rust/lex/rust-lex.h|  271 
 gcc/rust/lex/rust-token.cc |  134 ++
 gcc/rust/lex/rust-token.h  |  450 ++
 gcc/rust/rust-buffered-queue.h |  204 +++
 6 files changed, 3833 insertions(+)
 create mode 100644 gcc/rust/lex/rust-codepoint.h
 create mode 100644 gcc/rust/lex/rust-lex.cc
 create mode 100644 gcc/rust/lex/rust-lex.h
 create mode 100644 gcc/rust/lex/rust-token.cc
 create mode 100644 gcc/rust/lex/rust-token.h
 create mode 100644 gcc/rust/rust-buffered-queue.h

diff --git a/gcc/rust/lex/rust-codepoint.h b/gcc/rust/lex/rust-codepoint.h
new file mode 100644
index 000..1a9f0ca7a21
--- /dev/null
+++ b/gcc/rust/lex/rust-codepoint.h
@@ -0,0 +1,46 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#ifndef RUST_CODEPOINT_H
+#define RUST_CODEPOINT_H
+
+#include "rust-system.h"
+
+namespace Rust {
+struct Codepoint
+{
+  uint32_t value;
+
+  // Creates a zero codepoint.
+  Codepoint () : value (0) {}
+
+  // Creates a codepoint from an encoded UTF-8 value.
+  Codepoint (uint32_t value) : value (value) {}
+
+  static Codepoint eof () { return Codepoint (UINT32_MAX); }
+  bool is_eof () const { return value == UINT32_MAX; }
+
+  // Returns a C++ string containing string value of codepoint.
+  std::string as_string ();
+
+  bool operator== (Codepoint other) const { return value == other.value; }
+  bool operator!= (Codepoint other) const { return !operator== (other); }
+};
+} // namespace Rust
+
+#endif
diff --git a/gcc/rust/lex/rust-lex.cc b/gcc/rust/lex/rust-lex.cc
new file mode 100644
index 000..82949f5fe5f
--- /dev/null
+++ b/gcc/rust/lex/rust-lex.cc
@@ -0,0 +1,2728 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#include "rust-system.h"
+#include "rust-lex.h"
+#include "rust-diagnostics.h"
+#include "rust-linemap.h"
+#include "rust-session-manager.h"
+#include "safe-ctype.h"
+
+namespace Rust {
+// TODO: move to separate compilation unit?
+// overload += for uint32_t to allow 32-bit encoded utf-8 to be added
+std::string &
+operator+= (std::string &str, Codepoint char32)
+{
+  if (char32.value < 0x80)
+{
+  str += static_cast (char32.value);
+}
+  else if (char32.value < (0x1F + 1) << (1 * 6))
+{
+  str += static_cast (0xC0 | ((char32.value >> 6) & 0x1F));
+  str += static_cast (0x80 | ((char32.value >> 0) & 0x3F));
+}
+  else if (char32.value < (0x0F + 1) << (2 * 6))
+{
+  str += static_cast (0xE0 | ((char32.value >> 12) & 0x0F));
+  str += static_cast (0x80 | ((char32.value >> 6) & 0x3F));
+  str += static_cast (0x80 | ((char32.value >> 0) & 0x3F));
+}
+  else if (char32.value < (0x07 + 1) << (3 * 6))
+{
+  str += static_cast (0xF0 | ((char32.value >> 18) & 0x07));
+  str += static_cast (0x80 | ((char32.value >> 12) & 0x3F));
+  str += static_cast (0x80 | ((char32.value >> 6) & 0x3F));
+  str += static_cast (0x80 | ((char32.value >> 0) & 0x3F));
+}
+  else
+{
+  rust_debug ("Invalid unicode codepoint found: '%u' ", char32.value);
+}
+  return str;
+}
+
+std::string
+Codepoint::as_string ()
+{
+  std::string str;
+
+  // str += Codepoint (value);
+  str += *this;
+
+  return str;
+}
+
+/* Includes all allowable float digits EXCEPT _ and . as that needs lookahea

[PATCH Rust front-end v4 09/46] gccrs: Add definitions of Rust Items in AST data structures

2022-12-06 Thread arthur . cohen
From: The Other 

This adds the proper definitions of our AST Item nodes.

Co-authored-by: Philip Herron 
---
 gcc/rust/ast/rust-item.h | 4382 ++
 1 file changed, 4382 insertions(+)
 create mode 100644 gcc/rust/ast/rust-item.h

diff --git a/gcc/rust/ast/rust-item.h b/gcc/rust/ast/rust-item.h
new file mode 100644
index 000..4987674cba1
--- /dev/null
+++ b/gcc/rust/ast/rust-item.h
@@ -0,0 +1,4382 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#ifndef RUST_AST_ITEM_H
+#define RUST_AST_ITEM_H
+
+#include "rust-ast.h"
+#include "rust-path.h"
+#include "rust-common.h"
+
+namespace Rust {
+namespace AST {
+// forward decls
+class BlockExpr;
+class TypePath;
+
+// TODO: inline?
+/*struct AbiName {
+std::string abi_name;
+// Technically is meant to be STRING_LITERAL
+
+  public:
+// Returns whether abi name is empty, i.e. doesn't exist.
+bool is_empty() const {
+   return abi_name.empty();
+}
+
+AbiName(std::string name) : abi_name(std::move(name)) {}
+
+// Empty AbiName constructor
+AbiName() {}
+};*/
+
+// A type generic parameter (as opposed to a lifetime generic parameter)
+class TypeParam : public GenericParam
+{
+  // bool has_outer_attribute;
+  // std::unique_ptr outer_attr;
+  Attribute outer_attr;
+
+  Identifier type_representation;
+
+  // bool has_type_param_bounds;
+  // TypeParamBounds type_param_bounds;
+  std::vector>
+type_param_bounds; // inlined form
+
+  // bool has_type;
+  std::unique_ptr type;
+
+  Location locus;
+
+public:
+  Identifier get_type_representation () const { return type_representation; }
+
+  // Returns whether the type of the type param has been specified.
+  bool has_type () const { return type != nullptr; }
+
+  // Returns whether the type param has type param bounds.
+  bool has_type_param_bounds () const { return !type_param_bounds.empty (); }
+
+  // Returns whether the type param has an outer attribute.
+  bool has_outer_attribute () const { return !outer_attr.is_empty (); }
+
+  TypeParam (Identifier type_representation, Location locus = Location (),
+std::vector> type_param_bounds
+= std::vector> (),
+std::unique_ptr type = nullptr,
+Attribute outer_attr = Attribute::create_empty ())
+: GenericParam (Analysis::Mappings::get ()->get_next_node_id ()),
+  outer_attr (std::move (outer_attr)),
+  type_representation (std::move (type_representation)),
+  type_param_bounds (std::move (type_param_bounds)),
+  type (std::move (type)), locus (locus)
+  {}
+
+  // Copy constructor uses clone
+  TypeParam (TypeParam const &other)
+: GenericParam (other.node_id), outer_attr (other.outer_attr),
+  type_representation (other.type_representation), locus (other.locus)
+  {
+// guard to prevent null pointer dereference
+if (other.type != nullptr)
+  type = other.type->clone_type ();
+
+type_param_bounds.reserve (other.type_param_bounds.size ());
+for (const auto &e : other.type_param_bounds)
+  type_param_bounds.push_back (e->clone_type_param_bound ());
+  }
+
+  // Overloaded assignment operator to clone
+  TypeParam &operator= (TypeParam const &other)
+  {
+type_representation = other.type_representation;
+outer_attr = other.outer_attr;
+locus = other.locus;
+node_id = other.node_id;
+
+// guard to prevent null pointer dereference
+if (other.type != nullptr)
+  type = other.type->clone_type ();
+else
+  type = nullptr;
+
+type_param_bounds.reserve (other.type_param_bounds.size ());
+for (const auto &e : other.type_param_bounds)
+  type_param_bounds.push_back (e->clone_type_param_bound ());
+
+return *this;
+  }
+
+  // move constructors
+  TypeParam (TypeParam &&other) = default;
+  TypeParam &operator= (TypeParam &&other) = default;
+
+  std::string as_string () const override;
+
+  Location get_locus () const override final { return locus; }
+
+  Kind get_kind () const override final { return Kind::Type; }
+
+  void accept_vis (ASTVisitor &vis) override;
+
+  // TODO: is this better? Or is a "vis_block" better?
+  std::unique_ptr &get_type ()
+  {
+rust_assert (type != nullptr);
+return type;
+  }
+
+  // TODO: mutable getter seems kinda dodgy
+  std::vector> &get_t

[PATCH Rust front-end v4 23/46] gccrs: Add Base62 implementation

2022-12-06 Thread arthur . cohen
From: Arthur Cohen 

Used for V0 symbol mangling scheme which is still in development.
---
 gcc/rust/util/rust-base62.cc | 46 
 gcc/rust/util/rust-base62.h  | 34 ++
 2 files changed, 80 insertions(+)
 create mode 100644 gcc/rust/util/rust-base62.cc
 create mode 100644 gcc/rust/util/rust-base62.h

diff --git a/gcc/rust/util/rust-base62.cc b/gcc/rust/util/rust-base62.cc
new file mode 100644
index 000..bdab23338c3
--- /dev/null
+++ b/gcc/rust/util/rust-base62.cc
@@ -0,0 +1,46 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#include "rust-base62.h"
+
+namespace Rust {
+
+std::string
+base62_integer (uint64_t value)
+{
+  const static std::string base_64
+= "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@$";
+  std::string buffer (128, '\0');
+  size_t idx = 0;
+  size_t base = 62;
+
+  do
+{
+  buffer[idx] = base_64[(value % base)];
+  idx++;
+  value = value / base;
+}
+  while (value != 0);
+
+  std::reverse (buffer.begin (), buffer.begin () + idx);
+  return buffer.substr (0, idx);
+}
+
+} // namespace Rust
+
+// FIXME: Add unit testing using the selftest framework
diff --git a/gcc/rust/util/rust-base62.h b/gcc/rust/util/rust-base62.h
new file mode 100644
index 000..fa610d3e5a4
--- /dev/null
+++ b/gcc/rust/util/rust-base62.h
@@ -0,0 +1,34 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#ifndef RUST_BASE62_H
+#define RUST_BASE62_H
+
+#include "rust-system.h"
+
+namespace Rust {
+
+/**
+ * Get the Base62 representation of an integer
+ */
+std::string
+base62_integer (uint64_t value);
+
+} // namespace Rust
+
+#endif /* !RUST_BASE62_H */
-- 
2.38.1



[PATCH Rust front-end v4 20/46] gccrs: Add wrapper for make_unique

2022-12-06 Thread arthur . cohen
From: Philip Herron 

This is a wrapper for make_unique. We can likely get rid of this, as there
are other implementations available, or simply keep using the unique_ptr
constructor.
---
 gcc/rust/util/rust-make-unique.h | 35 
 1 file changed, 35 insertions(+)
 create mode 100644 gcc/rust/util/rust-make-unique.h

diff --git a/gcc/rust/util/rust-make-unique.h b/gcc/rust/util/rust-make-unique.h
new file mode 100644
index 000..7b79e625ff1
--- /dev/null
+++ b/gcc/rust/util/rust-make-unique.h
@@ -0,0 +1,35 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#ifndef RUST_MAKE_UNIQUE_H
+#define RUST_MAKE_UNIQUE_H
+
+#include "rust-system.h"
+
+namespace Rust {
+
+template 
+std::unique_ptr
+make_unique (Ts &&...params)
+{
+  return std::unique_ptr (new T (std::forward (params)...));
+}
+
+} // namespace Rust
+
+#endif // RUST_MAKE_UNIQUE_H
-- 
2.38.1



[PATCH Rust front-end v4 26/46] gccrs: Add helpers mappings canonical path and lang items

2022-12-06 Thread arthur . cohen
From: Philip Herron 

These are various helper classes used in the compiler pipeline.
---
 gcc/rust/util/rust-canonical-path.h   | 195 +
 gcc/rust/util/rust-common.h   |  53 ++
 gcc/rust/util/rust-hir-map.cc | 980 ++
 gcc/rust/util/rust-hir-map.h  | 356 ++
 gcc/rust/util/rust-identifier.h   |  49 ++
 gcc/rust/util/rust-lang-item.h| 377 ++
 gcc/rust/util/rust-mapping-common.h   |  85 +++
 gcc/rust/util/rust-stacked-contexts.h |  86 +++
 8 files changed, 2181 insertions(+)
 create mode 100644 gcc/rust/util/rust-canonical-path.h
 create mode 100644 gcc/rust/util/rust-common.h
 create mode 100644 gcc/rust/util/rust-hir-map.cc
 create mode 100644 gcc/rust/util/rust-hir-map.h
 create mode 100644 gcc/rust/util/rust-identifier.h
 create mode 100644 gcc/rust/util/rust-lang-item.h
 create mode 100644 gcc/rust/util/rust-mapping-common.h
 create mode 100644 gcc/rust/util/rust-stacked-contexts.h

diff --git a/gcc/rust/util/rust-canonical-path.h 
b/gcc/rust/util/rust-canonical-path.h
new file mode 100644
index 000..54cc0390849
--- /dev/null
+++ b/gcc/rust/util/rust-canonical-path.h
@@ -0,0 +1,195 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#ifndef RUST_CANONICAL_PATH
+#define RUST_CANONICAL_PATH
+
+#include "rust-system.h"
+#include "rust-mapping-common.h"
+
+namespace Rust {
+namespace Resolver {
+
+// https://doc.rust-lang.org/reference/paths.html#canonical-paths
+//
+// struct X - path X
+// impl X { fn test - path X::test }
+//
+// struct X - path X
+//
+// impl X   { fn test - path X::test}
+// impl X { fn test - path X::test }
+// impl X { fn test - path X::test }
+//
+// pub trait Trait { // ::a::Trait
+//   fn f(&self); // ::a::Trait::f
+// }
+//
+// impl Trait for Struct {
+//fn f(&self) {} // <::a::Struct as ::a::Trait>::f
+// }
+class CanonicalPath
+{
+public:
+  CanonicalPath (const CanonicalPath &other) : segs (other.segs) {}
+
+  CanonicalPath &operator= (const CanonicalPath &other)
+  {
+segs = other.segs;
+return *this;
+  }
+
+  static CanonicalPath new_seg (NodeId id, const std::string &path)
+  {
+rust_assert (!path.empty ());
+return CanonicalPath ({std::pair (id, path)},
+ UNKNOWN_CREATENUM);
+  }
+
+  static CanonicalPath
+  trait_impl_projection_seg (NodeId id, const CanonicalPath &trait_seg,
+const CanonicalPath &impl_type_seg)
+  {
+return CanonicalPath::new_seg (id, "<" + impl_type_seg.get () + " as "
++ trait_seg.get () + ">");
+  }
+
+  std::string get () const
+  {
+std::string buf;
+for (size_t i = 0; i < segs.size (); i++)
+  {
+   bool have_more = (i + 1) < segs.size ();
+   const std::string &seg = segs.at (i).second;
+   buf += seg + (have_more ? "::" : "");
+  }
+return buf;
+  }
+
+  static CanonicalPath get_big_self (NodeId id)
+  {
+return CanonicalPath::new_seg (id, "Self");
+  }
+
+  static CanonicalPath create_empty ()
+  {
+return CanonicalPath ({}, UNKNOWN_CREATENUM);
+  }
+
+  bool is_empty () const { return segs.size () == 0; }
+
+  CanonicalPath append (const CanonicalPath &other) const
+  {
+rust_assert (!other.is_empty ());
+if (is_empty ())
+  return CanonicalPath (other.segs, crate_num);
+
+std::vector> copy (segs);
+for (auto &s : other.segs)
+  copy.push_back (s);
+
+return CanonicalPath (copy, crate_num);
+  }
+
+  // if we have the path A::B::C this will give a callback for each segment
+  // including the prefix, example:
+  //
+  // path:
+  //   A::B::C
+  //
+  // iterate:
+  //   A
+  //   A::B
+  //   A::B::C
+  void iterate (std::function cb) const
+  {
+std::vector> buf;
+for (auto &seg : segs)
+  {
+   buf.push_back (seg);
+   if (!cb (CanonicalPath (buf, crate_num)))
+ return;
+  }
+  }
+
+  // if we have the path A::B::C this will give a callback for each segment
+  // example:
+  //
+  // path:
+  //   A::B::C
+  //
+  // iterate:
+  //   A
+  //  B
+  // C
+  void iterate_segs (std::function cb) const
+  {
+for (auto &seg : segs)
+  {
+   std::vector> buf;
+   buf.push_back ({seg.first, seg.second});
+   if (!cb (CanonicalPath (buf, crate_num)))

[PATCH Rust front-end v4 24/46] gccrs: Add implementation of Optional

2022-12-06 Thread arthur . cohen
From: Arthur Cohen 

This adds an Optional class to improve error handling.
---
 gcc/rust/util/rust-optional-test.cc | 110 +++
 gcc/rust/util/rust-optional.h   | 278 
 2 files changed, 388 insertions(+)
 create mode 100644 gcc/rust/util/rust-optional-test.cc
 create mode 100644 gcc/rust/util/rust-optional.h

diff --git a/gcc/rust/util/rust-optional-test.cc 
b/gcc/rust/util/rust-optional-test.cc
new file mode 100644
index 000..43fa175fa40
--- /dev/null
+++ b/gcc/rust/util/rust-optional-test.cc
@@ -0,0 +1,110 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#include "rust-system.h"
+#include "rust-optional.h"
+#include "selftest.h"
+
+#if CHECKING_P
+
+static void
+rust_optional_create ()
+{
+  auto opt = Rust::Optional::some (15);
+
+  ASSERT_TRUE (opt.is_some ());
+  ASSERT_EQ (opt.get (), 15);
+
+  Rust::Optional const_opt = Rust::Optional::some (15);
+  const int &value = const_opt.get ();
+
+  ASSERT_EQ (value, 15);
+}
+
+static void
+rust_optional_operators ()
+{
+  auto opt = Rust::Optional::some (15);
+
+  // as bool
+  ASSERT_TRUE (opt);
+
+  // deref
+  ASSERT_EQ (*opt, 15);
+
+  class Methodable
+  {
+  public:
+int method () { return 15; }
+  };
+
+  auto m_opt = Rust::Optional::some (Methodable ());
+  ASSERT_EQ (m_opt->method (), 15);
+}
+
+static void
+rust_optional_take ()
+{
+  auto opt = Rust::Optional::some (15);
+  auto value = opt.take ();
+
+  ASSERT_EQ (value, 15);
+  ASSERT_TRUE (opt.is_none ());
+}
+
+static void
+rust_optional_map ()
+{
+  auto opt = Rust::Optional::some (15);
+  auto twice = opt.map ([] (int value) { return value * 2; });
+
+  ASSERT_FALSE (opt);
+  ASSERT_TRUE (twice);
+  ASSERT_EQ (*twice, 30);
+}
+
+static void
+rust_optional_reference ()
+{
+  auto value = std::vector ();
+  value.emplace_back ("rust");
+  value.emplace_back ("+");
+  value.emplace_back ("gcc");
+  value.emplace_back ("=");
+  value.emplace_back ("<3");
+
+  auto opt = Rust::Optional &>::some (value);
+
+  ASSERT_EQ (opt->at (0), "rust");
+  ASSERT_EQ (opt->at (2), "gcc");
+}
+
+#endif /* #if CHECKING_P */
+
+void
+rust_optional_test ()
+{
+#if CHECKING_P
+  rust_optional_create ();
+  rust_optional_operators ();
+  rust_optional_take ();
+  rust_optional_map ();
+  rust_optional_reference ();
+
+#endif /* #if CHECKING_P */
+}
diff --git a/gcc/rust/util/rust-optional.h b/gcc/rust/util/rust-optional.h
new file mode 100644
index 000..56465400250
--- /dev/null
+++ b/gcc/rust/util/rust-optional.h
@@ -0,0 +1,278 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#ifndef RUST_OPTIONAL_H
+#define RUST_OPTIONAL_H
+
+#include "config.h"
+#include "rust-system.h"
+
+#include "selftest.h"
+
+namespace Rust {
+
+/**
+ * Tagged union to try and simulate a sum type. This is safer and more 
ergonomic
+ * than one of the two alternatives we're currently using in the compiler:
+ *
+ * 1. Storing a raw pointer, which can be `nullptr` or valid
+ *
+ * This is wildly unsafe, and usable in conjunction with local references, 
stack
+ * variables, or pointers managed elsewhere, which can cause crashes, hard to
+ * debug issues or undefined behavior. Likewise, if you do not check for the
+ * pointer's validity, this will cause a crash.
+ *
+ * 2. Storing an extra boolean alongside the object
+ *
+ * This causes implementors to use a "dummy object": Either an empty version or
+ * an error version. But what happens if what you really wanted to store was
+ * the empty or error version? You can also easily incorporate logic bugs if 
you
+ * forget to check for the associated boolean.
+ *
+ * The `Optional` type has 

[PATCH Rust front-end v4 18/46] gccrs: Add HIR definitions and visitor framework

2022-12-06 Thread arthur . cohen
From: Philip Herron 

This patch implements the classes mentioned in the previous HIR patch,
as well as a set of visitor frameworks used in handling that HIR.
---
 gcc/rust/hir/tree/rust-hir-full-decls.h |  232 +
 gcc/rust/hir/tree/rust-hir-full-test.cc | 5292 +++
 gcc/rust/hir/tree/rust-hir-full.h   |   30 +
 gcc/rust/hir/tree/rust-hir-visitor.h|  493 +++
 gcc/rust/hir/tree/rust-hir.h|  921 
 5 files changed, 6968 insertions(+)
 create mode 100644 gcc/rust/hir/tree/rust-hir-full-decls.h
 create mode 100644 gcc/rust/hir/tree/rust-hir-full-test.cc
 create mode 100644 gcc/rust/hir/tree/rust-hir-full.h
 create mode 100644 gcc/rust/hir/tree/rust-hir-visitor.h
 create mode 100644 gcc/rust/hir/tree/rust-hir.h

diff --git a/gcc/rust/hir/tree/rust-hir-full-decls.h 
b/gcc/rust/hir/tree/rust-hir-full-decls.h
new file mode 100644
index 000..2798ba9fd84
--- /dev/null
+++ b/gcc/rust/hir/tree/rust-hir-full-decls.h
@@ -0,0 +1,232 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#ifndef RUST_HIR_FULL_DECLS_H
+#define RUST_HIR_FULL_DECLS_H
+
+namespace Rust {
+namespace HIR {
+
+struct Literal;
+class Stmt;
+class Item;
+class Expr;
+class ExprWithoutBlock;
+class Pattern;
+class Type;
+class TypeNoBounds;
+class TypeParamBound;
+class Lifetime;
+class GenericParam;
+class LifetimeParam;
+
+class TraitItem;
+class ImplItem;
+struct Crate;
+class PathExpr;
+
+// rust-path.h
+class PathIdentSegment;
+struct GenericArgsBinding;
+struct GenericArgs;
+class PathExprSegment;
+class PathPattern;
+class PathInExpression;
+class TypePathSegment;
+class TypePathSegmentGeneric;
+struct TypePathFunction;
+class TypePathSegmentFunction;
+class TypePath;
+struct QualifiedPathType;
+class QualifiedPathInExpression;
+class QualifiedPathInType;
+
+// rust-expr.h
+class ExprWithBlock;
+class LiteralExpr;
+class AttrInputLiteral;
+class OperatorExpr;
+class BorrowExpr;
+class DereferenceExpr;
+class ErrorPropagationExpr;
+class NegationExpr;
+class ArithmeticOrLogicalExpr;
+class ComparisonExpr;
+class LazyBooleanExpr;
+class TypeCastExpr;
+class AssignmentExpr;
+class CompoundAssignmentExpr;
+class GroupedExpr;
+class ArrayElems;
+class ArrayElemsValues;
+class ArrayElemsCopied;
+class ArrayExpr;
+class ArrayIndexExpr;
+class TupleExpr;
+class TupleIndexExpr;
+class StructExpr;
+class StructExprStruct;
+struct StructBase;
+class StructExprField;
+class StructExprFieldIdentifier;
+class StructExprFieldWithVal;
+class StructExprFieldIdentifierValue;
+class StructExprFieldIndexValue;
+class StructExprStructFields;
+class StructExprStructBase;
+class CallExpr;
+class MethodCallExpr;
+class FieldAccessExpr;
+struct ClosureParam;
+class ClosureExpr;
+class ClosureExprInner;
+class BlockExpr;
+class ClosureExprInnerTyped;
+class ContinueExpr;
+class BreakExpr;
+class RangeExpr;
+class RangeFromToExpr;
+class RangeFromExpr;
+class RangeToExpr;
+class RangeFullExpr;
+class RangeFromToInclExpr;
+class RangeToInclExpr;
+class ReturnExpr;
+class UnsafeBlockExpr;
+class LoopLabel;
+class BaseLoopExpr;
+class LoopExpr;
+class WhileLoopExpr;
+class WhileLetLoopExpr;
+class ForLoopExpr;
+class IfExpr;
+class IfExprConseqElse;
+class IfExprConseqIf;
+class IfLetExpr;
+class IfExprConseqIfLet;
+class IfLetExprConseqElse;
+class IfLetExprConseqIf;
+class IfLetExprConseqIfLet;
+struct MatchArm;
+// class MatchCase;
+// class MatchCaseBlockExpr;
+// class MatchCaseExpr;
+struct MatchCase;
+class MatchExpr;
+class AwaitExpr;
+class AsyncBlockExpr;
+
+// rust-stmt.h
+class EmptyStmt;
+class LetStmt;
+class ExprStmt;
+class ExprStmtWithoutBlock;
+class ExprStmtWithBlock;
+
+// rust-item.h
+class TypeParam;
+class ConstGenericParam;
+class WhereClauseItem;
+class LifetimeWhereClauseItem;
+class TypeBoundWhereClauseItem;
+struct WhereClause;
+struct SelfParam;
+struct FunctionQualifiers;
+struct FunctionParam;
+struct Visibility;
+class VisItem;
+class Module;
+class ExternCrate;
+class UseTree;
+class UseTreeGlob;
+class UseTreeList;
+class UseTreeRebind;
+class UseDeclaration;
+class Function;
+class TypeAlias;
+class Struct;
+struct StructField;
+class StructStruct;
+struct TupleField;
+class TupleStruct;
+class EnumItem;
+class EnumItemTuple;
+class EnumItemStruct;
+class EnumItemDiscriminant;
+class Enum;
+class Union;
+class ConstantI

[PATCH Rust front-end v4 31/46] gccrs: Add const checker

2022-12-06 Thread arthur . cohen
From: Arthur Cohen 

Similarly to the unsafe checker, constant evaluation can only be performed
in a few contexts and include restrictions on the Rust language. Should
the user fail to uphold those conditions, errors will be reported and the
compilation pipeline interrupted.

These contexts are as follow:

- Array type length expressions
- Array repeat length expressions
- Constants
- Statics
- Enum discriminants
- Const generic arguments

In these contexts, the user is restricted to calling only functions marked
as `const` or perform arithmetic operations only on certain types, among
other restrictions.
---
 gcc/rust/checks/errors/rust-const-checker.cc | 844 +++
 gcc/rust/checks/errors/rust-const-checker.h  | 189 +
 2 files changed, 1033 insertions(+)
 create mode 100644 gcc/rust/checks/errors/rust-const-checker.cc
 create mode 100644 gcc/rust/checks/errors/rust-const-checker.h

diff --git a/gcc/rust/checks/errors/rust-const-checker.cc 
b/gcc/rust/checks/errors/rust-const-checker.cc
new file mode 100644
index 000..35c61fe03f0
--- /dev/null
+++ b/gcc/rust/checks/errors/rust-const-checker.cc
@@ -0,0 +1,844 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#include "rust-const-checker.h"
+#include "rust-hir.h"
+#include "rust-hir-expr.h"
+#include "rust-hir-stmt.h"
+#include "rust-hir-item.h"
+
+namespace Rust {
+namespace HIR {
+
+ConstChecker::ConstChecker ()
+  : resolver (*Resolver::Resolver::get ()),
+mappings (*Analysis::Mappings::get ())
+{}
+
+void
+ConstChecker::go (HIR::Crate &crate)
+{
+  for (auto &item : crate.items)
+item->accept_vis (*this);
+}
+
+bool
+ConstChecker::is_const_extern_fn (HIR::ExternalFunctionItem &fn)
+{
+  // FIXME: Is it really how we want to handle `rustc_const_stable`
+  // and `rustc_const_unstable`?
+  // TODO: Add these attributes to the attribute check and handle
+  // `stable` and `unstable` as well
+  return std::any_of (
+fn.get_outer_attrs ().begin (), fn.get_outer_attrs ().end (),
+[] (const AST::Attribute &attr) {
+  // `starts_with` in C++11...
+  return attr.get_path ().as_string ().rfind ("rustc_const_", 0) == 0;
+});
+}
+
+void
+ConstChecker::visit (Lifetime &lifetime)
+{}
+
+void
+ConstChecker::visit (LifetimeParam &lifetime_param)
+{}
+
+void
+ConstChecker::visit (PathInExpression &path)
+{}
+
+void
+ConstChecker::visit (TypePathSegment &segment)
+{}
+
+void
+ConstChecker::visit (TypePathSegmentGeneric &segment)
+{}
+
+void
+ConstChecker::visit (TypePathSegmentFunction &segment)
+{}
+
+void
+ConstChecker::visit (TypePath &path)
+{}
+
+void
+ConstChecker::visit (QualifiedPathInExpression &path)
+{}
+
+void
+ConstChecker::visit (QualifiedPathInType &path)
+{}
+
+void
+ConstChecker::visit (LiteralExpr &expr)
+{}
+
+void
+ConstChecker::visit (BorrowExpr &expr)
+{
+  expr.get_expr ()->accept_vis (*this);
+}
+
+void
+ConstChecker::visit (DereferenceExpr &expr)
+{
+  expr.get_expr ()->accept_vis (*this);
+}
+
+void
+ConstChecker::visit (ErrorPropagationExpr &expr)
+{
+  expr.get_expr ()->accept_vis (*this);
+}
+
+void
+ConstChecker::visit (NegationExpr &expr)
+{
+  expr.get_expr ()->accept_vis (*this);
+}
+
+void
+ConstChecker::visit (ArithmeticOrLogicalExpr &expr)
+{
+  expr.get_lhs ()->accept_vis (*this);
+  expr.get_rhs ()->accept_vis (*this);
+}
+
+void
+ConstChecker::visit (ComparisonExpr &expr)
+{
+  expr.get_lhs ()->accept_vis (*this);
+  expr.get_rhs ()->accept_vis (*this);
+}
+
+void
+ConstChecker::visit (LazyBooleanExpr &expr)
+{
+  expr.get_lhs ()->accept_vis (*this);
+  expr.get_rhs ()->accept_vis (*this);
+}
+
+void
+ConstChecker::visit (TypeCastExpr &expr)
+{
+  expr.get_expr ()->accept_vis (*this);
+}
+
+void
+ConstChecker::visit (AssignmentExpr &expr)
+{
+  expr.get_lhs ()->accept_vis (*this);
+  expr.get_rhs ()->accept_vis (*this);
+}
+
+void
+ConstChecker::visit (CompoundAssignmentExpr &expr)
+{
+  expr.get_left_expr ()->accept_vis (*this);
+  expr.get_right_expr ()->accept_vis (*this);
+}
+
+void
+ConstChecker::visit (GroupedExpr &expr)
+{
+  expr.get_expr_in_parens ()->accept_vis (*this);
+}
+
+void
+ConstChecker::visit (ArrayElemsValues &elems)
+{
+  for (auto &elem : elems.get_values ())
+elem->accept_vis (*this);
+}
+
+void
+ConstChecker::visit (ArrayElemsCopied &elems)
+{
+  elems.get_elem_to_copy ()->accept_

[PATCH Rust front-end v4 22/46] gccrs: Add Rust ABI enum helpers

2022-12-06 Thread arthur . cohen
From: Philip Herron 

This is a simple helper over an enum of possible ABI options in Rust.
---
 gcc/rust/util/rust-abi.cc | 72 +++
 gcc/rust/util/rust-abi.h  | 45 
 2 files changed, 117 insertions(+)
 create mode 100644 gcc/rust/util/rust-abi.cc
 create mode 100644 gcc/rust/util/rust-abi.h

diff --git a/gcc/rust/util/rust-abi.cc b/gcc/rust/util/rust-abi.cc
new file mode 100644
index 000..6477c3790af
--- /dev/null
+++ b/gcc/rust/util/rust-abi.cc
@@ -0,0 +1,72 @@
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#include "rust-abi.h"
+
+namespace Rust {
+
+Rust::ABI
+get_abi_from_string (const std::string &abi)
+{
+  if (abi.compare ("rust") == 0)
+return Rust::ABI::RUST;
+  else if (abi.compare ("rust-intrinsic") == 0)
+return Rust::ABI::INTRINSIC;
+  else if (abi.compare ("C") == 0)
+return Rust::ABI::C;
+  else if (abi.compare ("cdecl") == 0)
+return Rust::ABI::CDECL;
+  else if (abi.compare ("stdcall") == 0)
+return Rust::ABI::STDCALL;
+  else if (abi.compare ("fastcall") == 0)
+return Rust::ABI::FASTCALL;
+  else if (abi.compare ("sysv64") == 0)
+return Rust::ABI::SYSV64;
+  else if (abi.compare ("win64") == 0)
+return Rust::ABI::WIN64;
+
+  return Rust::ABI::UNKNOWN;
+}
+
+std::string
+get_string_from_abi (Rust::ABI abi)
+{
+  switch (abi)
+{
+case Rust::ABI::RUST:
+  return "rust";
+case Rust::ABI::INTRINSIC:
+  return "rust-intrinsic";
+case Rust::ABI::C:
+  return "C";
+case Rust::ABI::CDECL:
+  return "cdecl";
+case Rust::ABI::STDCALL:
+  return "stdcall";
+case Rust::ABI::FASTCALL:
+  return "fastcall";
+case Rust::ABI::SYSV64:
+  return "sysv64";
+case Rust::ABI::WIN64:
+  return "win64";
+
+case Rust::ABI::UNKNOWN:
+  return "unknown";
+}
+  return "unknown";
+}
+
+} // namespace Rust
diff --git a/gcc/rust/util/rust-abi.h b/gcc/rust/util/rust-abi.h
new file mode 100644
index 000..d794cc35fb3
--- /dev/null
+++ b/gcc/rust/util/rust-abi.h
@@ -0,0 +1,45 @@
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#ifndef RUST_ABI_OPTIONS_H
+#define RUST_ABI_OPTIONS_H
+
+#include "rust-system.h"
+
+namespace Rust {
+
+enum ABI
+{
+  UNKNOWN,
+  RUST,
+  INTRINSIC,
+  C,
+  CDECL,
+  STDCALL,
+  FASTCALL,
+  WIN64,
+  SYSV64
+};
+
+extern Rust::ABI
+get_abi_from_string (const std::string &abi);
+
+extern std::string
+get_string_from_abi (Rust::ABI abi);
+
+} // namespace Rust
+
+#endif // RUST_ABI_OPTIONS_H
-- 
2.38.1



[PATCH Rust front-end v4 25/46] gccrs: Add attributes checker

2022-12-06 Thread arthur . cohen
From: Arthur Cohen 

The attribute checker is responsible for checking the validity of various
attributes including built-in ones. It is currently unfinished and will
receive some modifications, as well as become the host of some existing
code in the compiler which needs to be refactored. One of its
responsibilities is to make sure that arguments given to built-in
attributes are correct, or contain the correct type of information. This
visitor also checks that an attribute is allowed to be used in the current
particular context.
---
 gcc/rust/util/rust-attributes.cc | 839 +++
 gcc/rust/util/rust-attributes.h  | 270 ++
 2 files changed, 1109 insertions(+)
 create mode 100644 gcc/rust/util/rust-attributes.cc
 create mode 100644 gcc/rust/util/rust-attributes.h

diff --git a/gcc/rust/util/rust-attributes.cc b/gcc/rust/util/rust-attributes.cc
new file mode 100644
index 000..b73e9534414
--- /dev/null
+++ b/gcc/rust/util/rust-attributes.cc
@@ -0,0 +1,839 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#include "rust-system.h"
+#include "rust-attributes.h"
+#include "rust-ast.h"
+#include "rust-ast-full.h"
+#include "rust-diagnostics.h"
+
+namespace Rust {
+namespace Analysis {
+
+// 
https://doc.rust-lang.org/stable/nightly-rustc/src/rustc_feature/builtin_attrs.rs.html#248
+static const BuiltinAttrDefinition __definitions[] = {
+  {"inline", CODE_GENERATION},
+  {"cold", CODE_GENERATION},
+  {"cfg", EXPANSION},
+  {"cfg_attr", EXPANSION},
+  {"deprecated", STATIC_ANALYSIS},
+  {"allow", STATIC_ANALYSIS},
+  {"doc", HIR_LOWERING},
+  {"must_use", STATIC_ANALYSIS},
+  {"lang", HIR_LOWERING},
+  {"link_section", CODE_GENERATION},
+  {"no_mangle", CODE_GENERATION},
+  {"repr", CODE_GENERATION},
+  {"path", EXPANSION},
+};
+
+BuiltinAttributeMappings *
+BuiltinAttributeMappings::get ()
+{
+  static BuiltinAttributeMappings *instance = nullptr;
+  if (instance == nullptr)
+instance = new BuiltinAttributeMappings ();
+
+  return instance;
+}
+
+const BuiltinAttrDefinition &
+BuiltinAttributeMappings::lookup_builtin (const std::string &attr_name) const
+{
+  auto it = mappings.find (attr_name);
+  if (it == mappings.end ())
+return BuiltinAttrDefinition::error_node ();
+
+  return it->second;
+}
+
+BuiltinAttributeMappings::BuiltinAttributeMappings ()
+{
+  size_t ndefinitions = sizeof (__definitions) / sizeof 
(BuiltinAttrDefinition);
+  for (size_t i = 0; i < ndefinitions; i++)
+{
+  const BuiltinAttrDefinition &def = __definitions[i];
+  mappings.insert ({def.name, def});
+}
+}
+
+AttributeChecker::AttributeChecker () {}
+
+void
+AttributeChecker::go (AST::Crate &crate)
+{
+  check_attributes (crate.get_inner_attrs ());
+
+  for (auto &item : crate.items)
+item->accept_vis (*this);
+}
+
+static bool
+is_builtin (const AST::Attribute &attribute, BuiltinAttrDefinition &builtin)
+{
+  auto &segments = attribute.get_path ().get_segments ();
+
+  // Builtin attributes always have a single segment. This avoids us creating
+  // strings all over the place and performing a linear search in the builtins
+  // map
+  if (segments.size () != 1)
+return false;
+
+  builtin = BuiltinAttributeMappings::get ()->lookup_builtin (
+segments.at (0).get_segment_name ());
+
+  return !builtin.is_error ();
+}
+
+/**
+ * Check that the string given to #[doc(alias = ...)] or #[doc(alias(...))] is
+ * valid.
+ *
+ * This means no whitespace characters other than spaces and no quoting
+ * characters.
+ */
+static void
+check_doc_alias (const std::string &alias_input, const Location &locus)
+{
+  // FIXME: The locus here is for the whole attribute. Can we get the locus
+  // of the alias input instead?
+  for (auto c : alias_input)
+if ((ISSPACE (c) && c != ' ') || c == '\'' || c == '\"')
+  {
+   auto to_print = std::string (1, c);
+   switch (c)
+ {
+ case '\n':
+   to_print = "\\n";
+   break;
+ case '\t':
+   to_print = "\\t";
+   break;
+ default:
+   break;
+ }
+   rust_error_at (locus,
+  "invalid character used in %<#[doc(alias)]%> input: %qs",
+  to_print.c_str ());
+  }
+
+  if (alias_input.empty ())
+return;
+
+  if (alias_input.front

[PATCH Rust front-end v4 21/46] gccrs: Add port of FNV hash used during legacy symbol mangling

2022-12-06 Thread arthur . cohen
From: Philip Herron 

This hash was ported from the Go runtime, as we needed a hash for the legacy
symbol mangling system. All symbols in Rust contain a hash of some
metadata for uniqueness on generic functions.
---
 gcc/rust/util/fnv-hash.h | 95 
 1 file changed, 95 insertions(+)
 create mode 100644 gcc/rust/util/fnv-hash.h

diff --git a/gcc/rust/util/fnv-hash.h b/gcc/rust/util/fnv-hash.h
new file mode 100644
index 000..78e54c99411
--- /dev/null
+++ b/gcc/rust/util/fnv-hash.h
@@ -0,0 +1,95 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#ifndef RUST_FNV_HASH_H
+#define RUST_FNV_HASH_H
+
+namespace Rust {
+namespace Hash {
+
+const uint64_t offset128Lower = 0x62b821756295c58d;
+const uint64_t offset128Higher = 0x6c62272e07bb0142;
+const uint64_t prime128Lower = 0x13b;
+const uint64_t prime128Shift = 24;
+
+// ported from https://github.com/golang/go/blob/master/src/hash/fnv/fnv.go
+class FNV128
+{
+public:
+  FNV128 () { reset (); }
+
+  void reset ()
+  {
+buf[0] = offset128Higher;
+buf[1] = offset128Lower;
+  }
+
+  void write (const unsigned char *in, size_t len)
+  {
+for (size_t i = 0; i < len; i++)
+  {
+   unsigned char c = in[i];
+
+   // 
https://stackoverflow.com/questions/28868367/getting-the-high-part-of-64-bit-integer-multiplication
+   uint64_t a = prime128Lower;
+   uint64_t b = buf[1];
+
+   uint64_t a_lo = (uint32_t) a;
+   uint64_t a_hi = a >> 32;
+   uint64_t b_lo = (uint32_t) b;
+   uint64_t b_hi = b >> 32;
+
+   uint64_t a_x_b_hi = a_hi * b_hi;
+   uint64_t a_x_b_mid = a_hi * b_lo;
+   uint64_t b_x_a_mid = b_hi * a_lo;
+   uint64_t a_x_b_lo = a_lo * b_lo;
+
+   uint64_t carry_bit
+ = ((uint64_t) (uint32_t) a_x_b_mid + (uint64_t) (uint32_t) b_x_a_mid
++ (a_x_b_lo >> 32))
+   >> 32;
+
+   uint64_t multhi
+ = a_x_b_hi + (a_x_b_mid >> 32) + (b_x_a_mid >> 32) + carry_bit;
+
+   uint64_t s0 = multhi; // high
+   uint64_t s1 = prime128Lower * buf[1]; // low
+
+   s0 += buf[1] << (prime128Shift + prime128Lower * buf[0]);
+
+   // Update the values
+   buf[1] = s1;
+   buf[0] = s0;
+   buf[1] ^= (uint64_t) c;
+  }
+  }
+
+  void sum (uint64_t *hi, uint64_t *lo) const
+  {
+*hi = buf[0];
+*lo = buf[1];
+  }
+
+private:
+  uint64_t buf[2];
+};
+
+} // namespace Hash
+} // namespace Rust
+
+#endif // RUST_FNV_HASH_H
-- 
2.38.1



[PATCH Rust front-end v4 30/46] gccrs: Add unsafe checks for Rust

2022-12-06 Thread arthur . cohen
From: Arthur Cohen 

The UnsafeChecker visitor verifies that unsafe actions are only performed
in unsafe contexts. Otherwise, an error should be reported to the user and
the compilation pipeline should be halted. These contexts, which include
unsafe blocks or unsafe functions, are allowed to perform more actions
than regular safe Rust code. These actions currently include:

- Dereferencing raw pointers
- Calls to unsafe functions
- Use of inline assembly
- Use of mutable static
- Use of extern static
- Access to a union's field
- Call to functions with #[target(feature)] attribute
- Initializing type with rustc_layout_scalar_valid_range attribute
- Mutation of layout constrained field
- Borrow of layout constrained field
---
 gcc/rust/checks/errors/rust-unsafe-checker.cc | 963 ++
 gcc/rust/checks/errors/rust-unsafe-checker.h  | 191 
 2 files changed, 1154 insertions(+)
 create mode 100644 gcc/rust/checks/errors/rust-unsafe-checker.cc
 create mode 100644 gcc/rust/checks/errors/rust-unsafe-checker.h

diff --git a/gcc/rust/checks/errors/rust-unsafe-checker.cc 
b/gcc/rust/checks/errors/rust-unsafe-checker.cc
new file mode 100644
index 000..e3f32539562
--- /dev/null
+++ b/gcc/rust/checks/errors/rust-unsafe-checker.cc
@@ -0,0 +1,963 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#include "rust-unsafe-checker.h"
+#include "rust-hir.h"
+#include "rust-hir-expr.h"
+#include "rust-hir-stmt.h"
+#include "rust-hir-item.h"
+
+namespace Rust {
+namespace HIR {
+
+UnsafeChecker::UnsafeChecker ()
+  : context (*Resolver::TypeCheckContext::get ()),
+resolver (*Resolver::Resolver::get ()),
+mappings (*Analysis::Mappings::get ())
+{}
+
+void
+UnsafeChecker::go (HIR::Crate &crate)
+{
+  for (auto &item : crate.items)
+item->accept_vis (*this);
+}
+
+static void
+check_static_mut (HIR::Item *maybe_static, Location locus)
+{
+  if (maybe_static->get_hir_kind () == Node::BaseKind::VIS_ITEM)
+{
+  auto item = static_cast (maybe_static);
+  if (item->get_item_kind () == Item::ItemKind::Static)
+   {
+ auto static_item = static_cast (item);
+ if (static_item->is_mut ())
+   rust_error_at (
+ locus, "use of mutable static requires unsafe function or block");
+   }
+}
+}
+
+static void
+check_extern_static (HIR::ExternalItem *maybe_static, Location locus)
+{
+  if (maybe_static->get_extern_kind () == ExternalItem::ExternKind::Static)
+rust_error_at (locus,
+  "use of extern static requires unsafe function or block");
+}
+
+void
+UnsafeChecker::check_use_of_static (HirId node_id, Location locus)
+{
+  if (unsafe_context.is_in_context ())
+return;
+
+  auto maybe_static_mut = mappings.lookup_hir_item (node_id);
+
+  HirId extern_block;
+  auto maybe_extern_static
+= mappings.lookup_hir_extern_item (node_id, &extern_block);
+
+  if (maybe_static_mut)
+check_static_mut (maybe_static_mut, locus);
+
+  if (maybe_extern_static)
+check_extern_static (static_cast (maybe_extern_static),
+locus);
+}
+
+static void
+check_unsafe_call (HIR::Function *fn, Location locus, const std::string &kind)
+{
+  if (fn->get_qualifiers ().is_unsafe ())
+rust_error_at (locus, "call to unsafe %s requires unsafe function or 
block",
+  kind.c_str ());
+}
+
+static bool
+is_safe_intrinsic (const std::string &fn_name)
+{
+  static const std::unordered_set safe_intrinsics = {
+"abort",
+"size_of",
+"min_align_of",
+"needs_drop",
+"caller_location",
+"add_with_overflow",
+"sub_with_overflow",
+"mul_with_overflow",
+"wrapping_add",
+"wrapping_sub",
+"wrapping_mul",
+"saturating_add",
+"saturating_sub",
+"rotate_left",
+"rotate_right",
+"ctpop",
+"ctlz",
+"cttz",
+"bswap",
+"bitreverse",
+"discriminant_value",
+"type_id",
+"likely",
+"unlikely",
+"ptr_guaranteed_eq",
+"ptr_guaranteed_ne",
+"minnumf32",
+"minnumf64",
+"maxnumf32",
+"rustc_peek",
+"maxnumf64",
+"type_name",
+"forget",
+"black_box",
+"variant_count",
+  };
+
+  return safe_intrinsics.find (fn_name) != safe_intrinsics.end ();
+}
+
+static void
+check_extern_call (HIR::ExternalItem *maybe_fn, HIR::ExternBlock *paren

[PATCH Rust front-end v4 35/46] gccrs: Add metadata output pass

2022-12-06 Thread arthur . cohen
From: Philip Herron 

Extern crates statements to tell the front-end to look for another library.
The mechanism here is heavily inspired from gccgo, so when we compile a
library for example we invoke:

  gccrs -g -O2 -frust-crate=mylib -c src/lib.rs -o src/mylib.o

All going well this object file will now contain extra data inside
.rust-export section inside the object file which will be preserved inside
archives and shared objects. When we have another application which uses
this library 'mylib'.

  extern crate mylib;
  use mylib::foo;

  fn main() {
foo();
  }

We compile using:

  gcc -g -O2 -frust-crate=test -c src/main.rs -o src/main.o

When the extern crate line is hit the front-end will look for mylib.o,
libmylib.a, mylib.rox. If it finds a raw object file it will read the
.rust-export section directly from the object for the public metadata
such as public functions, types constants etc. If it fails to find an
object it might find .rox which is the objdump of the .rust-export to a
raw file, it might even find libmylib.a and read the export directly out
of the archive file reusing code from gccgo to do so.

The full compiler pipeline is reused here, so the metatadata is actually
just real rust code. The benifit here is that Rust supports exporting,
macros and generics so this requires the name-resolution and type info
all to be generated and inserted into the apropriate context classes. Since
the metadata is real rust code it means we can reuse the full pipeline to
generate the code as necessary. So for the simple case of a public struct
we simply emit the AST dump of this struct directly into the metadata. If
its a non-generic public function we emit and extern rust abi block for
that function. If its a trait we can simply emit the trait with the public
memebers. Generics are more complicated since we need to emit the function
fully for it to be compiled correctly this still needs tests to be added.
The hardest part is non generic impl blocks which is still a WIP.

To finally link the two crates together you run:

  gcc -g -O2 -o rust-program.exe src/main.o src/mylib.o
---
 gcc/rust/metadata/rust-export-metadata.cc | 385 ++
 gcc/rust/metadata/rust-export-metadata.h  |  85 +++
 gcc/rust/metadata/rust-extern-crate.cc| 173 +
 gcc/rust/metadata/rust-extern-crate.h |  55 ++
 gcc/rust/metadata/rust-import-archive.cc  | 885 ++
 gcc/rust/metadata/rust-imports.cc | 441 +++
 gcc/rust/metadata/rust-imports.h  | 257 +++
 gcc/rust/rust-object-export.cc| 176 +
 gcc/rust/rust-object-export.h |  33 +
 9 files changed, 2490 insertions(+)
 create mode 100644 gcc/rust/metadata/rust-export-metadata.cc
 create mode 100644 gcc/rust/metadata/rust-export-metadata.h
 create mode 100644 gcc/rust/metadata/rust-extern-crate.cc
 create mode 100644 gcc/rust/metadata/rust-extern-crate.h
 create mode 100644 gcc/rust/metadata/rust-import-archive.cc
 create mode 100644 gcc/rust/metadata/rust-imports.cc
 create mode 100644 gcc/rust/metadata/rust-imports.h
 create mode 100644 gcc/rust/rust-object-export.cc
 create mode 100644 gcc/rust/rust-object-export.h

diff --git a/gcc/rust/metadata/rust-export-metadata.cc 
b/gcc/rust/metadata/rust-export-metadata.cc
new file mode 100644
index 000..4856bc26149
--- /dev/null
+++ b/gcc/rust/metadata/rust-export-metadata.cc
@@ -0,0 +1,385 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#include "rust-export-metadata.h"
+#include "rust-hir-visitor.h"
+#include "rust-hir-full.h"
+#include "rust-hir-map.h"
+#include "rust-ast-dump.h"
+#include "rust-abi.h"
+#include "rust-object-export.h"
+
+#include "md5.h"
+
+namespace Rust {
+namespace Metadata {
+
+static const std::string extension_path = ".rox";
+
+ExportContext::ExportContext () : mappings (Analysis::Mappings::get ()) {}
+
+ExportContext::~ExportContext () {}
+
+void
+ExportContext::push_module_scope (const HIR::Module &module)
+{
+  module_stack.push_back (module);
+}
+
+const HIR::Module &
+ExportContext::pop_module_scope ()
+{
+  rust_assert (!module_stack.empty ());
+  const HIR::Module &poped = module_stack.back ();
+  module_stack.pop_back ();
+  return poped;
+}
+
+void
+ExportContext::emit_trait (const HIR::Trait &trait)
+{
+  // lookup the AST node for th

[PATCH Rust front-end v4 32/46] gccrs: Add privacy checks

2022-12-06 Thread arthur . cohen
From: Arthur Cohen 

This pass is responsible for resolving the privacy of items and verifying
that access to these items is performed within the limits of that privacy.
By default, items in Rust are private and only public to the current
module and its submodules. However, the user can annotate an item with
various qualifiers such as `pub` to publicly expose an item. Furthermore,
a module path can be given to `pub` to restrict an item's privacy to a
certain module: These paths need to be resolved and later on checked by
the privacy error reporter.
---
 .../errors/privacy/rust-privacy-check.cc  |  63 ++
 .../errors/privacy/rust-privacy-check.h   |  44 +
 .../errors/privacy/rust-privacy-common.h  |  67 ++
 .../checks/errors/privacy/rust-privacy-ctx.cc |  93 +++
 .../checks/errors/privacy/rust-privacy-ctx.h  |  79 ++
 .../errors/privacy/rust-privacy-reporter.cc   | 771 ++
 .../errors/privacy/rust-privacy-reporter.h| 173 
 .../privacy/rust-pub-restricted-visitor.cc| 182 +
 .../privacy/rust-pub-restricted-visitor.h | 120 +++
 .../errors/privacy/rust-reachability.cc   | 236 ++
 .../checks/errors/privacy/rust-reachability.h |  87 ++
 .../privacy/rust-visibility-resolver.cc   | 245 ++
 .../errors/privacy/rust-visibility-resolver.h | 103 +++
 13 files changed, 2263 insertions(+)
 create mode 100644 gcc/rust/checks/errors/privacy/rust-privacy-check.cc
 create mode 100644 gcc/rust/checks/errors/privacy/rust-privacy-check.h
 create mode 100644 gcc/rust/checks/errors/privacy/rust-privacy-common.h
 create mode 100644 gcc/rust/checks/errors/privacy/rust-privacy-ctx.cc
 create mode 100644 gcc/rust/checks/errors/privacy/rust-privacy-ctx.h
 create mode 100644 gcc/rust/checks/errors/privacy/rust-privacy-reporter.cc
 create mode 100644 gcc/rust/checks/errors/privacy/rust-privacy-reporter.h
 create mode 100644 
gcc/rust/checks/errors/privacy/rust-pub-restricted-visitor.cc
 create mode 100644 gcc/rust/checks/errors/privacy/rust-pub-restricted-visitor.h
 create mode 100644 gcc/rust/checks/errors/privacy/rust-reachability.cc
 create mode 100644 gcc/rust/checks/errors/privacy/rust-reachability.h
 create mode 100644 gcc/rust/checks/errors/privacy/rust-visibility-resolver.cc
 create mode 100644 gcc/rust/checks/errors/privacy/rust-visibility-resolver.h

diff --git a/gcc/rust/checks/errors/privacy/rust-privacy-check.cc 
b/gcc/rust/checks/errors/privacy/rust-privacy-check.cc
new file mode 100644
index 000..9664d62f65c
--- /dev/null
+++ b/gcc/rust/checks/errors/privacy/rust-privacy-check.cc
@@ -0,0 +1,63 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#include "rust-privacy-check.h"
+#include "rust-reachability.h"
+#include "rust-hir-type-check.h"
+#include "rust-hir-map.h"
+#include "rust-name-resolver.h"
+#include "rust-visibility-resolver.h"
+#include "rust-pub-restricted-visitor.h"
+#include "rust-privacy-reporter.h"
+
+extern bool
+saw_errors (void);
+
+namespace Rust {
+namespace Privacy {
+
+void
+Resolver::resolve (HIR::Crate &crate)
+{
+  PrivacyContext ctx;
+  auto mappings = Analysis::Mappings::get ();
+  auto resolver = Rust::Resolver::Resolver::get ();
+  auto ty_ctx = ::Rust::Resolver::TypeCheckContext::get ();
+
+  VisibilityResolver (*mappings, *resolver).go (crate);
+  PubRestrictedVisitor (*mappings).go (crate);
+  PrivacyReporter (*mappings, *resolver, *ty_ctx).go (crate);
+
+  auto visitor = ReachabilityVisitor (ctx, *ty_ctx);
+
+  const auto &items = crate.items;
+
+  for (auto &item : items)
+{
+  if (item->get_hir_kind () == HIR::Node::VIS_ITEM)
+   {
+ auto vis_item = static_cast (item.get ());
+ vis_item->accept_vis (visitor);
+   }
+}
+
+  if (saw_errors ())
+return;
+}
+} // namespace Privacy
+} // namespace Rust
diff --git a/gcc/rust/checks/errors/privacy/rust-privacy-check.h 
b/gcc/rust/checks/errors/privacy/rust-privacy-check.h
new file mode 100644
index 000..290b5eacb6c
--- /dev/null
+++ b/gcc/rust/checks/errors/privacy/rust-privacy-check.h
@@ -0,0 +1,44 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundat

[PATCH Rust front-end v4 33/46] gccrs: Add dead code scan on HIR

2022-12-06 Thread arthur . cohen
From: Thomas Young 

In order to find dead code we use a depth first search and keep liveness
variables, after type resolution. In this case, if a function is unused
and it calls another function the 2nd function is now unused since the
caller is not used etc. The algorithm is a depth first search.
---
 .../checks/lints/rust-lint-marklive-base.h|  45 +++
 gcc/rust/checks/lints/rust-lint-marklive.cc   | 282 
 gcc/rust/checks/lints/rust-lint-marklive.h| 308 ++
 .../checks/lints/rust-lint-scan-deadcode.h| 154 +
 4 files changed, 789 insertions(+)
 create mode 100644 gcc/rust/checks/lints/rust-lint-marklive-base.h
 create mode 100644 gcc/rust/checks/lints/rust-lint-marklive.cc
 create mode 100644 gcc/rust/checks/lints/rust-lint-marklive.h
 create mode 100644 gcc/rust/checks/lints/rust-lint-scan-deadcode.h

diff --git a/gcc/rust/checks/lints/rust-lint-marklive-base.h 
b/gcc/rust/checks/lints/rust-lint-marklive-base.h
new file mode 100644
index 000..97c068188b1
--- /dev/null
+++ b/gcc/rust/checks/lints/rust-lint-marklive-base.h
@@ -0,0 +1,45 @@
+// Copyright (C) 2021-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#ifndef RUST_HIR_LIVENESS_BASE
+#define RUST_HIR_LIVENESS_BASE
+
+#include "rust-diagnostics.h"
+#include "rust-lint-marklive.h"
+#include "rust-lint-marklive-base.h"
+#include "rust-hir-visitor.h"
+#include "rust-hir-map.h"
+
+namespace Rust {
+namespace Analysis {
+
+class MarkLiveBase : public HIR::HIRFullVisitorBase
+{
+public:
+  virtual ~MarkLiveBase () {}
+
+protected:
+  MarkLiveBase () : mappings (Analysis::Mappings::get ()) {}
+
+  Analysis::Mappings *mappings;
+};
+
+} // namespace Analysis
+} // namespace Rust
+
+#endif
diff --git a/gcc/rust/checks/lints/rust-lint-marklive.cc 
b/gcc/rust/checks/lints/rust-lint-marklive.cc
new file mode 100644
index 000..245632b4b4c
--- /dev/null
+++ b/gcc/rust/checks/lints/rust-lint-marklive.cc
@@ -0,0 +1,282 @@
+// Copyright (C) 2021-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+// The idea is that all reachable symbols are live, codes called
+// from live codes are live, and everything else is dead.
+
+#include "rust-lint-marklive.h"
+#include "rust-hir-full.h"
+#include "rust-name-resolver.h"
+
+namespace Rust {
+namespace Analysis {
+
+// This class trys to find the live symbols which can be used as
+// seeds in MarkLive
+//
+// 1. TODO: explicit live
+//- Attribute like #[allow(dead_code)]
+//- Attribute like #[lang=".."], it's not a intra-crate item.
+// 2. TODO: foreign item
+class FindEntryPoint : public MarkLiveBase
+{
+  using Rust::Analysis::MarkLiveBase::visit;
+
+public:
+  static std::vector find (HIR::Crate &crate)
+  {
+FindEntryPoint findEntryPoint;
+for (auto it = crate.items.begin (); it != crate.items.end (); it++)
+  {
+   it->get ()->accept_vis (findEntryPoint);
+  }
+return findEntryPoint.getEntryPoint ();
+  }
+
+  // TODO not only fn main can be a entry point.
+  void visit (HIR::Function &function) override
+  {
+if (function.get_function_name () == "main")
+  {
+   entryPoints.push_back (function.get_mappings ().get_hirid ());
+  }
+  }
+
+private:
+  FindEntryPoint () : MarkLiveBase () {}
+  std::vector entryPoints;
+  std::vector getEntryPoint () { return entryPoints; }
+};
+
+std::set
+MarkLive::Analysis (HIR::Crate &crate)
+{
+  MarkLive marklive (FindEntryPoint::find (crate));
+  marklive.go (crate);
+
+  return marklive.liveSymbols;
+}
+
+// pop a live symbol from worklist every iteration,
+// if it's a function then walk the function body, and
+// 1. save all the live symbols in worklist which is
+//visi

[PATCH Rust front-end v4 34/46] gccrs: Add unused variable scan

2022-12-06 Thread arthur . cohen
From: Philip Herron 

This is a simple walk_tree which acts on the monomorphized code by walking
the compiled translation unit of functions.
---
 gcc/rust/checks/lints/rust-lint-unused-var.cc | 98 +++
 gcc/rust/checks/lints/rust-lint-unused-var.h  | 36 +++
 2 files changed, 134 insertions(+)
 create mode 100644 gcc/rust/checks/lints/rust-lint-unused-var.cc
 create mode 100644 gcc/rust/checks/lints/rust-lint-unused-var.h

diff --git a/gcc/rust/checks/lints/rust-lint-unused-var.cc 
b/gcc/rust/checks/lints/rust-lint-unused-var.cc
new file mode 100644
index 000..d4317e53280
--- /dev/null
+++ b/gcc/rust/checks/lints/rust-lint-unused-var.cc
@@ -0,0 +1,98 @@
+// Copyright (C) 2021-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#include "rust-lint-unused-var.h"
+#include "print-tree.h"
+
+namespace Rust {
+namespace Analysis {
+
+static void
+check_decl (tree *t)
+{
+  rust_assert (TREE_CODE (*t) == VAR_DECL || TREE_CODE (*t) == PARM_DECL
+  || TREE_CODE (*t) == CONST_DECL);
+
+  tree var_name = DECL_NAME (*t);
+  const char *var_name_ptr = IDENTIFIER_POINTER (var_name);
+  bool starts_with_under_score = strncmp (var_name_ptr, "_", 1) == 0;
+
+  bool is_constant = TREE_CODE (*t) == CONST_DECL;
+  // if (!is_constant)
+  //   {
+  // debug_tree (*t);
+  // rust_debug ("found var-decl: used %s artifical %s underscore %s name
+  // %s",
+  // TREE_USED (*t) ? "true" : "false",
+  // DECL_ARTIFICIAL (*t) ? "true" : "false",
+  // starts_with_under_score ? "true" : "false", var_name_ptr);
+  //   }
+
+  if (!TREE_USED (*t) && !DECL_ARTIFICIAL (*t) && !starts_with_under_score)
+{
+  warning_at (DECL_SOURCE_LOCATION (*t),
+ is_constant ? OPT_Wunused_const_variable_
+ : OPT_Wunused_variable,
+ "unused name %qE", *t);
+}
+}
+
+static tree
+unused_var_walk_fn (tree *t, int *walk_subtrees, void *closure)
+{
+  switch (TREE_CODE (*t))
+{
+case VAR_DECL:
+case CONST_DECL:
+  check_decl (t);
+  break;
+
+default:
+  break;
+}
+  return NULL_TREE;
+}
+
+void
+UnusedVariables::Lint (Compile::Context &ctx)
+{
+  for (auto &fndecl : ctx.get_func_decls ())
+{
+  for (tree p = DECL_ARGUMENTS (fndecl); p != NULL_TREE; p = DECL_CHAIN 
(p))
+   {
+ check_decl (&p);
+   }
+
+  walk_tree_without_duplicates (&DECL_SAVED_TREE (fndecl),
+   &unused_var_walk_fn, &ctx);
+}
+
+  for (auto &var : ctx.get_var_decls ())
+{
+  tree t = ctx.get_backend ()->var_expression (var, Location ());
+  check_decl (&t);
+}
+
+  for (auto &const_decl : ctx.get_const_decls ())
+{
+  check_decl (&const_decl);
+}
+}
+
+} // namespace Analysis
+} // namespace Rust
diff --git a/gcc/rust/checks/lints/rust-lint-unused-var.h 
b/gcc/rust/checks/lints/rust-lint-unused-var.h
new file mode 100644
index 000..6fabfeff01b
--- /dev/null
+++ b/gcc/rust/checks/lints/rust-lint-unused-var.h
@@ -0,0 +1,36 @@
+// Copyright (C) 2021-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#ifndef RUST_LINT_UNUSED_VAR
+#define RUST_LINT_UNUSED_VAR
+
+#include "rust-compile-context.h"
+
+namespace Rust {
+namespace Analysis {
+
+class UnusedVariables
+{
+public:
+  static void Lint (Compile::Context &ctx);
+};
+
+} // namespace Analysis
+} // namespace Rust
+
+#endif // RUST_LINT_UNUSED_VAR
-- 
2.38.1



[PATCH Rust front-end v4 39/46] gccrs: These are wrappers ported from reusing gccgo

2022-12-06 Thread arthur . cohen
From: Philip Herron 

The wrappers over linemap and location will eventually disappear here but
served as a useful starting point for us. We have wrappers over the
diagnostics system which we might be able to get rid of as well.
---
 gcc/rust/rust-diagnostics.cc | 244 +++
 gcc/rust/rust-diagnostics.h  | 154 +++
 gcc/rust/rust-gcc-diagnostics.cc |  84 +++
 gcc/rust/rust-linemap.cc | 229 +
 gcc/rust/rust-linemap.h  | 163 +
 gcc/rust/rust-location.h | 105 +
 gcc/rust/rust-system.h   |  86 +++
 7 files changed, 1065 insertions(+)
 create mode 100644 gcc/rust/rust-diagnostics.cc
 create mode 100644 gcc/rust/rust-diagnostics.h
 create mode 100644 gcc/rust/rust-gcc-diagnostics.cc
 create mode 100644 gcc/rust/rust-linemap.cc
 create mode 100644 gcc/rust/rust-linemap.h
 create mode 100644 gcc/rust/rust-location.h
 create mode 100644 gcc/rust/rust-system.h

diff --git a/gcc/rust/rust-diagnostics.cc b/gcc/rust/rust-diagnostics.cc
new file mode 100644
index 000..c2d3e4ee8be
--- /dev/null
+++ b/gcc/rust/rust-diagnostics.cc
@@ -0,0 +1,244 @@
+// rust-diagnostics.cc -- GCC implementation of rust diagnostics interface.
+// Copyright (C) 2016-2022 Free Software Foundation, Inc.
+// Contributed by Than McIntosh, Google.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#include "rust-system.h"
+#include "rust-diagnostics.h"
+
+static std::string
+mformat_value ()
+{
+  return std::string (xstrerror (errno));
+}
+
+// Rewrite a format string to expand any extensions not
+// supported by sprintf(). See comments in rust-diagnostics.h
+// for list of supported format specifiers.
+
+static std::string
+expand_format (const char *fmt)
+{
+  std::stringstream ss;
+  for (const char *c = fmt; *c; ++c)
+{
+  if (*c != '%')
+   {
+ ss << *c;
+ continue;
+   }
+  c++;
+  switch (*c)
+   {
+ case '\0': {
+   // malformed format string
+   rust_unreachable ();
+ }
+ case '%': {
+   ss << "%";
+   break;
+ }
+ case 'm': {
+   ss << mformat_value ();
+   break;
+ }
+ case '<': {
+   ss << rust_open_quote ();
+   break;
+ }
+ case '>': {
+   ss << rust_close_quote ();
+   break;
+ }
+ case 'q': {
+   ss << rust_open_quote ();
+   c++;
+   if (*c == 'm')
+ {
+   ss << mformat_value ();
+ }
+   else
+ {
+   ss << "%" << *c;
+ }
+   ss << rust_close_quote ();
+   break;
+ }
+ default: {
+   ss << "%" << *c;
+ }
+   }
+}
+  return ss.str ();
+}
+
+// Expand message format specifiers, using a combination of
+// expand_format above to handle extensions (ex: %m, %q) and vasprintf()
+// to handle regular printf-style formatting. A pragma is being used here to
+// suppress this warning:
+//
+//   warning: function ‘std::__cxx11::string expand_message(const char*,
+//   __va_list_tag*)’ might be a candidate for ‘gnu_printf’ format attribute
+//   [-Wsuggest-attribute=format]
+//
+// What appears to be happening here is that the checker is deciding that
+// because of the call to vasprintf() (which has attribute gnu_printf), the
+// calling function must need to have attribute gnu_printf as well, even
+// though there is already an attribute declaration for it.
+
+static std::string
+expand_message (const char *fmt, va_list ap) RUST_ATTRIBUTE_GCC_DIAG (1, 0);
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
+
+static std::string
+expand_message (const char *fmt, va_list ap)
+{
+  char *mbuf = 0;
+  std::string expanded_fmt = expand_format (fmt);
+  int nwr = vasprintf (&mbuf, expanded_fmt.c_str (), ap);
+  if (nwr == -1)
+{
+  // memory allocation failed
+  rust_be_error_at (Linemap::unknown_location (),
+   "memory allocation failed in vasprintf");
+  rust_assert (0);
+}
+  std::string rval = std::string (mbuf);
+  free (mbuf);
+  return rval;
+}
+
+#pragma GCC diagnostic pop
+
+static const char *cached_open_quote = NULL;
+s

[PATCH Rust front-end v4 41/46] gccrs: Add config-lang.in

2022-12-06 Thread arthur . cohen
From: Philip Herron 

This was a copy/paste from gccgo front-end. We do not use any of the
target_libs yet, but we will need these when we support the libpanic crate.
---
 gcc/rust/config-lang.in | 34 ++
 1 file changed, 34 insertions(+)
 create mode 100644 gcc/rust/config-lang.in

diff --git a/gcc/rust/config-lang.in b/gcc/rust/config-lang.in
new file mode 100644
index 000..d2ff376032a
--- /dev/null
+++ b/gcc/rust/config-lang.in
@@ -0,0 +1,34 @@
+# config-lang.in -- Top level configure fragment for gcc Rust frontend.
+
+# Copyright (C) 2009-2022 Free Software Foundation, Inc.
+
+# This file is part of GCC.
+
+# GCC is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3, or (at your option)
+# any later version.
+
+# GCC is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+
+# You should have received a copy of the GNU General Public License
+# along with GCC; see the file COPYING3.  If not see
+# .
+
+# Configure looks for the existence of this file to auto-config each language.
+# We define several parameters used by configure:
+#
+# language - name of language as it would appear in $(LANGUAGES)
+# compilers- value to add to $(COMPILERS)
+
+language="rust"
+compilers="rust1\$(exeext)"
+
+build_by_default="no"
+
+target_libs="target-libffi target-libbacktrace"
+
+gtfiles="\$(srcdir)/rust/rust-lang.cc"
-- 
2.38.1



[PATCH Rust front-end v4 28/46] gccrs: Add Rust type information

2022-12-06 Thread arthur . cohen
From: Philip Herron 

Contains abstractions over Rust's types, used when performing the
HIR's type-resolution.
---
 gcc/rust/typecheck/rust-tyty.cc | 2885 +++
 gcc/rust/typecheck/rust-tyty.h  | 2533 +++
 2 files changed, 5418 insertions(+)
 create mode 100644 gcc/rust/typecheck/rust-tyty.cc
 create mode 100644 gcc/rust/typecheck/rust-tyty.h

diff --git a/gcc/rust/typecheck/rust-tyty.cc b/gcc/rust/typecheck/rust-tyty.cc
new file mode 100644
index 000..3c2c6786940
--- /dev/null
+++ b/gcc/rust/typecheck/rust-tyty.cc
@@ -0,0 +1,2885 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#include "rust-tyty.h"
+#include "rust-tyty-visitor.h"
+#include "rust-tyty-call.h"
+#include "rust-hir-type-check-expr.h"
+#include "rust-hir-type-check-type.h"
+#include "rust-tyty-rules.h"
+#include "rust-tyty-cmp.h"
+#include "rust-hir-map.h"
+#include "rust-substitution-mapper.h"
+#include "rust-hir-trait-ref.h"
+#include "rust-hir-type-bounds.h"
+
+namespace Rust {
+namespace TyTy {
+
+std::string
+TypeKindFormat::to_string (TypeKind kind)
+{
+  switch (kind)
+{
+case TypeKind::INFER:
+  return "Infer";
+
+case TypeKind::ADT:
+  return "ADT";
+
+case TypeKind::STR:
+  return "STR";
+
+case TypeKind::REF:
+  return "REF";
+
+case TypeKind::POINTER:
+  return "POINTER";
+
+case TypeKind::PARAM:
+  return "PARAM";
+
+case TypeKind::ARRAY:
+  return "ARRAY";
+
+case TypeKind::SLICE:
+  return "SLICE";
+
+case TypeKind::FNDEF:
+  return "FnDef";
+
+case TypeKind::FNPTR:
+  return "FnPtr";
+
+case TypeKind::TUPLE:
+  return "Tuple";
+
+case TypeKind::BOOL:
+  return "Bool";
+
+case TypeKind::CHAR:
+  return "Char";
+
+case TypeKind::INT:
+  return "Int";
+
+case TypeKind::UINT:
+  return "Uint";
+
+case TypeKind::FLOAT:
+  return "Float";
+
+case TypeKind::USIZE:
+  return "Usize";
+
+case TypeKind::ISIZE:
+  return "Isize";
+
+case TypeKind::NEVER:
+  return "Never";
+
+case TypeKind::PLACEHOLDER:
+  return "Placeholder";
+
+case TypeKind::PROJECTION:
+  return "Projection";
+
+case TypeKind::DYNAMIC:
+  return "Dynamic";
+
+case TypeKind::CLOSURE:
+  return "Closure";
+
+case TypeKind::ERROR:
+  return "ERROR";
+}
+  gcc_unreachable ();
+}
+
+bool
+is_primitive_type_kind (TypeKind kind)
+{
+  switch (kind)
+{
+case TypeKind::BOOL:
+case TypeKind::CHAR:
+case TypeKind::INT:
+case TypeKind::UINT:
+case TypeKind::ISIZE:
+case TypeKind::USIZE:
+case TypeKind::FLOAT:
+case TypeKind::NEVER:
+case TypeKind::STR:
+  return true;
+default:
+  return false;
+}
+}
+
+bool
+BaseType::satisfies_bound (const TypeBoundPredicate &predicate) const
+{
+  const Resolver::TraitReference *query = predicate.get ();
+  for (auto &bound : specified_bounds)
+{
+  const Resolver::TraitReference *item = bound.get ();
+  bool found = item->get_mappings ().get_defid ()
+  == query->get_mappings ().get_defid ();
+  if (found)
+   return true;
+}
+
+  auto probed = Resolver::TypeBoundsProbe::Probe (this);
+  for (auto &b : probed)
+{
+  const Resolver::TraitReference *bound = b.first;
+  bool found = bound->get_mappings ().get_defid ()
+  == query->get_mappings ().get_defid ();
+  if (found)
+   return true;
+}
+
+  return false;
+}
+
+bool
+BaseType::bounds_compatible (const BaseType &other, Location locus,
+bool emit_error) const
+{
+  std::vector>
+unsatisfied_bounds;
+  for (auto &bound : get_specified_bounds ())
+{
+  if (!other.satisfies_bound (bound))
+   unsatisfied_bounds.push_back (bound);
+}
+
+  // lets emit a single error for this
+  if (unsatisfied_bounds.size () > 0)
+{
+  RichLocation r (locus);
+  std::string missing_preds;
+  for (size_t i = 0; i < unsatisfied_bounds.size (); i++)
+   {
+ const TypeBoundPredicate &pred = unsatisfied_bounds.at (i);
+ r.add_range (pred.get_locus ());
+ missing_preds += pred.get_name ();
+
+ bool have_next = (i + 1) < unsatisfied_bounds.size ();
+  

[PATCH Rust front-end v4 42/46] gccrs: Add lang-spec.h

2022-12-06 Thread arthur . cohen
From: Philip Herron 

This specifies the extensions of the Rust language.
---
 gcc/rust/lang-specs.h | 26 ++
 1 file changed, 26 insertions(+)
 create mode 100644 gcc/rust/lang-specs.h

diff --git a/gcc/rust/lang-specs.h b/gcc/rust/lang-specs.h
new file mode 100644
index 000..eed28b1eb06
--- /dev/null
+++ b/gcc/rust/lang-specs.h
@@ -0,0 +1,26 @@
+/* lang-specs.h -- gcc driver specs for Rust frontend.
+   Copyright (C) 2009-2022 Free Software Foundation, Inc.
+
+   This file is part of GCC.
+
+   GCC is free software; you can redistribute it and/or modify it under
+   the terms of the GNU General Public License as published by the Free
+   Software Foundation; either version 3, or (at your option) any later
+   version.
+
+   GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+   WARRANTY; without even the implied warranty of MERCHANTABILITY or
+   FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+   for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with GCC; see the file COPYING3.  If not see
+   .  */
+
+/* This is the contribution to the `default_compilers' array in gcc.cc
+   for the Rust language.  */
+
+{".rs", "@rust", 0, 1, 0},
+  {"@rust",
+   "rust1 %i %(cc1_options) %{I*} %{L*} %D %{!fsyntax-only:%(invoke_as)}", 0, 
1,
+   0},
-- 
2.38.1



[PATCH Rust front-end v4 43/46] gccrs: Add lang.opt

2022-12-06 Thread arthur . cohen
From: Philip Herron 

We have some Rust-specific language options. Note that -fwrapv is
enabled by default in the code. We are trying to respect options such as
-Wunused-result which we get by porting over C++'s no-discard for Rust's
must-use attribute, so we have enabled these by default directly here.
---
 gcc/rust/lang.opt | 118 ++
 1 file changed, 118 insertions(+)
 create mode 100644 gcc/rust/lang.opt

diff --git a/gcc/rust/lang.opt b/gcc/rust/lang.opt
new file mode 100644
index 000..1130999d277
--- /dev/null
+++ b/gcc/rust/lang.opt
@@ -0,0 +1,118 @@
+; Options for the Rust front end.
+; Copyright (C) 2003-2022 Free Software Foundation, Inc.
+;
+; This file is part of GCC.
+;
+; GCC is free software; you can redistribute it and/or modify it under
+; the terms of the GNU General Public License as published by the Free
+; Software Foundation; either version 3, or (at your option) any later
+; version.
+; 
+; GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+; WARRANTY; without even the implied warranty of MERCHANTABILITY or
+; FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+; for more details.
+; 
+; You should have received a copy of the GNU General Public License
+; along with GCC; see the file COPYING3.  If not see
+; .
+
+; See the GCC internals manual for a description of this file's format.
+
+; Please try to keep this file in ASCII collating order.
+
+; Describes command-line options used by this frontend
+
+Language
+Rust
+
+I
+Rust Joined Separate
+; Documented in c.opt
+
+L
+Rust Joined Separate
+; Not documented
+
+Wall
+Rust
+; Documented in c.opt
+
+Wunused-variable
+Rust Var(warn_unused_variable) Warning
+; documented in common.opt
+
+Wunused-const-variable
+Rust Warning Alias(Wunused-const-variable=, 2, 0)
+Warn when a const variable is unused.
+
+Wunused-const-variable=
+Rust Joined RejectNegative UInteger Var(warn_unused_const_variable) Warning 
LangEnabledBy(Rust,Wunused-variable, 1, 0) IntegerRange(0, 2)
+Warn when a const variable is unused.
+
+Wunused-result
+Rust Var(warn_unused_result) Warning
+Warn if a caller of a function, marked with attribute warn_unused_result, does 
not use its return value.
+
+frust-crate=
+Rust Joined RejectNegative
+-frust-crate= Set the crate name for the compilation
+
+frust-debug
+Rust Var(flag_rust_debug)
+Dump various Rust front end internals.
+
+frust-dump-
+Rust Joined RejectNegative
+-frust-dump- Dump Rust frontend internal information.
+
+frust-max-recursion-depth=
+Rust RejectNegative Type(int) Var(rust_max_recursion_depth) Init(64)
+-frust-max-recursion-depth=integer
+
+frust-mangling=
+Rust Joined RejectNegative Enum(frust_mangling) Var(flag_rust_mangling)
+-frust-mangling=[legacy|v0] Choose which version to use for name mangling
+
+Enum
+Name(frust_mangling) Type(int) UnknownError(unknown rust mangling option %qs)
+
+EnumValue
+Enum(frust_mangling) String(legacy) Value(0)
+
+EnumValue
+Enum(frust_mangling) String(v0) Value(1)
+
+frust-cfg=
+Rust Joined RejectNegative
+-frust-cfg= Set a config expansion option
+
+frust-edition=
+Rust Joined RejectNegative Enum(frust_edition) Var(flag_rust_edition)
+-frust-edition=[2015|2018|2021] Choose which edition to use when 
compiling rust code
+
+Enum
+Name(frust_edition) Type(int) UnknownError(unknown rust edition %qs)
+
+EnumValue
+Enum(frust_edition) String(2015) Value(0)
+
+EnumValue
+Enum(frust_edition) String(2018) Value(1)
+
+EnumValue
+Enum(frust_edition) String(2021) Value(2)
+
+frust-embed-metadata
+Rust Var(flag_rust_embed_metadata)
+Flag to enable embeding metadata directly into object files
+
+frust-metadata-output=
+Rust Joined RejectNegative
+-frust-metadata-output=  Path to output crate metadata
+
+o
+Rust Joined Separate
+; Documented in common.opt
+
+; This comment is to ensure we retain the blank line above.
-- 
2.38.1



[PATCH Rust front-end v4 38/46] gccrs: Add HIR to GCC GENERIC lowering entry point

2022-12-06 Thread arthur . cohen
From: Philip Herron 

This patch contains the entry point and utilities used for the lowering
of HIR nodes to `tree`s. It also contains a constant evaluator, ported
over from the C++ frontend.

Co-authored-by: David Faust 
Co-authored-by: Faisal Abbas <90.abbasfai...@gmail.com>
---
 gcc/rust/backend/rust-compile-context.cc | 146 
 gcc/rust/backend/rust-compile-context.h  | 343 ++
 gcc/rust/backend/rust-compile.cc | 414 ++
 gcc/rust/backend/rust-compile.h  |  47 +++
 gcc/rust/backend/rust-constexpr.cc   | 433 +++
 gcc/rust/backend/rust-constexpr.h|  31 ++
 6 files changed, 1414 insertions(+)
 create mode 100644 gcc/rust/backend/rust-compile-context.cc
 create mode 100644 gcc/rust/backend/rust-compile-context.h
 create mode 100644 gcc/rust/backend/rust-compile.cc
 create mode 100644 gcc/rust/backend/rust-compile.h
 create mode 100644 gcc/rust/backend/rust-constexpr.cc
 create mode 100644 gcc/rust/backend/rust-constexpr.h

diff --git a/gcc/rust/backend/rust-compile-context.cc 
b/gcc/rust/backend/rust-compile-context.cc
new file mode 100644
index 000..cb2addf6c21
--- /dev/null
+++ b/gcc/rust/backend/rust-compile-context.cc
@@ -0,0 +1,146 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#include "rust-compile-context.h"
+#include "rust-compile-type.h"
+
+namespace Rust {
+namespace Compile {
+
+Context::Context (::Backend *backend)
+  : backend (backend), resolver (Resolver::Resolver::get ()),
+tyctx (Resolver::TypeCheckContext::get ()),
+mappings (Analysis::Mappings::get ()), mangler (Mangler ())
+{
+  setup_builtins ();
+}
+
+void
+Context::setup_builtins ()
+{
+  auto builtins = resolver->get_builtin_types ();
+  for (auto it = builtins.begin (); it != builtins.end (); it++)
+{
+  HirId ref;
+  bool ok = tyctx->lookup_type_by_node_id ((*it)->get_node_id (), &ref);
+  rust_assert (ok);
+
+  TyTy::BaseType *lookup;
+  ok = tyctx->lookup_type (ref, &lookup);
+  rust_assert (ok);
+
+  TyTyResolveCompile::compile (this, lookup);
+}
+}
+
+hashval_t
+Context::type_hasher (tree type)
+{
+  inchash::hash hstate;
+
+  hstate.add_int (TREE_CODE (type));
+
+  if (TYPE_NAME (type))
+{
+  hashval_t record_name_hash
+   = IDENTIFIER_HASH_VALUE (DECL_NAME (TYPE_NAME (type)));
+  hstate.add_object (record_name_hash);
+}
+
+  for (tree t = TYPE_ATTRIBUTES (type); t; t = TREE_CHAIN (t))
+/* Just the identifier is adequate to distinguish.  */
+hstate.add_object (IDENTIFIER_HASH_VALUE (TREE_PURPOSE (t)));
+
+  switch (TREE_CODE (type))
+{
+case METHOD_TYPE:
+  hstate.add_object (TYPE_HASH (TYPE_METHOD_BASETYPE (type)));
+  /* FALLTHROUGH. */
+case FUNCTION_TYPE:
+  for (tree t = TYPE_ARG_TYPES (type); t; t = TREE_CHAIN (t))
+   if (TREE_VALUE (t) != error_mark_node)
+ hstate.add_object (TYPE_HASH (TREE_VALUE (t)));
+  break;
+
+case OFFSET_TYPE:
+  hstate.add_object (TYPE_HASH (TYPE_OFFSET_BASETYPE (type)));
+  break;
+
+  case ARRAY_TYPE: {
+   if (TYPE_DOMAIN (type))
+ hstate.add_object (TYPE_HASH (TYPE_DOMAIN (type)));
+   if (!AGGREGATE_TYPE_P (TREE_TYPE (type)))
+ {
+   unsigned typeless = TYPE_TYPELESS_STORAGE (type);
+   hstate.add_object (typeless);
+ }
+  }
+  break;
+
+  case INTEGER_TYPE: {
+   tree t = TYPE_MAX_VALUE (type);
+   if (!t)
+ t = TYPE_MIN_VALUE (type);
+   for (int i = 0; i < TREE_INT_CST_NUNITS (t); i++)
+ hstate.add_object (TREE_INT_CST_ELT (t, i));
+   break;
+  }
+
+case REAL_TYPE:
+  case FIXED_POINT_TYPE: {
+   unsigned prec = TYPE_PRECISION (type);
+   hstate.add_object (prec);
+   break;
+  }
+
+case VECTOR_TYPE:
+  hstate.add_poly_int (TYPE_VECTOR_SUBPARTS (type));
+  break;
+
+case RECORD_TYPE:
+case UNION_TYPE:
+  case QUAL_UNION_TYPE: {
+   for (tree t = TYPE_FIELDS (type); t; t = TREE_CHAIN (t))
+ {
+   hashval_t name_hash = IDENTIFIER_HASH_VALUE (DECL_NAME (t));
+   hashval_t type_hash = type_hasher (TREE_TYPE (t));
+   hstate.add_object (name_hash);
+   hstate.add_object (type_hash);
+ }
+  }
+ 

[PATCH Rust front-end v4 40/46] gccrs: Add GCC Rust front-end Make-lang.in

2022-12-06 Thread arthur . cohen
From: Philip Herron 

This is the Makefile for our front-end.
---
 gcc/rust/Make-lang.in | 402 ++
 1 file changed, 402 insertions(+)
 create mode 100644 gcc/rust/Make-lang.in

diff --git a/gcc/rust/Make-lang.in b/gcc/rust/Make-lang.in
new file mode 100644
index 000..f3a03a3199d
--- /dev/null
+++ b/gcc/rust/Make-lang.in
@@ -0,0 +1,402 @@
+# Make-lang.in -- Top level -*- makefile -*- fragment for GCC Rust frontend.
+
+# Copyright (C) 2009-2022 Free Software Foundation, Inc.
+
+# This file is part of GCC.
+
+# GCC is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3, or (at your option)
+# any later version.
+
+# GCC is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+
+# You should have received a copy of the GNU General Public License
+# along with GCC; see the file COPYING3.  If not see
+# .
+
+# This file provides the language dependent support in the main Makefile.
+
+#RUST_EXES = rust
+
+# Use strict warnings for this front end.
+rust-warn = $(STRICT_WARN)
+# ..., with the exception of '-Wunused-parameter'; waiting for
+#  "bootstrap build failure".
+rust-warn += -Wno-unused-parameter
+
+# Installation name. Useful for cross compilers and used during install.
+GCCRS_INSTALL_NAME := $(shell echo gccrs|sed '$(program_transform_name)')
+GCCRS_TARGET_INSTALL_NAME := $(target_noncanonical)-$(shell echo gccrs|sed 
'$(program_transform_name)')
+
+# Define the names for selecting rust in LANGUAGES.
+rust: rust1$(exeext)
+
+# Tell GNU make to ignore files by these names if they exist.
+.PHONY: rust
+
+# removed GRS_CFLAGS from here
+
+CFLAGS-rust/rustspec.o += $(DRIVER_DEFINES)
+
+# Create the compiler driver gccrs.
+# A compiler driver is the program that interprets command argument and can be 
called from the command
+# line - e.g. gcc or g++, and not cc1, which is the actual compiler
+
+# Create driver objects
+GCCRS_D_OBJS = \
+   $(GCC_OBJS) \
+   rust/rustspec.o \
+   $(END)
+
+gccrs$(exeext): $(GCCRS_D_OBJS) $(EXTRA_GCC_OBJS) libcommon-target.a $(LIBDEPS)
+   +$(LINKER) $(ALL_LINKERFLAGS) $(LDFLAGS) -o $@ \
+ $(GCCRS_D_OBJS) $(EXTRA_GCC_OBJS) libcommon-target.a \
+ $(EXTRA_GCC_LIBS) $(LIBS)
+
+# List of host object files used by the rust language - files for translation 
from the parse tree
+# to GENERIC
+# The compiler proper, not driver
+GRS_OBJS = \
+rust/rust-lang.o \
+rust/rust-object-export.o \
+rust/rust-linemap.o \
+rust/rust-gcc-diagnostics.o \
+rust/rust-diagnostics.o \
+rust/rust-gcc.o \
+rust/rust-token.o \
+rust/rust-lex.o \
+rust/rust-cfg-parser.o \
+rust/rust-parse.o \
+rust/rust-ast-full-test.o \
+rust/rust-ast-dump.o \
+rust/rust-hir-dump.o \
+rust/rust-session-manager.o \
+rust/rust-compile.o \
+rust/rust-mangle.o \
+rust/rust-compile-resolve-path.o \
+rust/rust-macro-expand.o \
+rust/rust-attribute-visitor.o \
+rust/rust-macro-invoc-lexer.o \
+rust/rust-macro-substitute-ctx.o \
+rust/rust-macro-builtins.o \
+rust/rust-hir-full-test.o \
+rust/rust-hir-map.o \
+rust/rust-attributes.o \
+rust/rust-abi.o \
+rust/rust-ast-lower.o \
+rust/rust-ast-lower-base.o \
+rust/rust-ast-lower-pattern.o \
+rust/rust-ast-lower-item.o \
+rust/rust-name-resolver.o \
+rust/rust-ast-resolve.o \
+rust/rust-ast-resolve-base.o \
+rust/rust-ast-resolve-item.o \
+rust/rust-ast-resolve-pattern.o \
+rust/rust-ast-resolve-expr.o \
+rust/rust-ast-resolve-type.o \
+rust/rust-ast-resolve-path.o \
+rust/rust-ast-resolve-stmt.o \
+rust/rust-ast-resolve-struct-expr-field.o \
+rust/rust-hir-type-check.o \
+rust/rust-privacy-check.o \
+rust/rust-privacy-ctx.o \
+rust/rust-reachability.o \
+rust/rust-visibility-resolver.o \
+rust/rust-pub-restricted-visitor.o \
+rust/rust-privacy-reporter.o \
+rust/rust-tyty.o \
+rust/rust-tyty-call.o \
+rust/rust-tyctx.o \
+rust/rust-tyty-bounds.o \
+rust/rust-hir-type-check-util.o \
+rust/rust-hir-trait-resolve.o \
+rust/rust-hir-type-check-toplevel.o \
+rust/rust-hir-type-check-item.o \
+rust/rust-hir-type-check-type.o \
+rust/rust-hir-type-check-struct.o \
+rust/rust-hir-type-check-pattern.o \
+rust/rust-hir-type-check-expr.o \
+rust/rust-hir-type-check-stmt.o \
+rust/rust-hir-type-check-enumitem.o \
+rust/rust-hir-type-check-implitem.o \
+rust/rust-hir-dot-operator.o \
+rust/rust-coercion.o \
+rust/rust-casts.o \
+rust/rust-hir-type-check-base.o \
+rust/rust-autoderef.o \
+rust/ru

RE: [PATCH] aarch64: Specify that FEAT_MOPS sequences clobber CC

2022-12-06 Thread Kyrylo Tkachov via Gcc-patches



> -Original Message-
> From: Kyrylo Tkachov
> Sent: Wednesday, November 30, 2022 5:40 PM
> To: gcc-patches@gcc.gnu.org
> Subject: [PATCH] aarch64: Specify that FEAT_MOPS sequences clobber CC
> 
> Hi all,
> 
> According to the architecture pseudocode the FEAT_MOPS sequences
> overwrite the NZCV flags
> as part of their operation, so GCC needs to model that in the relevant RTL
> patterns.
> For the testcase:
> void g();
> void foo (int a, size_t N, char *__restrict__ in,
>  char *__restrict__ out)
> {
>   if (a != 3)
> __builtin_memcpy (out, in, N);
>   if (a > 3)
> g ();
> }
> 
> we will currently generate:
> foo:
> cmp w0, 3
> bne .L6
> .L1:
> ret
> .L6:
> cpyfp   [x3]!, [x2]!, x1!
> cpyfm   [x3]!, [x2]!, x1!
> cpyfe   [x3]!, [x2]!, x1!
> ble .L1 // Flags reused after CPYF* sequence
> b   g
> 
> This is wrong as the result of cmp needs to be recalculated after the MOPS
> sequence.
> With this patch we'll insert a "cmp w0, 3" before the ble, like what clang
> does.
> 
> Bootstrapped and tested on aarch64-none-linux-gnu.
> Pushing to trunk and to the GCC 12 branch after some baking time.

Pushed to releases/gcc-12 now.

Thanks,
Kyrill

> 
> Thanks,
> Kyrill
> 
> gcc/ChangeLog:
> 
>   * config/aarch64/aarch64.md (aarch64_cpymemdi): Specify clobber
> of CC reg.
>   (*aarch64_cpymemdi): Likewise.
>   (aarch64_movmemdi): Likewise.
>   (aarch64_setmemdi): Likewise.
>   (*aarch64_setmemdi): Likewise.
> 
> gcc/testsuite/ChangeLog:
> 
>   * gcc.target/aarch64/mops_5.c: New test.
>   * gcc.target/aarch64/mops_6.c: Likewise.
>   * gcc.target/aarch64/mops_7.c: Likewise.


[PATCH Rust front-end v4 44/46] gccrs: Add compiler driver

2022-12-06 Thread arthur . cohen
From: Philip Herron 

Our compiler driver is fairly simple so far. The key piece to enforce is
that a compilation unit in Rust is the whole crate, so the process for
compiling Rust means pointing the compiler at the main entry point such as
src/lib.rs or src/main.rs where the expansion pass takes over loading the
other source files to include them in the crate.
---
 gcc/rust/rustspec.cc | 191 +++
 1 file changed, 191 insertions(+)
 create mode 100644 gcc/rust/rustspec.cc

diff --git a/gcc/rust/rustspec.cc b/gcc/rust/rustspec.cc
new file mode 100644
index 000..b05f8ae5454
--- /dev/null
+++ b/gcc/rust/rustspec.cc
@@ -0,0 +1,191 @@
+/* rustspec.c -- Specific flags and argument handling of the gcc Rust front 
end.
+   Copyright (C) 2009-2022 Free Software Foundation, Inc.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3.  If not see
+.  */
+
+#include "config.h"
+#include "system.h"
+#include "coretypes.h"
+#include "tm.h"
+#include "opts.h"
+
+// satisfy intellisense
+#include "options.h"
+
+/* This bit is set if we saw a `-xfoo' language specification.  */
+#define LANGSPEC (1 << 1)
+/* This bit is set if they did `-lc'.  */
+#define WITHLIBC (1 << 2)
+/* Skip this option.  */
+#define SKIPOPT (1 << 3)
+
+void
+lang_specific_driver (struct cl_decoded_option **in_decoded_options,
+ unsigned int *in_decoded_options_count,
+ int *in_added_libraries)
+{
+  unsigned int i, j;
+
+  /* The new argument list will be contained in this.  */
+  struct cl_decoded_option *new_decoded_options;
+
+  /* "-lc" if it appears on the command line.  */
+  const struct cl_decoded_option *saw_libc = 0;
+
+  /* An array used to flag each argument that needs a bit set for
+ LANGSPEC or WITHLIBC.  */
+  int *args;
+
+  /* True if we saw -static.  */
+  int static_link = 0;
+
+  /* True if we should add -shared-libgcc to the command-line.  */
+  int shared_libgcc = 1;
+
+  /* The total number of arguments with the new stuff.  */
+  unsigned int argc;
+
+  /* The argument list.  */
+  struct cl_decoded_option *decoded_options;
+
+  /* The number of libraries added in.  */
+  int added_libraries;
+
+  /* The total number of arguments with the new stuff.  */
+  int num_args = 1;
+
+  /* Whether the -o option was used.  */
+  bool saw_opt_o = false;
+
+  /* The first input file with an extension of .rs.  */
+  const char *first_rust_file = NULL;
+
+  argc = *in_decoded_options_count;
+  decoded_options = *in_decoded_options;
+  added_libraries = *in_added_libraries;
+
+  args = XCNEWVEC (int, argc);
+
+  for (i = 1; i < argc; i++)
+{
+  const char *arg = decoded_options[i].arg;
+
+  switch (decoded_options[i].opt_index)
+   {
+   case OPT_l:
+ if (strcmp (arg, "c") == 0)
+   args[i] |= WITHLIBC;
+ break;
+
+   case OPT_o:
+ saw_opt_o = true;
+ break;
+
+   case OPT_static:
+ static_link = 1;
+ break;
+
+   case OPT_static_libgcc:
+ shared_libgcc = 0;
+ break;
+
+   case OPT_SPECIAL_input_file:
+ if (first_rust_file == NULL)
+   {
+ int len;
+
+ len = strlen (arg);
+ if (len > 3 && strcmp (arg + len - 3, ".rs") == 0)
+   first_rust_file = arg;
+   }
+ else
+   {
+ // FIXME: ARTHUR: Do we want to error here? If there's already one
+ // file?
+ // How do we error here? Do we want to instead just handle that in
+ // the session manager?
+   }
+
+ break;
+   }
+}
+
+/* There's no point adding -shared-libgcc if we don't have a shared
+   libgcc.  */
+#ifndef ENABLE_SHARED_LIBGCC
+  shared_libgcc = 0;
+#endif
+
+  /* Make sure to have room for the trailing NULL argument.  */
+  num_args = argc + shared_libgcc * 5 + 10;
+  new_decoded_options = XNEWVEC (struct cl_decoded_option, num_args);
+
+  i = 0;
+  j = 0;
+
+  /* Copy the 0th argument, i.e., the name of the program itself.  */
+  new_decoded_options[j++] = decoded_options[i++];
+
+  /* NOTE: We start at 1 now, not 0.  */
+  while (i < argc)
+{
+  new_decoded_options[j] = decoded_options[i];
+
+  if (!saw_libc && (args[i] & WITHLIBC))
+   {
+ --j;
+ saw_libc = &decoded_options[i];
+   }
+
+  if ((args[i] & SKIPOPT) != 0)
+   --

[PATCH Rust front-end v4 45/46] gccrs: Compiler proper interface kicks off the pipeline

2022-12-06 Thread arthur . cohen
From: Philip Herron 

This is a wrapper to get out of C land in the rust-lang.cc and into our
class hierarchy for the rust front-end. We expect that the front-end only
support one source file input as the expansion pass will attempt to resolve
that relative pass and parse accordingly.

The main missing piece here is that we are using saw_errors() to return
early which is unnecessary but as our error handling has been improving
over time we will start to take advantage of error node in our type system
as well as error_mark_node from GCC. The caveat being that our lints/checks
expect no errors and will throw an assertion.
---
 gcc/rust/rust-lang.cc|  456 
 gcc/rust/rust-session-manager.cc | 1189 ++
 gcc/rust/rust-session-manager.h  |  358 +
 3 files changed, 2003 insertions(+)
 create mode 100644 gcc/rust/rust-lang.cc
 create mode 100644 gcc/rust/rust-session-manager.cc
 create mode 100644 gcc/rust/rust-session-manager.h

diff --git a/gcc/rust/rust-lang.cc b/gcc/rust/rust-lang.cc
new file mode 100644
index 000..241a9b4dae3
--- /dev/null
+++ b/gcc/rust/rust-lang.cc
@@ -0,0 +1,456 @@
+// Copyright (C) 2020-2022 Free Software Foundation, Inc.
+
+// This file is part of GCC.
+
+// GCC is free software; you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free
+// Software Foundation; either version 3, or (at your option) any later
+// version.
+
+// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+// for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with GCC; see the file COPYING3.  If not see
+// .
+
+#include "rust-system.h"
+#include "rust-diagnostics.h"
+#include "coretypes.h"
+#include "target.h"
+#include "tree.h"
+#include "gimple-expr.h"
+#include "diagnostic.h"
+#include "opts.h"
+#include "fold-const.h"
+#include "gimplify.h"
+#include "stor-layout.h"
+#include "debug.h"
+#include "convert.h"
+#include "langhooks.h"
+#include "langhooks-def.h"
+#include "selftest.h"
+#include "rust-cfg-parser.h"
+#include "rust-privacy-ctx.h"
+#include "rust-ast-resolve-item.h"
+#include "rust-optional.h"
+
+#include 
+// note: header files must be in this order or else forward declarations don't
+// work properly. Kinda dumb system, but have to live with it. clang-format
+// seems to mess it up
+/* Order: config, system, coretypes, target, tree, gimple-expr, diagnostic,
+ * opts, fold-const, gimplify, stor-layout, debug, convert, langhooks,
+ * langhooks-def */
+
+// FIXME: test saving intellisense
+#include "options.h"
+
+// version check to stop compiling if c++ isn't c++11 or higher
+#if __cplusplus < 201103
+#error 
\
+  "GCC Rust frontend requires C++11 or higher. You can compile the g++ 
frontend first and then compile the Rust frontend using that."
+#endif
+// TODO: is this best way to do it? Is it allowed? (should be)
+
+/* General TODOs:
+ *  - convert all copies of expensive-to-copy (deep copy) AST objects into
+ * moves, if possible. Don't remove clone functionality - it may be required 
for
+ * e.g. HIR conversion.
+ */
+
+#include "rust-session-manager.h"
+
+// Language-dependent contents of a type. GTY() mark used for garbage 
collector.
+struct GTY (()) lang_type
+{
+};
+
+// Language-dependent contents of a decl.
+struct GTY (()) lang_decl
+{
+};
+
+// Language-dependent contents of an identifier.  This must include a
+// tree_identifier.
+struct GTY (()) lang_identifier
+{
+  struct tree_identifier common;
+};
+
+// The resulting tree type.
+union GTY ((
+  desc ("TREE_CODE (&%h.generic) == IDENTIFIER_NODE"),
+  chain_next (
+"CODE_CONTAINS_STRUCT (TREE_CODE (&%h.generic), "
+"TS_COMMON) ? ((union lang_tree_node *) TREE_CHAIN (&%h.generic)) : 
NULL")))
+  lang_tree_node
+{
+  union tree_node GTY ((tag ("0"), desc ("tree_node_structure (&%h)"))) 
generic;
+  struct lang_identifier GTY ((tag ("1"))) identifier;
+};
+
+// We don't use language_function.
+struct GTY (()) language_function
+{
+};
+
+// has to be in same compilation unit as session, so here for now
+void
+rust_add_target_info (const char *key, const char *value)
+{
+  sorry ("TODO");
+
+  Rust::Session::get_instance ().options.target_data.insert_key_value_pair (
+key, value);
+}
+
+/* Language hooks.  */
+
+/* Initial lang hook called (possibly), used for initialisation.
+ * Must call build_common_tree_nodes, set_sizetype, build_common_tree_nodes_2,
+ * and build_common_builtin_nodes, as well as set global variable
+ * void_list_node. Apparently called after option handling? */
+static bool
+grs_langhook_init (void)
+{
+  /* Something to do with this:
+   This allows the code in d-builtin

[PATCH Rust front-end v4 46/46] gccrs: Add README, CONTRIBUTING and compiler logo

2022-12-06 Thread arthur . cohen
From: Philip Herron 

We still need to write out a documentation section, but these READMEs will
help in the meantime.
---
 gcc/rust/CONTRIBUTING.md | 130 +++
 gcc/rust/README.md   | 264 +++
 gcc/rust/logo.png| Bin 0 -> 70864 bytes
 3 files changed, 394 insertions(+)
 create mode 100644 gcc/rust/CONTRIBUTING.md
 create mode 100644 gcc/rust/README.md
 create mode 100644 gcc/rust/logo.png

diff --git a/gcc/rust/CONTRIBUTING.md b/gcc/rust/CONTRIBUTING.md
new file mode 100644
index 000..20e499c29e1
--- /dev/null
+++ b/gcc/rust/CONTRIBUTING.md
@@ -0,0 +1,130 @@
+## How to contribute to GCC Rust
+
+ **Did you find a bug?**
+
+* **Ensure the bug was not already reported** by searching on GitHub under 
[Issues](https://github.com/Rust-GCC/gccrs/issues).
+
+* If you're unable to find an open issue addressing the problem, [open a new 
one](https://github.com/Rust-GCC/gccrs/issues/new). 
+  Be sure to include a **title and clear description**, as much relevant 
information as possible, and a **code sample** 
+  or an **executable test case** demonstrating the expected behavior that is 
not occurring.
+
+ **Do you want to submit a patch?**
+
+* Open a new GitHub pull request with the patch.
+
+* Ensure the PR description clearly describes the problem and solution. 
Include the relevant issue number if applicable.
+
+* Before submitting, GCC development requires copyright assignment or the 
Developer's Certificate of Origin sign-off.
+   Please see the [Contributing to GCC](https://gcc.gnu.org/contribute.html) 
guide or [Developer's Certificate of Origin (DCO) 
Sign-off](https://gcc.gnu.org/dco.html) guide.
+
+* Patches sent to the [`gcc-rust` mailing 
list](https://gcc.gnu.org/mailman/listinfo/gcc-rust) are likewise welcome.
+These will be imported into a GitHub PR to follow the normal review process, 
+and the link to the GitHub PR sent to the submitter.
+
+ **Do you intend to add a new feature or change an existing one?**
+
+* Suggest your change in the [Zulip](https://gcc-rust.zulipchat.com/) and 
start writing code.
+
+* Do not open an issue on GitHub until you have collected positive feedback 
about the change. 
+  GitHub issues are primarily intended for bug reports and fixes.
+
+ **Do you have questions about the source code?**
+
+* Ask any question about how to use GCCRS in 
[Zulip](https://gcc-rust.zulipchat.com/).
+
+### **PR Policy**
+
+* The PR policy: Everything has to go through a PR
+  - An exception to this rule will be the merge commits of updating the repo 
against upstream GCC
+
+* Reviewers/Maintainers of the project (aka people who have bors rights) 
should be pinged for reviews/questions.
+
+* A PR can have one or several commits (split should have a technical/logical 
reason, ie. no fixup-ish commit)
+
+* Avoid PR's with merge commit unless there's a good reason
+
+* Where possible please add test cases to `gcc/testsuite/rust/` for all PRs. 
+  Some issues may not be testable via dejagnu/automation such as debug dump 
changes.
+
+* Follow the [GCC coding style](https://gcc.gnu.org/codingconventions.html) 
(see `clang-format` below).
+
+* PRs won't be merged until the build and tests pass.
+
+* Please take the time to create good git commit messages. 
+  See the existing format of them in the git log or refer to something like: 
https://chris.beams.io/posts/git-commit/
+
+ Running `clang-format` locally
+
+* on all files using python scripts
+... corresponding to what the _Clang Format Lint_ 
(`.github/workflows/clang-format.yml`) 
+is doing, with `clang-format-10` being available locally, and avoiding the 
Docker overhead.
+
+```shell
+$ wget 
'https://github.com/DoozyX/clang-format-lint-action/raw/v0.11/run-clang-format.py'
+$ cp contrib/clang-format .clang-format
+$ python3 run-clang-format.py --clang-format-executable clang-format-10 
--recursive --extensions h,cc gcc/rust/
+```
+
+* on a given patch using python scripts
+See the [clang-format 
documentation](https://clang.llvm.org/docs/ClangFormat.html#script-for-patch-reformatting)
 :
+
+$ git diff -U0 --no-color HEAD^ | clang-format-diff.py -i -p1
+
+* using `git` interface
+
+At least on Debian and its derivative, each `clang-format` packages also comes
+with `git-clang-format` command that can be used easily. It applies on staged
+changes, and any modification can be seen as unstaged changes:
+
+```diff
+$ git diff --cached
+diff --git a/gcc/rust/rust-abi.h b/gcc/rust/rust-abi.h
+index bd3043295ce..9559374ce60 100644
+--- a/gcc/rust/rust-abi.h
 b/gcc/rust/rust-abi.h
+@@ -22,10 +22,10 @@ namespace Rust {
+ enum ABI
+ {
+   UNKNOWN,
+-  RUST,
++ RUST,
+   INTRINSIC,
+   C,
+-  CDECL,
++ CDECL,
+   STDCALL,
+   FASTCALL,
+ };
+ 
+gccrs/gcc/rust on  dkm/clang_format [$!+?]
+❯ git clang-format
+changed files:
+gcc/rust/rust-abi.h
+ 
+gccrs/gcc/rust on  dkm/clang_format [$!+?]
+$ git diff rust-abi.h
+diff --git a/gcc/rust/rust-abi.

Re: [PATCH 5/8]AArch64 aarch64: Make existing V2HF be usable.

2022-12-06 Thread Richard Sandiford via Gcc-patches
Tamar Christina  writes:
> Hi,
>
>
>> This name might cause confusion with the SVE iterators, where FULL means
>> "every bit of the register is used".  How about something like VMOVE
>> instead?
>> 
>> With this change, I guess VALL_F16 represents "The set of all modes for
>> which the vld1 intrinsics are provided" and VMOVE or whatever is "All
>> Advanced SIMD modes suitable for moving, loading, and storing".
>> That is, VMOVE extends VALL_F16 with modes that are not manifested via
>> intrinsics.
>> 
>
> Done.
>
>> Where is the 2h used, and is it valid syntax in that context?
>> 
>> Same for later instances of 2h.
>
> They are, but they weren't meant to be in this patch.  They belong in a 
> separate FP16 series that
> I won't get to finish for GCC 13 due not being able to finish writing all the 
> tests.  I have moved them
> to that patch series though.
>
> While the addp patch series has been killed, this patch is still good 
> standalone and improves codegen
> as shown in the updated testcase.
>
> Bootstrapped Regtested on aarch64-none-linux-gnu and no issues.
>
> Ok for master?
>
> Thanks,
> Tamar
>
> gcc/ChangeLog:
>
>   * config/aarch64/aarch64-simd.md (*aarch64_simd_movv2hf): New.
>   (mov, movmisalign, aarch64_dup_lane,
>   aarch64_store_lane0, aarch64_simd_vec_set,
>   @aarch64_simd_vec_copy_lane, vec_set,
>   reduc__scal_, reduc__scal_,
>   aarch64_reduc__internal, aarch64_get_lane,
>   vec_init, vec_extract): Support V2HF.
>   (aarch64_simd_dupv2hf): New.
>   * config/aarch64/aarch64.cc (aarch64_classify_vector_mode):
>   Add E_V2HFmode.
>   * config/aarch64/iterators.md (VHSDF_P): New.
>   (V2F, VMOVE, nunits, Vtype, Vmtype, Vetype, stype, VEL,
>   Vel, q, vp): Add V2HF.
>   * config/arm/types.md (neon_fp_reduc_add_h): New.
>
> gcc/testsuite/ChangeLog:
>
>   * gcc.target/aarch64/sve/slp_1.c: Update testcase.
>
> --- inline copy of patch ---
>
> diff --git a/gcc/config/aarch64/aarch64-simd.md 
> b/gcc/config/aarch64/aarch64-simd.md
> index 
> f4152160084d6b6f34bd69f0ba6386c1ab50f77e..487a31010245accec28e779661e6c2d578fca4b7
>  100644
> --- a/gcc/config/aarch64/aarch64-simd.md
> +++ b/gcc/config/aarch64/aarch64-simd.md
> @@ -19,10 +19,10 @@
>  ;; .
>  
>  (define_expand "mov"
> -  [(set (match_operand:VALL_F16 0 "nonimmediate_operand")
> - (match_operand:VALL_F16 1 "general_operand"))]
> +  [(set (match_operand:VMOVE 0 "nonimmediate_operand")
> + (match_operand:VMOVE 1 "general_operand"))]
>"TARGET_SIMD"
> -  "
> +{
>/* Force the operand into a register if it is not an
>   immediate whose use can be replaced with xzr.
>   If the mode is 16 bytes wide, then we will be doing
> @@ -46,12 +46,11 @@ (define_expand "mov"
>aarch64_expand_vector_init (operands[0], operands[1]);
>DONE;
>  }
> -  "
> -)
> +})
>  
>  (define_expand "movmisalign"
> -  [(set (match_operand:VALL_F16 0 "nonimmediate_operand")
> -(match_operand:VALL_F16 1 "general_operand"))]
> +  [(set (match_operand:VMOVE 0 "nonimmediate_operand")
> +(match_operand:VMOVE 1 "general_operand"))]
>"TARGET_SIMD && !STRICT_ALIGNMENT"
>  {
>/* This pattern is not permitted to fail during expansion: if both 
> arguments
> @@ -73,6 +72,16 @@ (define_insn "aarch64_simd_dup"
>[(set_attr "type" "neon_dup, neon_from_gp")]
>  )
>  
> +(define_insn "aarch64_simd_dupv2hf"
> +  [(set (match_operand:V2HF 0 "register_operand" "=w")
> + (vec_duplicate:V2HF
> +   (match_operand:HF 1 "register_operand" "0")))]

Seems like this should be "w" rather than "0", since SLI is a
two-register instruction.

> +  "TARGET_SIMD"
> +  "@
> +   sli\\t%d0, %d1, 16"
> +  [(set_attr "type" "neon_shift_imm")]
> +)
> +
>  (define_insn "aarch64_simd_dup"
>[(set (match_operand:VDQF_F16 0 "register_operand" "=w,w")
>   (vec_duplicate:VDQF_F16
> @@ -85,10 +94,10 @@ (define_insn "aarch64_simd_dup"
>  )
>  
>  (define_insn "aarch64_dup_lane"
> -  [(set (match_operand:VALL_F16 0 "register_operand" "=w")
> - (vec_duplicate:VALL_F16
> +  [(set (match_operand:VMOVE 0 "register_operand" "=w")
> + (vec_duplicate:VMOVE
> (vec_select:
> - (match_operand:VALL_F16 1 "register_operand" "w")
> + (match_operand:VMOVE 1 "register_operand" "w")
>   (parallel [(match_operand:SI 2 "immediate_operand" "i")])
>)))]
>"TARGET_SIMD"
> @@ -142,6 +151,29 @@ (define_insn "*aarch64_simd_mov"
>mov_reg, neon_move")]
>  )
>  
> +(define_insn "*aarch64_simd_movv2hf"
> +  [(set (match_operand:V2HF 0 "nonimmediate_operand"
> + "=w, m,  m,  w, ?r, ?w, ?r, w, w")
> + (match_operand:V2HF 1 "general_operand"
> + "m,  Dz, w,  w,  w,  r,  r, Dz, Dn"))]
> +  "TARGET_SIMD_F16INST
> +   && (register_operand (operands[0], V2HFmode)
> +   || aarch64_simd_reg_or_zero (operands[1], V2HFmode))"
> +   "@
> +ldr\\t%s0, %1
> +str\\twzr, %0
> +

Re: Zen4 tuning part 1 - cost tables

2022-12-06 Thread Richard Biener via Gcc-patches
On Tue, Dec 6, 2022 at 11:01 AM Jan Hubicka via Gcc-patches
 wrote:
>
> Hi
> this patch updates cost of znver4 mostly based on data measued by Agner Fog.
> Compared to previous generations x87 became bit slower which is probably not
> big deal (and we have minimal benchmarking coverage for it).  One interesting
> improvement is reducation of FMA cost.  I also updated costs of AVX256
> loads/stores  based on latencies (not throughput which is twice of avx256).
> Overall AVX512 vectorization seems to improve noticeably some of TSVC
> benchmarks but since internally 512 vectors are split to 256 vectors it is
> somewhat risky and does not win in SPEC scores (mostly by regressing 
> benchmarks
> with loop that have small trip count like x264 and exchange), so for now I am
> going to set AVX256_OPTIMAL tune but I am still playing with it.  We improved
> since ZNVER1 on choosing vectorization size and also have vectorized
> prologues/epilogues so it may be possible to make avx512 small win overall.
>
> In general I would like to keep cost tables latency based unless we have
> a good reason to not do so.  There are some interesting diferences in
> znver3 tables that I also patched and seems performance neutral.  I will
> send that separately.
>
> Bootstrapped/regtested x86_64-linux, also benchmarked on SPEC2017 along
> with AVX512 tuning.  I plan to commit it tomorrow unless there are some
> comments.
>
> Honza
>
> * x86-tune-costs.h (znver4_cost): Upate costs of FP and SSE moves,
> division multiplication, gathers, L2 cache size, and more complex
> FP instrutions.
> diff --git a/gcc/config/i386/x86-tune-costs.h 
> b/gcc/config/i386/x86-tune-costs.h
> index f01b8ee9eef..3a6ce02f093 100644
> --- a/gcc/config/i386/x86-tune-costs.h
> +++ b/gcc/config/i386/x86-tune-costs.h
> @@ -1867,9 +1868,9 @@ struct processor_costs znver4_cost = {
>{8, 8, 8},   /* cost of storing integer
>registers.  */
>2,   /* cost of reg,reg fld/fst.  */
> -  {6, 6, 16},  /* cost of loading fp registers
> +  {14, 14, 17},/* cost of loading fp 
> registers
>in SFmode, DFmode and XFmode.  */
> -  {8, 8, 16},  /* cost of storing fp registers
> +  {12, 12, 16},/* cost of storing fp 
> registers
>in SFmode, DFmode and XFmode.  */
>2,   /* cost of moving MMX register.  */
>{6, 6},  /* cost of loading MMX registers
> @@ -1878,13 +1879,13 @@ struct processor_costs znver4_cost = {
>in SImode and DImode.  */
>2, 2, 3, /* cost of moving XMM,YMM,ZMM
>register.  */
> -  {6, 6, 6, 6, 12},/* cost of loading SSE registers
> +  {6, 6, 10, 10, 12},  /* cost of loading SSE registers
>in 32,64,128,256 and 512-bit.  */
> -  {8, 8, 8, 8, 16},/* cost of storing SSE registers
> +  {8, 8, 8, 12, 12},   /* cost of storing SSE registers
>in 32,64,128,256 and 512-bit.  */
> -  6, 6,/* SSE->integer and 
> integer->SSE
> +  6, 8,/* SSE->integer and 
> integer->SSE
>moves.  */
> -  8, 8,/* mask->integer and integer->mask 
> moves */
> +  8, 8,/* mask->integer and 
> integer->mask moves */
>{6, 6, 6},   /* cost of loading mask register
>in QImode, HImode, SImode.  */
>{8, 8, 8},   /* cost if storing mask register
> @@ -1894,6 +1895,7 @@ struct processor_costs znver4_cost = {
>},
>
>COSTS_N_INSNS (1),   /* cost of an add instruction.  */
> +  /* TODO: Lea with 3 components has cost 2.  */
>COSTS_N_INSNS (1),   /* cost of a lea instruction.  */
>COSTS_N_INSNS (1),   /* variable shift costs.  */
>COSTS_N_INSNS (1),   /* constant shift costs.  */
> @@ -1904,11 +1906,11 @@ struct processor_costs znver4_cost = {
> COSTS_N_INSNS (3)}, /*  other.  */
>0,   /* cost of multiply per each bit
>set.  */
> -  {COSTS_N_INSNS (9),  /* cost of a divide/mod for QI.  */
> -   COSTS_N_INSNS (10), /*  HI.  */
> -   COSTS_N_INSNS (12), /*  SI.  *

[committed] testsuite: Use -mnofpu for rx-*-* in ieee testsuite [PR107046]

2022-12-06 Thread Jakub Jelinek via Gcc-patches
Hi!

add_options_for_ieee has:
if { [istarget alpha*-*-*]
 || [istarget sh*-*-*] } {
   return "$flags -mieee"
}
if { [istarget rx-*-*] } {
   return "$flags -mnofpu"
}
but ieee.exp doesn't use add_options_for_ieee, instead it has:
if { [istarget "alpha*-*-*"]
 || [istarget "sh*-*-*"] } then {
  lappend additional_flags "-mieee"
}
among other things (plus -ffloat-store on some arches etc.).

The following patch adds the rx -mnofpu similarly in the hope
of fixing ieee.exp FAILs on rx.

Preapproved in the PR by Jeff, committed to trunk.

2022-12-06  Jakub Jelinek  

PR testsuite/107046
* gcc.c-torture/execute/ieee/ieee.exp: For rx-*-* append
-mnofpu.

--- gcc/testsuite/gcc.c-torture/execute/ieee/ieee.exp.jj2022-01-11 
23:11:22.969282018 +0100
+++ gcc/testsuite/gcc.c-torture/execute/ieee/ieee.exp   2022-12-02 
12:15:22.307173074 +0100
@@ -52,6 +52,9 @@ if { [istarget "alpha*-*-*"]
  || [istarget "sh*-*-*"] } then {
   lappend additional_flags "-mieee"
 }
+if [istarget rx-*-*] then {
+  lappend additional_flags "-mnofpu"
+}
 
 if { ![check_effective_target_signal] } {
 lappend additional_flags "-DSIGNAL_SUPPRESS"

Jakub



[PATCH] i386: Fix up expander conditions on cbranchbf4 and cstorebf4 [PR107969]

2022-12-06 Thread Jakub Jelinek via Gcc-patches
Hi!

With -msoft-float we ICE on __bf16 comparisons, because the
insns we want to use under the hood (cbranchsf4 and cstoresf4)
after performing the fast extensions aren't available.

The following patch copies the conditions from the c*sf4 expanders
to the corresponding c*bf4 expanders.

Bootstrapped/regtested on x86_64-linux and i686-linux, ok for trunk?

2022-12-06  Jakub Jelinek  

PR target/107969
* config/i386/i386.md (cbranchbf4, cstorebf4): Guard expanders
with the same condition as cbranchsf4 or cstoresf4 expanders.

* gcc.target/i386/pr107969.c: New test.

--- gcc/config/i386/i386.md.jj  2022-12-02 10:28:30.0 +0100
+++ gcc/config/i386/i386.md 2022-12-05 17:21:53.062085995 +0100
@@ -1667,7 +1667,7 @@ (define_expand "cbranchbf4"
(const_int 0)])
  (label_ref (match_operand 3))
  (pc)))]
-  ""
+  "TARGET_80387 || (SSE_FLOAT_MODE_P (SFmode) && TARGET_SSE_MATH)"
 {
   rtx op1 = ix86_expand_fast_convert_bf_to_sf (operands[1]);
   rtx op2 = ix86_expand_fast_convert_bf_to_sf (operands[2]);
@@ -1702,7 +1702,7 @@ (define_expand "cstorebf4"
(match_operator 1 "comparison_operator"
  [(reg:CC FLAGS_REG)
   (const_int 0)]))]
-  ""
+  "TARGET_80387 || (SSE_FLOAT_MODE_P (SFmode) && TARGET_SSE_MATH)"
 {
   rtx op1 = ix86_expand_fast_convert_bf_to_sf (operands[2]);
   rtx op2 = ix86_expand_fast_convert_bf_to_sf (operands[3]);
--- gcc/testsuite/gcc.target/i386/pr107969.c.jj 2022-12-05 17:27:36.229060068 
+0100
+++ gcc/testsuite/gcc.target/i386/pr107969.c2022-12-05 17:27:14.839373669 
+0100
@@ -0,0 +1,12 @@
+/* PR target/107969 */
+/* { dg-do compile } */
+/* { dg-options "-O2 -fexcess-precision=16 -msoft-float -msse2" } */
+
+int i;
+__bf16 f;
+
+void
+bar (void)
+{
+  i *= 0 <= f;
+}

Jakub



Re: [PATCH] libgcc: Fix uninitialized RA signing on AArch64 [PR107678]

2022-12-06 Thread Szabolcs Nagy via Gcc-patches
The 12/05/2022 19:04, Richard Sandiford wrote:
> Wilco Dijkstra  writes:
> > A recent change only initializes the regs.how[] during Dwarf unwinding
> > which resulted in an uninitialized offset used in return address signing
> > and random failures during unwinding.  The fix is to use REG_SAVED_OFFSET
> > as the state where the return address signing bit is valid, and if the
> > state is REG_UNSAVED, initialize it to 0.
> >
> > Passes bootstrap & regress, OK for commit?
> >
> > libgcc/
> > PR target/107678
> > * unwind-dw2.c (execute_cfa_program): Initialize offset of
> > DWARF_REGNUM_AARCH64_RA_STATE if in REG_UNSAVED state.
> > * config/aarch64/aarch64-unwind.h (aarch64_frob_update_contex):
> > Check state is REG_SAVED_OFFSET before using offset for RA state.
> >
> > ---
> >
> > diff --git a/libgcc/config/aarch64/aarch64-unwind.h 
> > b/libgcc/config/aarch64/aarch64-unwind.h
> > index 
> > 26db9cbd9e5c526e0c410a4fc6be2bedb7d261cf..597133b3d708a50a366c8bfeff57475f5522b3f6
> >  100644
> > --- a/libgcc/config/aarch64/aarch64-unwind.h
> > +++ b/libgcc/config/aarch64/aarch64-unwind.h
> > @@ -71,21 +71,15 @@ aarch64_demangle_return_addr (struct _Unwind_Context 
> > *context,
> >  }
> >  
> >  /* Do AArch64 private initialization on CONTEXT based on frame info FS.  
> > Mark
> > -   CONTEXT as return address signed if bit 0 of 
> > DWARF_REGNUM_AARCH64_RA_STATE is
> > -   set.  */
> > +   CONTEXT as having a signed return address if 
> > DWARF_REGNUM_AARCH64_RA_STATE
> > +   is initialized (REG_SAVED_OFFSET state) and the offset has bit 0 set.  
> > */
> >  
> >  static inline void
> >  aarch64_frob_update_context (struct _Unwind_Context *context,
> >  _Unwind_FrameState *fs)
> >  {
> > -  const int reg = DWARF_REGNUM_AARCH64_RA_STATE;
> > -  int ra_signed;
> > -  if (fs->regs.how[reg] == REG_UNSAVED)
> > -ra_signed = fs->regs.reg[reg].loc.offset & 0x1;
> > -  else
> > -ra_signed = _Unwind_GetGR (context, reg) & 0x1;
> > -  if (ra_signed)
> > -/* The flag is used for re-authenticating EH handler's address.  */
> > +  if (fs->regs.how[DWARF_REGNUM_AARCH64_RA_STATE] == REG_SAVED_OFFSET
> > +  && (fs->regs.reg[DWARF_REGNUM_AARCH64_RA_STATE].loc.offset & 1) != 0)
> >  context->flags |= RA_SIGNED_BIT;
> >else
> >  context->flags &= ~RA_SIGNED_BIT;
> 
> Hmm, but the point of the original patch was to support code generators
> that emit DW_CFA_val_expression instead of DW_CFA_AARCH64_negate_ra_state.
> Doesn't this patch undo that?
> 
> Also, if I understood correctly, the reason we use REG_UNSAVED is to
> ensure that state from one frame isn't carried across to a parent frame,
> in cases where the parent frame lacks any signing.  That is, each frame
> should start out with a zero bit even if a child frame is unwound while
> it has a set bit.

yes.

i don't think how[*RA_STATE] can ever be set to REG_SAVED_OFFSET,
this pseudo reg is not spilled to the stack, it is reset to 0 in
each frame and then toggled within a frame.

unwind-dw2.c has

case DW_CFA_GNU_window_save:
#if defined (__aarch64__) && !defined (__ILP32__)
  /* This CFA is multiplexed with Sparc.  On AArch64 it's used to toggle
 return address signing status.  */
  reg = DWARF_REGNUM_AARCH64_RA_STATE;
  gcc_assert (fs->regs.how[reg] == REG_UNSAVED);
  fs->regs.reg[reg].loc.offset ^= 1;

for this to work, loc.offset must be reset in uw_frame_state_for.
we may need a new hook for that.


> 
> Thanks,
> Richard
> 
> > diff --git a/libgcc/unwind-dw2.c b/libgcc/unwind-dw2.c
> > index 
> > eaceace20298b9b13344aff9d1fe9ee5f9c7bd73..87f2ae065b67982ce48f74e45523d9c754a7661c
> >  100644
> > --- a/libgcc/unwind-dw2.c
> > +++ b/libgcc/unwind-dw2.c
> > @@ -1203,11 +1203,16 @@ execute_cfa_program (const unsigned char *insn_ptr,
> >  
> > case DW_CFA_GNU_window_save:
> >  #if defined (__aarch64__) && !defined (__ILP32__)
> > - /* This CFA is multiplexed with Sparc.  On AArch64 it's used to toggle
> > -return address signing status.  */
> > - reg = DWARF_REGNUM_AARCH64_RA_STATE;
> > - gcc_assert (fs->regs.how[reg] == REG_UNSAVED);
> > - fs->regs.reg[reg].loc.offset ^= 1;
> > +/* This CFA is multiplexed with Sparc.  On AArch64 it's used to toggle
> > +   the return address signing status.  It is initialized at the first
> > +   use and the state is stored in bit 0 of the offset.  */
> > +reg = DWARF_REGNUM_AARCH64_RA_STATE;
> > +if (fs->regs.how[reg] == REG_UNSAVED)
> > +  {
> > +fs->regs.how[reg] = REG_SAVED_OFFSET;
> > +fs->regs.reg[reg].loc.offset = 0;
> > +  }
> > +fs->regs.reg[reg].loc.offset ^= 1;
> >  #else
> >   /* ??? Hardcoded for SPARC register window configuration.  */
> >   if (__LIBGCC_DWARF_FRAME_REGISTERS__ >= 32)


Re: [PATCH] i386: Fix up expander conditions on cbranchbf4 and cstorebf4 [PR107969]

2022-12-06 Thread Uros Bizjak via Gcc-patches
On Tue, Dec 6, 2022 at 11:47 AM Jakub Jelinek  wrote:
>
> Hi!
>
> With -msoft-float we ICE on __bf16 comparisons, because the
> insns we want to use under the hood (cbranchsf4 and cstoresf4)
> after performing the fast extensions aren't available.
>
> The following patch copies the conditions from the c*sf4 expanders
> to the corresponding c*bf4 expanders.
>
> Bootstrapped/regtested on x86_64-linux and i686-linux, ok for trunk?
>
> 2022-12-06  Jakub Jelinek  
>
> PR target/107969
> * config/i386/i386.md (cbranchbf4, cstorebf4): Guard expanders
> with the same condition as cbranchsf4 or cstoresf4 expanders.
>
> * gcc.target/i386/pr107969.c: New test.

OK.

Thanks,
Uros.

>
> --- gcc/config/i386/i386.md.jj  2022-12-02 10:28:30.0 +0100
> +++ gcc/config/i386/i386.md 2022-12-05 17:21:53.062085995 +0100
> @@ -1667,7 +1667,7 @@ (define_expand "cbranchbf4"
> (const_int 0)])
>   (label_ref (match_operand 3))
>   (pc)))]
> -  ""
> +  "TARGET_80387 || (SSE_FLOAT_MODE_P (SFmode) && TARGET_SSE_MATH)"
>  {
>rtx op1 = ix86_expand_fast_convert_bf_to_sf (operands[1]);
>rtx op2 = ix86_expand_fast_convert_bf_to_sf (operands[2]);
> @@ -1702,7 +1702,7 @@ (define_expand "cstorebf4"
> (match_operator 1 "comparison_operator"
>   [(reg:CC FLAGS_REG)
>(const_int 0)]))]
> -  ""
> +  "TARGET_80387 || (SSE_FLOAT_MODE_P (SFmode) && TARGET_SSE_MATH)"
>  {
>rtx op1 = ix86_expand_fast_convert_bf_to_sf (operands[2]);
>rtx op2 = ix86_expand_fast_convert_bf_to_sf (operands[3]);
> --- gcc/testsuite/gcc.target/i386/pr107969.c.jj 2022-12-05 17:27:36.229060068 
> +0100
> +++ gcc/testsuite/gcc.target/i386/pr107969.c2022-12-05 17:27:14.839373669 
> +0100
> @@ -0,0 +1,12 @@
> +/* PR target/107969 */
> +/* { dg-do compile } */
> +/* { dg-options "-O2 -fexcess-precision=16 -msoft-float -msse2" } */
> +
> +int i;
> +__bf16 f;
> +
> +void
> +bar (void)
> +{
> +  i *= 0 <= f;
> +}
>
> Jakub
>


RE: [PATCH 5/8]AArch64 aarch64: Make existing V2HF be usable.

2022-12-06 Thread Tamar Christina via Gcc-patches
> -Original Message-
> From: Richard Sandiford 
> Sent: Tuesday, December 6, 2022 10:28 AM
> To: Tamar Christina 
> Cc: gcc-patches@gcc.gnu.org; nd ; Richard Earnshaw
> ; Marcus Shawcroft
> ; Kyrylo Tkachov 
> Subject: Re: [PATCH 5/8]AArch64 aarch64: Make existing V2HF be usable.
> 
> Tamar Christina  writes:
> > Hi,
> >
> >
> >> This name might cause confusion with the SVE iterators, where FULL
> >> means "every bit of the register is used".  How about something like
> >> VMOVE instead?
> >>
> >> With this change, I guess VALL_F16 represents "The set of all modes
> >> for which the vld1 intrinsics are provided" and VMOVE or whatever is
> >> "All Advanced SIMD modes suitable for moving, loading, and storing".
> >> That is, VMOVE extends VALL_F16 with modes that are not manifested
> >> via intrinsics.
> >>
> >
> > Done.
> >
> >> Where is the 2h used, and is it valid syntax in that context?
> >>
> >> Same for later instances of 2h.
> >
> > They are, but they weren't meant to be in this patch.  They belong in
> > a separate FP16 series that I won't get to finish for GCC 13 due not
> > being able to finish writing all the tests.  I have moved them to that patch
> series though.
> >
> > While the addp patch series has been killed, this patch is still good
> > standalone and improves codegen as shown in the updated testcase.
> >
> > Bootstrapped Regtested on aarch64-none-linux-gnu and no issues.
> >
> > Ok for master?
> >
> > Thanks,
> > Tamar
> >
> > gcc/ChangeLog:
> >
> > * config/aarch64/aarch64-simd.md (*aarch64_simd_movv2hf): New.
> > (mov, movmisalign, aarch64_dup_lane,
> > aarch64_store_lane0, aarch64_simd_vec_set,
> > @aarch64_simd_vec_copy_lane, vec_set,
> > reduc__scal_, reduc__scal_,
> > aarch64_reduc__internal,
> aarch64_get_lane,
> > vec_init, vec_extract): Support V2HF.
> > (aarch64_simd_dupv2hf): New.
> > * config/aarch64/aarch64.cc (aarch64_classify_vector_mode):
> > Add E_V2HFmode.
> > * config/aarch64/iterators.md (VHSDF_P): New.
> > (V2F, VMOVE, nunits, Vtype, Vmtype, Vetype, stype, VEL,
> > Vel, q, vp): Add V2HF.
> > * config/arm/types.md (neon_fp_reduc_add_h): New.
> >
> > gcc/testsuite/ChangeLog:
> >
> > * gcc.target/aarch64/sve/slp_1.c: Update testcase.
> >
> > --- inline copy of patch ---
> >
> > diff --git a/gcc/config/aarch64/aarch64-simd.md
> > b/gcc/config/aarch64/aarch64-simd.md
> > index
> >
> f4152160084d6b6f34bd69f0ba6386c1ab50f77e..487a31010245accec28e779661
> e6
> > c2d578fca4b7 100644
> > --- a/gcc/config/aarch64/aarch64-simd.md
> > +++ b/gcc/config/aarch64/aarch64-simd.md
> > @@ -19,10 +19,10 @@
> >  ;; .
> >
> >  (define_expand "mov"
> > -  [(set (match_operand:VALL_F16 0 "nonimmediate_operand")
> > -   (match_operand:VALL_F16 1 "general_operand"))]
> > +  [(set (match_operand:VMOVE 0 "nonimmediate_operand")
> > +   (match_operand:VMOVE 1 "general_operand"))]
> >"TARGET_SIMD"
> > -  "
> > +{
> >/* Force the operand into a register if it is not an
> >   immediate whose use can be replaced with xzr.
> >   If the mode is 16 bytes wide, then we will be doing @@ -46,12
> > +46,11 @@ (define_expand "mov"
> >aarch64_expand_vector_init (operands[0], operands[1]);
> >DONE;
> >  }
> > -  "
> > -)
> > +})
> >
> >  (define_expand "movmisalign"
> > -  [(set (match_operand:VALL_F16 0 "nonimmediate_operand")
> > -(match_operand:VALL_F16 1 "general_operand"))]
> > +  [(set (match_operand:VMOVE 0 "nonimmediate_operand")
> > +(match_operand:VMOVE 1 "general_operand"))]
> >"TARGET_SIMD && !STRICT_ALIGNMENT"
> >  {
> >/* This pattern is not permitted to fail during expansion: if both
> > arguments @@ -73,6 +72,16 @@ (define_insn
> "aarch64_simd_dup"
> >[(set_attr "type" "neon_dup, neon_from_gp")]
> >  )
> >
> > +(define_insn "aarch64_simd_dupv2hf"
> > +  [(set (match_operand:V2HF 0 "register_operand" "=w")
> > +   (vec_duplicate:V2HF
> > + (match_operand:HF 1 "register_operand" "0")))]
> 
> Seems like this should be "w" rather than "0", since SLI is a two-register
> instruction.

Yes, but for a dup it's only valid when the same register is used. i.e. it has 
to
write into the original src register.

Thanks,
Tamar

> 
> > +  "TARGET_SIMD"
> > +  "@
> > +   sli\\t%d0, %d1, 16"
> > +  [(set_attr "type" "neon_shift_imm")]
> > +)
> > +
> >  (define_insn "aarch64_simd_dup"
> >[(set (match_operand:VDQF_F16 0 "register_operand" "=w,w")
> > (vec_duplicate:VDQF_F16
> > @@ -85,10 +94,10 @@ (define_insn "aarch64_simd_dup"
> >  )
> >
> >  (define_insn "aarch64_dup_lane"
> > -  [(set (match_operand:VALL_F16 0 "register_operand" "=w")
> > -   (vec_duplicate:VALL_F16
> > +  [(set (match_operand:VMOVE 0 "register_operand" "=w")
> > +   (vec_duplicate:VMOVE
> >   (vec_select:
> > -   (match_operand:VALL_F16 1 "register_operand" "w")
> > +   (match_operand:VMOVE 1 "register_operand" "w")
> > (parallel [(match_operand:SI 2 "

Re: Rust front-end patches v4

2022-12-06 Thread Richard Biener via Gcc-patches
On Tue, Dec 6, 2022 at 11:11 AM  wrote:
>
> This patchset contains the fixed version of our most recent patchset. We
> have fixed most of the issues noted in the previous round of reviews, and are
> keeping some for later as they would otherwise create too many conflicts with
> our updated development branch.
>
> Similarly to the previous round of patches, this patchset does not contain any
> new features - only fixes for the reviews of the v3. New features will follow
> shortly once that first patchset is merged.
>
> Once again, thank you to all the contributors who made this possible and
> especially to Philip Herron for his dedication to the project.

Thanks a lot - this is OK to merge now, thanks for your patience and I'm
looking forward for the future improvements.

Thanks,
Richard.

> You can see the current status of our work on our branch:
> https://gcc.gnu.org/git/?p=gcc.git;a=shortlog;h=refs/heads/devel/rust/master
>
> Patch status table:
>
> An 'x' in the first column indicates a patch has been reviewed.
> One in the second column indicates that a patch has been approved.
>
> |0001-Use-DW_ATE_UTF-for-the-Rust-char-type.patch   |x|x|
> |0002-gccrs-Add-necessary-hooks-for-a-Rust-front-end-tests.patch|x|x|
> |0003-gccrs-Add-Debug-info-testsuite.patch  | | |
> |0004-gccrs-Add-link-cases-testsuite.patch  | | |
> |0005-gccrs-Add-general-compilation-test-cases.patch| | |
> |0006-gccrs-Add-execution-test-cases.patch  | | |
> |0007-gccrs-Add-gcc-check-target-check-rust.patch   |x| |
> |0008-gccrs-Add-Rust-front-end-base-AST-data-structures.patch   | | |
> |0009-gccrs-Add-definitions-of-Rust-Items-in-AST-data-stru.patch| | |
> |0010-gccrs-Add-full-definitions-of-Rust-AST-data-structur.patch| | |
> |0011-gccrs-Add-Rust-AST-visitors.patch | | |
> |0012-gccrs-Add-Lexer-for-Rust-front-end.patch  |x| |
> |0013-gccrs-Add-Parser-for-Rust-front-end-pt.1.patch| | |
> |0014-gccrs-Add-Parser-for-Rust-front-end-pt.2.patch| | |
> |0015-gccrs-Add-expansion-pass-for-the-Rust-front-end.patch | | |
> |0016-gccrs-Add-name-resolution-pass-to-the-Rust-front-end.patch| | |
> |0017-gccrs-Add-declarations-for-Rust-HIR.patch | | |
> |0018-gccrs-Add-HIR-definitions-and-visitor-framework.patch | | |
> |0019-gccrs-Add-AST-to-HIR-lowering-pass.patch  | | |
> |0020-gccrs-Add-wrapper-for-make_unique.patch   | | |
> |0021-gccrs-Add-port-of-FNV-hash-used-during-legacy-symbol.patch| | |
> |0022-gccrs-Add-Rust-ABI-enum-helpers.patch | | |
> |0023-gccrs-Add-Base62-implementation.patch | | |
> |0024-gccrs-Add-implementation-of-Optional.patch| | |
> |0025-gccrs-Add-attributes-checker.patch| | |
> |0026-gccrs-Add-helpers-mappings-canonical-path-and-lang-i.patch| | |
> |0027-gccrs-Add-type-resolution-and-trait-solving-pass.patch| | |
> |0028-gccrs-Add-Rust-type-information.patch | | |
> |0029-gccrs-Add-remaining-type-system-transformations.patch | | |
> |0030-gccrs-Add-unsafe-checks-for-Rust.patch| | |
> |0031-gccrs-Add-const-checker.patch | | |
> |0032-gccrs-Add-privacy-checks.patch| | |
> |0033-gccrs-Add-dead-code-scan-on-HIR.patch | | |
> |0034-gccrs-Add-unused-variable-scan.patch  | | |
> |0035-gccrs-Add-metadata-output-pass.patch  | | |
> |0036-gccrs-Add-base-for-HIR-to-GCC-GENERIC-lowering.patch  | | |
> |0037-gccrs-Add-HIR-to-GCC-GENERIC-lowering-for-all-nodes.patch |x|x|
> |0038-gccrs-Add-HIR-to-GCC-GENERIC-lowering-entry-point.patch   |x|x|
> |0039-gccrs-These-are-wrappers-ported-from-reusing-gccgo.patch  | | |
> |0040-gccrs-Add-GCC-Rust-front-end-Make-lang.in.patch   |x| |
> |0041-gccrs-Add-config-lang.in.patch|x|x|
> |0042-gccrs-Add-lang-spec.h.patch   | | |
> |0043-gccrs-Add-lang.opt.patch  |x| |
> |0044-gccrs-Add-compiler-driver.patch   | | |
> |0045-gccrs-Compiler-proper-interface-kicks-off-the-pipeli.patch| | |
> |0046-gccrs-Add-README-CONTRIBUTING-and-compiler-logo.patch | | |
>
> Patches 34 to 39 and 44 to 45 interact with common GCC APIs:
>
> 0034-gccrs-Add-unused-variable-scan.patch
> 0035-gccrs-Add-metadata-output-pass.patch
> 0036-gccrs-Add-base-for-HIR-to-GCC-GENERIC-lowering.patch
> 0037-gccrs-Add-HIR-to-GCC-GENERIC-lowering-for-all-nodes.patch
> 0038-gccrs-Add-HIR-to-GCC-GENERIC-lowering-entry-point.patch
> 0039-gccrs-These-are-wrappers-ported-from-reusing-gccgo.patch
> 0044-gccrs-Add-compiler-driver.patch
> 0045-gccrs-Compiler-proper-interface-kicks-off-the-pipeli.patch
>
> Patch 02 and 07 contain test infrastructure changes:
>
> 0002-gccrs-A

Re: [PATCH 5/8]AArch64 aarch64: Make existing V2HF be usable.

2022-12-06 Thread Richard Sandiford via Gcc-patches
Tamar Christina  writes:
>> -Original Message-
>> From: Richard Sandiford 
>> Sent: Tuesday, December 6, 2022 10:28 AM
>> To: Tamar Christina 
>> Cc: gcc-patches@gcc.gnu.org; nd ; Richard Earnshaw
>> ; Marcus Shawcroft
>> ; Kyrylo Tkachov 
>> Subject: Re: [PATCH 5/8]AArch64 aarch64: Make existing V2HF be usable.
>> 
>> Tamar Christina  writes:
>> > Hi,
>> >
>> >
>> >> This name might cause confusion with the SVE iterators, where FULL
>> >> means "every bit of the register is used".  How about something like
>> >> VMOVE instead?
>> >>
>> >> With this change, I guess VALL_F16 represents "The set of all modes
>> >> for which the vld1 intrinsics are provided" and VMOVE or whatever is
>> >> "All Advanced SIMD modes suitable for moving, loading, and storing".
>> >> That is, VMOVE extends VALL_F16 with modes that are not manifested
>> >> via intrinsics.
>> >>
>> >
>> > Done.
>> >
>> >> Where is the 2h used, and is it valid syntax in that context?
>> >>
>> >> Same for later instances of 2h.
>> >
>> > They are, but they weren't meant to be in this patch.  They belong in
>> > a separate FP16 series that I won't get to finish for GCC 13 due not
>> > being able to finish writing all the tests.  I have moved them to that 
>> > patch
>> series though.
>> >
>> > While the addp patch series has been killed, this patch is still good
>> > standalone and improves codegen as shown in the updated testcase.
>> >
>> > Bootstrapped Regtested on aarch64-none-linux-gnu and no issues.
>> >
>> > Ok for master?
>> >
>> > Thanks,
>> > Tamar
>> >
>> > gcc/ChangeLog:
>> >
>> >* config/aarch64/aarch64-simd.md (*aarch64_simd_movv2hf): New.
>> >(mov, movmisalign, aarch64_dup_lane,
>> >aarch64_store_lane0, aarch64_simd_vec_set,
>> >@aarch64_simd_vec_copy_lane, vec_set,
>> >reduc__scal_, reduc__scal_,
>> >aarch64_reduc__internal,
>> aarch64_get_lane,
>> >vec_init, vec_extract): Support V2HF.
>> >(aarch64_simd_dupv2hf): New.
>> >* config/aarch64/aarch64.cc (aarch64_classify_vector_mode):
>> >Add E_V2HFmode.
>> >* config/aarch64/iterators.md (VHSDF_P): New.
>> >(V2F, VMOVE, nunits, Vtype, Vmtype, Vetype, stype, VEL,
>> >Vel, q, vp): Add V2HF.
>> >* config/arm/types.md (neon_fp_reduc_add_h): New.
>> >
>> > gcc/testsuite/ChangeLog:
>> >
>> >* gcc.target/aarch64/sve/slp_1.c: Update testcase.
>> >
>> > --- inline copy of patch ---
>> >
>> > diff --git a/gcc/config/aarch64/aarch64-simd.md
>> > b/gcc/config/aarch64/aarch64-simd.md
>> > index
>> >
>> f4152160084d6b6f34bd69f0ba6386c1ab50f77e..487a31010245accec28e779661
>> e6
>> > c2d578fca4b7 100644
>> > --- a/gcc/config/aarch64/aarch64-simd.md
>> > +++ b/gcc/config/aarch64/aarch64-simd.md
>> > @@ -19,10 +19,10 @@
>> >  ;; .
>> >
>> >  (define_expand "mov"
>> > -  [(set (match_operand:VALL_F16 0 "nonimmediate_operand")
>> > -  (match_operand:VALL_F16 1 "general_operand"))]
>> > +  [(set (match_operand:VMOVE 0 "nonimmediate_operand")
>> > +  (match_operand:VMOVE 1 "general_operand"))]
>> >"TARGET_SIMD"
>> > -  "
>> > +{
>> >/* Force the operand into a register if it is not an
>> >   immediate whose use can be replaced with xzr.
>> >   If the mode is 16 bytes wide, then we will be doing @@ -46,12
>> > +46,11 @@ (define_expand "mov"
>> >aarch64_expand_vector_init (operands[0], operands[1]);
>> >DONE;
>> >  }
>> > -  "
>> > -)
>> > +})
>> >
>> >  (define_expand "movmisalign"
>> > -  [(set (match_operand:VALL_F16 0 "nonimmediate_operand")
>> > -(match_operand:VALL_F16 1 "general_operand"))]
>> > +  [(set (match_operand:VMOVE 0 "nonimmediate_operand")
>> > +(match_operand:VMOVE 1 "general_operand"))]
>> >"TARGET_SIMD && !STRICT_ALIGNMENT"
>> >  {
>> >/* This pattern is not permitted to fail during expansion: if both
>> > arguments @@ -73,6 +72,16 @@ (define_insn
>> "aarch64_simd_dup"
>> >[(set_attr "type" "neon_dup, neon_from_gp")]
>> >  )
>> >
>> > +(define_insn "aarch64_simd_dupv2hf"
>> > +  [(set (match_operand:V2HF 0 "register_operand" "=w")
>> > +  (vec_duplicate:V2HF
>> > +(match_operand:HF 1 "register_operand" "0")))]
>> 
>> Seems like this should be "w" rather than "0", since SLI is a two-register
>> instruction.
>
> Yes, but for a dup it's only valid when the same register is used. i.e. it 
> has to
> write into the original src register.

Ah, right.  In that case it might be better to use %d0 for the source
operand:

  For operands to match in a particular case usually means that they
  are identical-looking RTL expressions.  But in a few special cases
  specific kinds of dissimilarity are allowed.  For example, @code{*x}
  as an input operand will match @code{*x++} as an output operand.
  For proper results in such cases, the output template should always
  use the output-operand's number when printing the operand.

Thanks,
Richard


Re: Rust front-end patches v4

2022-12-06 Thread John Paul Adrian Glaubitz

On 12/6/22 12:03, Richard Biener via Gcc-rust wrote:

On Tue, Dec 6, 2022 at 11:11 AM  wrote:


This patchset contains the fixed version of our most recent patchset. We
have fixed most of the issues noted in the previous round of reviews, and are
keeping some for later as they would otherwise create too many conflicts with
our updated development branch.

Similarly to the previous round of patches, this patchset does not contain any
new features - only fixes for the reviews of the v3. New features will follow
shortly once that first patchset is merged.

Once again, thank you to all the contributors who made this possible and
especially to Philip Herron for his dedication to the project.


Thanks a lot - this is OK to merge now, thanks for your patience and I'm
looking forward for the future improvements.


Woohooo, finally. Congratulations to everyone involved in this massive effort
and thanks a lot for this huge step forward for the Rust community.

Can't wait to see this becoming available in the distributions :D.

I will make sure we get the frontend enabled in Debian as soon as possible.

Adrian

--
 .''`.  John Paul Adrian Glaubitz
: :' :  Debian Developer
`. `'   Physicist
  `-GPG: 62FF 8A75 84E0 2956 9546  0006 7426 3B37 F5B5 F913



Zen4 tuning part 2 - tuning flags

2022-12-06 Thread Jan Hubicka via Gcc-patches
Hi,
this patch adds tunes needed for zen4 microarchitecture.  I added two new knobs.
TARGET_AVX512_SPLIT_REGS which is used to specify that internally 512 vectors
are split to 256 vectors.  This affects vectorization costs and reassociation
width. It probably should also affect RTX costs however I doubt it is very 
useful
since RTL optimizers are usually not judging between 256 and 512 vectors.

I also added X86_TUNE_AVOID_256FMA_CHAINS. Since fma has improved in zen4 this
flag may not be a win except for very specific benchmarks. I am still doing some
more detailed testing here.

Oherwise I disabled gathers on zen4 for 2 parts nad 4 parts. We can open code 
them
and since the latencies has only increased since zen3 opencoding is better than 
actual instrucction.  This shows at 4 tsvc benchmarks.

I ended up setting AVX256_OPTIMAL. This is a compromise.  There are some tsvc
benchmarks that increase noticeably (up to 250%) however there are also few
regressions.  Most of these can be solved by incrasing vec_perm cost in the
vectorizer.  However this does not cure about 14% regression on x264 that is
quite important.  Here we produce vectorized loops for avx512 that probably
would be faster if the loops in question had high enough iteration count.
We hit this problem with avx256 too: since the loop iterates few times, only
prologues/epilogues are used.  Adding another round of prologue/epilogue
code does not make it better.

Finally I enabled avx stores for constnat sized memcpy and memset.  I am not
sure why this is an opt-in feature.  I think for most hardware this is a win.

Bootstrapped/regtested x86_64-linux.  I am waiting for final SPEC benchmarking
to finish and plan to commit the patch and do possible additional tuning
incrementally.

* config/i386/i386-expand.cc (ix86_expand_set_or_cpymem): Add
TARGET_AVX512_SPLIT_REGS
* config/i386/i386-options.cc (ix86_option_override_internal):
Honor x86_TONE_AVOID_256FMA_CHAINS.
* config/i386/i386.cc (ix86_vec_cost): Honor TARGET_AVX512_SPLIT_REGS.
(ix86_reassociation_width): Likewise.
* i386.h (TARGET_AVX512_SPLIT_REGS): New tune.
* x86-tune.def (X86_TUNE_GATHER_2PARTS, X86_TUNE_GATHER_4PARTS): Disable
for zen4.
(X86_TUNE_AVOID_256FMA_CHAINS): New; set for znver4.
(x86_TUNE_AVOID_512FMA_CHAINS): New tune; set for znver4.
(x86_TUNE_AVX256_MOVE_BY_PIECES): Add Zens 1-3.
(x86_TUNE_AVX256_STORE_BY_PIECES): Add Zens 1-3.
(x86_TUNE_AVX512_MOVE_BY_PIECES): Add Zen 4.
(x86_TUNE_AVX512_STORE_BY_PIECES): Add Zen 4.
diff --git a/gcc/config/i386/i386-expand.cc b/gcc/config/i386/i386-expand.cc
index b920cfbaf90..ae58619cd12 100644
--- a/gcc/config/i386/i386-expand.cc
+++ b/gcc/config/i386/i386-expand.cc
@@ -8660,6 +8660,8 @@ ix86_expand_set_or_cpymem (rtx dst, rtx src, rtx 
count_exp, rtx val_exp,
 
   if (TARGET_AVX256_SPLIT_REGS && GET_MODE_BITSIZE (move_mode) > 128)
move_mode = TImode;
+  if (TARGET_AVX512_SPLIT_REGS && GET_MODE_BITSIZE (move_mode) > 256)
+   move_mode = OImode;
 
   /* Find the corresponding vector mode with the same size as MOVE_MODE.
 MOVE_MODE is an integer mode at the moment (SI, DI, TI, etc.).  */
diff --git a/gcc/config/i386/i386-options.cc b/gcc/config/i386/i386-options.cc
index 44dcccb0a73..c188835b231 100644
--- a/gcc/config/i386/i386-options.cc
+++ b/gcc/config/i386/i386-options.cc
@@ -2980,6 +2980,8 @@ ix86_option_override_internal (bool main_args_p,
 }
 
   if (ix86_tune_features [X86_TUNE_AVOID_256FMA_CHAINS])
+SET_OPTION_IF_UNSET (opts, opts_set, param_avoid_fma_max_bits, 512);
+  else if (ix86_tune_features [X86_TUNE_AVOID_256FMA_CHAINS])
 SET_OPTION_IF_UNSET (opts, opts_set, param_avoid_fma_max_bits, 256);
   else if (ix86_tune_features [X86_TUNE_AVOID_128FMA_CHAINS])
 SET_OPTION_IF_UNSET (opts, opts_set, param_avoid_fma_max_bits, 128);
diff --git a/gcc/config/i386/i386.cc b/gcc/config/i386/i386.cc
index 95babd93c9d..8fa94cc9837 100644
--- a/gcc/config/i386/i386.cc
+++ b/gcc/config/i386/i386.cc
@@ -20363,10 +20363,13 @@ ix86_vec_cost (machine_mode mode, int cost)
 
   if (GET_MODE_BITSIZE (mode) == 128
   && TARGET_SSE_SPLIT_REGS)
-return cost * 2;
-  if (GET_MODE_BITSIZE (mode) > 128
+return cost * GET_MODE_BITSIZE (mode) / 64;
+  else if (GET_MODE_BITSIZE (mode) > 128
   && TARGET_AVX256_SPLIT_REGS)
 return cost * GET_MODE_BITSIZE (mode) / 128;
+  else if (GET_MODE_BITSIZE (mode) > 256
+  && TARGET_AVX512_SPLIT_REGS)
+return cost * GET_MODE_BITSIZE (mode) / 256;
   return cost;
 }
 
@@ -23090,7 +23093,9 @@ ix86_reassociation_width (unsigned int op, machine_mode 
mode)
return 1;
 
   /* Account for targets that splits wide vectors into multiple parts.  */
-  if (TARGET_AVX256_SPLIT_REGS && GET_MODE_BITSIZE (mode) > 128)
+  if (TARGET_AVX512_SPLIT_REGS && GET_MODE_BITSIZE (mode) > 256)
+   div = GET_MODE_BITSIZE (mode) / 

[PATCH] arm: Fix MVE's vcmp vector-scalar patterns [PR107987]

2022-12-06 Thread Andre Simoes Dias Vieira via Gcc-patches
Hi,

This patch surrounds the scalar operand of the MVE vcmp patterns with a
vec_duplicate to ensure both operands of the comparision operator have the same
(vector) mode.

Regression tested on arm-none-eabi. Is this OK for trunk? And a backport to GCC 
12?

gcc/ChangeLog:

PR target/107987
* config/arm/mve.md (mve_vcmpq_n_,
@mve_vcmpq_n_f): Apply vec_duplicate to scalar
operand.

gcc/testsuite/ChangeLog:

* gcc/testsuite/gcc.target/arm/mve/pr107987.c: New test.


pr107987.patch
Description: pr107987.patch


RE: [PATCH] arm: Fix MVE's vcmp vector-scalar patterns [PR107987]

2022-12-06 Thread Kyrylo Tkachov via Gcc-patches



> -Original Message-
> From: Andre Simoes Dias Vieira 
> Sent: Tuesday, December 6, 2022 11:19 AM
> To: 'gcc-patches@gcc.gnu.org' 
> Cc: Kyrylo Tkachov ; Richard Earnshaw
> 
> Subject: [PATCH] arm: Fix MVE's vcmp vector-scalar patterns [PR107987]
> 
> Hi,
> 
> This patch surrounds the scalar operand of the MVE vcmp patterns with a
> vec_duplicate to ensure both operands of the comparision operator have the
> same
> (vector) mode.
> 
> Regression tested on arm-none-eabi. Is this OK for trunk? And a backport to
> GCC 12?

Ok.
Thanks,
Kyrill

> 
> gcc/ChangeLog:
> 
>   PR target/107987
>   * config/arm/mve.md (mve_vcmpq_n_,
>   @mve_vcmpq_n_f): Apply vec_duplicate to
> scalar
>   operand.
> 
> gcc/testsuite/ChangeLog:
> 
>   * gcc/testsuite/gcc.target/arm/mve/pr107987.c: New test.



Re: Java front-end and library patches.

2022-12-06 Thread Zopolis0 via Gcc-patches
> Patches 1 and 2 don't seem to have reached the mailing list.

File size issues on the receiving server. I bzip3 compressed them, but
they were still too big.


Re: Zen4 tuning part 1 - cost tables

2022-12-06 Thread Jan Hubicka via Gcc-patches
> > -  COSTS_N_INSNS (5),   /* cost of FADD and FSUB insns.  */
> > -  COSTS_N_INSNS (5),   /* cost of FMUL instruction.  */
> > +  COSTS_N_INSNS (7),   /* cost of FADD and FSUB insns.  */
> > +  COSTS_N_INSNS (7),   /* cost of FMUL instruction.  */
> >/* Latency of fdiv is 8-15.  */
> >COSTS_N_INSNS (15),  /* cost of FDIV instruction.  */
> >COSTS_N_INSNS (1),   /* cost of FABS instruction.  */
> >COSTS_N_INSNS (1),   /* cost of FCHS instruction.  */
> >/* Latency of fsqrt is 4-10.  */
> 
> the above comment looks like it needs updating as well

You are right. I will go through the comments for all zen revisions
incrementally.  Many of them are outdated are still referes to znver1.

Honza


Re: [PATCH 2/3] Make __float128 use the _Float128 type, PR target/107299

2022-12-06 Thread Kewen.Lin via Gcc-patches
Hi Mike,

Thanks for fixing this, some comments are inlined below.

on 2022/11/2 10:42, Michael Meissner wrote:
> This patch fixes the issue that GCC cannot build when the default long double
> is IEEE 128-bit.  It fails in building libgcc, specifically when it is trying
> to buld the __mulkc3 function in libgcc.  It is failing in 
> gimple-range-fold.cc
> during the evrp pass.  Ultimately it is failing because the code declared the
> type to use TFmode but it used F128 functions (i.e. KFmode).
> 
>   typedef float TFtype __attribute__((mode (TF)));
>   typedef __complex float TCtype __attribute__((mode (TC)));
> 
>   TCtype
>   __mulkc3_sw (TFtype a, TFtype b, TFtype c, TFtype d)
>   {
> TFtype ac, bd, ad, bc, x, y;
> TCtype res;
> 
> ac = a * c;
> bd = b * d;
> ad = a * d;
> bc = b * c;
> 
> x = ac - bd;
> y = ad + bc;
> 
> if (__builtin_isnan (x) && __builtin_isnan (y))
>   {
> _Bool recalc = 0;
> if (__builtin_isinf (a) || __builtin_isinf (b))
>   {
> 
> a = __builtin_copysignf128 (__builtin_isinf (a) ? 1 : 0, a);
> b = __builtin_copysignf128 (__builtin_isinf (b) ? 1 : 0, b);
> if (__builtin_isnan (c))
>   c = __builtin_copysignf128 (0, c);
> if (__builtin_isnan (d))
>   d = __builtin_copysignf128 (0, d);
> recalc = 1;
>   }
> if (__builtin_isinf (c) || __builtin_isinf (d))
>   {
> 
> c = __builtin_copysignf128 (__builtin_isinf (c) ? 1 : 0, c);
> d = __builtin_copysignf128 (__builtin_isinf (d) ? 1 : 0, d);
> if (__builtin_isnan (a))
>   a = __builtin_copysignf128 (0, a);
> if (__builtin_isnan (b))
>   b = __builtin_copysignf128 (0, b);
> recalc = 1;
>   }
> if (!recalc
> && (__builtin_isinf (ac) || __builtin_isinf (bd)
> || __builtin_isinf (ad) || __builtin_isinf (bc)))
>   {
> 
> if (__builtin_isnan (a))
>   a = __builtin_copysignf128 (0, a);
> if (__builtin_isnan (b))
>   b = __builtin_copysignf128 (0, b);
> if (__builtin_isnan (c))
>   c = __builtin_copysignf128 (0, c);
> if (__builtin_isnan (d))
>   d = __builtin_copysignf128 (0, d);
> recalc = 1;
>   }
> if (recalc)
>   {
> x = __builtin_inff128 () * (a * c - b * d);
> y = __builtin_inff128 () * (a * d + b * c);
>   }
>   }
> 
> __real__ res = x;
> __imag__ res = y;
> return res;
>   }
> 

One further reduced test case can be:

typedef float TFtype __attribute__((mode (TF)));

TFtype test (TFtype t)
{
  return __builtin_copysignf128 (1.0q, t);
}

Since this reduced test case is quite small, maybe it's good to make it as one
test case associated with this patch.

> Currently GCC uses the long double type node for __float128 if long double is
> IEEE 128-bit.  It did not use the node for _Float128.
> 
> Originally this was noticed if you call the nansq function to make a signaling
> NaN (nansq is mapped to nansf128).  Because the type node for _Float128 is
> different from __float128, the machine independent code converts signaling 
> NaNs
> to quiet NaNs if the types are not compatible.  The following tests used to
> fail when run on a system where long double is IEEE 128-bit:
> 
>   gcc.dg/torture/float128-nan.c
>   gcc.target/powerpc/nan128-1.c
> 
> This patch makes both __float128 and _Float128 use the same type node.
> 
> One side effect of not using the long double type node for __float128 is that 
> we
> must only use KFmode for _Float128/__float128.  The libstdc++ library won't
> build if we use TFmode for _Float128 and __float128 when long double is IEEE
> 128-bit.
> 

Sorry that I didn't get the point of the latter sentence, this proposed patch
uses KFmode for _Float128 and __float128, do you mean that would be fine for
libstdc++ library building since we don't use TFmode for them?

> Another minor side effect is that the f128 round to odd fused multiply-add
> function will not merge negatition with the FMA operation when the type is 
> long
> double.  If the type is __float128 or _Float128, then it will continue to do 
> the
> optimization.  The round to odd functions are defined in terms of __float128
> arguments.  For example:
> 
>   long double
>   do_fms (long double a, long double b, long double c)
>   {
>   return __builtin_fmaf128_round_to_odd (a, b, -c);
>   }
> 
> will generate (assuming -mabi=ieeelongdouble):
> 
>   xsnegqp 4,4
>   xsmaddqpo 4,2,3
>   xxlor 34,36,36
> 
> w

Re: [GCC][PATCH v2] arm: Add pacbti related multilib support for armv8.1-m.main.

2022-12-06 Thread Srinath Parvathaneni via Gcc-patches
Ping!!

From: Gcc-patches 
 on behalf of 
Srinath Parvathaneni via Gcc-patches 
Sent: 31 October 2022 15:36
To: gcc-patches@gcc.gnu.org 
Cc: Richard Earnshaw 
Subject: [GCC][PATCH v2] arm: Add pacbti related multilib support for 
armv8.1-m.main.

Hi,

This patch adds the support for pacbti multlilib linking by making
"-mbranch-protection=none" as default in the command line for all M-profile
targets and uses "-mbranch-protection=none" for multilib matching. If any
valid value is passed to "-mbranch-protection" in the command line, this
new value overwrites the default value in the command line and uses
"-mbranch-protection=standard" for multilib matching.

Eg 1.

If the passed command line flags are:
a) -march=armv8.1-m.main+mve -mfloat-abi=hard -mfpu=auto
b) -mcpu=cortex-m85+nopacbti -mfloat-abi=hard -mfpu=auto

After this patch the command line flags the compiler receives will be:
a) -march=armv8.1-m.main+mve -mfloat-abi=hard -mfpu=auto 
-mbranch-protection=none
b) -mcpu=cortex-m85+nopacbti -mfloat-abi=hard -mfpu=auto 
-mbranch-protection=none

"-mbranch-protection=none" will be used in the multilib matching.

Eg 2.

If the passed command line flags are:
a) -march=armv8.1-m.main+mve+pacbti -mfloat-abi=hard -mfpu=auto  
-mbranch-protection=pac-ret
b) -mcpu=cortex-m85 -mfloat-abi=hard -mfpu=auto  -mbranch-protection=pac-ret+bti

After this patch the command line flags the compiler receives will be:
a) -march=armv8.1-m.main+mve+pacbti -mfloat-abi=hard -mfpu=auto 
-mbranch-protection=pac-ret
b) -mcpu=cortex-m85 -mfloat-abi=hard -mfpu=auto -mbranch-protection=pac-ret+bti

"-mbranch-protection=standard" will be used in the multilib matching.

Eg 3.

For A-profile target, if the passed command line flags are:
-march=armv8-a+simd -mfloat-abi=hard -mfpu=auto

Even after this patch the command line flags compiler receives will remain the 
same:
-march=armv8-a+simd -mfloat-abi=hard -mfpu=auto

Regression tested on arm-none-eabi and bootstrapped on arm-none-linux-gnueabihf.

Ok for master?

Regards,
Srinath.

gcc/ChangeLog:

2022-10-28  Srinath Parvathaneni  

* common/config/arm/arm-common.cc
(arm_canon_branch_protection_option): Define new function.
* config/arm/arm-cpus.in (armv8.1-m.main): Move dsp option below pacbti
option.
* config/arm/arm.h (arm_canon_branch_protection_option): Define function
prototype.
(CANON_BRANCH_PROTECTION_SPEC_FUNCTION): Define macro.
(MBRANCH_PROTECTION_SPECS): Likewise.
* config/arm/t-rmprofile (MULTI_ARCH_OPTS_RM): Add new options.
(MULTI_ARCH_DIRS_RM): Add new directories.
(MULTILIB_REQUIRED): Add new option.
(MULTILIB_REUSE): Reuse existing multlibs.
(MULTILIB_MATCHES): Match multilib strings.

gcc/testsuite/ChangeLog:

2022-10-28  Srinath Parvathaneni  

* gcc.target/arm/multilib.exp (multilib_config "rmprofile"): Update
tests.
* gcc.target/arm/pac-10.c: New test.
* gcc.target/arm/pac-11.c: Likewise.
* gcc.target/arm/pac-12.c: Likewise.


Re: [GCC][PATCH v2] arm: Add cde feature support for Cortex-M55 CPU.

2022-12-06 Thread Srinath Parvathaneni via Gcc-patches
Ping!!

From: Srinath Parvathaneni
Sent: 31 October 2022 12:38
To: gcc-patches@gcc.gnu.org 
Cc: Richard Earnshaw ; Christophe Lyon 

Subject: RE: [GCC][PATCH v2] arm: Add cde feature support for Cortex-M55 CPU.

Hi,

> -Original Message-
> From: Christophe Lyon 
> Sent: Monday, October 17, 2022 2:30 PM
> To: Srinath Parvathaneni ; gcc-
> patc...@gcc.gnu.org
> Cc: Richard Earnshaw 
> Subject: Re: [GCC][PATCH] arm: Add cde feature support for Cortex-M55
> CPU.
>
> Hi Srinath,
>
>
> On 10/10/22 10:20, Srinath Parvathaneni via Gcc-patches wrote:
> > Hi,
> >
> > This patch adds cde feature (optional) support for Cortex-M55 CPU,
> > please refer [1] for more details. To use this feature we need to
> > specify +cdecpN (e.g. -mcpu=cortex-m55+cdecp), where N is the
> coprocessor number 0 to 7.
> >
> > Bootstrapped for arm-none-linux-gnueabihf target, regression tested on
> > arm-none-eabi target and found no regressions.
> >
> > [1] https://developer.arm.com/documentation/101051/0101/?lang=en
> (version: r1p1).
> >
> > Ok for master?
> >
> > Regards,
> > Srinath.
> >
> > gcc/ChangeLog:
> >
> > 2022-10-07  Srinath Parvathaneni  
> >
> >  * common/config/arm/arm-common.cc (arm_canon_arch_option_1):
> Ignore cde
> >  options for mlibarch.
> >  * config/arm/arm-cpus.in (begin cpu cortex-m55): Add cde options.
> >  * doc/invoke.texi (CDE): Document options for Cortex-M55 CPU.
> >
> > gcc/testsuite/ChangeLog:
> >
> > 2022-10-07  Srinath Parvathaneni  
> >
> >  * gcc.target/arm/multilib.exp: Add multilib tests for Cortex-M55 
> > CPU.
> >
> >
> > ### Attachment also inlined for ease of reply
> ###
> >
> >
> > diff --git a/gcc/common/config/arm/arm-common.cc
> > b/gcc/common/config/arm/arm-common.cc
> > index
> >
> c38812f1ea6a690cd19b0dc74d963c4f5ae155ca..b6f955b3c012475f398382e72
> c9a
> > 3966412991ec 100644
> > --- a/gcc/common/config/arm/arm-common.cc
> > +++ b/gcc/common/config/arm/arm-common.cc
> > @@ -753,6 +753,15 @@ arm_canon_arch_option_1 (int argc, const char
> **argv, bool arch_for_multilib)
> > arm_initialize_isa (target_isa, selected_cpu->common.isa_bits);
> > arm_parse_option_features (target_isa, &selected_cpu->common,
> >   strchr (cpu, '+'));
> > +  if (arch_for_multilib)
> > +   {
> > + const enum isa_feature removable_bits[] =
> {ISA_IGNORE_FOR_MULTILIB,
> > +isa_nobit};
> > + sbitmap isa_bits = sbitmap_alloc (isa_num_bits);
> > + arm_initialize_isa (isa_bits, removable_bits);
> > + bitmap_and_compl (target_isa, target_isa, isa_bits);
> > +   }
> > +
>
> I can see the piece of code you add here is exactly the same as the one a few
> lines above when handling "if (arch)". Can this be moved below and thus be
> common to the two cases, or does it have to be performed before
> bitmap_ior of fpu_isa?

Thanks for pointing out this, I have moved the common code below the arch and 
cpu
if blocks in the attached patch.

> Also, IIUC, CDE was already optional for other CPUs (M33, M35P, star-mc1),
> so the hunk above fixes a latent bug when handling multilibs for these CPUs
> too? If so, maybe worth splitting the patch into two parts since the above is
> not strictly related to M55?
>
Even though CDE is optional for the mentioned CPUs as per the specs, the code to
enable CDE as optional feature is missing in current compiler.
Current GCC compiler supports CDE as optional feature only with -march options 
and
this pass adds CDE as optional for M55 and so this is not a fix bug.

> But I'm not a maintainer ;-)
>
> Thanks,
>
> Christophe
>
> > if (fpu && strcmp (fpu, "auto") != 0)
> >  {
> >/* The easiest and safest way to remove the default fpu diff
> > --git a/gcc/config/arm/arm-cpus.in b/gcc/config/arm/arm-cpus.in index
> >
> 5a63bc548e54dbfdce5d1df425bd615d81895d80..aa02c04c4924662f3ddd58e
> 69673
> > 92ba3f4b4a87 100644
> > --- a/gcc/config/arm/arm-cpus.in
> > +++ b/gcc/config/arm/arm-cpus.in
> > @@ -1633,6 +1633,14 @@ begin cpu cortex-m55
> >option nomve remove mve mve_float
> >option nofp remove ALL_FP mve_float
> >option nodsp remove MVE mve_float
> > + option cdecp0 add cdecp0
> > + option cdecp1 add cdecp1
> > + option cdecp2 add cdecp2
> > + option cdecp3 add cdecp3
> > + option cdecp4 add cdecp4
> > + option cdecp5 add cdecp5
> > + option cdecp6 add cdecp6
> > + option cdecp7 add cdecp7
> >isa quirk_no_asmcpu quirk_vlldm
> >costs v7m
> >vendor 41
> > diff --git a/gcc/doc/invoke.texi b/gcc/doc/invoke.texi index
> >
> aa5655764a0360959f9c1061749d2cc9ebd23489..26857f7a90e42d925bc69086
> 86ac
> > 78138a53c4ad 100644
> > --- a/gcc/doc/invoke.texi
> > +++ b/gcc/doc/invoke.texi
> > @@ -21698,6 +21698,10 @@ floating-point instructions on @samp{cortex-
> m55}.
> >   Disable the M-Profile Vector Extension (MVE) single precision floating-
> point
> >   inst

Re: [GCC][PATCH 13/15, v4] arm: Add support for dwarf debug directives and pseudo hard-register for PAC feature.

2022-12-06 Thread Srinath Parvathaneni via Gcc-patches
Ping!!

From: Gcc-patches 
 on behalf of 
Srinath Parvathaneni via Gcc-patches 
Sent: 09 November 2022 14:32
To: gcc-patches@gcc.gnu.org 
Cc: Richard Earnshaw ; Kyrylo Tkachov 

Subject: [GCC][PATCH 13/15, v4] arm: Add support for dwarf debug directives and 
pseudo hard-register for PAC feature.

Hello,

This patch teaches the DWARF support in gcc about RA_AUTH_CODE pseudo 
hard-register and also
updates the ".save", ".cfi_register", ".cfi_offset", ".cfi_restore" directives 
accordingly.
This patch also adds support to emit ".pacspval" directive when "pac ip, lr, 
sp" instruction
in generated in the assembly.

RA_AUTH_CODE register number is 107 and it's dwarf register number is 143.

Applying this patch on top of PACBTI series posted here
https://gcc.gnu.org/pipermail/gcc-patches/2022-August/599658.html and when 
compiling the following
test.c with "-march=armv8.1-m.main+mve+pacbti -mbranch-protection=pac-ret 
-mthumb -mfloat-abi=hard
fasynchronous-unwind-tables -g -O0 -S" command line options, the assembly 
output after this patch
looks like below:

$cat test.c

void fun1(int a);
void fun(int a,...)
{
  fun1(a);
}

int main()
{
  fun (10);
  return 0;
}

$ arm-none-eabi-gcc -march=armv8.1-m.main+mve+pacbti 
-mbranch-protection=pac-ret -mthumb -mfloat-abi=hard
-fasynchronous-unwind-tables -g -O0 -S test.s

Assembly output:
...
fun:
...
.pacspval
pac ip, lr, sp
.cfi_register 143, 12
push{r3, r7, ip, lr}
.save {r3, r7, ra_auth_code, lr}
...
.cfi_offset 143, -24
...
.cfi_restore 143
...
aut ip, lr, sp
bx  lr
...
main:
...
.pacspval
pac ip, lr, sp
.cfi_register 143, 12
push{r3, r7, ip, lr}
.save {r3, r7, ra_auth_code, lr}
...
.cfi_offset 143, -8
...
.cfi_restore 143
...
aut ip, lr, sp
bx  lr
...

Regression tested on arm-none-eabi target and found no regressions.

Ok for master?

Regards,
Srinath.

gcc/testsuite/ChangeLog:

2022-11-04  Srinath Parvathaneni  

* g++.target/arm/pac-1.C: New test.
* gcc.target/arm/pac-9.c: New test.


2022-11-04  Srinath Parvathaneni  

* config/arm/aout.h (ra_auth_code): Add entry in enum.
* config/arm/arm.cc (pac_emit): Declare new global boolean variable.
(emit_multi_reg_push): Add RA_AUTH_CODE register to
dwarf frame expression.
(arm_emit_multi_reg_pop): Restore RA_AUTH_CODE register.
(arm_expand_prologue): Update frame related infomration and reg notes
for pac/pacbit insn.
(arm_regno_class): Check for pac pseudo reigster.
(arm_dbx_register_number): Assign ra_auth_code register number in dwarf.
(arm_unwind_emit_sequence): Print .save directive with ra_auth_code
register.
(arm_unwind_emit_set): Add entry for IP_REGNUM in switch case.
(arm_unwind_emit): Update REG_CFA_REGISTER case._
(arm_conditional_register_usage): Mark ra_auth_code in fixed reigsters.
* config/arm/arm.h (FIRST_PSEUDO_REGISTER): Modify.
(IS_PAC_PSEUDO_REGNUM): Define.
(enum reg_class): Add PAC_REG entry.
* config/arm/arm.md (RA_AUTH_CODE): Define.

gcc/testsuite/ChangeLog:

2022-11-04  Srinath Parvathaneni  

* g++.target/arm/pac-1.C: New test.
* gcc.target/arm/pac-9.c: Likewise.


### Attachment also inlined for ease of reply###


diff --git a/gcc/config/arm/aout.h b/gcc/config/arm/aout.h
index 
b918ad3782fbee82320febb8b6e72ad615780261..ffeed45a678f17c63d5b42c21f020ca416cbf23f
 100644
--- a/gcc/config/arm/aout.h
+++ b/gcc/config/arm/aout.h
@@ -74,7 +74,8 @@
   "wr8",   "wr9",   "wr10",  "wr11",   \
   "wr12",  "wr13",  "wr14",  "wr15",   \
   "wcgr0", "wcgr1", "wcgr2", "wcgr3",  \
-  "cc", "vfpcc", "sfp", "afp", "apsrq", "apsrge", "p0" \
+  "cc", "vfpcc", "sfp", "afp", "apsrq", "apsrge", "p0",\
+  "ra_auth_code"   \
 }
 #endif

diff --git a/gcc/config/arm/arm.h b/gcc/config/arm/arm.h
index 
a2dc3fc145c52d8381c54634687376089a47e704..91c400f12568156ed29bf5d5e59460bf887fbefb
 100644
--- a/gcc/config/arm/arm.h
+++ b/gcc/config/arm/arm.h
@@ -820,7 +820,8 @@ extern const int arm_arch_cde_coproc_bits[];
 s16-s31   S  VFP variable (aka d8-d15).
 vfpcc   Not a real register.  Represents the VFP condition
 code flags.
-   vpr Used to represent MVE VPR predication.  */
+   vpr Used to represent MVE VPR predication.
+   ra_auth_codePseudo register to save PAC.  */

 /* The stack backtrace structure is as follows:
   fp points to here:  |  save code pointer  |  [fp]
@@ -861,7 +862,7 @@ extern const int arm_arch_cde_coproc_bits[];
   1,1,1,1,1,1,1,1, \
   1,1,1,1,  

Re: Rust front-end patches v4

2022-12-06 Thread Arthur Cohen



On 12/6/22 12:09, John Paul Adrian Glaubitz wrote:

On 12/6/22 12:03, Richard Biener via Gcc-rust wrote:

On Tue, Dec 6, 2022 at 11:11 AM  wrote:


This patchset contains the fixed version of our most recent patchset. We
have fixed most of the issues noted in the previous round of reviews, 
and are
keeping some for later as they would otherwise create too many 
conflicts with

our updated development branch.

Similarly to the previous round of patches, this patchset does not 
contain any
new features - only fixes for the reviews of the v3. New features 
will follow

shortly once that first patchset is merged.

Once again, thank you to all the contributors who made this possible and
especially to Philip Herron for his dedication to the project.


Thanks a lot - this is OK to merge now, thanks for your patience and I'm
looking forward for the future improvements.


Woohooo, finally. Congratulations to everyone involved in this massive 
effort

and thanks a lot for this huge step forward for the Rust community.


Thank you!



Can't wait to see this becoming available in the distributions :D.

I will make sure we get the frontend enabled in Debian as soon as possible.


Haha, I appreciate the enthusiasm :) Please note however that despite 
the language being in, the compiler is still at an extremely early 
stage. We are still not able to properly compile Rust code in the 
version that we target, 1.49.


To do anything meaningful with the language, you will also need the core 
library, which again, we cannot compile yet in its 1.49 version.


This is very much an extremely experimental compiler and will still get 
a lot of changes in the coming weeks and months up until the release.




Adrian



--
Arthur Cohen 

Toolchain Engineer

Embecosm GmbH

Geschäftsführer: Jeremy Bennett
Niederlassung: Nürnberg
Handelsregister: HR-B 36368
www.embecosm.de

Fürther Str. 27
90429 Nürnberg


Tel.: 091 - 128 707 040
Fax: 091 - 128 707 077


OpenPGP_0x1B3465B044AD9C65.asc
Description: OpenPGP public key


OpenPGP_signature
Description: OpenPGP digital signature


Re: Rust front-end patches v4

2022-12-06 Thread Iain Buclaw via Gcc-patches
Excerpts from Richard Biener via Gcc-patches's message of Dezember 6, 2022 
12:03 pm:
> On Tue, Dec 6, 2022 at 11:11 AM  wrote:
>>
>> This patchset contains the fixed version of our most recent patchset. We
>> have fixed most of the issues noted in the previous round of reviews, and are
>> keeping some for later as they would otherwise create too many conflicts with
>> our updated development branch.
>>
>> Similarly to the previous round of patches, this patchset does not contain 
>> any
>> new features - only fixes for the reviews of the v3. New features will follow
>> shortly once that first patchset is merged.
>>
>> Once again, thank you to all the contributors who made this possible and
>> especially to Philip Herron for his dedication to the project.
> 
> Thanks a lot - this is OK to merge now, thanks for your patience and I'm
> looking forward for the future improvements.
> 
> Thanks,
> Richard.
> 

Finally! Some competition. :-)

Don't feel any pressure, and reach out if you ever need any guidance.

All the best.

Iain.


Re: Rust front-end patches v4

2022-12-06 Thread John Paul Adrian Glaubitz

On 12/6/22 12:40, Arthur Cohen wrote:

Can't wait to see this becoming available in the distributions :D.

I will make sure we get the frontend enabled in Debian as soon as possible.


Haha, I appreciate the enthusiasm :) Please note however that despite the 
language
being in, the compiler is still at an extremely early stage. We are still not 
able
to properly compile Rust code in the version that we target, 1.49.


Don't worry, I'm fully aware of that. However, I still consider the inclusion 
of gccrs
into the main gcc code a major step forward as it means the code is exposed to 
a much
broader audience which means it will see more testing.

Since Matthias Klose is regularly uploading gcc snapshots to Debian unstable, 
the gccrs
will be compiled and testrun on more than 20 architectures ;-).

And I will report back every issue that is discovered this way.


To do anything meaningful with the language, you will also need the core 
library,
which again, we cannot compile yet in its 1.49 version.


No worries.


This is very much an extremely experimental compiler and will still get a lot 
of changes
in the coming weeks and months up until the release.


And I'm looking forward to that.

Again, thanks everyone for this fantastic effort!

Adrian

--
 .''`.  John Paul Adrian Glaubitz
: :' :  Debian Developer
`. `'   Physicist
  `-GPG: 62FF 8A75 84E0 2956 9546  0006 7426 3B37 F5B5 F913



Re: [PATCH] libgcc: Fix uninitialized RA signing on AArch64 [PR107678]

2022-12-06 Thread Wilco Dijkstra via Gcc-patches
Hi,

> i don't think how[*RA_STATE] can ever be set to REG_SAVED_OFFSET,
> this pseudo reg is not spilled to the stack, it is reset to 0 in
> each frame and then toggled within a frame.

It's is just a state, we can use any state we want since it is a pseudo reg.
These registers are global and shared across all functions in an unwind,
so their state or value isn't reset for each frame. So if we want to reset
it in each frame then using a virtual register to hold per-function data
seems like a bad design. I'm surprised nobody has ever tested it...

Cheers,
Wilco

Re: [PATCH 14/56] middle-end: Set TREE_ADDRESSABLE in folding debug stmts.

2022-12-06 Thread Zopolis0 via Gcc-patches
New plan-- this patch is entirely pointless! I have reverted it in a
local build and had no regressions.

As such, simply do not review or consider this patch. I am not not
planning on re-sending the patchset even though it adjusts the patch
numbers because it is such an arduous process given that gmail no
longer supports git send-email.


Re: [PATCH] Add a new conversion for conditional ternary set into ifcvt [PR106536]

2022-12-06 Thread Segher Boessenkool
Hi!

On Thu, Nov 24, 2022 at 11:24:15AM +0100, Richard Biener wrote:
> On Thu, Nov 24, 2022 at 8:25 AM HAO CHEN GUI  wrote:
> > 在 2022/11/24 4:06, Richard Biener 写道:
> > > Wouldn't we usually either add an optab or try to recog a canonical
> > > RTL form instead of adding a new target hook for things like this?
> >
> > Thanks so much for your comments. Please let me make it clear.
> >
> > Do you mean we should create an optab for "setb" pattern (the nested
> > if-then-else insn) and detect candidate insns in ifcvt pass? Then
> > generate the insn with the new optab?
> 
> Yes, that would be one way to do it.  Another way would be to
> generate a (to be defined) canonical form of such instruction and
> see whether it can be recognized (whether there's a define_insn
> for it).

But these insns are most useful when they come up "naturally", so we
really have to recognise many formulations of it separately.

The machine insn  setb x,BF  returns:
  { -1,  if BF.0 is set
  { 1,   if BF.1 is set
  { 0,   otherwise
This "otherwise" includes when a floating point comparison returned
"unordered" (BF.3, set if an operand was NaN), and BF.2 ("equal").  If
the comparison was only three-way (integer or fast-math) it is natural
to test for equality first (given we always have exactly one of the
first three BF bits set in that case!)

> Note that were just things that came into my mind here, I'm not too
> familiar with how we handle such situations but at least I'm not
> aware of dozens of target hooks to handle instruction availability.

In similar cases I never could up with anything that worked better than
recognising all possible patterns, unfortunately.  We can do a predicate
for that though, there is no need to write it out all over the place :-)


Segher


[committed] onlinedocs: Add documentation links to gdc

2022-12-06 Thread Iain Buclaw via Gcc-patches
Hi,

Now that the D front-end documentation has been generated and pushed to
the site after r13-4421, this can be added to the main index page.

This is a simple copy from other entries, so have gone ahead and
committed it.

Regards,
Iain.

---
 htdocs/onlinedocs/index.html | 6 ++
 1 file changed, 6 insertions(+)

diff --git a/htdocs/onlinedocs/index.html b/htdocs/onlinedocs/index.html
index c5787f32..343ff9f5 100644
--- a/htdocs/onlinedocs/index.html
+++ b/htdocs/onlinedocs/index.html
@@ -1641,6 +1641,12 @@ existing release.
href="https://gcc.gnu.org/onlinedocs/gccgo.ps.gz";>PostScript or 
https://gcc.gnu.org/onlinedocs/gccgo-html.tar.gz";>an
HTML tarball)
+https://gcc.gnu.org/onlinedocs/gdc/";>GNU D Manual (https://gcc.gnu.org/onlinedocs/gdc.pdf";>also in
+   PDF or https://gcc.gnu.org/onlinedocs/gdc.ps.gz";>PostScript or https://gcc.gnu.org/onlinedocs/gdc-html.tar.gz";>an
+   HTML tarball)
 https://gcc.gnu.org/onlinedocs/libgomp/";>GNU Offloading and
Multi Processing Runtime Library Manual (https://gcc.gnu.org/onlinedocs/libgomp.pdf";>also in
-- 
2.37.2



Re: Rust front-end patches v4

2022-12-06 Thread Mark Wielaard
Hi John,

On Tue, Dec 06, 2022 at 12:57:17PM +0100, John Paul Adrian Glaubitz wrote:
> On 12/6/22 12:40, Arthur Cohen wrote:
> > > Can't wait to see this becoming available in the distributions :D.
> > > 
> > > I will make sure we get the frontend enabled in Debian as soon as 
> > > possible.
> > 
> > Haha, I appreciate the enthusiasm :) Please note however that despite the 
> > language
> > being in, the compiler is still at an extremely early stage. We are still 
> > not able
> > to properly compile Rust code in the version that we target, 1.49.
> 
> Don't worry, I'm fully aware of that. However, I still consider the inclusion 
> of gccrs
> into the main gcc code a major step forward as it means the code is exposed 
> to a much
> broader audience which means it will see more testing.
> 
> Since Matthias Klose is regularly uploading gcc snapshots to Debian unstable, 
> the gccrs
> will be compiled and testrun on more than 20 architectures ;-).
> 
> And I will report back every issue that is discovered this way.

That is highly appreciated. But again, do be warned that at the moment
the testsuite is only green for i386, x86_64 and arm64:
https://builder.sourceware.org/buildbot/#/builders?tags=gccrust&tags=gccrust-bootstrap
ppc64, ppc64le and s390x still have some testsuite failures.

That is with the "upstream", unmerged frontend code though. Once the
code lands in the gcc git repo we should think about switching the
buildbot to that.

Cheers,

Mark


Re: [committed] onlinedocs: Add documentation links to gdc

2022-12-06 Thread Gerald Pfeifer
On Tue, 6 Dec 2022, Iain Buclaw wrote:
> Now that the D front-end documentation has been generated and pushed to
> the site after r13-4421, this can be added to the main index page.
> 
> This is a simple copy from other entries, so have gone ahead and
> committed it.

Cool, thank you. And sorry, I applied the change on the gcc.gnu.org 
system and then missed droping you a note once it successfully ran 
the first time.

With your web page patch, are we complete now? Or is anything missing?

Gerald


[PATCH RFA] build: add -Wconditionally-supported to strict_warn [PR64867]

2022-12-06 Thread Jason Merrill via Gcc-patches
Tested x86_64-pc-linux-gnu, OK for trunk?

-- 8< --

The PR (which isn't resolved by this commit) pointed out to me that GCC
should build with -Wconditionally-supported to support bootstrapping with a
C++11 compiler that makes different choices.

PR c++/64867

gcc/ChangeLog:

* configure.ac (strict_warn): Add -Wconditionally-supported.
* configure: Regenerate.
---
 gcc/configure.ac | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/gcc/configure.ac b/gcc/configure.ac
index 7ca08726efa..12771fc292c 100644
--- a/gcc/configure.ac
+++ b/gcc/configure.ac
@@ -580,7 +580,7 @@ ACX_PROG_CC_WARNING_OPTS(
m4_quote(m4_do([-Wstrict-prototypes -Wmissing-prototypes ],
   [])), [c_loose_warn])
 ACX_PROG_CXX_WARNING_OPTS(
-   m4_quote(m4_do([-Wmissing-format-attribute ],
+   m4_quote(m4_do([-Wmissing-format-attribute ], 
[-Wconditionally-supported ],
   [-Woverloaded-virtual])), [strict_warn])
 ACX_PROG_CC_WARNING_OPTS(
m4_quote(m4_do([-Wold-style-definition -Wc++-compat])), [c_strict_warn])

base-commit: d19aa6af6634b1e97f38431ad091f3b3f12baf2f
-- 
2.31.1



[COMMITTED] ada: Add Codepeer Exemption + simplify TO_C code.

2022-12-06 Thread Marc Poulhiès via Gcc-patches
From: Liaiss Merzougue 

This patch simplify the TO_C code to have a single branch for
raising exception. Furthermore, adding pragma annotate for codepeer
to ignore uninitialized value since this is caused because we have
input check before the initialization.

gcc/ada/

* libgnat/i-c.adb (To_C): Simplify code for having a single
exception raise. Add pragma annotate about uninitialized value
which happen only on exception raising.

Tested on x86_64-pc-linux-gnu, committed on master.

---
 gcc/ada/libgnat/i-c.adb | 15 ++-
 1 file changed, 6 insertions(+), 9 deletions(-)

diff --git a/gcc/ada/libgnat/i-c.adb b/gcc/ada/libgnat/i-c.adb
index 4b50d18a5a1..28660219b6e 100644
--- a/gcc/ada/libgnat/i-c.adb
+++ b/gcc/ada/libgnat/i-c.adb
@@ -186,7 +186,7 @@ is
  (Item : char_array;
   Trim_Nul : Boolean := True) return String
is
-  Count : Natural;
+  Count : Natural := 0;
   From  : size_t;
 
begin
@@ -1177,7 +1177,7 @@ is
   To : size_t;
 
begin
-  if Target'Length < Item'Length then
+  if Target'Length < Item'Length + (if Append_Nul then 1 else 0) then
  raise Constraint_Error;
 
   else
@@ -1210,17 +1210,14 @@ is
  Target'First + (Item'Length - 1))'Initialized);
 
  if Append_Nul then
-if To > Target'Last then
-   raise Constraint_Error;
-else
-   Target (To) := char32_nul;
-   Count := Item'Length + 1;
-end if;
-
+Target (To) := char32_nul;
+Count := Item'Length + 1;
  else
 Count := Item'Length;
  end if;
   end if;
end To_C;
+   pragma Annotate (CodePeer, False_Positive, "validity check",
+ "Count is only uninitialized on abnormal return.");
 
 end Interfaces.C;
-- 
2.34.1



[COMMITTED] ada: Use larger type for membership test of universal value

2022-12-06 Thread Marc Poulhiès via Gcc-patches
From: Eric Botcazou 

When a membership test is applied to a nonstatic expression of a universal
type, for example an attribute whose type is universal_integer and whose
prefix is not static, the operation is performed using the tested type that
is determined by the choice list.  In particular, a check that the value of
the expression lies in the range of the tested type may be generated before
the test is actually performed.

This goes against the spirit of membership tests, which are typically used
to guard a specific operation and ought not to fail a check in doing so.

Therefore the resolution of the operands of membership tests is changed in
this case to use the universal type instead of the tested type. The final
computation of the type used to actually perform the test is left to the
expander, which already has the appropriate circuitry.

This nevertheless requires fixing an irregularity in the expansion of the
subtype_mark form of membership tests, which was dependent on the presence
of predicates for the subtype; the confusing name of a routine used by this
expansion is also changed in the process.

gcc/ada/

* exp_ch4.adb (Expand_N_In) : Rename to...
: ...this.
Use Is_Entity_Name to test for the presence of entity references.
Do not warn or substitute a valid test for a test with a mark for
a subtype that is predicated.
Apply the same transformation for a test with a mark for a subtype
that is predicated as for a subtype that is not.
Remove useless return statement.
* sem_res.adb (Resolve_Membership_Op): Perform a special resolution
if the left operand is of a universal numeric type.

Tested on x86_64-pc-linux-gnu, committed on master.

---
 gcc/ada/exp_ch4.adb | 93 +
 gcc/ada/sem_res.adb | 46 ++
 2 files changed, 106 insertions(+), 33 deletions(-)

diff --git a/gcc/ada/exp_ch4.adb b/gcc/ada/exp_ch4.adb
index 00d19e765a6..7edef4c39c3 100644
--- a/gcc/ada/exp_ch4.adb
+++ b/gcc/ada/exp_ch4.adb
@@ -6454,15 +6454,15 @@ package body Exp_Ch4 is
   Rop: constant Node_Id:= Right_Opnd (N);
   Static : constant Boolean:= Is_OK_Static_Expression (N);
 
-  procedure Substitute_Valid_Check;
+  procedure Substitute_Valid_Test;
   --  Replaces node N by Lop'Valid. This is done when we have an explicit
   --  test for the left operand being in range of its subtype.
 
-  
-  -- Substitute_Valid_Check --
-  
+  ---
+  -- Substitute_Valid_Test --
+  ---
 
-  procedure Substitute_Valid_Check is
+  procedure Substitute_Valid_Test is
  function Is_OK_Object_Reference (Nod : Node_Id) return Boolean;
  --  Determine whether arbitrary node Nod denotes a source object that
  --  may safely act as prefix of attribute 'Valid.
@@ -6502,7 +6502,7 @@ package body Exp_Ch4 is
 return False;
  end Is_OK_Object_Reference;
 
-  --  Start of processing for Substitute_Valid_Check
+  --  Start of processing for Substitute_Valid_Test
 
   begin
  Rewrite (N,
@@ -6526,7 +6526,7 @@ package body Exp_Ch4 is
 Error_Msg_N -- CODEFIX
   ("\??use ''Valid attribute instead", N);
  end if;
-  end Substitute_Valid_Check;
+  end Substitute_Valid_Test;
 
   --  Local variables
 
@@ -6579,7 +6579,7 @@ package body Exp_Ch4 is
 --  eliminates the cases where MINIMIZED/ELIMINATED mode overflow
 --  checks have changed the type of the left operand.
 
-and then Nkind (Rop) in N_Has_Entity
+and then Is_Entity_Name (Rop)
 and then Ltyp = Entity (Rop)
 
 --  Skip this for predicated types, where such expressions are a
@@ -6587,7 +6587,7 @@ package body Exp_Ch4 is
 
 and then No (Predicate_Function (Ltyp))
   then
- Substitute_Valid_Check;
+ Substitute_Valid_Test;
  return;
   end if;
 
@@ -6605,26 +6605,42 @@ package body Exp_Ch4 is
 Lo : constant Node_Id := Low_Bound (Rop);
 Hi : constant Node_Id := High_Bound (Rop);
 
-Lo_Orig : constant Node_Id := Original_Node (Lo);
-Hi_Orig : constant Node_Id := Original_Node (Hi);
-
-Lcheck : Compare_Result;
-Ucheck : Compare_Result;
+Lo_Orig  : constant Node_Id := Original_Node (Lo);
+Hi_Orig  : constant Node_Id := Original_Node (Hi);
+Rop_Orig : constant Node_Id := Original_Node (Rop);
+
+Comes_From_Simple_Range_In_Source : constant Boolean :=
+  Comes_From_Source (N)
+and then not
+  (Is_Entity_Name (Rop_Orig)
+and then Is_Type (Entity (Rop_Orig))
+and then Present (Predicate_Function (Entity (Rop_Orig;
+

[COMMITTED] ada: Spurious error on nested call using the prefix notation

2022-12-06 Thread Marc Poulhiès via Gcc-patches
From: Javier Miranda 

gcc/ada/

* exp_ch6.adb
(Build_Static_Check_Helper_Call): Perform implicit type conversion
to ensure matching types and avoid reporting spurious errors.

Tested on x86_64-pc-linux-gnu, committed on master.

---
 gcc/ada/exp_ch6.adb | 7 ---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/gcc/ada/exp_ch6.adb b/gcc/ada/exp_ch6.adb
index 7555bf5dcf5..c026b63fcf6 100644
--- a/gcc/ada/exp_ch6.adb
+++ b/gcc/ada/exp_ch6.adb
@@ -7552,9 +7552,10 @@ package body Exp_Ch6 is
 
 Remove_Side_Effects (A);
 
-if Is_Controlling_Actual (A)
-  and then Etype (F) /= Etype (A)
-then
+--  Ensure matching types to avoid reporting spurious errors since
+--  the called helper may have been built for a parent type.
+
+if Etype (F) /= Etype (A) then
Append_To (Actuals,
  Unchecked_Convert_To (Etype (F), New_Copy_Tree (A)));
 else
-- 
2.34.1



[COMMITTED] ada: Elide the copy in extended returns for nonlimited by-reference types

2022-12-06 Thread Marc Poulhiès via Gcc-patches
From: Eric Botcazou 

This implements elision of the copy operation for extended return statements
in the case of nonlimited by-reference types (the copy operation is already
elided for limited types by the front-end and nonlimited non-by-reference
types by the code generator), which comprise controlled and tagged types.

The implementation partly reuses the machinery implemented for limited types
(the build-in-place machinery) to allocate the return object directly on the
primary or the secondary stack, depending on whether the result type of the
function is constrained or not.

This requires further special-casing for the allocators generated by this
machinery as well as an adjustment to the implementation of a specific case
of string concatenation.

gcc/ada/

* einfo.ads (Actual_Subtype): Document additional usage.
* exp_aggr.adb (Expand_Array_Aggregate): Replace test on
Is_Build_In_Place_Return_Object with Is_Special_Return_Object.
* exp_ch3.adb (Expand_N_Object_Declaration): Factor out parts of the
processing done for build-in-place return objects and reuse them to
implement a similar processing for specific return objects.
* exp_ch4.adb (Expand_Allocator_Expression): Do not generate a tag
assignment or an adjustment if the allocator was made for a special
return object.
(Expand_Concatenate): If the result is allocated on the secondary
stack, use an unconstrained allocation.
* exp_ch6.ads (Apply_CW_Accessibility_Check): New declaration.
(Is_By_Reference_Return_Object): Likewise.
(Is_Secondary_Stack_Return_Object): Likewise.
(Is_Special_Return_Object): Likewise.
* exp_ch6.adb (Expand_Ctrl_Function_Call): Do not bail out for the
expression in the declaration of a special return object.
(Expand_N_Extended_Return_Statement): Add missing guard and move
the class-wide accessibility check to Expand_N_Object_Declaration.
(Expand_Simple_Function_Return): Delete obsolete commentary.
Skip the special processing for types that require finalization or
are returned on the secondary stack if the return originally comes
from an extended return statement.  Add missing Constant_Present.
(Is_By_Reference_Return_Object): New predicate.
(Is_Secondary_Stack_Return_Object): Likewise.
(Is_Special_Return_Object): Likewise.
* exp_util.adb (Is_Related_To_Func_Return): Also return true if the
parent of the expression is the renaming declaration generated for
the expansion of a return object.
* gen_il-fields.ads (Opt_Field_Enum): Replace Alloc_For_BIP_Return
with For_Special_Return_Object.
* gen_il-gen-gen_nodes.adb (N_Allocator): Likewise.
* gen_il-internals.adb (Image): Remove Alloc_For_BIP_Return.
* sem_ch3.adb (Check_Return_Subtype_Indication): New procedure
moved from sem_ch6.adb.
(Analyze_Object_Declaration): Call it on a return object.
* sem_ch4.adb: Add with and use clauses for Rtsfind.
(Analyze_Allocator): Test For_Special_Return_Object to skip checks
for allocators made for special return objects.
Do not report restriction violations for the return stack pool.
* sem_ch5.adb (Analyze_Assignment.Set_Assignment_Type): Return the
Actual_Subtype for return objects that live on the secondary stack.
* sem_ch6.adb (Check_Return_Subtype_Indication): Move procedure to
sem_ch3.adb.
(Analyze_Function_Return): Do not call above procedure.
* sem_res.adb (Resolve_Allocator): Replace Alloc_For_BIP_Return
with For_Special_Return_Object.
* sinfo.ads: Likewise.
* treepr.adb (Image): Remove Alloc_For_BIP_Return.
* gcc-interface/trans.cc (gnat_to_gnu): Do not convert to the result
type in the unconstrained array type case if the parent is a simple
return statement.

Tested on x86_64-pc-linux-gnu, committed on master.

---
 gcc/ada/einfo.ads|   8 +-
 gcc/ada/exp_aggr.adb |   2 +-
 gcc/ada/exp_ch3.adb  | 468 +++
 gcc/ada/exp_ch4.adb  | 126 +
 gcc/ada/exp_ch6.adb  | 101 ---
 gcc/ada/exp_ch6.ads  |  27 +-
 gcc/ada/exp_util.adb |   6 +-
 gcc/ada/gcc-interface/trans.cc   |  12 +-
 gcc/ada/gen_il-fields.ads|   2 +-
 gcc/ada/gen_il-gen-gen_nodes.adb |   2 +-
 gcc/ada/gen_il-internals.adb |   2 -
 gcc/ada/sem_ch3.adb  | 139 +
 gcc/ada/sem_ch4.adb  |  64 ++---
 gcc/ada/sem_ch5.adb  |   6 +-
 gcc/ada/sem_ch6.adb  | 135 -
 gcc/ada/sem_res.adb  |   2 +-
 gcc/ada/sinfo.ads|  10 +-
 gcc/ada/treepr.adb   |   5 +-
 18 files changed, 706 insertions(+), 411 deletions(-)

diff --git a/gcc/ada/einfo.ads b/gcc/ada/

[COMMITTED] ada: Small adjustment to special resolution of membership test

2022-12-06 Thread Marc Poulhiès via Gcc-patches
From: Eric Botcazou 

It's needed because, in GNAT, universal_integer does not cover all the
values of all the supported integer types.

gcc/ada/

* sem_res.adb (Resolve_Membership_Op): Adjust latest change.

Tested on x86_64-pc-linux-gnu, committed on master.

---
 gcc/ada/sem_res.adb | 18 +++---
 1 file changed, 11 insertions(+), 7 deletions(-)

diff --git a/gcc/ada/sem_res.adb b/gcc/ada/sem_res.adb
index 3574afd19ac..4bbec65d6a0 100644
--- a/gcc/ada/sem_res.adb
+++ b/gcc/ada/sem_res.adb
@@ -10105,11 +10105,11 @@ package body Sem_Res is
   then
  T := Etype (R);
 
-  --  If the left operand is of a universal numeric type and the right
-  --  operand is not, we do not resolve the operands to the tested type
-  --  but to the universal type instead. If not conforming to the letter,
-  --  it's conforming to the spirit of the specification of membership
-  --  tests, which are typically used to guard a specific operation and
+  --  If the type of the left operand is universal_integer and that of the
+  --  right operand is smaller, then we do not resolve the operands to the
+  --  tested type but to universal_integer instead. If not conforming to
+  --  the letter, it's conforming to the spirit of the specification of
+  --  membership tests, which are typically used to guard an operation and
   --  ought not to fail a check in doing so. Without this, in the case of
 
   --type Small_Length is range 1 .. 16;
@@ -10122,10 +10122,14 @@ package body Sem_Res is
   --   the function Is_Small_String would fail a range check for strings
   --   larger than 127 characters.
 
+  --  The test on the size is required in GNAT because universal_integer
+  --  does not cover all the values of all the supported integer types,
+  --  for example the large values of Long_Long_Long_Unsigned.
+
   elsif not Is_Overloaded (L)
-and then Is_Universal_Numeric_Type (Etype (L))
+and then Etype (L) = Universal_Integer
 and then (Is_Overloaded (R)
-   or else not Is_Universal_Numeric_Type (Etype (R)))
+   or else RM_Size (Etype (R)) < RM_Size (Universal_Integer))
   then
  T := Etype (L);
 
-- 
2.34.1



[COMMITTED] ada: Suppress warning for specific constant valid condition

2022-12-06 Thread Marc Poulhiès via Gcc-patches
From: Eric Botcazou 

Like in Exp_Ch4, we do not want to give warnings in Sem_Warn on a membership
test with a mark for a subtype that is predicated.

gcc/ada/

* sem_warn.adb (Warn_On_Constant_Valid_Condition): Bail out for a
membership test with a mark for a subtype that is predicated.

Tested on x86_64-pc-linux-gnu, committed on master.

---
 gcc/ada/sem_warn.adb | 40 +++-
 1 file changed, 39 insertions(+), 1 deletion(-)

diff --git a/gcc/ada/sem_warn.adb b/gcc/ada/sem_warn.adb
index 1311916f19c..cb2a3819df6 100644
--- a/gcc/ada/sem_warn.adb
+++ b/gcc/ada/sem_warn.adb
@@ -3290,6 +3290,44 @@ package body Sem_Warn is
   Left  : constant Node_Id := Left_Opnd  (Op);
   Right : constant Node_Id := Right_Opnd (Op);
 
+  function Comes_From_Simple_Condition_In_Source
+(Op : Node_Id) return Boolean;
+  --  Return True if Op comes from a simple condition present in the source
+
+  ---
+  -- Comes_From_Simple_Condition_In_Source --
+  ---
+
+  function Comes_From_Simple_Condition_In_Source
+(Op : Node_Id) return Boolean
+  is
+ Orig_Op : constant Node_Id := Original_Node (Op);
+
+  begin
+ if not Comes_From_Source (Orig_Op) then
+return False;
+ end if;
+
+ --  We do not want to give warnings on a membership test with a mark
+ --  for a subtype that is predicated, see also Exp_Ch4.Expand_N_In.
+
+ if Nkind (Orig_Op) = N_In then
+declare
+   Orig_Rop : constant Node_Id :=
+Original_Node (Right_Opnd (Orig_Op));
+begin
+   if Is_Entity_Name (Orig_Rop)
+ and then Is_Type (Entity (Orig_Rop))
+ and then Present (Predicate_Function (Entity (Orig_Rop)))
+   then
+  return False;
+   end if;
+end;
+ end if;
+
+ return True;
+  end Comes_From_Simple_Condition_In_Source;
+
   True_Result  : Boolean;
   False_Result : Boolean;
 
@@ -3298,7 +3336,7 @@ package body Sem_Warn is
   --  scalar operands are valid.
 
   if Constant_Condition_Warnings
-and then Comes_From_Source (Original_Node (Op))
+and then Comes_From_Simple_Condition_In_Source (Op)
 and then Is_Scalar_Type (Etype (Left))
 and then Is_Scalar_Type (Etype (Right))
 
-- 
2.34.1



[COMMITTED] ada: Fix spurious error in checking of SPARK elaboration

2022-12-06 Thread Marc Poulhiès via Gcc-patches
From: Eric Botcazou 

The problem is that the computation of early call regions skips freeze nodes
but scenarios involving procedures declared as actions of these freeze nodes
are taken into account.  As a consequence if a subprogram body, typically of
an expression function, is placed just after a freeze node, its early call
region depends on whether the construct just before the freeze node can be
preelaborated or not; in other words, the legality of calls made from the
actions of this freeze node to the subprogram depends on what happens ahead
of the freeze node, which may be totally unrelated to the situation.

This change disables the ABE diagnostics in this case, as is done in a few
other similar cases leading to bogus errors too.

gcc/ada/

* sem_elab.adb (Processing_In_State): Add Within_Freezing_Actions
component.
(Process_Conditional_ABE_Call): Compute its value.
(Process_Conditional_ABE_Call_SPARK): For a call and a target in
the main unit, do not emit any ABE diagnostics if the call occurs
in a freezing actions context.

Tested on x86_64-pc-linux-gnu, committed on master.

---
 gcc/ada/sem_elab.adb | 24 +++-
 1 file changed, 23 insertions(+), 1 deletion(-)

diff --git a/gcc/ada/sem_elab.adb b/gcc/ada/sem_elab.adb
index a1e8f1ef30b..9bf8614fd52 100644
--- a/gcc/ada/sem_elab.adb
+++ b/gcc/ada/sem_elab.adb
@@ -881,6 +881,10 @@ package body Sem_Elab is
   --  The subprogram body traversal mode. Once set, this value should not
   --  be changed.
 
+  Within_Freezing_Actions : Boolean := False;
+  --  This flag is set when the Processing phase is currently examining a
+  --  scenario which was reached from the actions of a freeze node.
+
   Within_Generic : Boolean := False;
   --  This flag is set when the Processing phase is currently within a
   --  generic unit.
@@ -5353,6 +5357,7 @@ package body Sem_Elab is
  Subp_Id   : constant Entity_Id := Target (Call_Rep);
  Subp_Rep  : constant Target_Rep_Id :=
Target_Representation_Of (Subp_Id, In_State);
+ Body_Decl : constant Node_Id   := Body_Declaration (Subp_Rep);
  Subp_Decl : constant Node_Id   := Spec_Declaration (Subp_Rep);
 
  SPARK_Rules_On : constant Boolean :=
@@ -5452,6 +5457,16 @@ package body Sem_Elab is
  or else not Elaboration_Warnings_OK (Call_Rep)
  or else not Elaboration_Warnings_OK (Subp_Rep);
 
+ --  The call occurs in freezing actions context when a prior scenario
+ --  is already in that mode, or when the target is a subprogram whose
+ --  body has been generated as a freezing action. Update the state of
+ --  the Processing phase to reflect this.
+
+ New_In_State.Within_Freezing_Actions :=
+   New_In_State.Within_Freezing_Actions
+ or else (Present (Body_Decl)
+   and then Nkind (Parent (Body_Decl)) = N_Freeze_Entity);
+
  --  The call occurs in an initial condition context when a prior
  --  scenario is already in that mode, or when the target is an
  --  Initial_Condition procedure. Update the state of the Processing
@@ -5502,7 +5517,7 @@ package body Sem_Elab is
 In_State => New_In_State);
 
  Traverse_Conditional_ABE_Body
-   (N=> Body_Declaration (Subp_Rep),
+   (N=> Body_Decl,
 In_State => New_In_State);
   end Process_Conditional_ABE_Call;
 
@@ -5721,6 +5736,13 @@ package body Sem_Elab is
 if In_State.Suppress_Warnings then
null;
 
+--  Do not emit any ABE diagnostics when the call occurs in a
+--  freezing actions context because this leads to incorrect
+--  diagnostics.
+
+elsif In_State.Within_Freezing_Actions then
+   null;
+
 --  Do not emit any ABE diagnostics when the call occurs in an
 --  initial condition context because this leads to incorrect
 --  diagnostics.
-- 
2.34.1



[COMMITTED] ada: Allow No_Caching on volatile types

2022-12-06 Thread Marc Poulhiès via Gcc-patches
From: Yannick Moy 

SPARK RM now allow the property No_Caching on volatile types, to
indicate that they should be considered volatile for compilation, but
not by GNATprove's analysis.

gcc/ada/

* contracts.adb (Add_Contract_Item): Allow No_Caching on types.
(Check_Type_Or_Object_External_Properties): Check No_Caching.
Check that non-effectively volatile types does not contain an
effectively volatile component (instead of just a volatile
component).
(Analyze_Object_Contract): Remove shared checking of No_Caching.
* sem_prag.adb (Analyze_External_Property_In_Decl_Part): Adapt checking
of No_Caching for types.
(Analyze_Pragma): Allow No_Caching on types.
* sem_util.adb (Has_Effectively_Volatile_Component): New query function.
(Is_Effectively_Volatile): Type with Volatile and No_Caching is not
effectively volatile.
(No_Caching_Enabled): Remove assertion to apply to all entities.
* sem_util.ads: Same.

Tested on x86_64-pc-linux-gnu, committed on master.

---
 gcc/ada/contracts.adb | 32 ++--
 gcc/ada/sem_prag.adb  | 49 +++
 gcc/ada/sem_util.adb  | 37 +---
 gcc/ada/sem_util.ads  | 11 +++---
 4 files changed, 84 insertions(+), 45 deletions(-)

diff --git a/gcc/ada/contracts.adb b/gcc/ada/contracts.adb
index 6f474eb2944..59121ca9ea2 100644
--- a/gcc/ada/contracts.adb
+++ b/gcc/ada/contracts.adb
@@ -316,6 +316,7 @@ package body Contracts is
 | Name_Async_Writers
 | Name_Effective_Reads
 | Name_Effective_Writes
+| Name_No_Caching
   or else (Ekind (Id) = E_Task_Type
  and Prag_Nam in Name_Part_Of
| Name_Depends
@@ -859,6 +860,7 @@ package body Contracts is
   AW_Val  : Boolean := False;
   ER_Val  : Boolean := False;
   EW_Val  : Boolean := False;
+  NC_Val  : Boolean;
   Seen: Boolean := False;
   Prag: Node_Id;
   Obj_Typ : Entity_Id;
@@ -956,18 +958,25 @@ package body Contracts is
   end if;
 
   --  Verify the mutual interaction of the various external properties.
-  --  For variables for which No_Caching is enabled, it has been checked
-  --  already that only False values for other external properties are
-  --  allowed.
+  --  For types and variables for which No_Caching is enabled, it has been
+  --  checked already that only False values for other external properties
+  --  are allowed.
 
   if Seen
-and then (Ekind (Type_Or_Obj_Id) /= E_Variable
-   or else not No_Caching_Enabled (Type_Or_Obj_Id))
+and then not No_Caching_Enabled (Type_Or_Obj_Id)
   then
  Check_External_Properties
(Type_Or_Obj_Id, AR_Val, AW_Val, ER_Val, EW_Val);
   end if;
 
+  --  Analyze the non-external volatility property No_Caching
+
+  Prag := Get_Pragma (Type_Or_Obj_Id, Pragma_No_Caching);
+
+  if Present (Prag) then
+ Analyze_External_Property_In_Decl_Part (Prag, NC_Val);
+  end if;
+
   --  The following checks are relevant only when SPARK_Mode is on, as
   --  they are not standard Ada legality rules. Internally generated
   --  temporaries are ignored, as well as return objects.
@@ -1047,10 +1056,10 @@ package body Contracts is
 
 if Is_Type_Id
   and then not Is_Effectively_Volatile (Type_Or_Obj_Id)
-  and then Has_Volatile_Component (Type_Or_Obj_Id)
+  and then Has_Effectively_Volatile_Component (Type_Or_Obj_Id)
 then
Error_Msg_N
- ("non-volatile type & cannot have volatile"
+ ("non-volatile type & cannot have effectively volatile"
 & " components",
   Type_Or_Obj_Id);
 end if;
@@ -1076,7 +1085,6 @@ package body Contracts is
   Saved_SMP : constant Node_Id := SPARK_Mode_Pragma;
   --  Save the SPARK_Mode-related data to restore on exit
 
-  NC_Val   : Boolean;
   Items: Node_Id;
   Prag : Node_Id;
   Ref_Elmt : Elmt_Id;
@@ -1118,14 +1126,6 @@ package body Contracts is
 
   Check_Type_Or_Object_External_Properties (Type_Or_Obj_Id => Obj_Id);
 
-  --  Analyze the non-external volatility property No_Caching
-
-  Prag := Get_Pragma (Obj_Id, Pragma_No_Caching);
-
-  if Present (Prag) then
- Analyze_External_Property_In_Decl_Part (Prag, NC_Val);
-  end if;
-
   --  Constant-related checks
 
   if Ekind (Obj_Id) = E_Constant then
diff --git a/gcc/ada/sem_prag.adb b/gcc/ada/sem_prag.adb
index 27bd879903e..f3c23caeae4 100644
--- a/gcc/ada/sem_prag.adb
+++ b/gcc/ada/sem_prag.adb
@@ -2116,9 +2116,16 @@ package body Sem_Prag is
First (Pragma_Argument_A

[PATCH v3 6/19] modula2 front end: libgm2/libm2min contents

2022-12-06 Thread Gaius Mulley via Gcc-patches
 

This patch set consists of the makefiles, autoconf and a few C sources
to build the libgm2/libm2min libraries.

 
--8<--8<--8<--8<--8<--8< 
diff -ruw /dev/null gcc-git-devel-modula2/libgm2/libm2min/Makefile.am
--- /dev/null   2022-08-24 16:22:16.88870 +0100
+++ gcc-git-devel-modula2/libgm2/libm2min/Makefile.am   2022-12-06 
02:56:51.432775922 +
@@ -0,0 +1,147 @@
+# Makefile for libm2min.
+#   Copyright 2013-2022  Free Software Foundation, Inc.
+#
+# This file is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; see the file COPYING3.  If not see
+# .
+
+SUFFIXES = .c .mod .def .o .obj .lo .a .la
+
+ACLOCAL_AMFLAGS = -I . -I .. -I ../config
+
+VPATH = . @srcdir@/../../gcc/m2/gm2-libs-min
+
+# Multilib support.
+MAKEOVERRIDES=
+
+version := $(shell $(CC) -dumpversion)
+
+# Directory in which the compiler finds libraries etc.
+libsubdir = $(libdir)/gcc/$(target_alias)/$(version)
+# Used to install the shared libgcc.
+slibdir = @slibdir@
+
+toolexeclibdir=@toolexeclibdir@
+toolexecdir=@toolexecdir@
+GM2_FOR_TARGET=@GM2_FOR_TARGET@
+
+MULTIDIR := $(shell $(CC) $(CFLAGS) -print-multi-directory)
+MULTIOSDIR := $(shell $(CC) $(CFLAGS) -print-multi-os-directory)
+
+MULTIOSSUBDIR := $(shell if test x$(MULTIOSDIR) != x.; then echo 
/$(MULTIOSDIR); fi)
+inst_libdir = $(libsubdir)$(MULTISUBDIR)
+inst_slibdir = $(slibdir)$(MULTIOSSUBDIR)
+
+
+# Work around what appears to be a GNU make bug handling MAKEFLAGS
+# values defined in terms of make variables, as is the case for CC and
+# friends when we are called from the top level Makefile.
+AM_MAKEFLAGS = \
+"GCC_DIR=$(GCC_DIR)" \
+"GM2_SRC=$(GM2_SRC)" \
+   "AR_FLAGS=$(AR_FLAGS)" \
+   "CC_FOR_BUILD=$(CC_FOR_BUILD)" \
+   "CC_FOR_TARGET=$(CC_FOR_TARGET)" \
+   "GM2_FOR_TARGET=$(GM2_FOR_TARGET)" \
+   "CFLAGS=$(CFLAGS)" \
+   "CXXFLAGS=$(CXXFLAGS)" \
+   "CFLAGS_FOR_BUILD=$(CFLAGS_FOR_BUILD)" \
+   "CFLAGS_FOR_TARGET=$(CFLAGS_FOR_TARGET)" \
+   "INSTALL=$(INSTALL)" \
+   "INSTALL_DATA=$(INSTALL_DATA)" \
+   "INSTALL_PROGRAM=$(INSTALL_PROGRAM)" \
+   "INSTALL_SCRIPT=$(INSTALL_SCRIPT)" \
+   "LDFLAGS=$(LDFLAGS)" \
+   "LIBCFLAGS=$(LIBCFLAGS)" \
+   "LIBCFLAGS_FOR_TARGET=$(LIBCFLAGS_FOR_TARGET)" \
+   "MAKE=$(MAKE)" \
+   "MAKEINFO=$(MAKEINFO) $(MAKEINFOFLAGS)" \
+"MULTISUBDIR=$(MULTISUBDIR)" \
+"MULTIOSDIR=$(MULTIOSDIR)" \
+"MULTIBUILDTOP=$(MULTIBUILDTOP)" \
+"MULTIFLAGS=$(MULTIFLAGS)" \
+   "PICFLAG=$(PICFLAG)" \
+   "PICFLAG_FOR_TARGET=$(PICFLAG_FOR_TARGET)" \
+   "SHELL=$(SHELL)" \
+   "RUNTESTFLAGS=$(RUNTESTFLAGS)" \
+   "exec_prefix=$(exec_prefix)" \
+   "infodir=$(infodir)" \
+   "libdir=$(libdir)" \
+   "includedir=$(includedir)" \
+   "prefix=$(prefix)" \
+   "tooldir=$(tooldir)" \
+   "AR=$(AR)" \
+   "AS=$(AS)" \
+   "LD=$(LD)" \
+   "RANLIB=$(RANLIB)" \
+   "NM=$(NM)" \
+   "NM_FOR_BUILD=$(NM_FOR_BUILD)" \
+   "NM_FOR_TARGET=$(NM_FOR_TARGET)" \
+   "DESTDIR=$(DESTDIR)" \
+   "WERROR=$(WERROR)" \
+"TARGET_LIB_PATH_libgm2=$(TARGET_LIB_PATH_libgm2)"
+
+# Subdir rules rely on $(FLAGS_TO_PASS)
+FLAGS_TO_PASS = $(AM_MAKEFLAGS)
+
+M2DEFS = libc.def  M2RTS.def \
+ SYSTEM.def
+
+M2MODS = M2RTS.mod  SYSTEM.mod
+
+libm2mindir = libm2min
+toolexeclib_LTLIBRARIES = libm2min.la
+libm2min_la_SOURCES = $(M2MODS) libc.c
+libm2min_la_DEPENDENCIES = SYSTEM.def $(addsuffix .lo, $(basename 
$(libm2min_la_SOURCES)))
+libm2min_la_CFLAGS = -I. -I$(GM2_SRC)/gm2-libs-min -I$(GM2_SRC)/gm2-libs
+libm2min_la_M2FLAGS = -I. -I$(GM2_SRC)/gm2-libs-min -I$(GM2_SRC)/gm2-libs 
-fno-exceptions \
+   -fno-m2-plugin -fno-scaffold-dynamic -fno-scaffold-main
+libm2min_la_LINK = $(LINK) -version-info $(libtool_VERSION)
+BUILT_SOURCES = SYSTEM.def
+CLEANFILES = SYSTEM.def
+
+M2LIBDIR = /m2/m2min/
+
+.mod.lo:
+   $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile 
$(GM2_FOR_TARGET) -c $(CFLAGS_FOR_TARGET) $(LIBCFLAGS) $(libm2min_la_M2FLAGS) 
$< -o $@
+
+libc.o: $(GM2_SRC)/gm2-libs-min/libc.c
+
+
+SYSTEM.def: Makefile
+   echo "CC = $(CC_FOR_BUILD)  CC_FOR_TARGET = $(CC_FOR_TARGET)  GM2 = 
$(GM2)  GM2_FOR_TARGET = $(GM2_FOR_TARGET) GM2_FOR_BUILD = $(GM2_FOR_BUILD)"
+   bash $(GM2_SRC)/tools-src/makeSystem -fpim \
+ $(GM2_SRC)/gm2-libs-min/SYSTEM.def \
+

[PATCH v3 7/19] modula2 front end: libgm2/libm2log contents

2022-12-06 Thread Gaius Mulley via Gcc-patches
 

This patch set consists of the makefiles, autoconf sources necessary
to build the various libgm2 libraries.  The c/c++/h files are included
in the patch set.  The modula-2 sources are found in gcc/m2.

 
--8<--8<--8<--8<--8<--8< 
diff -ruw /dev/null gcc-git-devel-modula2/libgm2/libm2log/Break.c
--- /dev/null   2022-08-24 16:22:16.88870 +0100
+++ gcc-git-devel-modula2/libgm2/libm2log/Break.c   2022-12-06 
02:56:51.432775922 +
@@ -0,0 +1,134 @@
+/* Break.c implements an interrupt handler for SIGINT.
+
+Copyright (C) 2004-2022 Free Software Foundation, Inc.
+Contributed by Gaius Mulley .
+
+This file is part of GNU Modula-2.
+
+GNU Modula-2 is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3, or (at your option)
+any later version.
+
+GNU Modula-2 is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+General Public License for more details.
+
+Under Section 7 of GPL version 3, you are granted additional
+permissions described in the GCC Runtime Library Exception, version
+3.1, as published by the Free Software Foundation.
+
+You should have received a copy of the GNU General Public License and
+a copy of the GCC Runtime Library Exception along with this program;
+see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
+.  */
+
+#include 
+
+#if defined(HAVE_STDIO_H)
+#include 
+#endif
+
+#if defined(HAVE_STDARG_H)
+#include 
+#endif
+
+#if defined(HAVE_STDLIB_H)
+#include 
+#endif
+
+#if defined(HAVE_MALLOC_H)
+#include 
+#endif
+
+typedef void (*PROC) (void);
+
+#if defined(HAVE_SIGNAL_H)
+#include 
+
+struct plist
+{
+  PROC proc;
+  struct plist *next;
+};
+
+static struct plist *head = NULL;
+
+/* localHandler - dismisses the parameter, p, and invokes the GNU
+   Modula-2 handler.  */
+
+static void
+localHandler (int p)
+{
+  if (head != NULL)
+head->proc ();
+}
+
+/* EnableBreak - enable the current break handler.  */
+
+void
+Break_EnableBreak (void)
+{
+  signal (SIGINT, localHandler);
+}
+
+/* DisableBreak - disable the current break handler (and all
+   installed handlers).  */
+
+void
+Break_DisableBreak (void)
+{
+  signal (SIGINT, SIG_IGN);
+}
+
+/* InstallBreak - installs a procedure, p, to be invoked when a
+   ctrl-c is caught.  Any number of these procedures may be stacked.
+   Only the top procedure is run when ctrl-c is caught.  */
+
+void
+Break_InstallBreak (PROC p)
+{
+  struct plist *q = (struct plist *)malloc (sizeof (struct plist));
+
+  if (q == NULL)
+{
+  perror ("out of memory error in module Break");
+  exit (1);
+}
+  q->next = head;
+  head = q;
+  head->proc = p;
+}
+
+/* UnInstallBreak - pops the break handler stack.  */
+
+void
+Break_UnInstallBreak (void)
+{
+  struct plist *q = head;
+
+  if (head != NULL)
+{
+  head = head->next;
+  free (q);
+}
+}
+#else
+void
+Break_EnableBreak (void)
+{
+}
+void
+Break_DisableBreak (void)
+{
+}
+void
+Break_InstallBreak (PROC *p)
+{
+}
+void
+Break_UnInstallBreak (void)
+{
+}
+#endif
diff -ruw /dev/null gcc-git-devel-modula2/libgm2/libm2log/Makefile.am
--- /dev/null   2022-08-24 16:22:16.88870 +0100
+++ gcc-git-devel-modula2/libgm2/libm2log/Makefile.am   2022-12-06 
02:56:51.432775922 +
@@ -0,0 +1,166 @@
+# Makefile for libm2log.
+#   Copyright 2013-2022  Free Software Foundation, Inc.
+#
+# This file is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; see the file COPYING3.  If not see
+# .
+
+SUFFIXES = .c .mod .def .o .obj .lo .a .la
+
+ACLOCAL_AMFLAGS = -I . -I .. -I ../config
+
+VPATH = . @srcdir@ @srcdir@/../../gcc/m2/gm2-libs-pim
+
+# Multilib support.
+MAKEOVERRIDES=
+
+version := $(shell $(CC) -dumpversion)
+
+# Directory in which the compiler finds libraries etc.
+libsubdir = $(libdir)/gcc/$(target_alias)/$(version)
+# Used to install the shared libgcc.
+slibdir = @slibdir@
+
+toolexeclibdir=@toolexeclibdir@
+toolexecdir=@toolexecdir@
+GM2_FOR_TARGET=@GM2_FOR_TARGET@
+
+MULTIDIR := $(shell $(CC) $(CFLAGS) -print-multi-directory)
+MULTIOSDIR := $(shell $(CC) $(CFLAGS) -print-multi-os-directory)
+
+MULTIOSSUBDIR := $(shell if test x$(MULTIOSDIR) != x.; then echo 
/$(MULTIOSDIR); fi

[PATCH v3 5/19] modula2 front end: libgm2/libm2iso contents

2022-12-06 Thread Gaius Mulley via Gcc-patches
 

This patch set consists of the makefiles, autoconf sources necessary
to build the various libgm2/libm2iso libraries.  The c/c++/h files
are also included in the patch set.  The modula-2 sources are found
in gcc/m2.

 
--8<--8<--8<--8<--8<--8< 
diff -ruw /dev/null gcc-git-devel-modula2/libgm2/libm2iso/wrapsock.c
--- /dev/null   2022-08-24 16:22:16.88870 +0100
+++ gcc-git-devel-modula2/libgm2/libm2iso/wrapsock.c2022-12-06 
02:56:51.432775922 +
@@ -0,0 +1,250 @@
+/* wrapsock.c provides access to socket related system calls.
+
+Copyright (C) 2008-2022 Free Software Foundation, Inc.
+Contributed by Gaius Mulley .
+
+This file is part of GNU Modula-2.
+
+GNU Modula-2 is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3, or (at your option)
+any later version.
+
+GNU Modula-2 is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+General Public License for more details.
+
+Under Section 7 of GPL version 3, you are granted additional
+permissions described in the GCC Runtime Library Exception, version
+3.1, as published by the Free Software Foundation.
+
+You should have received a copy of the GNU General Public License and
+a copy of the GCC Runtime Library Exception along with this program;
+see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
+.  */
+
+#include "config.h"
+
+#if defined(HAVE_SYS_TYPES_H)
+#include "sys/types.h"
+#endif
+
+#if defined(HAVE_SYS_SOCKET_H)
+#include "sys/socket.h"
+#endif
+
+#if defined(HAVE_NETINET_IN_H)
+#include "netinet/in.h"
+#endif
+
+#if defined(HAVE_NETDB_H)
+#include "netdb.h"
+#endif
+
+#if defined(HAVE_UNISTD_H)
+#include "unistd.h"
+#endif
+
+#if defined(HAVE_SIGNAL_H)
+#include "signal.h"
+#endif
+
+#if defined(HAVE_SYS_ERRNO_H)
+#include "sys/errno.h"
+#endif
+
+#if defined(HAVE_ERRNO_H)
+#include "errno.h"
+#endif
+
+#if defined(HAVE_MALLOC_H)
+#include "malloc.h"
+#endif
+
+#if defined(HAVE_MALLOC_H)
+#include "signal.h"
+#endif
+
+#if defined(HAVE_STRING_H)
+#include "string.h"
+#endif
+
+#if defined(HAVE_STDLIB_H)
+#include "stdlib.h"
+#endif
+
+#if !defined(TRUE)
+#define TRUE (1 == 1)
+#endif
+#if !defined(FALSE)
+#define FALSE (1 == 0)
+#endif
+
+#include "ChanConsts.h"
+
+#define MAXHOSTNAME 1024
+#define MAXPBBUF 1024
+
+#if defined(HAVE_NETINET_IN_H)
+
+typedef struct
+{
+  char hostname[MAXHOSTNAME];
+  struct hostent *hp;
+  struct sockaddr_in sa;
+  int sockFd;
+  int portNo;
+  int hasChar;
+  char pbChar[MAXPBBUF];
+} clientInfo;
+
+static openResults clientConnect (clientInfo *c);
+
+/* clientOpen - returns an ISO Modula-2 OpenResult.  It attempts to
+   connect to: hostname:portNo.  If successful then the data
+   structure, c, will have its fields initialized.  */
+
+openResults
+wrapsock_clientOpen (clientInfo *c, char *hostname, unsigned int length,
+ int portNo)
+{
+  /* remove SIGPIPE which is raised on the server if the client is killed.  */
+  signal (SIGPIPE, SIG_IGN);
+
+  c->hp = gethostbyname (hostname);
+  if (c->hp == NULL)
+return noSuchFile;
+
+  memset ((void *)&c->sa, 0, sizeof (c->sa));
+  c->sa.sin_family = AF_INET;
+  memcpy ((void *)&c->sa.sin_addr, (void *)c->hp->h_addr, c->hp->h_length);
+  c->portNo = portNo;
+  c->sa.sin_port = htons (portNo);
+  c->hasChar = 0;
+  /* Open a TCP socket (an Internet stream socket) */
+
+  c->sockFd = socket (c->hp->h_addrtype, SOCK_STREAM, 0);
+  return clientConnect (c);
+}
+
+/* clientOpenIP - returns an ISO Modula-2 OpenResult.  It attempts to
+   connect to: ipaddress:portNo.  If successful then the data
+   structure, c, will have its fields initialized.  */
+
+openResults
+wrapsock_clientOpenIP (clientInfo *c, unsigned int ip, int portNo)
+{
+  /* remove SIGPIPE which is raised on the server if the client is killed.  */
+  signal (SIGPIPE, SIG_IGN);
+
+  memset ((void *)&c->sa, 0, sizeof (c->sa));
+  c->sa.sin_family = AF_INET;
+  memcpy ((void *)&c->sa.sin_addr, (void *)&ip, sizeof (ip));
+  c->portNo = portNo;
+  c->sa.sin_port = htons (portNo);
+
+  /* Open a TCP socket (an Internet stream socket) */
+
+  c->sockFd = socket (PF_INET, SOCK_STREAM, 0);
+  return clientConnect (c);
+}
+
+/* clientConnect - returns an ISO Modula-2 OpenResult once a connect
+   has been performed.  If successful the clientInfo will include the
+   file descriptor ready for read/write operations.  */
+
+static openResults
+clientConnect (clientInfo *c)
+{
+  if (connect (c->sockFd, (struct sockaddr *)&c->sa, sizeof (c->sa)) < 0)
+return noSuchFile;
+
+  return opened;
+}
+
+/* getClientPortNo - returns the portNo from structure, c.  */
+
+int
+wrapsock_getClientPortNo (clientInfo *c)
+{
+  return c->portNo;
+}
+
+/* getClientHos

[PATCH v3 1/19] modula2 front end: changes outside gcc/m2, libgm2 and gcc/testsuite.

2022-12-06 Thread Gaius Mulley via Gcc-patches
 

This patch set contains the non machine generated changes found in /
for example the language die and documentation changes.  It also
contains the changes to the top level build Makefile infastructure
and the install.texi sourcebuild.texi documentation.

 
--8<--8<--8<--8<--8<--8< 
diff -ruw gcc-git-master/configure.ac gcc-git-devel-modula2/configure.ac
--- gcc-git-master/configure.ac 2022-12-06 02:56:41.628643384 +
+++ gcc-git-devel-modula2/configure.ac  2022-12-06 02:56:51.240773327 +
@@ -140,7 +140,7 @@
 # binutils, gas and ld appear in that order because it makes sense to run
 # "make check" in that particular order.
 # If --enable-gold is used, "gold" may replace "ld".
-host_tools="texinfo flex bison binutils gas ld fixincludes gcc cgen sid sim 
gdb gdbserver gprof etc expect dejagnu m4 utils guile fastjar gnattools libcc1 
gotools c++tools"
+host_tools="texinfo flex bison binutils gas ld fixincludes gcc cgen sid sim 
gdb gdbserver gprof etc expect dejagnu m4 utils guile fastjar gnattools libcc1 
gm2tools gotools c++tools"
 
 # these libraries are built for the target environment, and are built after
 # the host libraries and the host tools (which may be a cross compiler)
@@ -161,6 +161,7 @@
target-libffi \
target-libobjc \
target-libada \
+   target-libgm2 \
target-libgo \
target-libphobos \
target-zlib"
@@ -464,6 +465,14 @@
   noconfigdirs="$noconfigdirs gnattools"
 fi
 
+AC_ARG_ENABLE(libgm2,
+[AS_HELP_STRING([--enable-libgm2], [build libgm2 directory])],
+ENABLE_LIBGM2=$enableval,
+ENABLE_LIBGM2=no)
+if test "${ENABLE_LIBGM2}" != "yes" ; then
+  noconfigdirs="$noconfigdirs gm2tools"
+fi
+
 AC_ARG_ENABLE(libssp,
 [AS_HELP_STRING([--enable-libssp], [build libssp directory])],
 ENABLE_LIBSSP=$enableval,
@@ -3569,6 +3578,7 @@
 NCN_STRICT_CHECK_TARGET_TOOLS(GFORTRAN_FOR_TARGET, gfortran)
 NCN_STRICT_CHECK_TARGET_TOOLS(GOC_FOR_TARGET, gccgo)
 NCN_STRICT_CHECK_TARGET_TOOLS(GDC_FOR_TARGET, gdc)
+NCN_STRICT_CHECK_TARGET_TOOLS(GM2_FOR_TARGET, gm2)
 
 ACX_CHECK_INSTALLED_TARGET_TOOL(AR_FOR_TARGET, ar)
 ACX_CHECK_INSTALLED_TARGET_TOOL(AS_FOR_TARGET, as)
@@ -3607,6 +3617,8 @@
[gcc/gccgo -B$$r/$(HOST_SUBDIR)/gcc/], go)
 GCC_TARGET_TOOL(gdc, GDC_FOR_TARGET, GDC,
[gcc/gdc -B$$r/$(HOST_SUBDIR)/gcc/], d)
+GCC_TARGET_TOOL(gm2, GM2_FOR_TARGET, GM2,
+   [gcc/gm2 -B$$r/$(HOST_SUBDIR)/gcc/], m2)
 GCC_TARGET_TOOL(ld, LD_FOR_TARGET, LD, [ld/ld-new])
 GCC_TARGET_TOOL(lipo, LIPO_FOR_TARGET, LIPO)
 GCC_TARGET_TOOL(nm, NM_FOR_TARGET, NM, [binutils/nm-new])
@@ -3733,6 +3745,9 @@
 # Specify what files to not compare during bootstrap.
 
 compare_exclusions="gcc/cc*-checksum\$(objext) | gcc/ada/*tools/*"
+compare_exclusions="$compare_exclusions | gcc/m2/gm2-compiler-boot/M2Version*"
+compare_exclusions="$compare_exclusions | gcc/m2/gm2-compiler-boot/SYSTEM*"
+compare_exclusions="$compare_exclusions | gcc/m2/gm2version*"
 case "$target" in
   hppa*64*-*-hpux*) ;;
   powerpc*-ibm-aix*) compare_exclusions="$compare_exclusions | 
*libgomp*\$(objext)" ;;
diff -ruw gcc-git-master/gcc/doc/sourcebuild.texi 
gcc-git-devel-modula2/gcc/doc/sourcebuild.texi
diff -ruw gcc-git-master/gcc/doc/install.texi 
gcc-git-devel-modula2/gcc/doc/install.texi
diff -ruw gcc-git-master/gcc/dwarf2out.cc gcc-git-devel-modula2/gcc/dwarf2out.cc
--- gcc-git-master/gcc/dwarf2out.cc 2022-12-06 02:56:42.392653713 +
+++ gcc-git-devel-modula2/gcc/dwarf2out.cc  2022-12-06 02:56:51.312774299 
+
@@ -25206,6 +25206,8 @@
 }
   else if (strcmp (language_string, "GNU F77") == 0)
 language = DW_LANG_Fortran77;
+  else if (strcmp (language_string, "GNU Modula-2") == 0)
+language = DW_LANG_Modula2;
   else if (dwarf_version >= 3 || !dwarf_strict)
 {
   if (strcmp (language_string, "GNU Ada") == 0)
diff -ruw gcc-git-master/Makefile.def gcc-git-devel-modula2/Makefile.def
--- gcc-git-master/Makefile.def 2022-12-06 02:56:41.612643168 +
+++ gcc-git-devel-modula2/Makefile.def  2022-12-06 02:56:51.228773165 +
@@ -184,6 +184,7 @@
 target_modules = { module= zlib; bootstrap=true; };
 target_modules = { module= rda; };
 target_modules = { module= libada; };
+target_modules = { module= libgm2; lib_path=.libs; };
 target_modules = { module= libgomp; bootstrap= true; lib_path=.libs; };
 target_modules = { module= libitm; lib_path=.libs; };
 target_modules = { module= libatomic; bootstrap=true; lib_path=.libs; };
@@ -306,6 +307,8 @@
 flags_to_pass = { flag= GOCFLAGS_FOR_TARGET ; };
 flags_to_pass = { flag= GDC_FOR_TARGET ; };
 flags_to_pass = { flag= GDCFLAGS_FOR_TARGET ; };
+flags_to_pass = { flag= GM2_FOR_TARGET ; };
+flags_to_pass = { flag= GM2FLAGS_FOR_TARGET ; };
 flags_to_pass = { flag= LD_FOR_TARGET ; };
 flags_to_pass = { flag= LIPO_FOR_TARGET ; };
 flags_to_pass = { flag= LDFLAGS_FOR_TARGET ; };
@@ -617,6 +620,8 @@
 dependencies = 

[PATCH v3 9/19] modula2 front end: plugin source files

2022-12-06 Thread Gaius Mulley via Gcc-patches
 

This patchset contains the modula2 plugin which detects some runtime
errors at compiletime.

 
--8<--8<--8<--8<--8<--8< 
diff -ruw /dev/null gcc-git-devel-modula2/gcc/m2/plugin/m2rte.cc
--- /dev/null   2022-08-24 16:22:16.88870 +0100
+++ gcc-git-devel-modula2/gcc/m2/plugin/m2rte.cc2022-12-06 
02:56:51.380775219 +
@@ -0,0 +1,335 @@
+/* m2rte.cc a plugin to detect runtime exceptions at compiletime.
+
+Copyright (C) 2017-2022 Free Software Foundation, Inc.
+Contributed by Gaius Mulley .
+
+This file is part of GNU Modula-2.
+
+GNU Modula-2 is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3, or (at your option)
+any later version.
+
+GNU Modula-2 is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Modula-2; see the file COPYING3.  If not see
+.  */
+
+
+#include "gcc-plugin.h"
+#include "config.h"
+#include "system.h"
+#include "coretypes.h"
+#include "options.h"
+#include "tree-pass.h"
+#include "diagnostic-core.h"
+#include "flags.h"
+#include "intl.h"
+#include "plugin.h"
+#include "tree.h"
+#include "gimple.h"
+#include "gimplify.h"
+#include "gimple-iterator.h"
+#include "gimplify-me.h"
+#include "gimple-pretty-print.h"
+#include "plugin-version.h"
+#include "diagnostic.h"
+#include "context.h"
+
+#include "rtegraph.h"
+extern bool ggc_force_collect;
+extern void ggc_collect (void);
+
+#undef DEBUG_BASICBLOCK
+
+int plugin_is_GPL_compatible;
+
+void debug_tree (tree);
+
+/* All dialects of Modula-2 issue some or all of these runtime error calls.
+   This plugin detects whether a runtime error will be called in the first
+   basic block of a reachable function.  */
+
+static const char *m2_runtime_error_calls[] = {
+  "M2RTS_AssignmentException",
+  "M2RTS_ReturnException",
+  "M2RTS_IncException",
+  "M2RTS_DecException",
+  "M2RTS_InclException",
+  "M2RTS_ExclException",
+  "M2RTS_ShiftException",
+  "M2RTS_RotateException",
+  "M2RTS_StaticArraySubscriptException",
+  "M2RTS_DynamicArraySubscriptException",
+  "M2RTS_ForLoopBeginException",
+  "M2RTS_ForLoopToException",
+  "M2RTS_ForLoopEndException",
+  "M2RTS_PointerNilException",
+  "M2RTS_NoReturnException",
+  "M2RTS_CaseException",
+  "M2RTS_WholeNonPosDivException",
+  "M2RTS_WholeNonPosModException",
+  "M2RTS_WholeZeroDivException",
+  "M2RTS_WholeZeroRemException",
+  "M2RTS_WholeValueException",
+  "M2RTS_RealValueException",
+  "M2RTS_ParameterException",
+  "M2RTS_NoException",
+  NULL,
+};
+
+
+#if defined(DEBUG_BASICBLOCK)
+/* pretty_function display the name of the function.  */
+
+static void
+pretty_function (tree fndecl)
+{
+  if (fndecl != NULL && (DECL_NAME (fndecl) != NULL))
+{
+  const char *n = IDENTIFIER_POINTER (DECL_NAME (fndecl));
+  fprintf (stderr, "PROCEDURE %s ;\n", n);
+}
+}
+#endif
+
+void
+print_rtl (FILE *outf, const_rtx rtx_first);
+
+/* strend returns true if string name has ending.  */
+
+static bool
+strend (const char *name, const char *ending)
+{
+  unsigned int len = strlen (name);
+  return (len > strlen (ending)
+ && (strcmp (&name[len-strlen (ending)], ending) == 0));
+}
+
+/* is_constructor returns true if the function name is that of a module
+   constructor or deconstructor.  */
+
+static bool
+is_constructor (tree fndecl)
+{
+  const char *name = IDENTIFIER_POINTER (DECL_NAME (fndecl));
+  unsigned int len = strlen (name);
+
+  return ((len > strlen ("_M2_"))
+ && (strncmp (name, "_M2_", strlen ("_M2_")) == 0)
+ && (strend (name, "_init") || strend (name, "_finish")));
+}
+
+/* is_external returns true if the function is extern.  */
+
+static bool
+is_external (tree function)
+{
+  return (! DECL_EXTERNAL (function))
+&& TREE_PUBLIC (function)
+&& TREE_STATIC (function);
+}
+
+/* is_external returns true if the function is a call to a Modula-2
+   runtime exception handler.  */
+
+static bool
+is_rte (tree fndecl)
+{
+  const char *n = IDENTIFIER_POINTER (DECL_NAME (fndecl));
+
+  for (int i = 0; m2_runtime_error_calls[i] != NULL; i++)
+if (strcmp (m2_runtime_error_calls[i], n) == 0)
+  return true;
+  return false;
+}
+
+/* examine_call extract the function tree from the gimple call
+   statement and check whether it is a call to a runtime exception.  */
+
+static void
+examine_call (gimple *stmt)
+{
+  tree fndecl = gimple_call_fndecl (stmt);
+  rtenode *func = rtegraph_lookup (stmt, fndecl, true);
+  // rtegraph_dump ();
+  if (fndecl != NULL && (DECL_NAME (fndecl) != NULL))
+{
+  /* Firstly check if the function is a runtime exception.  */
+  if (is_rte (fndecl))

[PATCH v3 8/19] modula2 front end: libgm2 contents

2022-12-06 Thread Gaius Mulley via Gcc-patches
 

This patch set consists of the libgm2 makefile, autoconf sources
necessary to build the libm2pim, libm2iso, libm2min, libm2cor
and libm2log.

 
--8<--8<--8<--8<--8<--8< 
diff -ruw /dev/null gcc-git-devel-modula2/libgm2/ChangeLog
--- /dev/null   2022-08-24 16:22:16.88870 +0100
+++ gcc-git-devel-modula2/libgm2/ChangeLog  2022-12-06 02:56:51.428775868 
+
@@ -0,0 +1,506 @@
+2022-05-18  Gaius Mulley  
+
+   * Corrected dates on all source files.
+   * libm2pim/Selective.c: Reformatted comments.
+   * libm2pim/SysExceptions.c: Reformatted comments.
+   * libm2pim/dtoa.c: Reformatted comments.
+   * libm2pim/ldtoa.c: Reformatted comments.
+   * libm2pim/sckt.c: Reformatted comments.
+   * libm2pim/termios.c: Reformatted comments.
+   * libm2pim/wrapc.c: Reformatted comments.
+   * libm2pim/termios.c: Reformatted comments within enum.
+   * libm2pim/Selective.c: Correct spelling.
+   * libm2pim/termios.c: Use GNU comment formatting.
+
+2022-05-17  Gaius Mulley  
+
+   * Corrected dates on all source files.
+
+2022-03-02  Gaius Mulley  
+
+   * libm2pim/sckt.c (tcpServerEstablishPort): Corrected spelling.
+   (tcpServerEstablish) Corrected spelling.
+
+2021-06-27  Gaius Mulley  
+
+   * Makefile.am: renamed getopt.c to cgetopt.c.
+
+2021-05-29  Gaius Mulley  
+
+   * Makefile.in: (rebuilt).
+   * aclocal.m4: (rebuilt).
+   * configure: (rebuilt).
+   * configure.ac: tidied up messages.  Removed android
+   from the list of supported hosts.  Corrected a comment
+   * libm2pim/Makefile.am: Conditionally build.
+   * libm2cor/Makefile.am: Conditionally build.
+   * libm2log/Makefile.am: Conditionally build.
+   * libm2iso/Makefile.am: Conditionally build.
+   * libm2cor/Makefile.in: (Rebuilt).
+   * libm2iso/Makefile.in: (Rebuilt).
+   * libm2log/Makefile.in: (Rebuilt).
+   * libm2min/Makefile.in: (Rebuilt).
+   * libm2pim/Makefile.in: (Rebuilt).
+
+2021-05-28  Gaius Mulley  
+
+   * Makefile.in: (Rebuilt).
+   * aclocal.m4: (Rebuilt).
+   * configure: (Rebuilt).
+   * configure.ac: Introduce checks for supported host
+   operating system and also known detect target architectures
+   which are currently restricted to minimal runtime libraries.
+   * libm2cor/Makefile.in: (Rebuilt).
+   * libm2iso/Makefile.in: (Rebuilt).
+   * libm2log/Makefile.in: (Rebuilt).
+   * libm2min/Makefile.in: (Rebuilt).
+   * libm2pim/Makefile.in: (Rebuilt).
+
+2021-02-12  Gaius Mulley  
+
+   * libm2iso/RTco.c: (threadSem) new declaration
+and implmentation of thread semaphores used internally by
+the m2 runtime system.
+
+2021-01-13  Gaius Mulley  
+
+   * Makefile.am: Updated dates.
+   * aclocal.m4: (Rebuilt).
+   * autogen.sh: Updated dates.
+   * configure: (Rebuilt).
+   * configure.ac: Updated dates.
+   * libm2cor/KeyBoardLEDs.c: Updated dates.
+   * libm2cor/Makefile.am: Updated dates.
+   * libm2iso/ChanConsts.h: Updated dates.
+   * libm2iso/ErrnoCategory.c: Updated dates.
+   * libm2iso/Makefile.am: Updated dates.
+   * libm2iso/RTco.c: Updated dates.
+   * libm2iso/wrapsock.c: Updated dates.
+   * libm2iso/wraptime.c: Updated dates.
+   * libm2log/Break.c: Updated dates.
+   * libm2log/Makefile.am: Updated dates.
+   * libm2min/Makefile.am: Updated dates.
+   * libm2min/libc.c: Updated dates.
+   * libm2pim/Makefile.am: Updated dates.
+   * libm2pim/Selective.c: Updated dates.
+   * libm2pim/SysExceptions.c: Updated dates.
+   * libm2pim/UnixArgs.c: Updated dates.
+   * libm2pim/dtoa.c: Updated dates.
+   * libm2pim/errno.c: Updated dates.
+   * libm2pim/getopt.c: Updated dates.
+   * libm2pim/ldtoa.c: Updated dates.
+   * libm2pim/sckt.c: Updated dates.
+   * libm2pim/target.c: Updated dates.
+   * libm2pim/termios.c: Updated dates.
+   * libm2pim/wrapc.c: Updated dates.
+
+2020-11-20  Gaius Mulley  
+
+   * Makefile.in: (Rebuilt).
+   * aclocal.m4: (Rebuilt).
+   * configure: (Rebuilt).
+   * configure.ac: (libtool_VERSION=17.0.0)
+
+2020-06-18  Gaius Mulley  
+
+   * Makefile.in: (Rebuilt).
+   * aclocal.m4: (Rebuilt).
+   * autogen.sh: Execute automake including dependencies.
+   * configure: (Rebuilt).
+   * libm2cor/Makefile.in: (Rebuilt).
+   * libm2iso/Makefile.in: (Rebuilt).
+   * libm2log/Makefile.am: SYSTEM.def is a dependency using
+ BUILT_SOURCES.
+   * libm2log/Makefile.in: (Rebuilt).
+   * libm2min/Makefile.in: (Rebuilt).
+   * libm2pim/Makefile.in: (Rebuilt).
+
+2020-06-15  Gaius Mulley  
+
+   * libm2pim/Makefile.am: Added SYSTEM.def as a dependency.
+   * libm2log/Makefile.am: Added SYSTEM.def as a dependency.
+
+2020-06-11  Matthias Klose  
+
+   * Makefile.am: Reordered libraries.

[PATCH v3 3/19] modula2 front end: gm2 driver files.

2022-12-06 Thread Gaius Mulley via Gcc-patches
 

This patchset contains the c++, h and option related files necessary
to build the driver program gm2.  The patch also consists of the
autoconf/configure related build infastructure sources found in
gcc/m2.  The reviewer might need to look at the 01-02-make patchset.
The gm2 driver is heavily based on the fortran driver, it also adds
the c++ libraries and modula-2 search paths and libraries depending
upon dialect for user convenience.  Users could link modula-2 objects
using g++ if they supply the include and link paths.

 
--8<--8<--8<--8<--8<--8< 
diff -ruw /dev/null gcc-git-devel-modula2/gcc/m2/gm2spec.cc
--- /dev/null   2022-08-24 16:22:16.88870 +0100
+++ gcc-git-devel-modula2/gcc/m2/gm2spec.cc 2022-12-06 02:56:51.360774949 
+
@@ -0,0 +1,946 @@
+/* gm2spec.cc specific flags and argument handling within GNU Modula-2.
+
+Copyright (C) 2007-2022 Free Software Foundation, Inc.
+Contributed by Gaius Mulley .
+
+This file is part of GNU Modula-2.
+
+GNU Modula-2 is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3, or (at your option)
+any later version.
+
+GNU Modula-2 is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Modula-2; see the file COPYING3.  If not see
+.  */
+
+#include "config.h"
+#include "system.h"
+#include "coretypes.h"
+#include "tm.h"
+#include "xregex.h"
+#include "obstack.h"
+#include "intl.h"
+#include "prefix.h"
+#include "opt-suggestions.h"
+#include "gcc.h"
+#include "opts.h"
+#include "vec.h"
+
+#include "m2/gm2config.h"
+
+#ifdef HAVE_DIRENT_H
+#include 
+#else
+#ifdef HAVE_SYS_NDIR_H
+#include 
+#endif
+#ifdef HAVE_SYS_DIR_H
+#include 
+#endif
+#ifdef HAVE_NDIR_H
+#include 
+#endif
+#endif
+
+/* This bit is set if we saw a `-xfoo' language specification.  */
+#define LANGSPEC   (1<<1)
+/* This bit is set if they did `-lm' or `-lmath'.  */
+#define MATHLIB(1<<2)
+/* This bit is set if they did `-lc'.  */
+#define WITHLIBC   (1<<3)
+/* Skip this option.  */
+#define SKIPOPT(1<<4)
+
+#ifndef MATH_LIBRARY
+#define MATH_LIBRARY "m"
+#endif
+#ifndef MATH_LIBRARY_PROFILE
+#define MATH_LIBRARY_PROFILE MATH_LIBRARY
+#endif
+
+#ifndef LIBSTDCXX
+#define LIBSTDCXX "stdc++"
+#endif
+#ifndef LIBSTDCXX_PROFILE
+#define LIBSTDCXX_PROFILE LIBSTDCXX
+#endif
+#ifndef LIBSTDCXX_STATIC
+#define LIBSTDCXX_STATIC NULL
+#endif
+
+#ifndef LIBCXX
+#define LIBCXX "c++"
+#endif
+#ifndef LIBCXX_PROFILE
+#define LIBCXX_PROFILE LIBCXX
+#endif
+#ifndef LIBCXX_STATIC
+#define LIBCXX_STATIC NULL
+#endif
+
+#ifndef LIBCXXABI
+#define LIBCXXABI "c++abi"
+#endif
+#ifndef LIBCXXABI_PROFILE
+#define LIBCXXABI_PROFILE LIBCXXABI
+#endif
+#ifndef LIBCXXABI_STATIC
+#define LIBCXXABI_STATIC NULL
+#endif
+
+/* The values used here must match those of the stdlib_kind enumeration
+   in c.opt.  */
+enum stdcxxlib_kind
+{
+  USE_LIBSTDCXX = 1,
+  USE_LIBCXX = 2
+};
+
+#define DEFAULT_DIALECT "pim"
+#undef DEBUG_ARG
+
+typedef enum { iso, pim, min, logitech, pimcoroutine, maxlib } libs;
+
+/* These are the library names which are installed as part of gm2 and reflect
+   -flibs=name.  The -flibs= option provides the user with a short cut to add
+   libraries without having to know the include and link path.  */
+
+static const char *library_name[maxlib]
+= { "m2iso", "m2pim", "m2min", "m2log", "m2cor" };
+
+/* They match the installed archive name for example libm2iso.a,
+   libm2pim.a, libm2min.a, libm2log.a and libm2cor.a.  They also match a
+   subdirectory name where the definition modules are kept.  The driver
+   checks the argument to -flibs= for an entry in library_name or
+   alternatively the existance of the subdirectory (to allow for third
+   party libraries to coexist).  */
+
+static const char *library_abbrev[maxlib]
+= { "iso", "pim", "min", "log", "cor" };
+
+/* Users may specifiy -flibs=pim,iso etc which are mapped onto
+   -flibs=m2pim,m2iso respectively.  This provides a match between
+   the dialect of Modula-2 and the library set.  */
+
+static const char *add_include (const char *libpath, const char *library);
+
+static bool seen_scaffold_static = false;
+static bool seen_scaffold_dynamic = false;
+static bool scaffold_static = false;
+static bool scaffold_dynamic = true;  // Default uses -fscaffold-dynamic.
+static bool seen_gen_module_list = false;
+static bool seen_uselist = false;
+static bool uselist = false;
+static bool gen_module_list = true;  // Default uses -fgen-module-list=-.
+static const char *gen_module_filename = "-";
+static const char *multilib_dir = NULL;
+/* The original argum

[PATCH v3 17/19] modula2 front end: dejagnu expect library scripts

2022-12-06 Thread Gaius Mulley via Gcc-patches
 

Here are the dejagnu expect library scripts for the gm2
testsuite.

 
--8<--8<--8<--8<--8<--8< 
diff -ruw /dev/null gcc-git-devel-modula2/gcc/testsuite/lib/gm2.exp
--- /dev/null   2022-08-24 16:22:16.88870 +0100
+++ gcc-git-devel-modula2/gcc/testsuite/lib/gm2.exp 2022-12-06 
02:56:51.424775814 +
@@ -0,0 +1,498 @@
+# Copyright (C) 2003-2020 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with GCC; see the file COPYING3.  If not see
+# .
+
+# This file was written by Gaius Mulley (gaius.mul...@southwales.ac.uk)
+# for GNU Modula-2.
+
+# we want to use libgloss so we can get find_gcc.
+load_lib libgloss.exp
+load_lib prune.exp
+load_lib gcc-defs.exp
+load_lib target-libpath.exp
+
+
+#
+# GCC_UNDER_TEST is the compiler under test.
+#
+
+#
+# default_gcc_version -- extract and print the version number of the compiler
+#
+
+proc default_gcc_version { } {
+global GCC_UNDER_TEST
+
+gm2_init;
+
+# ignore any arguments after the command
+set compiler [lindex $GCC_UNDER_TEST 0]
+
+if ![is_remote host] {
+   set compiler_name [which $compiler];
+} else {
+   set compiler_name $compiler;
+}
+
+# verify that the compiler exists
+if { $compiler_name != 0 } then {
+   set tmp [remote_exec host "$compiler --version"]
+   set status [lindex $tmp 0];
+   set output [lindex $tmp 1];
+   regexp "version.*$" $output version
+   if { $status == 0 && [info exists version] } then {
+   clone_output "$compiler_name $version\n"
+   } else {
+   clone_output "Couldn't determine version of $compiler_name: 
$output\n"
+   }
+} else {
+   # compiler does not exist (this should have already been detected)
+   warning "$compiler does not exist"
+}
+}
+
+#
+# gcc_version -- Call default_gcc_version, so we can override it if needed.
+#
+
+proc gcc_version { } {
+default_gcc_version;
+}
+
+#
+# gm2_init -- called at the start of each .exp script.
+#
+# There currently isn't much to do, but always using it allows us to
+# make some enhancements without having to go back and rewrite the scripts.
+#
+
+set gm2_initialized 0;
+set gm2_compile_method "default";
+set gm2_link_path "";
+set gm2_link_libraries "m2pim m2iso";
+set gm2_link_objects "";
+
+proc gm2_set_compile_method { arg } {
+global gm2_compile_method;
+
+send_log "\n"
+send_log " setting gm2_compile_method to $arg \n"
+send_log "\n"
+set gm2_compile_method $arg;
+}
+
+
+proc gm2_init { args } {
+global tmpdir;
+global objdir;
+global rootme;
+global base_dir;
+global tool_root_dir;
+global gluefile wrap_flags;
+global gm2_initialized;
+global GCC_UNDER_TEST;
+global TOOL_EXECUTABLE;
+global gm2_link_libraries;
+global gm2_link_objects;
+global gm2_link_path;
+global HAVE_LIBSTDCXX_V3;
+
+if { $gm2_initialized == 1 } { return; }
+
+set gm2_link_objects "";
+set GCC_UNDER_TEST [lookfor_file $rootme gm2];
+append GCC_UNDER_TEST " " -B[file dirname $rootme]/gcc " " ${args};
+append GCC_UNDER_TEST " " -fno-diagnostics-show-caret
+append GCC_UNDER_TEST " " -fno-diagnostics-show-line-numbers
+append GCC_UNDER_TEST " " -fdiagnostics-color=never
+send_log "GCC_UNDER_TEST is ${GCC_UNDER_TEST}\n"
+
+if ![info exists tmpdir] then {
+   set tmpdir /tmp;
+}
+if {[target_info needs_status_wrapper] != "" && \
+   [target_info needs_status_wrapper] != "0" && \
+   ![info exists gluefile]} {
+   set gluefile ${tmpdir}/gcc-testglue.o;
+   set result [build_wrapper $gluefile];
+   if { $result != "" } {
+   set gluefile [lindex $result 0];
+   set wrap_flags [lindex $result 1];
+   } else {
+   unset gluefile
+   }
+}
+
+set gm2_link_path "[gm2_link_flags [get_multilibs]]";
+verbose $gm2_link_path 1
+}
+
+#
+# gm2_target_compile_default -- compile a source file
+#
+
+proc gm2_target_compile_default { source dest type options } {
+global gluefile wrap_flags
+global GCC_UNDER_TEST
+global TOOL_OPTIONS
+global TEST_ALWAYS_FLAGS
+global gm2_link_objects
+global gm2_link_libraries
+global gm2_link_path
+
+if {[target_info needs_status_wrapp

[PATCH v3 4/19] modula2 front end: libgm2/libm2pim contents

2022-12-06 Thread Gaius Mulley via Gcc-patches
 

This patch set consists of the makefiles, autoconf sources necessary
to build the various libgm2/libm2pim libraries.  The c/c++/h files
are included in the patch set.  The modula-2 sources are found in
gcc/m2/ as they are used by the compiler.

 
--8<--8<--8<--8<--8<--8< 
diff -ruw /dev/null gcc-git-devel-modula2/libgm2/libm2pim/target.c
--- /dev/null   2022-08-24 16:22:16.88870 +0100
+++ gcc-git-devel-modula2/libgm2/libm2pim/target.c  2022-12-06 
02:56:51.432775922 +
@@ -0,0 +1,61 @@
+/* target.c provide access to miscellaneous math functions.
+
+Copyright (C) 2005-2022 Free Software Foundation, Inc.
+Contributed by Gaius Mulley .
+
+This file is part of GNU Modula-2.
+
+GNU Modula-2 is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3, or (at your option)
+any later version.
+
+GNU Modula-2 is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+General Public License for more details.
+
+Under Section 7 of GPL version 3, you are granted additional
+permissions described in the GCC Runtime Library Exception, version
+3.1, as published by the Free Software Foundation.
+
+You should have received a copy of the GNU General Public License and
+a copy of the GCC Runtime Library Exception along with this program;
+see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
+.  */
+
+#include 
+
+#if defined(HAVE_MATH_H)
+#include 
+#endif
+
+#if !defined(HAVE_EXP10)
+#if defined(M_LN10)
+double
+exp10 (double x)
+{
+  return exp (x * M_LN10);
+}
+#endif
+#endif
+
+#if !defined(HAVE_EXP10F)
+#if defined(M_LN10)
+float
+exp10f (float x)
+{
+  return expf (x * M_LN10);
+}
+#endif
+#endif
+
+#if !defined(HAVE_EXP10L)
+#if defined(M_LN10)
+long double
+exp10l (long double x)
+{
+  return expl (x * M_LN10);
+}
+#endif
+#endif
diff -ruw /dev/null gcc-git-devel-modula2/libgm2/libm2pim/Selective.cc
--- /dev/null   2022-08-24 16:22:16.88870 +0100
+++ gcc-git-devel-modula2/libgm2/libm2pim/Selective.cc  2022-12-06 
02:56:51.432775922 +
@@ -0,0 +1,319 @@
+/* Selective.c provide access to timeval and select.
+
+Copyright (C) 2009-2022 Free Software Foundation, Inc.
+Contributed by Gaius Mulley .
+
+This file is part of GNU Modula-2.
+
+GNU Modula-2 is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3, or (at your option)
+any later version.
+
+GNU Modula-2 is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+General Public License for more details.
+
+Under Section 7 of GPL version 3, you are granted additional
+permissions described in the GCC Runtime Library Exception, version
+3.1, as published by the Free Software Foundation.
+
+You should have received a copy of the GNU General Public License and
+a copy of the GCC Runtime Library Exception along with this program;
+see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
+.  */
+
+#include 
+#include 
+
+#if defined(HAVE_STDDEF_H)
+/* Obtain a definition for NULL.  */
+#include 
+#endif
+
+#if defined(HAVE_STDIO_H)
+/* Obtain a definition for NULL.  */
+#include 
+#endif
+
+#if defined(HAVE_SYS_TIME_H)
+#include 
+#endif
+
+#if defined(HAVE_TIME_H)
+/* Obtain a definition for NULL.  */
+#include 
+#endif
+
+#if defined(HAVE_STRING_H)
+/* Obtain a definition for NULL.  */
+#include 
+#endif
+
+#if defined(HAVE_WCHAR_H)
+/* Obtain a definition for NULL.  */
+#include 
+#endif
+
+#if defined(HAVE_STDLIB_H)
+/* Obtain a prototype for free and malloc.  */
+#include 
+#endif
+
+#if defined(HAVE_SYS_TYPES_H)
+#include 
+#endif
+
+#if defined(HAVE_UNISTD_H)
+#include 
+#endif
+
+#if !defined(NULL)
+#define NULL (void *)0
+#endif
+
+#if defined(HAVE_SELECT)
+#define FDSET_T fd_set
+#else
+#define FDSET_T void
+#endif
+
+/* Select wrap a call to the C select.  */
+
+#if defined(HAVE_STRUCT_TIMEVAL)
+extern "C" int
+Selective_Select (int nooffds, fd_set *readfds, fd_set *writefds,
+  fd_set *exceptfds, struct timeval *timeout)
+{
+  return select (nooffds, readfds, writefds, exceptfds, timeout);
+}
+#else
+extern "C" int
+Selective_Select (int nooffds, void *readfds, void *writefds, void *exceptfds,
+  void *timeout)
+{
+  return 0;
+}
+#endif
+
+/* InitTime initializes a timeval structure and returns a pointer to it.  */
+
+#if defined(HAVE_STRUCT_TIMEVAL)
+extern "C" struct timeval *
+Selective_InitTime (unsigned int sec, unsigned int usec)
+{
+  struct timeval *t = (struct timeval *)malloc (sizeof (struc

[PATCH v3 15/19] modula2 front end: cc1gm2 additional non modula2 source files

2022-12-06 Thread Gaius Mulley via Gcc-patches
 

This patch set contains the .h, .cc and .flex files found in
gcc/m2.  The files are tightly coupled with the gimple interface
(see 04-gimple-interface) and built using the rules found in
(01-03-make).

 
--8<--8<--8<--8<--8<--8< 
diff -ruw /dev/null gcc-git-devel-modula2/gcc/m2/gm2-lang.cc
--- /dev/null   2022-08-24 16:22:16.88870 +0100
+++ gcc-git-devel-modula2/gcc/m2/gm2-lang.cc2022-12-06 02:57:10.909039217 
+
@@ -0,0 +1,887 @@
+/* gm2-lang.cc language-dependent hooks for GNU Modula-2.
+
+Copyright (C) 2002-2022 Free Software Foundation, Inc.
+Contributed by Gaius Mulley .
+
+This file is part of GNU Modula-2.
+
+GNU Modula-2 is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3, or (at your option)
+any later version.
+
+GNU Modula-2 is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Modula-2; see the file COPYING.  If not, write to the
+Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301, USA.  */
+
+#include "gm2-gcc/gcc-consolidation.h"
+
+#include "langhooks-def.h" /* FIXME: for lhd_set_decl_assembler_name.  */
+#include "tree-pass.h" /* FIXME: only for PROP_gimple_any.  */
+#include "toplev.h"
+#include "debug.h"
+
+#include "opts.h"
+
+#define GM2_LANG_C
+#include "gm2-lang.h"
+#include "m2block.h"
+#include "dynamicstrings.h"
+#include "m2options.h"
+#include "m2convert.h"
+#include "m2linemap.h"
+#include "init.h"
+#include "m2-tree.h"
+#include "convert.h"
+#include "rtegraph.h"
+
+static void write_globals (void);
+
+static int insideCppArgs = FALSE;
+
+#define EXPR_STMT_EXPR(NODE) TREE_OPERAND (EXPR_STMT_CHECK (NODE), 0)
+
+/* start of new stuff.  */
+
+/* Language-dependent contents of a type.  */
+
+struct GTY (()) lang_type
+{
+  char dummy;
+};
+
+/* Language-dependent contents of a decl.  */
+
+struct GTY (()) lang_decl
+{
+  char dummy;
+};
+
+/* Language-dependent contents of an identifier.  This must include a
+   tree_identifier.  */
+
+struct GTY (()) lang_identifier
+{
+  struct tree_identifier common;
+};
+
+/* The resulting tree type.  */
+
+union GTY ((desc ("TREE_CODE (&%h.generic) == IDENTIFIER_NODE"),
+chain_next ("CODE_CONTAINS_STRUCT (TREE_CODE (&%h.generic), "
+"TS_COMMON) ? ((union lang_tree_node *) TREE_CHAIN "
+"(&%h.generic)) : NULL"))) lang_tree_node
+{
+  union tree_node GTY ((tag ("0"),
+desc ("tree_node_structure (&%h)"))) generic;
+  struct lang_identifier GTY ((tag ("1"))) identifier;
+};
+
+struct GTY (()) language_function
+{
+
+  /* While we are parsing the function, this contains information about
+  the statement-tree that we are building.  */
+  /* struct stmt_tree_s stmt_tree;  */
+  tree stmt_tree;
+};
+
+/* Language hooks.  */
+
+bool
+gm2_langhook_init (void)
+{
+  build_common_tree_nodes (false);
+  build_common_builtin_nodes ();
+
+  /* The default precision for floating point numbers.  This is used
+ for floating point constants with abstract type.  This may eventually
+ be controllable by a command line option.  */
+  mpfr_set_default_prec (256);
+
+  /* GNU Modula-2 uses exceptions.  */
+  using_eh_for_cleanups ();
+  return true;
+}
+
+/* The option mask.  */
+
+static unsigned int
+gm2_langhook_option_lang_mask (void)
+{
+  return CL_ModulaX2;
+}
+
+/* Initialize the options structure.  */
+
+static void
+gm2_langhook_init_options_struct (struct gcc_options *opts)
+{
+  /* Default to avoiding range issues for complex multiply and divide.  */
+  opts->x_flag_complex_method = 2;
+
+  /* The builtin math functions should not set errno.  */
+  opts->x_flag_errno_math = 0;
+  opts->frontend_set_flag_errno_math = true;
+
+  /* Exceptions are used.  */
+  opts->x_flag_exceptions = 1;
+  init_FrontEndInit ();
+}
+
+/* Infrastructure for a VEC of bool values.  */
+
+/* This array determines whether the filename is associated with the
+   C preprocessor.  */
+
+static vec filename_cpp;
+
+void
+gm2_langhook_init_options (unsigned int decoded_options_count,
+   struct cl_decoded_option *decoded_options)
+{
+  unsigned int i;
+  bool in_cpp_args = false;
+
+  for (i = 1; i < decoded_options_count; i++)
+{
+  switch (decoded_options[i].opt_index)
+{
+case OPT_fcpp_begin:
+  in_cpp_args = true;
+  break;
+case OPT_fcpp_end:
+  in_cpp_args = false;
+  break;
+case OPT_SPECIAL_input_file:
+case OPT_SPECIAL_program_name:
+  filename_cpp.safe_push (in_cpp_args);
+}
+}
+  filename_cpp.sa

[PATCH v3 2/19] modula2 front end: Make-lang.in

2022-12-06 Thread Gaius Mulley via Gcc-patches
 

The makefile fragment for modula2 which builds the gm2 driver and cc1gm2.

 
--8<--8<--8<--8<--8<--8< 
diff -ruw /dev/null gcc-git-devel-modula2/gcc/m2/Make-lang.in
--- /dev/null   2022-08-24 16:22:16.88870 +0100
+++ gcc-git-devel-modula2/gcc/m2/Make-lang.in   2022-12-06 02:56:51.328774517 
+
@@ -0,0 +1,1649 @@
+# Top level -*- makefile -*- fragment for GNU M2.
+
+# Copyright (C) 2000-2022 Free Software Foundation, Inc.
+
+#This file is part of GCC.
+
+#GCC is free software; you can redistribute it and/or modify
+#it under the terms of the GNU General Public License as published by
+#the Free Software Foundation; either version 3, or (at your option)
+#any later version.
+
+#GCC is distributed in the hope that it will be useful,
+#but WITHOUT ANY WARRANTY; without even the implied warranty of
+#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#GNU General Public License for more details.
+
+#You should have received a copy of the GNU General Public License
+#along with GCC; see the file COPYING3.  If not see
+#.
+
+# Actual names to use when installing a native compiler.
+GM2_INSTALL_NAME = $(shell echo gm2|sed '$(program_transform_name)')
+GM2_TARGET_INSTALL_NAME = $(target_noncanonical)-$(shell echo gm2|sed 
'$(program_transform_name)')
+
+# Actual names to use when installing a cross-compiler.
+GM2_CROSS_NAME = `echo gm2|sed '$(program_transform_cross_name)'`
+
+M2_MAINTAINER = no
+
+GM2_1 = ./gm2 -B./stage1/m2 -g -fm2-g
+
+GM2_FOR_TARGET = $(STAGE_CC_WRAPPER) ./gm2 -B./ -B$(build_tooldir)/bin/ 
-L$(objdir)/../ld $(TFLAGS)
+
+TEXISRC = $(objdir)/m2/images/gnu.eps \
+  $(srcdir)/doc/gm2.texi \
+  m2/gm2-libs.texi \
+  m2/gm2-ebnf.texi \
+  m2/SYSTEM-pim.texi \
+  m2/SYSTEM-iso.texi \
+  m2/Builtins.texi
+
+RSTSRC = $(objdir)/m2/images/gnu.eps \
+  $(srcdir)/doc/gm2.texi \
+  m2/gm2-libs.rst \
+  m2/gm2-ebnf.rst \
+  m2/SYSTEM-pim.rst \
+  m2/SYSTEM-iso.rst \
+  m2/Builtins.rst
+
+# Define the names for selecting modula-2 in LANGUAGES.
+m2 modula-2 modula2: gm2$(exeext) xgcc$(exeext) cc1gm2$(exeext) \
+ $(GCC_PASSES) $(GCC_PARTS)
+m2.serial = cc1gm2$(exeext)
+
+# Tell GNU make to ignore these if they exist.
+.PHONY: m2 modula-2 modula2
+
+GM2_PROG_DEP=gm2$(exeext) xgcc$(exeext) cc1gm2$(exeext)
+
+include m2/config-make
+
+LIBSTDCXX=../$(TARGET_SUBDIR)/libstdc++-v3/src/.libs/libstdc++.a
+
+PGE=m2/pge$(exeext)
+
+SRC_PREFIX=G
+
+m2/gm2spec.o: $(srcdir)/m2/gm2spec.cc $(SYSTEM_H) $(GCC_H) $(CONFIG_H) \
+   m2/gm2config.h $(TARGET_H) $(PLUGIN_HEADERS) \
+   $(generated_files) $(C_TREE_H) insn-attr-common.h
+   (SHLIB_LINK='$(SHLIB_LINK)' \
+   SHLIB_MULTILIB='$(SHLIB_MULTILIB)'; \
+   $(COMPILER) $(ALL_COMPILERFLAGS) $(ALL_CPPFLAGS) $(INCLUDES) \
+ $(DRIVER_DEFINES) \
+   -DLIBSUBDIR=\"$(libsubdir)\" \
+-DPREFIX=\"$(prefix)\" \
+-c $(srcdir)/m2/gm2spec.cc $(OUTPUT_OPTION))
+
+# Create the compiler driver for M2.
+CFLAGS-m2/m2/gm2spec.o += $(DRIVER_DEFINES)
+
+GM2_OBJS = $(GCC_OBJS) prefix.o intl.o m2/gm2spec.o
+
+# Create the compiler driver for gm2.
+gm2$(exeext): $(GM2_OBJS) $(EXTRA_GCC_OBJS) libcommon-target.a $(LIBDEPS) \
+m2/gm2config.h
+   +$(LINKER) $(ALL_LINKERFLAGS) $(LDFLAGS) -o $@ \
+ $(GM2_OBJS) $(EXTRA_GCC_OBJS) libcommon-target.a \
+ $(EXTRA_GCC_LIBS) $(LIBS)
+
+# Create a version of the gm2 driver which calls the cross-compiler.
+gm2-cross$(exeext): gm2$(exeext)
+   -rm -f gm2-cross$(exeext)
+   cp gm2$(exeext) gm2-cross$(exeext)
+
+po-generated:
+
+# Build hooks:
+
+m2.all.cross: gm2-cross$(exeext) plugin/m2rte$(exeext).so
+
+m2.start.encap: gm2$(exeext) plugin/m2rte$(exeext).so
+m2.rest.encap:
+
+
+m2.info: doc/m2.info
+
+m2.man: doc/m2.1
+
+m2.install-man: $(DESTDIR)$(man1dir)/$(GM2_INSTALL_NAME)$(man1ext)
+
+$(DESTDIR)$(man1dir)/$(GM2_INSTALL_NAME)$(man1ext): doc/m2.1 installdirs
+   -rm -f $@
+   -$(INSTALL_DATA) $< $@
+   -chmod a-x $@
+
+m2.dvi: $(TEXISRC)
+   $(TEXI2DVI) -I $(objdir)/m2 -I $(srcdir)/doc/include 
$(srcdir)/doc/gm2.texi -o $@
+
+m2.ps: m2.dvi
+   dvips -o $@ $<
+
+m2.pdf: m2.ps
+   gs -q -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=$@ $<
+
+.INTERMEDIATE: gm2.pod
+
+m2.pod: doc/gm2.texi $(TEXISRC)
+   -$(TEXI2POD) -I $(objdir)/m2 -D m2 < $< > $@
+
+doc/m2.info: $(TEXISRC)
+   if test "x$(BUILD_INFO)" = xinfo; then \
+ rm -f doc/m2.info*; \
+  $(MAKEINFO) -I$(objdir)/m2 -I$(srcdir)/doc/include \
+  -o $@ $(srcdir)/doc/gm2.texi ; \
+   else true; fi
+
+$(objdir)/m2/images/gnu.eps: $(srcdir)/m2/images/gnupng
+   test -d m2/images || mkdir -p m2/images
+   if [ -f $(srcdir)/m2/images/gnu.eps ] ; then \
+   cp $(srcdir)/m2/images/gnu.eps $@ ; \
+else 

[PATCH v3 16/19] modula2 front end: bootstrap and documentation tools

2022-12-06 Thread Gaius Mulley via Gcc-patches
 

Hi Martin,
here is the revised patch having applied all previous recommendations:
https://gcc.gnu.org/pipermail/gcc-patches/2022-October/603436.html.
Is this ok now?  Thanks for the improvement suggestions.

 
--8<--8<--8<--8<--8<--8< 
diff -ruw /dev/null gcc-git-devel-modula2/mli...@suse.cz
diff -ruw /dev/null gcc-git-devel-modula2/gcc/m2/tools-src/tidydates.py
--- /dev/null   2022-08-24 16:22:16.88870 +0100
+++ gcc-git-devel-modula2/gcc/m2/tools-src/tidydates.py 2022-12-06 
02:56:51.380775219 +
@@ -0,0 +1,166 @@
+#!/usr/bin/env python3
+
+# utility to tidy dates and detect lack of copyright.
+
+# Copyright (C) 2016-2022 Free Software Foundation, Inc.
+#
+# This file is part of GNU Modula-2.
+#
+# GNU Modula-2 is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3, or (at your option)
+# any later version.
+#
+# GNU Modula-2 is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with GNU Modula-2; see the file COPYING.  If not, write to the
+# Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301, USA.
+
+import os
+import sys
+import pathlib
+import shutil
+
+max_line_length = 60
+
+COPYRIGHT = 'Copyright (C)'
+
+
+def visit_dir(directory, ext, func):
+# visit_dir - call func for each file below, dir, matching extension, ext.
+list_of_files = os.listdir(directory)
+list_of_files.sort()
+for filename in list_of_files:
+path = pathlib.PurePath(filename)
+full = os.path.join(directory, filename)
+if path.is_file(full):
+if path.suffix == ext:
+func(full)
+elif path.is_dir(full):
+visit_dir(full, ext, func)
+
+
+def is_year(year):
+# is_year - returns True if, year, is legal.
+if len(year) == 5:
+year = year[:-1]
+for c in year:
+if not c.isdigit():
+return False
+return True
+
+
+def handle_copyright(outfile, lines, n, leader1, leader2):
+# handle_copyright look for Copyright in the comment.
+global max_line_length
+i = lines[n]
+c = i.find(COPYRIGHT)+len(COPYRIGHT)
+outfile.write(i[:c])
+d = i[c:].split()
+start = c
+seen_date = True
+years = []
+while seen_date:
+if d == []:
+n += 1
+i = lines[n]
+d = i[2:].split()
+else:
+e = d[0]
+punctuation = ''
+if len(d) == 1:
+d = []
+else:
+d = d[1:]
+if c > max_line_length:
+outfile.write('\n')
+outfile.write(leader1)
+outfile.write(leader2)
+outfile.write(' '*(start-2))
+c = start
+if is_year(e):
+if (e[-1] == '.') or (e[-1] == ','):
+punctuation = e[-1]
+e = e[:-1]
+else:
+punctuation = ''
+else:
+seen_date = False
+if seen_date:
+if not (e in years):
+c += len(e) + len(punctuation)
+outfile.write(' ')
+outfile.write(e)
+outfile.write(punctuation)
+years += [e]
+else:
+if start < c:
+outfile.write('\n')
+outfile.write(leader1)
+outfile.write(leader2)
+outfile.write(' '*(start-2))
+
+outfile.write(' ')
+outfile.write(e)
+outfile.write(punctuation)
+for w in d:
+outfile.write(' ')
+outfile.write(w)
+outfile.write('\n')
+return outfile, n+1
+
+
+def handle_header(filename, leader1, leader2):
+# handle_header reads in the header of a file and inserts
+# a line break around the Copyright dates.
+print('--')
+lines = open(filename).readlines()
+if len(lines) > 20:
+with open('tmptidy', 'w') as outfile:
+n = 0
+for i in lines:
+if i.find('Copyright (C)') >= 0:
+outfile, n = handle_copyright(outfile, lines,
+ n, leader1, leader2)
+outfile.writelines(lines[n:])
+outfile.close()
+print('-> mv tmptidy', filename)
+shutil.move('tmptidy', filename)
+return
+else:
+ 

[PATCH v3 13/19] modula2 front end: gimple interface *[g-m]*.cc

2022-12-06 Thread Gaius Mulley via Gcc-patches
 

This patchset contains the gimple interface.

 
--8<--8<--8<--8<--8<--8< 
diff -ruw /dev/null gcc-git-devel-modula2/gcc/m2/gm2-gcc/m2linemap.cc
--- /dev/null   2022-08-24 16:22:16.88870 +0100
+++ gcc-git-devel-modula2/gcc/m2/gm2-gcc/m2linemap.cc   2022-12-06 
02:56:51.344774733 +
@@ -0,0 +1,254 @@
+/* m2linemap.cc provides an interface to GCC linemaps.
+
+Copyright (C) 2012-2022 Free Software Foundation, Inc.
+Contributed by Gaius Mulley .
+
+This file is part of GNU Modula-2.
+
+GNU Modula-2 is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3, or (at your option)
+any later version.
+
+GNU Modula-2 is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Modula-2; see the file COPYING3.  If not see
+.  */
+
+#include "gcc-consolidation.h"
+
+/* Utilize some of the C build routines */
+
+#include "../gm2-lang.h"
+#include "../m2-tree.h"
+
+#include "m2assert.h"
+#include "m2block.h"
+#include "m2decl.h"
+#include "m2expr.h"
+#include "m2options.h"
+#include "m2tree.h"
+#include "m2type.h"
+#define m2linemap_c
+#include "m2linemap.h"
+
+static int inFile = FALSE;
+
+#if defined(__cplusplus)
+#define EXTERN extern "C"
+#else
+#define EXTERN
+#endif
+
+/* Start getting locations from a new file.  */
+
+EXTERN
+void
+m2linemap_StartFile (void *filename, unsigned int linebegin)
+{
+  if (inFile)
+m2linemap_EndFile ();
+  linemap_add (line_table, LC_ENTER, false,
+   xstrdup (reinterpret_cast (filename)), linebegin);
+  inFile = TRUE;
+}
+
+/* Tell the line table the file has ended.  */
+
+EXTERN
+void
+m2linemap_EndFile (void)
+{
+  linemap_add (line_table, LC_LEAVE, 0, NULL, 0);
+  inFile = FALSE;
+}
+
+/* Indicate that there is a new source file line number with a
+   maximum width.  */
+
+EXTERN
+void
+m2linemap_StartLine (unsigned int linenumber, unsigned int linesize)
+{
+  linemap_line_start (line_table, linenumber, linesize);
+}
+
+/* GetLocationColumn, returns a location_t based on the current line
+   number and column.  */
+
+EXTERN
+location_t
+m2linemap_GetLocationColumn (unsigned int column)
+{
+  return linemap_position_for_column (line_table, column);
+}
+
+/* GetLocationRange, returns a location based on the start column
+   and end column.  */
+
+EXTERN
+location_t
+m2linemap_GetLocationRange (unsigned int start, unsigned int end)
+{
+  location_t caret = m2linemap_GetLocationColumn (start);
+
+  source_range where;
+  where.m_start = linemap_position_for_column (line_table, start);
+  where.m_finish = linemap_position_for_column (line_table, end);
+  return make_location (caret, where);
+}
+
+
+static
+int
+isSrcLocation (location_t location)
+{
+  return (location != BUILTINS_LOCATION) && (location != UNKNOWN_LOCATION);
+}
+
+
+/* GetLocationBinary, returns a location based on the expression
+   start caret finish locations.  */
+
+EXTERN
+location_t
+m2linemap_GetLocationBinary (location_t caret, location_t start, location_t 
finish)
+{
+  if (isSrcLocation (start) && isSrcLocation (finish) && isSrcLocation (caret)
+&& (m2linemap_GetFilenameFromLocation (start) != NULL))
+{
+  linemap_add (line_table, LC_ENTER, false, xstrdup 
(m2linemap_GetFilenameFromLocation (start)), 1);
+  gcc_assert (inFile);
+  location_t location = make_location (caret, start, finish);
+  return location;
+}
+  return caret;
+}
+
+/* GetLineNoFromLocation - returns the lineno given a location.  */
+
+EXTERN
+int
+m2linemap_GetLineNoFromLocation (location_t location)
+{
+  if (isSrcLocation (location) && (!M2Options_GetCpp ()))
+{
+  expanded_location xl = expand_location (location);
+  return xl.line;
+}
+  return 0;
+}
+
+/* GetColumnNoFromLocation - returns the columnno given a location.  */
+
+EXTERN
+int
+m2linemap_GetColumnNoFromLocation (location_t location)
+{
+  if (isSrcLocation (location) && (!M2Options_GetCpp ()))
+{
+  expanded_location xl = expand_location (location);
+  return xl.column;
+}
+  return 0;
+}
+
+/* GetFilenameFromLocation - returns the filename given a location.  */
+
+EXTERN
+const char *
+m2linemap_GetFilenameFromLocation (location_t location)
+{
+  if (isSrcLocation (location) && (!M2Options_GetCpp ()))
+{
+  expanded_location xl = expand_location (location);
+  return xl.file;
+}
+  return NULL;
+}
+
+/* ErrorAt - issue an error message.  */
+
+EXTERN
+void
+m2linemap_ErrorAt (location_t location, char *message)
+{
+  error_at (location, message);
+}
+
+/* m2linemap_ErrorAtf - wraps up an error message.  */
+
+void
+m2linemap_ErrorAtf (locat

[PATCH v3 0/19] modula-2 front end patches overview

2022-12-06 Thread Gaius Mulley via Gcc-patches


Here are the latest modula-2 front end patches.  Since the posting in
https://gcc.gnu.org/pipermail/gcc-patches/2022-October/603161.html
I've rewritten the python3 documentation scripts (feedback from
patchset 16) and applied all the suggestions from the feedback in
patchset 15 (gm2-lang.cc).

All the patches are can also be at:
https://splendidisolation.ddns.net/public/modula2/patchsummary.html
which contains the status of the patch, their contents and testing
summary.

Thanks for the feedback - and clean up suggestions!

regards,
Gaius


Patch Summary
=

The gm2 driver program and top level makefile infrastructure

[PATCH v3] 1/19: changes outside gcc/m2, libgm2 and gcc/testsuite.
[PATCH v3] 2/19: Make-lang.in
[PATCH v3] 3/19: gm2 driver files.

The libraries /libgm2

[PATCH v3] 4/19: libgm2/libm2pim contents
[PATCH v3] 5/19: libgm2/libm2iso contents
[PATCH v3] 6/19: libgm2/libm2min contents
[PATCH v3] 7/19: libgm2/libm2log contents
[PATCH v3] 8/19: libgm2 contents

Modula-2 plugin

[PATCH v3] 9/19: plugin source files

Modula-2 to gimple interface

[PATCH v3] 10/19: gimple interface header files *.h and *.def
[PATCH v3] 11/19: gimple interface *[a-d]*.cc
[PATCH v3] 12/19: gimple interface *[e-f]*.cc
[PATCH v3] 13/19: gimple interface *[g-m]*.cc
[PATCH v3] 14/19: gimple interface remainder

Lexical analysis (flex), lang hooks and debug tree module

[PATCH v3] 15/19: cc1gm2 additional non modula2 source files

Linking bootstrap tool and documentation build script

[PATCH v3] 16/19: bootstrap and documentation tools

Testsuite and remaining files

[PATCH v3] 17/19: dejagnu expect library scripts.

[PATCH v3] 18/19: remainder of the files for the compiler and libraries.  (not 
posted)
[PATCH v3] 19/19: modula2 testsuite.  (not posted)


  1   2   >