Re: [PATCH RFA] input: add get_source_text_between

2022-11-04 Thread David Malcolm via Gcc-patches
On Fri, 2022-11-04 at 13:06 -0400, Jason Merrill wrote:
> On 11/4/22 11:16, David Malcolm wrote:
> > On Fri, 2022-11-04 at 10:27 -0400, Jason Merrill wrote:
> > > On 11/3/22 19:06, David Malcolm wrote:
> > > > On Thu, 2022-11-03 at 15:59 -0400, Jason Merrill via Gcc-
> > > > patches
> > > > wrote:
> > 
> > [...snip...]
> > 
> > > > 
> > > > 
> > > > Do you have test coverage for this from the DejaGnu side?  If
> > > > not,
> > > > you
> > > > could add selftest coverage for this; see input.cc's
> > > > test_reading_source_line for something similar.
> > > 
> > > There is test coverage for the output of the the contract
> > > violation
> > > handler, which involves printing the result of this function.
> > 
> > Thanks.   Is this test posted somwehere?  I was looking in:
> >  
> > https://gcc.gnu.org/pipermail/gcc-patches/2022-November/604974.html
> > but I'm not seeing it.  Sorry if I'm missing something here.
> 
> The tests are in the newer message
> 
>   
> https://gcc.gnu.org/pipermail/gcc-patches/2022-November/605072.html
> 
> > Ideally we should have coverage for the three cases of:
> > (a) bails out and returns NULL
> 
> This isn't tested because it should never happen.

I'm guessing someone will run into it in the wild at some point.  With
very large files we eventually give up on tracking column numbers, and
so we get location_t values with column number == 0, and FWIW
  gcc/testsuite/gcc.dg/plugin/location_overflow_plugin.c
makes it feasible to test such cases.

But obviously that's low priority.

Dave

> 
> > (b) single-line case
> 
> contracts-tmpl-spec3.C etc.
> 
> > (c) multi-line case
> 
> contracts-multiline1.C
> 
> > > index a28abfac5ac..04d0809bfdf 100644
> > > --- a/gcc/input.cc
> > > +++ b/gcc/input.cc
> > > @@ -949,6 +949,97 @@ location_get_source_line (const char
> > > *file_path, int line)
> > >     return char_span (buffer, len);
> > >   }
> > 
> > Strings in input.cc are not always NUL-terminated, so...
> > 
> > >   
> > > +/* Return a copy of the source text between two locations.  The
> > > caller is
> > > +   responsible for freeing the return value.  */
> > 
> > ...please note in the comment that if non-NULL, the copy is NUL-
> > terminated (I checked both exit paths that can return non-NULL, and
> > they do NUL-terminate their buffers).
> > 
> > OK with that nit fixed.
> 
> Thanks, pushing this:



Re: [PATCH 5a/6] diagnostics: Handle generated data locations in edit_context

2022-11-04 Thread David Malcolm via Gcc-patches
On Fri, 2022-11-04 at 17:05 -0400, Lewis Hyatt wrote:
> [PATCH 5a/6] diagnostics: Handle generated data locations in
> edit_context
> 
> Class edit_context handles outputting fixit hints in diff form that
> could be
> manually or automatically applied by the user. This will not make
> sense for
> generated data locations, such as the contents of a _Pragma string,
> because
> the text to be modified does not appear in the user's input files. We
> do not
> currently ever generate fixit hints in such a context, but for
> future-proofing
> purposes, ignore such locations in edit context now.
> 
> gcc/ChangeLog:
> 
>   * edit-context.cc (edit_context::apply_fixit): Ignore
> locations in
>   generated data.
> 
> diff --git a/gcc/edit-context.cc b/gcc/edit-context.cc
> index 6879ddd41b4..aa95bc0834f 100644
> --- a/gcc/edit-context.cc
> +++ b/gcc/edit-context.cc
> @@ -301,8 +301,12 @@ edit_context::apply_fixit (const fixit_hint
> *hint)
>  return false;
>    if (start.column == 0)
>  return false;
> +  if (start.generated_data)
> +    return false;
>    if (next_loc.column == 0)
>  return false;
> +  if (next_loc.generated_data)
> +    return false;
>  
>    edited_file  = get_or_insert_file (start.file);
>    if (!m_valid)

This patch is OK for trunk once the prerequisite patch is also
approved.

Thanks
Dave



Re: [PATCH 5b/6] diagnostics: Remove null-termination requirement for json::string

2022-11-04 Thread David Malcolm via Gcc-patches
On Fri, 2022-11-04 at 17:05 -0400, Lewis Hyatt wrote:
> [PATCH 5b/6] diagnostics: Remove null-termination requirement for
> json::string
> 
> json::string currently handles null-terminated data and so can't work
> with
> data that may contain embedded null bytes or that is not null-
> terminated.
> Supporting such data will make json::string more robust in some
> contexts, such
> as SARIF output, which uses it to output user source code that may
> contain
> embedded null bytes.
> 
> gcc/ChangeLog:
> 
>   * json.h (class string): Add M_LEN member to store the
> length of
>   the data.  Add constructor taking an explicit length.
>   * json.cc (string::string):  Implement the new constructor.
>   (string::print): Support print strings that are not null-
> terminated.
>   Escape embdedded null bytes on output.
>   (test_writing_strings): Test the new null-byte-related
> features of
>   json::string.
> 

[...snip...]

> diff --git a/gcc/json.h b/gcc/json.h
> index f272981259b..f7afd843dc5 100644
> --- a/gcc/json.h
> +++ b/gcc/json.h
> @@ -156,16 +156,19 @@ class integer_number : public value
>  class string : public value
>  {
>   public:
> -  string (const char *utf8);
> +  explicit string (const char *utf8);
> +  string (const char *utf8, size_t len);
>    ~string () { free (m_utf8); }
>  
>    enum kind get_kind () const final override { return JSON_STRING; }
>    void print (pretty_printer *pp) const final override;
>  
>    const char *get_string () const { return m_utf8; }

I worried that json::string::get_string previously returned a NUL-
terminated string, but now there's no guarantee of termination, and
that this might break something.  But I checked, and it seems that this
accessor doesn't get used anywhere in our source tree.

> +  size_t get_length () const { return m_len; }

Does anything actually use this?

Perhaps it might make sense to delete the get_string accessor, and if
we ever need one, replace it with an accessor that returns a char_span?

>  
>   private:
>    char *m_utf8;
> +  size_t m_len;
>  };
>  

Thanks for adding the unit test.

The 5b patch is OK for trunk.

Dave



Re: [PATCH] riscv: implement TARGET_MODE_REP_EXTENDED

2022-11-04 Thread Philipp Tomsich
Alexander,

I had missed your comment until now.

On Tue, 6 Sept 2022 at 13:39, Alexander Monakov  wrote:
>
> On Mon, 5 Sep 2022, Philipp Tomsich wrote:
>
> > +riscv_mode_rep_extended (scalar_int_mode mode, scalar_int_mode
mode_rep)
> > +{
> > +  /* On 64-bit targets, SImode register values are sign-extended to
DImode.  */
> > +  if (TARGET_64BIT && mode == SImode && mode_rep == DImode)
> > +return SIGN_EXTEND;
>
> I think this leads to a counter-intuitive requirement that a hand-written
> inline asm must sign-extend its output operands that are bound to either
> signed or unsigned 32-bit lvalues. Will compiler users be aware of that?

I am not sure if I fully understand your concern, as the mode of the
asm-output will be derived from the variable type.
So "asm (... : "=r" (a))" will take DI/SI/HI/QImode depending on the type
of a.

The concern, as far as I understand would be the case where the
assembly-sequence leaves an incompatible extension in the register.
So l understand the problem being:
int a;
asm volatile ("zext.w %0, %1" : "=r"(a) : "r"(b));  // possible pitfall
-- the programmer wants a SImode representation (so it needs to be extended)
but not
long long a;
asm volatile ("zext.w %0, %1" : "=r"(a): "r"(b));   // possible pitfall
-- the programmer wants the DImode representation (don't extend)

If we look at the output of expand for the first case (I made sure to
consume "a" again using a "asm volatile ("nop" : : "r"(a))"), we see that
an explicit extension is created from SImode to DImode (the "(subreg:SI
(reg:DI ...) 0)" in the asm-operand for the next block is a bigger concern
— this may be an artifact of TARGET_TRULY_NOOP_TRUNCATION not being
properly defined on RISC-V; but this issue didn't originate from this
patch):

;; __asm__ __volatile__("zext.w %0,%1" : "=r" a_2 : "r" b_1(D));
(insn 7 5 6 (set (reg:SI 75 [ aD.1490 ])
(asm_operands/v:SI ("zext.w %0,%1") ("=r") 0 [
(reg/v:DI 74 [ bD.1487 ])
]
 [
(asm_input:DI ("r") ./rep-asm.c:5)
]
 [] ./rep-asm.c:5)) "./rep-asm.c":5:3 -1
 (nil))
(insn 6 7 0 (set (reg/v:DI 72 [ aD.1490 ])
(sign_extend:DI (reg:SI 75 [ aD.1490 ]))) "./rep-asm.c":5:3 -1
 (nil))
;; __asm__ __volatile__("nop" :  : "r" a_2);
(insn 8 6 0 (asm_operands/v ("nop") ("") 0 [
(subreg/s/u:SI (reg/v:DI 72 [ aD.1490 ]) 0)
]
 [
(asm_input:SI ("r") ./rep-asm.c:6)
]
 [] ./rep-asm.c:6) "./rep-asm.c":6:3 -1
 (nil))

which translates to:

f:

#APP

# 5 "./rep-asm.c" 1

zext.w a0,a0

# 0 "" 2

#NO_APP

sext.w a0,a0

#APP

# 6 "./rep-asm.c" 1

nop

# 0 "" 2

#NO_APP


If this patch is not applied (and TARGET_MODE_REP_EXTENDED is not defined),
we see the sext.w missing.
So in fact, we may have unintentionally fixed an issue?

> Moreover, without adjusting TARGET_TRULY_NOOP_TRUNCATION this should cause
> miscompilation when a 64-bit variable is truncated to 32 bits: the
pre-existing
> hook says that nothing needs to be done to truncate, but the new hook says
> that the result of the truncation is properly sign-extended.
>
> The documentation for TARGET_MODE_REP_EXTENDED warns about that:
>
> In order to enforce the representation of mode,
TARGET_TRULY_NOOP_TRUNCATION
> should return false when truncating to mode.

Good point.  This should indeed be added and we'll look into this in more
detail for v2.

Looking into this in more detail, it seems that this change doesn't make
things worse (we already had that problem before, as an explicit extension
might also lead to the same reasoning).
So somehow we've been avoiding this bullet so far, although I don't know
yet how...

Philipp.


Re: [PATCH 5/6] diagnostics: Support generated data in additional contexts

2022-11-04 Thread Lewis Hyatt via Gcc-patches
On Fri, Nov 04, 2022 at 12:42:29PM -0400, David Malcolm wrote:
> On Fri, 2022-11-04 at 09:44 -0400, Lewis Hyatt via Gcc-patches wrote:
> > Add awareness that diagnostic locations may be in generated buffers
> > rather
> > than an actual file to other places in the diagnostics code that may
> > care,
> > most notably SARIF output (which needs to obtain its own snapshots of
> > the code
> > involved). For edit context output, which outputs fixit hints as
> > diffs, for
> > now just make sure we ignore generated data buffers. At the moment,
> > there is
> > no ability for a fixit hint to be generated in such a buffer.
> > 
> > Because SARIF uses JSON as well, also add the ability to the
> > json::string
> > class to handle a buffer with nulls in the middle (since we place no
> > restriction on LC_GEN content) by providing the option to specify the
> > data
> > length.
> 
> Please can you split this patch into three parts:
> - the SARIF part
> - the json changes
> - the edit-context.cc changes (I think this at least counts as an
> "obvious" change with respect to the other changes in the kit, though
> I'm still working my way through patch 4 in the kit).
> 
> Please add a DejaGnu testcase to the SARIF part, with a diagnostic that
> references a generated data buffer; see
>   gcc/testsuite/c-c++-common/diagnostic-format-sarif-file-*.c 
> for examples of SARIF testcases.
> 
> Please add a selftest to the json change so that we have a unit test of
> constructing a json::string with an embedded NUL, and how we serialize
> such a string (probably to json.cc's test_writing_strings)
> 
> Thanks
> Dave

Yes, certainly, sorry for not splitting it up more to start with. Regarding
the SARIF testcase, it's not that easy to get SARIF output to actually output
generated data, because as of now it can only appear in a _Pragma, and SARIF
does not output macro definitions currently. I think the only way I know to do
it, is to make use of -fdump-internal-locations, which generates top-level
inform() calls inside the _Pragma that can end up in the SARIF output. So I
wrote a testcase that does this, but not sure how you will feel about having
the testsuite rely on this internal debugging option.

I wasn't sure what's the best way to send the 3 split up patches. I attached
them here as 5a/6, 5b/6, 5c/6, in case that's right, but I wasn't sure if I 
should just
resend the whole batch (minus perhaps the 2 you have already acked), and/or if
I should wait for feedback on the other patches first. Happy to do whatever
makes it easier for you, and thanks for your time! Note that the new SARIF
patch (5c/6) now needs to come last in the series, after the patch 6/6 that
actually supports _Pragma, so that the new testcase can make use of that.

-Lewis
[PATCH 5a/6] diagnostics: Handle generated data locations in edit_context

Class edit_context handles outputting fixit hints in diff form that could be
manually or automatically applied by the user. This will not make sense for
generated data locations, such as the contents of a _Pragma string, because
the text to be modified does not appear in the user's input files. We do not
currently ever generate fixit hints in such a context, but for future-proofing
purposes, ignore such locations in edit context now.

gcc/ChangeLog:

* edit-context.cc (edit_context::apply_fixit): Ignore locations in
generated data.

diff --git a/gcc/edit-context.cc b/gcc/edit-context.cc
index 6879ddd41b4..aa95bc0834f 100644
--- a/gcc/edit-context.cc
+++ b/gcc/edit-context.cc
@@ -301,8 +301,12 @@ edit_context::apply_fixit (const fixit_hint *hint)
 return false;
   if (start.column == 0)
 return false;
+  if (start.generated_data)
+return false;
   if (next_loc.column == 0)
 return false;
+  if (next_loc.generated_data)
+return false;
 
   edited_file  = get_or_insert_file (start.file);
   if (!m_valid)
[PATCH 5b/6] diagnostics: Remove null-termination requirement for json::string

json::string currently handles null-terminated data and so can't work with
data that may contain embedded null bytes or that is not null-terminated.
Supporting such data will make json::string more robust in some contexts, such
as SARIF output, which uses it to output user source code that may contain
embedded null bytes.

gcc/ChangeLog:

* json.h (class string): Add M_LEN member to store the length of
the data.  Add constructor taking an explicit length.
* json.cc (string::string):  Implement the new constructor.
(string::print): Support print strings that are not null-terminated.
Escape embdedded null bytes on output.
(test_writing_strings): Test the new null-byte-related features of
json::string.

diff --git a/gcc/json.cc b/gcc/json.cc
index 974f8c36825..3a79cac02ac 100644
--- a/gcc/json.cc
+++ b/gcc/json.cc
@@ -190,6 +190,15 @@ string::string (const char *utf8)
 {
   gcc_assert (utf8);
   m_utf8 = xstrdup (utf8);
+  m_len = strlen (utf8);
+}
+

Re: [PATCH] [PR24021] Implement PLUS_EXPR range-op entry for floats.

2022-11-04 Thread Jakub Jelinek via Gcc-patches
On Fri, Nov 04, 2022 at 08:14:23PM +0100, Jakub Jelinek via Gcc-patches wrote:
> One thing that is clear is that real_isdenormal is never true for these
> (but then a question is if flush_denormals_to_zero actually works).

So, after some more investigation, I think that is actually the case,
real_isdenormal is only meaningful (will ever return true) right after
round_for_format.
The uses inside of real.cc are fine, real_to_target first calls
round_for_format and then calls fmt->encode in which the real_isdenormal
calls are done.  And, round_for_format is what transforms the
normalized way of expressing the number into the denormal form:
  /* Check the range of the exponent.  If we're out of range,
 either underflow or overflow.  */
  if (REAL_EXP (r) > emax2)
goto overflow;
  else if (REAL_EXP (r) <= emin2m1)
{
  int diff;

  if (!fmt->has_denorm)
{
  /* Don't underflow completely until we've had a chance to round.  */
  if (REAL_EXP (r) < emin2m1)
goto underflow;
}
  else
{
  diff = emin2m1 - REAL_EXP (r) + 1;
  if (diff > p2)
goto underflow;

  /* De-normalize the significand.  */
  r->sig[0] |= sticky_rshift_significand (r, r, diff);
  SET_REAL_EXP (r, REAL_EXP (r) + diff);
}
}
But, real_to_target is one of the 4 callers of static round_for_format,
another one is real_convert, but that one undoes that immediately:
  round_for_format (fmt, r);

  /* Make resulting NaN value to be qNaN. The caller has the
 responsibility to avoid the operation if flag_signaling_nans
 is on.  */
  if (r->cl == rvc_nan)
r->signalling = 0;
  
  /* round_for_format de-normalizes denormals.  Undo just that part.  */
  if (r->cl == rvc_normal)
normalize (r);
and the last two are inside of encoding the IBM double double composite.
So, I think everywhere in the frange you'll see normalized REAL_VALUE_TYPE
and so real_isdenormal will always be false there.
You need to check for REAL_EXP (r) < fmt->emin or so (and ideally only on
REAL_VALUE_TYPE already real_converted to the right mode (your
frange_arithmetics does that already, which is good, but say conversions
and other unary ops might need it too).
If I in the hack from last mail replace
- fprintf (stderr, "%d %d %s %s\n", i, real_isdenormal (), buf, 
buf2);
+ fprintf (stderr, "%d %d %s %s\n", i, REAL_EXP () < 
REAL_MODE_FORMAT (mode)->emin, buf, buf2);
then it is 1 until:
102 1 0x0.8p-971 0x0.88p-971
103 1 0x0.8p-970 0x0.88p-970
104 1 0x0.8p-969 0x0.88p-969
105 0 0x0.8p-968 0x0.88p-968
106 0 0x0.8p-967 0x0.88p-967
107 0 0x0.8p-966 0x0.88p-966

Now, the __LDBL_MIN__ powerpc64 gcc announces is
2.00416836000897277799610805135016205e-292L
which is equivalent to:
0x1p-969
and that is equivalent to
0x0.8p-968, so I think that is exactly what we want.

Jakub



Re: [PATCH] [PR24021] Implement PLUS_EXPR range-op entry for floats.

2022-11-04 Thread Jakub Jelinek via Gcc-patches
On Mon, Oct 17, 2022 at 08:21:01AM +0200, Aldy Hernandez wrote:
> +// Set VALUE to its next real value, or INF if the operation overflows.
> +
> +inline void
> +frange_nextafter (enum machine_mode mode,
> +   REAL_VALUE_TYPE ,
> +   const REAL_VALUE_TYPE )
> +{
> +  const real_format *fmt = REAL_MODE_FORMAT (mode);
> +  REAL_VALUE_TYPE tmp;
> +  bool overflow = real_nextafter (, fmt, , );
> +  if (overflow)
> +value = inf;
> +  else
> +value = tmp;

Please change the above 5 lines to just
  real_nextafter (, fmt, , );
  value = tmp;
What real_nextafter returns isn't bool whether it overflowed, but
a bool whether some exception should be raised for the nextafter,
which can be either an overflow (in that case tmp will be already set
to infinity of the right sign:
  if (REAL_EXP (r) > fmt->emax)
{
  get_inf (r, x->sign);
  return true;
}
or underflow to zero:
  if (REAL_EXP (r) <= fmt->emin - fmt->p)
{
  get_zero (r, x->sign);
  return true;
}
or when the result is subnormal:
  return r->cl == rvc_zero || REAL_EXP (r) < fmt->emin;
But we shouldn't care about exceptions, we aren't emitting code, just
estimating floating point range, and +-inf, or +-0, or subnormal
are the right answers.

Just for playing with this, I've tried:
--- range-op-float.cc.jj2022-11-02 10:06:02.620960861 +0100
+++ range-op-float.cc   2022-11-04 19:49:14.188075070 +0100
@@ -1815,6 +1815,20 @@ frange_float (const char *lb, const char
   return frange (type, min, max);
 }
 
+inline void


+frange_nextafter (enum machine_mode mode,  


+ REAL_VALUE_TYPE ,   

  
+ const REAL_VALUE_TYPE )   

  
+{  


+  const real_format *fmt = REAL_MODE_FORMAT (mode);


+  REAL_VALUE_TYPE tmp; 


+  bool overflow = real_nextafter (, fmt, , );


+  if (overflow)


+value = inf;   


+  else 


+   value = tmp;

   
+}  


+
 void
 range_op_float_tests ()
 {
@@ -1833,6 +1847,30 @@ range_op_float_tests ()
   r1 = frange_float ("-1", "-0");
   r1.update_nan (false);
   ASSERT_EQ (r, r1);
+
+  if (MODE_COMPOSITE_P (TYPE_MODE (long_double_type_node)))
+{
+  enum machine_mode mode = TYPE_MODE (long_double_type_node);
+  REAL_VALUE_TYPE result = dconst0;
+  {
+   REAL_VALUE_TYPE tmp;
+   real_convert (, DFmode, );
+   frange_nextafter (DFmode, tmp, dconstinf);
+   real_convert (, mode, );
+  }
+  for (int i = 0; i < 108; ++i)
+   {
+ char buf[1024], buf2[1024];
+ REAL_VALUE_TYPE tmp, tmp2;
+ real_convert (, DFmode, );
+ frange_nextafter (DFmode, tmp, dconstinf);
+ real_convert (, mode, );
+ real_to_hexadecimal (buf, , 1024, 0, 1);
+ real_to_hexadecimal (buf2, , 1024, 0, 1);
+ fprintf (stderr, "%d %d %s %s\n", i, real_isdenormal (), buf, 
buf2);
+ real_arithmetic (, MULT_EXPR, , );
+   }
+}
 }
 
 } // namespace selftest

  
in cross to 

Re: [PATCH] c++: libcpp: Support raw strings with newlines in directives [PR55971]

2022-11-04 Thread Jason Merrill via Gcc-patches

On 10/27/22 13:30, Lewis Hyatt wrote:

Hello-

May I please ask for a review of this patch from June? I realize it's a
10-year-old PR that doesn't seem to be bothering people much, but I still feel
like it's an unfortunate gap in C++11 support that is not hard to fix.

Original submission is here:
https://gcc.gnu.org/pipermail/gcc-patches/2022-June/596820.html

But I have attached a new version here that is simplified, all the
_Pragma-related stuff has been removed and I will handle that in a later patch
instead. I also removed the changes to c-ppoutput.cc that I realized were not
needed after all. Bootstrap+regtest all languages on x86-64 Linux still looks
good. Thanks!

-Lewis


OK, thanks.


-- >8 --

It's not currently possible to use a C++11 raw string containing a newline as
part of the definition of a macro, or in any other preprocessing directive,
such as:

  #define X R"(two
lines)"

  #error R"(this error has
two lines)"

Add support for that by relaxing the conditions under which
_cpp_get_fresh_line() refuses to get a new line. For the case of lexing a raw
string, it's OK to do so as long as there is another line within the current
buffer. The code in cpp_get_fresh_line() was refactored into a new function
get_fresh_line_impl(), so that the new logic is applied only when processing a
raw string and not any other times.

libcpp/ChangeLog:

PR preprocessor/55971
* lex.cc (get_fresh_line_impl): New function refactoring the code
from...
(_cpp_get_fresh_line): ...here.
(lex_raw_string): Use the new version of get_fresh_line_impl() to
support raw strings containing new lines when processing a directive.

gcc/testsuite/ChangeLog:

PR preprocessor/55971
* c-c++-common/raw-string-directive-1.c: New test.
* c-c++-common/raw-string-directive-2.c: New test.

gcc/c-family/ChangeLog:

PR preprocessor/55971
* c-ppoutput.cc (adjust_for_newlines): Update comment.
---
  gcc/c-family/c-ppoutput.cc| 10 ++-
  .../c-c++-common/raw-string-directive-1.c | 74 +++
  .../c-c++-common/raw-string-directive-2.c | 33 +
  libcpp/lex.cc | 41 +++---
  4 files changed, 148 insertions(+), 10 deletions(-)
  create mode 100644 gcc/testsuite/c-c++-common/raw-string-directive-1.c
  create mode 100644 gcc/testsuite/c-c++-common/raw-string-directive-2.c

diff --git a/gcc/c-family/c-ppoutput.cc b/gcc/c-family/c-ppoutput.cc
index a99d9e9c5ca..6e054358e9e 100644
--- a/gcc/c-family/c-ppoutput.cc
+++ b/gcc/c-family/c-ppoutput.cc
@@ -433,7 +433,15 @@ scan_translation_unit_directives_only (cpp_reader *pfile)
  lang_hooks.preprocess_token (pfile, NULL, streamer.filter);
  }
  
-/* Adjust print.src_line for newlines embedded in output.  */

+/* Adjust print.src_line for newlines embedded in output.  For example, if a 
raw
+   string literal contains newlines, then we need to increment our notion of 
the
+   current line to keep in sync and avoid outputting a line marker
+   unnecessarily.  If a raw string literal containing newlines is the result of
+   macro expansion, then we have the opposite problem, where the token takes up
+   more lines in the output than it did in the input, and hence a line marker 
is
+   needed to restore the correct state for subsequent lines.  In this case,
+   incrementing print.src_line still does the job, because it will cause us to
+   emit the line marker the next time a token is streamed.  */
  static void
  account_for_newlines (const unsigned char *str, size_t len)
  {
diff --git a/gcc/testsuite/c-c++-common/raw-string-directive-1.c 
b/gcc/testsuite/c-c++-common/raw-string-directive-1.c
new file mode 100644
index 000..d6525e107bc
--- /dev/null
+++ b/gcc/testsuite/c-c++-common/raw-string-directive-1.c
@@ -0,0 +1,74 @@
+/* { dg-do compile } */
+/* { dg-options "-std=gnu99" { target c } } */
+/* { dg-options "-std=c++11" { target c++ } } */
+
+/* Test that multi-line raw strings are lexed OK for all preprocessing
+   directives where one could appear. Test raw-string-directive-2.c
+   checks that #define is also processed properly.  */
+
+/* Note that in cases where we cause GCC to produce a multi-line error
+   message, we construct the string so that the second line looks enough
+   like an error message for DejaGNU to process it as such, so that we
+   can use dg-warning or dg-error directives to check for it.  */
+
+#warning R"delim(line1 /* { dg-warning "line1" } */
+file:15:1: warning: line2)delim" /* { dg-warning "line2" } */
+
+#error R"delim(line3 /* { dg-error "line3" } */
+file:18:1: error: line4)delim" /* { dg-error "line4" } */
+
+#define X1 R"(line 5
+line 6
+line 7
+line 8
+/*
+//
+line 9)" R"delim(
+line10)delim"
+
+#define X2(a) X1 #a R"(line 11
+/*
+line12
+)"
+
+#if R"(line 13 /* { dg-error "line13" } */
+file:35:1: error: line14)" /* { dg-error "line14\\)\"\" is not valid" } */
+#endif R"(line 15 /* { 

Re: [PATCH 2/2] libstdc++: Move stream initialization into compiled library [PR44952]

2022-11-04 Thread Florian Weimer via Gcc-patches
* Patrick Palka:

> On Fri, 4 Nov 2022, Florian Weimer wrote:
>
>> * Patrick Palka via Gcc-patches:
>> 
>> > This patch moves the global object for constructing the standard streams
>> > out from  and into the compiled library on targets that support
>> > the init_priority attribute.  This means that  no longer
>> > introduces a separate global constructor in each TU that includes it.
>> >
>> > We can do this only if the init_priority attribute is supported because
>> > we need to force that the stream initialization runs first before any
>> > user-defined global initializer in programs that that use a static
>> > libstdc++.a.
>> 
>> I think this breaks initialization of iostreams of shared objects that
>> are preloaded with LD_PRELOAD.  With the constructor, they initialize
>> iostreams once they are loaded via their own ELF constructors (even
>> before libstdc++'s ELF constructors run).  Without the constructor in
>> , that no longer happens.
>
> IIUC wouldn't that shared object depend on libstdc++.so and hence
> libstdc++'s constructors would still run before the shared object's?

Hmm, right, we only reorder the symbol binding order, not the
initialization order.  The preloaded object will not participate in a
cycle with libstdc++, so I think this should indeed be a safe change.

Thanks,
Florian



Re: [PATCH 2/2] libstdc++: Move stream initialization into compiled library [PR44952]

2022-11-04 Thread Patrick Palka via Gcc-patches
On Fri, 4 Nov 2022, Florian Weimer wrote:

> * Patrick Palka via Gcc-patches:
> 
> > This patch moves the global object for constructing the standard streams
> > out from  and into the compiled library on targets that support
> > the init_priority attribute.  This means that  no longer
> > introduces a separate global constructor in each TU that includes it.
> >
> > We can do this only if the init_priority attribute is supported because
> > we need to force that the stream initialization runs first before any
> > user-defined global initializer in programs that that use a static
> > libstdc++.a.
> 
> I think this breaks initialization of iostreams of shared objects that
> are preloaded with LD_PRELOAD.  With the constructor, they initialize
> iostreams once they are loaded via their own ELF constructors (even
> before libstdc++'s ELF constructors run).  Without the constructor in
> , that no longer happens.

IIUC wouldn't that shared object depend on libstdc++.so and hence
libstdc++'s constructors would still run before the shared object's?

> 
> Thanks,
> Florian
> 
> 



Re: [AArch64] Enable generation of FRINTNZ instructions

2022-11-04 Thread Andre Vieira (lists) via Gcc-patches
Sorry for the delay, just been reminded I still had this patch 
outstanding from last stage 1. Hopefully since it has been mostly 
reviewed it could go in for this stage 1?


I addressed the comments and gave the slp-part of vectorizable_call some 
TLC to make it work.


I also changed vect_get_slp_defs as I noticed that the call from 
vectorizable_call was creating an auto_vec with 'nargs' that might be 
less than the number of children in the slp_node, so that quick_push 
might not be safe as is, so I added the reserve (n) to ensure it's safe 
to push. I didn't actually come across any failure because of it though. 
Happy to split this into a separate patch if needed.


Bootstrapped and regression tested on aarch64-none-linux-gnu and 
x86_64-pc-linux-gnu.


OK for trunk?

gcc/ChangeLog:

    * config/aarch64/aarch64.md (ftrunc2): New 
pattern.

    * config/aarch64/iterators.md (FRINTNZ): New iterator.
    (frintnz_mode): New int attribute.
    (VSFDF): Make iterator conditional.
    * internal-fn.def (FTRUNC_INT): New IFN.
    * internal-fn.cc (ftrunc_int_direct): New define.
    (expand_ftrunc_int_optab_fn): New custom expander.
    (direct_ftrunc_int_optab_supported_p): New supported_p.
    * internal-fn.h (direct_internal_fn_info): Add new member
    type1_is_scalar_p.
    * match.pd: Add to the existing TRUNC pattern match.
    * optabs.def (ftrunc_int): New entry.
    * stor-layout.h (element_precision): Moved from here...
    * tree.h (element_precision): ... to here.
    (element_type): New declaration.
    * tree.cc (element_type): New function.
    (element_precision): Changed to use element_type.
    * tree-vect-stmts.cc (vectorizable_internal_function): Add 
support for

    IFNs with different input types.
    (vect_get_scalar_oprnds): New function.
    (vectorizable_call): Teach to handle IFN_FTRUNC_INT.
    * tree-vect-slp.cc (check_scalar_arg_ok): New function.
    (vect_slp_analyze_node_operations): Use check_scalar_arg_ok.
    (vect_get_slp_defs): Ensure vec_oprnds has enough slots to push.
    * doc/md.texi: New entry for ftrunc pattern name.
    * doc/sourcebuild.texi (aarch64_frintzx_ok): New target.

gcc/testsuite/ChangeLog:

    * gcc.target/aarch64/merge_trunc1.c: Adapted to skip if frintnz 
instructions available.
    * lib/target-supports.exp: Added aarch64_frintnzx_ok target and 
aarch64_frintz options.

    * gcc.target/aarch64/frintnz.c: New test.
    * gcc.target/aarch64/frintnz_vec.c: New test.
    * gcc.target/aarch64/frintnz_slp.c: New test.diff --git a/gcc/config/aarch64/aarch64.md b/gcc/config/aarch64/aarch64.md
index 
f2e3d905dbbeb2949f2947f5cfd68208c94c9272..47368e09b106e5b43640bd4f113abd0b9a15b9c8
 100644
--- a/gcc/config/aarch64/aarch64.md
+++ b/gcc/config/aarch64/aarch64.md
@@ -7564,12 +7564,18 @@
(set_attr "speculation_barrier" "true")]
 )
 
+(define_expand "ftrunc2"
+  [(set (match_operand:VSFDF 0 "register_operand" "=w")
+(unspec:VSFDF [(match_operand:VSFDF 1 "register_operand" "w")]
+ FRINTNZ))]
+  "TARGET_FRINT"
+)
+
 (define_insn "aarch64_"
   [(set (match_operand:VSFDF 0 "register_operand" "=w")
(unspec:VSFDF [(match_operand:VSFDF 1 "register_operand" "w")]
  FRINTNZX))]
-  "TARGET_FRINT && TARGET_FLOAT
-   && !(VECTOR_MODE_P (mode) && !TARGET_SIMD)"
+  "TARGET_FRINT"
   "\\t%0, %1"
   [(set_attr "type" "f_rint")]
 )
diff --git a/gcc/config/aarch64/iterators.md b/gcc/config/aarch64/iterators.md
index 
a8ad4e5ff215ade06c3ca13a24ef18d259afcb6c..b1f78d87fbe6118e792b00580c6beb23ce63e27c
 100644
--- a/gcc/config/aarch64/iterators.md
+++ b/gcc/config/aarch64/iterators.md
@@ -173,7 +173,11 @@
  SF DF])
 
 ;; Scalar and vetor modes for SF, DF.
-(define_mode_iterator VSFDF [V2SF V4SF V2DF DF SF])
+(define_mode_iterator VSFDF [(V2SF "TARGET_SIMD")
+(V4SF "TARGET_SIMD")
+(V2DF "TARGET_SIMD")
+(DF "TARGET_FLOAT")
+(SF "TARGET_FLOAT")])
 
 ;; Advanced SIMD single Float modes.
 (define_mode_iterator VDQSF [V2SF V4SF])
@@ -3136,6 +3140,8 @@
 (define_int_iterator FRINTNZX [UNSPEC_FRINT32Z UNSPEC_FRINT32X
   UNSPEC_FRINT64Z UNSPEC_FRINT64X])
 
+(define_int_iterator FRINTNZ [UNSPEC_FRINT32Z UNSPEC_FRINT64Z])
+
 (define_int_iterator SVE_BRK_UNARY [UNSPEC_BRKA UNSPEC_BRKB])
 
 (define_int_iterator SVE_BRKP [UNSPEC_BRKPA UNSPEC_BRKPB])
@@ -3545,6 +3551,8 @@
 (define_int_attr frintnzs_op [(UNSPEC_FRINT32Z "frint32z") (UNSPEC_FRINT32X 
"frint32x")
  (UNSPEC_FRINT64Z "frint64z") (UNSPEC_FRINT64X 
"frint64x")])
 
+(define_int_attr frintnz_mode [(UNSPEC_FRINT32Z "si") (UNSPEC_FRINT64Z "di")])
+
 ;; The condition associated with an UNSPEC_COND_.
 (define_int_attr cmp_op [(UNSPEC_COND_CMPEQ_WIDE "eq")
   

[PATCH] gcc/file-prefix-map: Fix NULL filename handling

2022-11-04 Thread Richard Purdie via Gcc-patches
e5c15eb183f17e806ad6b58c9497321ded87866f introduced a regression as
some ada tests end up passing NULL as the filename to remap_filename().
Handle this as before to fix the tests.

gcc/ChangeLog:

* file-prefix-map.cc (remap_filename): Handle NULL filenames.

Signed-off-by: Richard Purdie 
---
 gcc/file-prefix-map.cc | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/gcc/file-prefix-map.cc b/gcc/file-prefix-map.cc
index 439586bd2b5..40b10edcf92 100644
--- a/gcc/file-prefix-map.cc
+++ b/gcc/file-prefix-map.cc
@@ -73,7 +73,7 @@ remap_filename (file_prefix_map *maps, const char *filename)
   char *realname;
   size_t name_len;
 
-  if (lbasename (filename) == filename)
+  if (!filename || lbasename (filename) == filename)
 return filename;
 
   realname = lrealpath (filename);
-- 
2.34.1



Re: [PATCH 1/2] gcc/file-prefix-map: Allow remapping of relative paths

2022-11-04 Thread Richard Purdie via Gcc-patches
On Fri, 2022-11-04 at 10:12 +0100, Eric Botcazou wrote:
> > gcc/ChangeLog:
> > 
> > * file-prefix-map.cc (remap_filename): Allow remapping of
> > relative paths
> 
> Small regression in Ada though, probably a missing guard somewhere:
> 
> === gnat tests ===
> 
> 
> Running target unix
> FAIL: gnat.dg/specs/coverage1.ads (test for excess errors)
> 
> In order to reproduce, configure the compiler with Ada enabled, build
> it, and 
> copy $[srcdir)/gcc/testsuite/gnat.dg/specs/coverage1.ads into the
> build 
> directory, then just issue:
> 
> gcc/gnat1 -quiet coverage1.ads -ftest-coverage -Igcc/ada/rts
> 
> raised STORAGE_ERROR : stack overflow or erroneous memory access

It took me a while to work out how to get ada to build. When I did I
found it was faulting due to a NULL filename being passed to lbasename:

Program received signal SIGSEGV, Segmentation fault.
lbasename (name=0x0) at gcc/libiberty/lbasename.c:82
82return unix_lbasename (name);
(gdb) bt
#0  lbasename (name=0x0) at gcc/libiberty/lbasename.c:82
#1  0x00f3d566 in remap_filename (maps=0x0, 
filename=filename@entry=0x0) at gcc/gcc/file-prefix-map.cc:76
#2  0x00f3d6df in remap_profile_filename (filename=filename@entry=0x0) 
at gcc/gcc/file-prefix-map.cc:158
#3  0x00e59f59 in coverage_begin_function 
(lineno_checksum=lineno_checksum@entry=595732889, 
cfg_checksum=cfg_checksum@entry=2754642872)
at gcc/gcc/coverage.cc:650
#4  0x012263c0 in branch_prob (thunk=thunk@entry=false) at 
gcc/gcc/profile.cc:1400
#5  0x013b1205 in tree_profiling () at gcc/gcc/tree-profile.cc:782
#6  (anonymous namespace)::pass_ipa_tree_profile::execute (this=) at gcc/gcc/tree-profile.cc:888
#7  0x011ef30b in execute_one_pass (pass=0x36ebea0) at 
gcc/gcc/passes.cc:2644
#8  0x011f0697 in execute_ipa_pass_list (pass=0x36ebea0) at 
gcc/gcc/passes.cc:3093
#9  0x00e4c28d in ipa_passes () at gcc/gcc/cgraphunit.cc:2170
#10 symbol_table::compile (this=0x7718f000) at gcc/gcc/cgraphunit.cc:2291
#11 0x00e4ec08 in symbol_table::compile (this=0x7718f000) at 
gcc/gcc/cgraphunit.cc:2271
#12 symbol_table::finalize_compilation_unit (this=0x7718f000) at 
gcc/gcc/cgraphunit.cc:2543
#13 0x012cfea0 in compile_file () at gcc/gcc/toplev.cc:471
#14 0x009a727c in do_compile (no_backend=false) at 
gcc/gcc/toplev.cc:2125
#15 toplev::main (this=this@entry=0x7fffe21e, argc=, 
argc@entry=4, argv=, argv@entry=0x7fffe348) at 
gcc/gcc/toplev.cc:2277
#16 0x009a8a8b in main (argc=4, argv=0x7fffe348) at 
gcc/gcc/main.cc:39

I can send the obvious patch to make it work as before and ignore the
NULL which fixes this. I'm not sure if it should really be passing NULL
around in the first place or not which is why I'm sharing the
backtrace.

Cheers,

Richard


Re: [PATCH] testsuite: Add testcase from C++23 P2314R4 - Character sets and encodings

2022-11-04 Thread Jason Merrill via Gcc-patches

On 11/4/22 05:14, Jakub Jelinek wrote:

Hi!

I've read the paper and I believe we just implement it with no changes
needed (at least since PR67224 and similar libcpp changes in GCC 10),
but I could be wrong.

The following patch at least adds a testcase from the start of the paper.

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


OK.


Do you agree that we can mark the paper as implemented or do you think
we need to change something (what?)?


I agree.


2022-11-04  Jakub Jelinek  

* g++.dg/cpp23/charset1.C: New testcase from C++23 P2314R4.

--- gcc/testsuite/g++.dg/cpp23/charset1.C.jj2022-11-03 10:56:48.114588796 
+0100
+++ gcc/testsuite/g++.dg/cpp23/charset1.C   2022-11-03 10:56:39.162711201 
+0100
@@ -0,0 +1,10 @@
+// P2314R4
+// { dg-do compile { target c++23 } }
+// { dg-options "-finput-charset=UTF-8 -fexec-charset=UTF-8" }
+
+#define S(x) # x
+const char s1[] = S(Köppe);   // "Köppe"
+const char s2[] = S(K\u00f6ppe);  // "Köppe"
+
+static_assert (sizeof (s1) == 7);
+static_assert (sizeof (s2) == 7);

Jakub





[committed] AArch64: Fix testcase

2022-11-04 Thread Wilco Dijkstra via Gcc-patches
Committed as trivial fix.

gcc/testsuite/
* gcc.target/aarch64/mgeneral-regs_3.c: Fix testcase.

---

diff --git a/gcc/testsuite/gcc.target/aarch64/mgeneral-regs_3.c 
b/gcc/testsuite/gcc.target/aarch64/mgeneral-regs_3.c
index 
fa6299960e77141ce747552cfbe3256a7a96d229..4e634f6ebe2b769b85417bca056457b9176645c4
 100644
--- a/gcc/testsuite/gcc.target/aarch64/mgeneral-regs_3.c
+++ b/gcc/testsuite/gcc.target/aarch64/mgeneral-regs_3.c
@@ -3,9 +3,9 @@
 extern void abort (void);
 
 int
-test (int i, ...)
+test (int i, ...) /* { dg-error "'-mgeneral-regs-only' is incompatible with 
the use of floating-point types" } */
 {
-  float f = (float) i; /* { dg-error "'-mgeneral-regs-only' is incompatible 
with the use of floating-point types" } */
-  if (f != f) abort ();
+  float f = (float) i;
+  if (f != 0) abort ();
   return 2;
 }


Re: [PATCH RFA] input: add get_source_text_between

2022-11-04 Thread Jason Merrill via Gcc-patches

On 11/4/22 11:16, David Malcolm wrote:

On Fri, 2022-11-04 at 10:27 -0400, Jason Merrill wrote:

On 11/3/22 19:06, David Malcolm wrote:

On Thu, 2022-11-03 at 15:59 -0400, Jason Merrill via Gcc-patches
wrote:


[...snip...]




Do you have test coverage for this from the DejaGnu side?  If not,
you
could add selftest coverage for this; see input.cc's
test_reading_source_line for something similar.


There is test coverage for the output of the the contract violation
handler, which involves printing the result of this function.


Thanks.   Is this test posted somwehere?  I was looking in:
  https://gcc.gnu.org/pipermail/gcc-patches/2022-November/604974.html
but I'm not seeing it.  Sorry if I'm missing something here.


The tests are in the newer message

  https://gcc.gnu.org/pipermail/gcc-patches/2022-November/605072.html


Ideally we should have coverage for the three cases of:
(a) bails out and returns NULL


This isn't tested because it should never happen.


(b) single-line case


contracts-tmpl-spec3.C etc.


(c) multi-line case


contracts-multiline1.C


index a28abfac5ac..04d0809bfdf 100644
--- a/gcc/input.cc
+++ b/gcc/input.cc
@@ -949,6 +949,97 @@ location_get_source_line (const char *file_path, int line)
return char_span (buffer, len);
  }


Strings in input.cc are not always NUL-terminated, so...

  
+/* Return a copy of the source text between two locations.  The caller is

+   responsible for freeing the return value.  */


...please note in the comment that if non-NULL, the copy is NUL-
terminated (I checked both exit paths that can return non-NULL, and
they do NUL-terminate their buffers).

OK with that nit fixed.


Thanks, pushing this:
From 35d436c8e9455e99015d0e414a4ede9e59e774c4 Mon Sep 17 00:00:00 2001
From: Jeff Chapman II 
Date: Thu, 3 Nov 2022 15:47:47 -0400
Subject: [PATCH] input: add get_source_text_between
To: gcc-patches@gcc.gnu.org

The c++-contracts branch uses this to retrieve the source form of the
contract predicate, to be returned by contract_violation::comment().

Co-authored-by: Jason Merrill  

gcc/ChangeLog:

	* input.cc (get_source_text_between): New fn.
	* input.h (get_source_text_between): Declare.
---
 gcc/input.h  |  1 +
 gcc/input.cc | 92 
 2 files changed, 93 insertions(+)

diff --git a/gcc/input.h b/gcc/input.h
index 11c571d076f..f18769950b5 100644
--- a/gcc/input.h
+++ b/gcc/input.h
@@ -111,6 +111,7 @@ class char_span
 };
 
 extern char_span location_get_source_line (const char *file_path, int line);
+extern char *get_source_text_between (location_t, location_t);
 
 extern bool location_missing_trailing_newline (const char *file_path);
 
diff --git a/gcc/input.cc b/gcc/input.cc
index a28abfac5ac..c185bd74c1f 100644
--- a/gcc/input.cc
+++ b/gcc/input.cc
@@ -949,6 +949,98 @@ location_get_source_line (const char *file_path, int line)
   return char_span (buffer, len);
 }
 
+/* Return a NUL-terminated copy of the source text between two locations, or
+   NULL if the arguments are invalid.  The caller is responsible for freeing
+   the return value.  */
+
+char *
+get_source_text_between (location_t start, location_t end)
+{
+  expanded_location expstart =
+expand_location_to_spelling_point (start, LOCATION_ASPECT_START);
+  expanded_location expend =
+expand_location_to_spelling_point (end, LOCATION_ASPECT_FINISH);
+
+  /* If the locations are in different files or the end comes before the
+ start, give up and return nothing.  */
+  if (!expstart.file || !expend.file)
+return NULL;
+  if (strcmp (expstart.file, expend.file) != 0)
+return NULL;
+  if (expstart.line > expend.line)
+return NULL;
+  if (expstart.line == expend.line
+  && expstart.column > expend.column)
+return NULL;
+  /* These aren't real column numbers, give up.  */
+  if (expstart.column == 0 || expend.column == 0)
+return NULL;
+
+  /* For a single line we need to trim both edges.  */
+  if (expstart.line == expend.line)
+{
+  char_span line = location_get_source_line (expstart.file, expstart.line);
+  if (line.length () < 1)
+	return NULL;
+  int s = expstart.column - 1;
+  int len = expend.column - s;
+  if (line.length () < (size_t)expend.column)
+	return NULL;
+  return line.subspan (s, len).xstrdup ();
+}
+
+  struct obstack buf_obstack;
+  obstack_init (_obstack);
+
+  /* Loop through all lines in the range and append each to buf; may trim
+ parts of the start and end lines off depending on column values.  */
+  for (int lnum = expstart.line; lnum <= expend.line; ++lnum)
+{
+  char_span line = location_get_source_line (expstart.file, lnum);
+  if (line.length () < 1 && (lnum != expstart.line && lnum != expend.line))
+	continue;
+
+  /* For the first line in the range, only start at expstart.column */
+  if (lnum == expstart.line)
+	{
+	  unsigned off = expstart.column - 1;
+	  if (line.length () < off)
+	return NULL;
+	  line = line.subspan 

Re: [PATCH 2/2] libstdc++: Move stream initialization into compiled library [PR44952]

2022-11-04 Thread Florian Weimer via Gcc-patches
* Patrick Palka via Gcc-patches:

> This patch moves the global object for constructing the standard streams
> out from  and into the compiled library on targets that support
> the init_priority attribute.  This means that  no longer
> introduces a separate global constructor in each TU that includes it.
>
> We can do this only if the init_priority attribute is supported because
> we need to force that the stream initialization runs first before any
> user-defined global initializer in programs that that use a static
> libstdc++.a.

I think this breaks initialization of iostreams of shared objects that
are preloaded with LD_PRELOAD.  With the constructor, they initialize
iostreams once they are loaded via their own ELF constructors (even
before libstdc++'s ELF constructors run).  Without the constructor in
, that no longer happens.

Thanks,
Florian



Re: [PATCH 2/2] libstdc++: Move stream initialization into compiled library [PR44952]

2022-11-04 Thread Jonathan Wakely via Gcc-patches
On Fri, 4 Nov 2022 at 16:31, Patrick Palka  wrote:
>
> On Fri, 4 Nov 2022, Jonathan Wakely wrote:
>
> > On Fri, 4 Nov 2022 at 15:08, Patrick Palka via Libstdc++
> >  wrote:
> > >
> > > This patch moves the global object for constructing the standard streams
> > > out from  and into the compiled library on targets that support
> > > the init_priority attribute.  This means that  no longer
> > > introduces a separate global constructor in each TU that includes it.
> > >
> > > We can do this only if the init_priority attribute is supported because
> > > we need to force that the stream initialization runs first before any
> > > user-defined global initializer in programs that that use a static
> > > libstdc++.a.
> > >
> > > Bootstrapped and regtested on x86_64-pc-linux-gnu, does this look right?
> > > Unfortunately I don't have access to a system that truly doesn't support
> > > init priorities, so I instead tested that situation by artificially
> > > disabling the init_priority attribute on x86_64.
> > >
> > > PR libstdc++/44952
> > > PR libstdc++/98108
> > >
> > > libstdc++-v3/ChangeLog:
> > >
> > > * include/bits/c++config (_GLIBCXX_HAS_ATTRIBUTE): Define.
> > > (_GLIBCXX_HAVE_ATTRIBUTE_INIT_PRIORITY): Define.
> > > * include/std/iostream (__ioinit): Define only if init_priority
> > > attribute isn't usable.
> > > * src/c++98/ios_init.cc (__ioinit): Define here instead if
> > > the init_priority is usable.
> > > * src/c++98/ios_base_init.h: New file.
> > > ---
> > >  libstdc++-v3/include/bits/c++config| 12 
> > >  libstdc++-v3/include/std/iostream  |  4 
> > >  libstdc++-v3/src/c++98/ios_base_init.h |  9 +
> > >  libstdc++-v3/src/c++98/ios_init.cc |  4 
> > >  4 files changed, 29 insertions(+)
> > >  create mode 100644 libstdc++-v3/src/c++98/ios_base_init.h
> > >
> > > diff --git a/libstdc++-v3/include/bits/c++config 
> > > b/libstdc++-v3/include/bits/c++config
> > > index 50406066afe..f93076191d9 100644
> > > --- a/libstdc++-v3/include/bits/c++config
> > > +++ b/libstdc++-v3/include/bits/c++config
> > > @@ -837,6 +837,18 @@ namespace __gnu_cxx
> > >
> > >  #undef _GLIBCXX_HAS_BUILTIN
> > >
> > > +#ifdef __has_attribute
> >
> > Do we need this?
> > I think all the compilers we support implemented this long ago (clang
> > had it before gcc, and Intel has it for gcc compat, and any others had
> > better have it by now too).
> >
> > So we can just use #if __has_attribute directly, instead of defining
> > these extra macros.
>
> Sounds good, I wasn't sure if we can assume support for __has_attribute
> or not.
>
> >
> > > +# define _GLIBCXX_HAS_ATTRIBUTE(B) __has_attribute(B)
> > > +#else
> > > +# define _GLIBCXX_HAS_ATTRIBUTE(B) 0
> > > +#endif
> > > +
> > > +#if _GLIBCXX_HAS_ATTRIBUTE(init_priority)
> > > +# define _GLIBCXX_HAVE_ATTRIBUTE_INIT_PRIORITY 1
> > > +#endif
> > > +
> > > +#undef _GLIBCXX_HAS_ATTRIBUTE
> > > +
> > >  // Mark code that should be ignored by the compiler, but seen by Doxygen.
> > >  #define _GLIBCXX_DOXYGEN_ONLY(X)
> > >
> > > diff --git a/libstdc++-v3/include/std/iostream 
> > > b/libstdc++-v3/include/std/iostream
> > > index 70318a45891..5eaa9755d9a 100644
> > > --- a/libstdc++-v3/include/std/iostream
> > > +++ b/libstdc++-v3/include/std/iostream
> > > @@ -73,7 +73,11 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
> > >///@}
> > >
> > >// For construction of filebuffers for cout, cin, cerr, clog et. al.
> > > +  // When the init_priority attribute is usable, we do this 
> > > initialization
> > > +  // in the compiled library instead (see src/c++98/ios_init.cc).
> > > +#if !_GLIBCXX_HAVE_ATTRIBUTE_INIT_PRIORITY
> > >static ios_base::Init __ioinit;
> > > +#endif
> > >
> > >  _GLIBCXX_END_NAMESPACE_VERSION
> > >  } // namespace
> > > diff --git a/libstdc++-v3/src/c++98/ios_base_init.h 
> > > b/libstdc++-v3/src/c++98/ios_base_init.h
> > > new file mode 100644
> > > index 000..f3087d1da3c
> > > --- /dev/null
> > > +++ b/libstdc++-v3/src/c++98/ios_base_init.h
> > > @@ -0,0 +1,9 @@
> > > +// This is only in a header so we can use the system_header pragma,
> > > +// to suppress the warning caused by using a reserved init_priority.
> > > +#pragma GCC system_header
> >
> > Ugh, that's annoying.
>
> Yeah :( we employ the same workaround in
> src/c++17/{memory_resource.cc,default_resource.h} too.
>
> Here's v2 which gets rid of the new macros, adds more comments and other
> minor improvements.  Only smoke tested so far, full bootstrap and
> regtesting in progress:

OK for trunk assuming testing passes.

Thanks for working on it.


>
> -- >8 --
>
> Subject: [PATCH 2/2] libstdc++: Move stream initialization into compiled
>  library [PR44952]
>
> This patch moves the global object for constructing the standard streams
> out from  and into the compiled library on targets that support
> init priorities.  This means that  no longer introduces a
> separate global constructor in 

Re: [PATCH 5/6] diagnostics: Support generated data in additional contexts

2022-11-04 Thread David Malcolm via Gcc-patches
On Fri, 2022-11-04 at 09:44 -0400, Lewis Hyatt via Gcc-patches wrote:
> Add awareness that diagnostic locations may be in generated buffers
> rather
> than an actual file to other places in the diagnostics code that may
> care,
> most notably SARIF output (which needs to obtain its own snapshots of
> the code
> involved). For edit context output, which outputs fixit hints as
> diffs, for
> now just make sure we ignore generated data buffers. At the moment,
> there is
> no ability for a fixit hint to be generated in such a buffer.
> 
> Because SARIF uses JSON as well, also add the ability to the
> json::string
> class to handle a buffer with nulls in the middle (since we place no
> restriction on LC_GEN content) by providing the option to specify the
> data
> length.

Please can you split this patch into three parts:
- the SARIF part
- the json changes
- the edit-context.cc changes (I think this at least counts as an
"obvious" change with respect to the other changes in the kit, though
I'm still working my way through patch 4 in the kit).

Please add a DejaGnu testcase to the SARIF part, with a diagnostic that
references a generated data buffer; see
  gcc/testsuite/c-c++-common/diagnostic-format-sarif-file-*.c 
for examples of SARIF testcases.

Please add a selftest to the json change so that we have a unit test of
constructing a json::string with an embedded NUL, and how we serialize
such a string (probably to json.cc's test_writing_strings)

Thanks
Dave

> 
> gcc/ChangeLog:
> 
> * diagnostic-format-sarif.cc (sarif_builder::xloc_to_fb): New
> function.
> (sarif_builder::maybe_make_physical_location_object): Support
> generated data locations.
> (sarif_builder::make_artifact_location_object): Likewise.
> (sarif_builder::maybe_make_region_object_for_context):
> Likewise.
> (sarif_builder::make_artifact_object): Likewise.
> (sarif_builder::maybe_make_artifact_content_object):
> Likewise.
> (get_source_lines): Likewise.
> * edit-context.cc (edit_context::apply_fixit): Ignore
> generated
> locations if one should make its way this far.
> * json.cc (string::string): Support non-null-terminated
> string.
> (string::print): Likewise.
> * json.h (class string): Likewise.
> ---
>  gcc/diagnostic-format-sarif.cc | 86 +---
> --
>  gcc/edit-context.cc    |  4 ++
>  gcc/json.cc    | 17 +--
>  gcc/json.h |  5 +-
>  4 files changed, 75 insertions(+), 37 deletions(-)
> 
> diff --git a/gcc/diagnostic-format-sarif.cc b/gcc/diagnostic-format-
> sarif.cc
> index 7110db4edd6..c2d18a1a16e 100644
> --- a/gcc/diagnostic-format-sarif.cc
> +++ b/gcc/diagnostic-format-sarif.cc
> @@ -125,7 +125,10 @@ private:
>    json::array *maybe_make_kinds_array (diagnostic_event::meaning m)
> const;
>    json::object *maybe_make_physical_location_object (location_t
> loc);
>    json::object *make_artifact_location_object (location_t loc);
> -  json::object *make_artifact_location_object (const char
> *filename);
> +
> +  typedef std::pair filename_or_buffer;
> +  json::object *make_artifact_location_object (filename_or_buffer
> fb);
> +
>    json::object *make_artifact_location_object_for_pwd () const;
>    json::object *maybe_make_region_object (location_t loc) const;
>    json::object *maybe_make_region_object_for_context (location_t
> loc) const;
> @@ -146,16 +149,17 @@ private:
>    json::object *make_reporting_descriptor_object_for_cwe_id (int
> cwe_id) const;
>    json::object *
>    make_reporting_descriptor_reference_object_for_cwe_id (int
> cwe_id);
> -  json::object *make_artifact_object (const char *filename);
> -  json::object *maybe_make_artifact_content_object (const char
> *filename) const;
> -  json::object *maybe_make_artifact_content_object (const char
> *filename,
> -   int start_line,
> +  json::object *make_artifact_object (filename_or_buffer fb);
> +  json::object *
> +  maybe_make_artifact_content_object (filename_or_buffer fb) const;
> +  json::object *maybe_make_artifact_content_object
> (expanded_location xloc,
>     int end_line)
> const;
>    json::object *make_fix_object (const rich_location _loc);
>    json::object *make_artifact_change_object (const rich_location
> );
>    json::object *make_replacement_object (const fixit_hint )
> const;
>    json::object *make_artifact_content_object (const char *text)
> const;
>    int get_sarif_column (expanded_location exploc) const;
> +  static filename_or_buffer xloc_to_fb (expanded_location xloc);
>  
>    diagnostic_context *m_context;
>  
> @@ -166,7 +170,11 @@ private:
>   diagnostic group.  */
>    sarif_result *m_cur_group_result;
>  
> -  hash_set  m_filenames;
> +  /* If the second member is >0, then this is a buffer of generated
> content,
> + with that length, not a filename.  */
> +  

[PATCH] symtab: also change RTL decl name [was: RFH: attr target_clones default assembler name ignored?]

2022-11-04 Thread Bernhard Reutner-Fischer via Gcc-patches
On Thu, 3 Nov 2022 23:23:55 +0100
Bernhard Reutner-Fischer  wrote:

> Hi!
> 
> I encounter a problem/pilot error when using the target_clones
> attribute.
> 
> The symptom is that the default clone is not renamed in the output and
> thus conflicts with the (proper) global name which is used for the
> ifunc:
> 
> $ nl -ba < /tmp/cc3jBX3x.s | grep sub1
> 12.type   __m_MOD_sub1, @function
> 13__m_MOD_sub1:
> 35.size   __m_MOD_sub1, .-__m_MOD_sub1
> ...
> 87__m_MOD_sub1.resolver:
> 95movl$__m_MOD_sub1.avx, %eax
>104movl$__m_MOD_sub1, %eax
>105movl$__m_MOD_sub1.sse, %edx
>110.size   __m_MOD_sub1.resolver, .-__m_MOD_sub1.resolver
>111.globl  __m_MOD_sub1
>112.type   __m_MOD_sub1, @gnu_indirect_function
>113.set__m_MOD_sub1,__m_MOD_sub1.resolver
> 
> I think that line 13 and 104 should talk about __m_MOD_sub1.default.
> 
> AFAICT the target_clones attr is built well.
> gcc/multiple_target.cc:expand_target_clones() adds the required
> attr "target" "default"
> and properly does:
> (gdb) p old_name
> $6 = 0x76dfc090 "__m_MOD_sub1"
> (gdb) call debug_tree ( DECL_ASSEMBLER_NAME (decl) )
>  
> (gdb) n
> 301 && DECL_RTL_SET_P (decl))
> (gdb) n
> 300 if (TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl))
> (gdb) n
> 304 SET_DECL_ASSEMBLER_NAME (decl, name);
> (gdb) n
> 305 if (alias)
> (gdb) call debug_tree ( DECL_ASSEMBLER_NAME (decl) )
>  
> 
> So if that would have been used for real, all would be fine i think.
> 
> But still, that name is somehow not used, see fnname:
> #0  assemble_start_function (decl=, 
> fnname=fnname@entry=0x76dfc090 "__m_MOD_sub1") at 
> ../../../src/gcc-13.mine/gcc/varasm.cc:1979

> I'd be grateful for help to understand why/who chooses to pick an unpleasant
> name, and, primarily, how to avoid that problem.
> 
> Thoughts or hints?
> TIA!
> PS: Should i have rather asked on gcc-help?

We make_decl_rtl rather early when creating a function and set the name
to the (unversioned, from the POV of target_clones) initial name of the
function. Then we parse the attributes and attach it to the fndecl when
lowering. Later on the ME creates the clones and renames the function
via symbol_table::change_decl_assembler_name() which changes just the
DECL_ASSEMBLER_NAME and not the name in the DECL_RTL.

With this, the target_clones attribute works for me from the Fortran
FE.

The following tests cleanly for --enable-languages=c,fortran,c++,lto
Ok for trunk?

PS: I did not look if it would be possible to change the way this
fnname (as per get_fnname_from_decl()) is stored in both RTL and tree
in apparently two different places. I would have assumed that varasm
uses a name via cgraph but that's obviously not (always) the case.

gcc/ChangeLog:

* symtab.cc: Remove stray comment.
(symbol_table::change_decl_assembler_name): Also update the
name in DECL_RTL.

diff --git a/gcc/symtab.cc b/gcc/symtab.cc
index f2d96c0268b..53a1a2a26bf 100644
--- a/gcc/symtab.cc
+++ b/gcc/symtab.cc
@@ -153,10 +153,8 @@ symbol_table::decl_assembler_name_equal (tree decl, 
const_tree asmname)
   return assembler_names_equal_p (decl_str, asmname_str);
 }
 
 
-/* Returns nonzero if P1 and P2 are equal.  */
-
 /* Insert NODE to assembler name hash.  */
 
 void
 symbol_table::insert_to_assembler_name_hash (symtab_node *node,
@@ -302,8 +301,12 @@ symbol_table::change_decl_assembler_name (tree decl, tree 
name)
  && DECL_RTL_SET_P (decl))
warning (0, "%qD renamed after being referenced in assembly", decl);
 
   SET_DECL_ASSEMBLER_NAME (decl, name);
+  /* Set the new name in rtl.  */
+  if (DECL_RTL_SET_P (decl))
+   XSTR (XEXP (DECL_RTL (decl), 0), 0) = IDENTIFIER_POINTER (name);
+
   if (alias)
{
  IDENTIFIER_TRANSPARENT_ALIAS (name) = 1;
  TREE_CHAIN (name) = alias;




Re: [PATCH 2/2] libstdc++: Move stream initialization into compiled library [PR44952]

2022-11-04 Thread Patrick Palka via Gcc-patches
On Fri, 4 Nov 2022, Jonathan Wakely wrote:

> On Fri, 4 Nov 2022 at 15:08, Patrick Palka via Libstdc++
>  wrote:
> >
> > This patch moves the global object for constructing the standard streams
> > out from  and into the compiled library on targets that support
> > the init_priority attribute.  This means that  no longer
> > introduces a separate global constructor in each TU that includes it.
> >
> > We can do this only if the init_priority attribute is supported because
> > we need to force that the stream initialization runs first before any
> > user-defined global initializer in programs that that use a static
> > libstdc++.a.
> >
> > Bootstrapped and regtested on x86_64-pc-linux-gnu, does this look right?
> > Unfortunately I don't have access to a system that truly doesn't support
> > init priorities, so I instead tested that situation by artificially
> > disabling the init_priority attribute on x86_64.
> >
> > PR libstdc++/44952
> > PR libstdc++/98108
> >
> > libstdc++-v3/ChangeLog:
> >
> > * include/bits/c++config (_GLIBCXX_HAS_ATTRIBUTE): Define.
> > (_GLIBCXX_HAVE_ATTRIBUTE_INIT_PRIORITY): Define.
> > * include/std/iostream (__ioinit): Define only if init_priority
> > attribute isn't usable.
> > * src/c++98/ios_init.cc (__ioinit): Define here instead if
> > the init_priority is usable.
> > * src/c++98/ios_base_init.h: New file.
> > ---
> >  libstdc++-v3/include/bits/c++config| 12 
> >  libstdc++-v3/include/std/iostream  |  4 
> >  libstdc++-v3/src/c++98/ios_base_init.h |  9 +
> >  libstdc++-v3/src/c++98/ios_init.cc |  4 
> >  4 files changed, 29 insertions(+)
> >  create mode 100644 libstdc++-v3/src/c++98/ios_base_init.h
> >
> > diff --git a/libstdc++-v3/include/bits/c++config 
> > b/libstdc++-v3/include/bits/c++config
> > index 50406066afe..f93076191d9 100644
> > --- a/libstdc++-v3/include/bits/c++config
> > +++ b/libstdc++-v3/include/bits/c++config
> > @@ -837,6 +837,18 @@ namespace __gnu_cxx
> >
> >  #undef _GLIBCXX_HAS_BUILTIN
> >
> > +#ifdef __has_attribute
> 
> Do we need this?
> I think all the compilers we support implemented this long ago (clang
> had it before gcc, and Intel has it for gcc compat, and any others had
> better have it by now too).
> 
> So we can just use #if __has_attribute directly, instead of defining
> these extra macros.

Sounds good, I wasn't sure if we can assume support for __has_attribute
or not.

> 
> > +# define _GLIBCXX_HAS_ATTRIBUTE(B) __has_attribute(B)
> > +#else
> > +# define _GLIBCXX_HAS_ATTRIBUTE(B) 0
> > +#endif
> > +
> > +#if _GLIBCXX_HAS_ATTRIBUTE(init_priority)
> > +# define _GLIBCXX_HAVE_ATTRIBUTE_INIT_PRIORITY 1
> > +#endif
> > +
> > +#undef _GLIBCXX_HAS_ATTRIBUTE
> > +
> >  // Mark code that should be ignored by the compiler, but seen by Doxygen.
> >  #define _GLIBCXX_DOXYGEN_ONLY(X)
> >
> > diff --git a/libstdc++-v3/include/std/iostream 
> > b/libstdc++-v3/include/std/iostream
> > index 70318a45891..5eaa9755d9a 100644
> > --- a/libstdc++-v3/include/std/iostream
> > +++ b/libstdc++-v3/include/std/iostream
> > @@ -73,7 +73,11 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
> >///@}
> >
> >// For construction of filebuffers for cout, cin, cerr, clog et. al.
> > +  // When the init_priority attribute is usable, we do this initialization
> > +  // in the compiled library instead (see src/c++98/ios_init.cc).
> > +#if !_GLIBCXX_HAVE_ATTRIBUTE_INIT_PRIORITY
> >static ios_base::Init __ioinit;
> > +#endif
> >
> >  _GLIBCXX_END_NAMESPACE_VERSION
> >  } // namespace
> > diff --git a/libstdc++-v3/src/c++98/ios_base_init.h 
> > b/libstdc++-v3/src/c++98/ios_base_init.h
> > new file mode 100644
> > index 000..f3087d1da3c
> > --- /dev/null
> > +++ b/libstdc++-v3/src/c++98/ios_base_init.h
> > @@ -0,0 +1,9 @@
> > +// This is only in a header so we can use the system_header pragma,
> > +// to suppress the warning caused by using a reserved init_priority.
> > +#pragma GCC system_header
> 
> Ugh, that's annoying.

Yeah :( we employ the same workaround in
src/c++17/{memory_resource.cc,default_resource.h} too.

Here's v2 which gets rid of the new macros, adds more comments and other
minor improvements.  Only smoke tested so far, full bootstrap and
regtesting in progress:

-- >8 --

Subject: [PATCH 2/2] libstdc++: Move stream initialization into compiled
 library [PR44952]

This patch moves the global object for constructing the standard streams
out from  and into the compiled library on targets that support
init priorities.  This means that  no longer introduces a
separate global constructor in each TU that includes it.

We can do this only if the init_priority attribute is supported because
we need a way to force the stream initialization to run first before any
user-defined global initializer, particularly for programs that use a
static libstdc++.a.

Bootstrapped and regtested on x86_64-pc-linux-gnu, does this look right?
Unfortunately I don't have 

Re: [PATCH 1/2] c++: correct __has_attribute(init_priority)

2022-11-04 Thread Jason Merrill via Gcc-patches

On 11/4/22 11:05, Patrick Palka wrote:

Currently __has_attribute(init_priority) always returns true, even on
targets that don't actually support init priorities, and when using
the attribute on such targets, we issue a hard error that init
priorities are unsupported.  This makes it impossible to conditionally
use the attribute by querying __has_attribute.

This patch fixes this by adding the attribute to the attribute table
only if the target supports init priorities, so that __has_attribute
returns false appropriately.  Thus on such targets we'll now treat it as
just another unrecognized attribute, so using it gives a -Wattribute
warning instead of an error.


OK.


gcc/cp/ChangeLog:

* tree.cc (cxx_attribute_table): Add entry for init_priority
only if SUPPORTS_INIT_PRIORITY.
(handle_init_priority_attribute): Assert SUPPORTS_INIT_PRIORITY
is true.

gcc/testsuite/ChangeLog:

* g++.dg/special/initpri3.C: New test.
---
  gcc/cp/tree.cc  | 20 +++-
  gcc/testsuite/g++.dg/special/initpri3.C |  9 +
  2 files changed, 16 insertions(+), 13 deletions(-)
  create mode 100644 gcc/testsuite/g++.dg/special/initpri3.C

diff --git a/gcc/cp/tree.cc b/gcc/cp/tree.cc
index 45348c58bb6..c30bbeb0839 100644
--- a/gcc/cp/tree.cc
+++ b/gcc/cp/tree.cc
@@ -5010,8 +5010,10 @@ const struct attribute_spec cxx_attribute_table[] =
  {
/* { name, min_len, max_len, decl_req, type_req, fn_type_req,
 affects_type_identity, handler, exclude } */
+#if SUPPORTS_INIT_PRIORITY
{ "init_priority",  1, 1, true,  false, false, false,
  handle_init_priority_attribute, NULL },
+#endif
{ "abi_tag", 1, -1, false, false, false, true,
  handle_abi_tag_attribute, NULL },
{ NULL, 0, 0, false, false, false, false, NULL, NULL }
@@ -5039,7 +5041,7 @@ const struct attribute_spec std_attribute_table[] =
  
  /* Handle an "init_priority" attribute; arguments as in

 struct attribute_spec.handler.  */
-static tree
+ATTRIBUTE_UNUSED static tree
  handle_init_priority_attribute (tree* node,
tree name,
tree args,
@@ -5103,18 +5105,10 @@ handle_init_priority_attribute (tree* node,
 pri);
  }
  
-  if (SUPPORTS_INIT_PRIORITY)

-{
-  SET_DECL_INIT_PRIORITY (decl, pri);
-  DECL_HAS_INIT_PRIORITY_P (decl) = 1;
-  return NULL_TREE;
-}
-  else
-{
-  error ("%qE attribute is not supported on this platform", name);
-  *no_add_attrs = true;
-  return NULL_TREE;
-}
+  gcc_assert (SUPPORTS_INIT_PRIORITY);
+  SET_DECL_INIT_PRIORITY (decl, pri);
+  DECL_HAS_INIT_PRIORITY_P (decl) = 1;
+  return NULL_TREE;
  }
  
  /* DECL is being redeclared; the old declaration had the abi tags in OLD,

diff --git a/gcc/testsuite/g++.dg/special/initpri3.C 
b/gcc/testsuite/g++.dg/special/initpri3.C
new file mode 100644
index 000..a181abdd0b1
--- /dev/null
+++ b/gcc/testsuite/g++.dg/special/initpri3.C
@@ -0,0 +1,9 @@
+// Verify __has_attribute(init_priority) is false whenever the platform
+// doesn't support it, and is treated as an unrecognized attribute.
+
+#if !__has_attribute(init_priority)
+#error init_priority /* { dg-error "" "" { target { ! init_priority } } } */
+#endif
+
+struct A { A(); } a __attribute__((init_priority(500)));
+// { dg-warning "attribute directive ignored" "" { target { ! init_priority } 
} .-1 }




Re: [PATCH 2/6] diagnostics: Use an inline function rather than hardcoding string

2022-11-04 Thread David Malcolm via Gcc-patches
On Fri, 2022-11-04 at 09:44 -0400, Lewis Hyatt via Gcc-patches wrote:
> The string "" is hard-coded in several places throughout
> the
> diagnostics code, and in some of those places, it is used incorrectly
> with
> respect to internationalization. (Comparing a translated string to an
> untranslated string.) The error is not currently observable in any
> output GCC
> actually produces, hence no testcase added here, but it's worth
> fixing, and
> also, I am shortly going to add a new such string and want to avoid
> hardcoding
> that one in similar places.

Thanks; looks good to me.

Dave

> 
> gcc/c-family/ChangeLog:
> 
> * c-opts.cc (c_finish_options): Use special_fname_builtin ()
> rather
> than a hard-coded string.
> 
> gcc/ChangeLog:
> 
> * diagnostic.cc (diagnostic_get_location_text): Use
> special_fname_builtin () rather than a hardcoded string
> (which was
> also incorrectly left untranslated previously.)
> * input.cc (special_fname_builtin): New function.
> (expand_location_1): Use special_fname_builtin () rather than
> a
> hard-coded string.
> (test_builtins): Likewise.
> * input.h (special_fname_builtin): Declare.
> 
> gcc/fortran/ChangeLog:
> 
> * cpp.cc (gfc_cpp_init): Use special_fname_builtin () rather
> than a
> hardcoded string (which was also incorrectly left
> untranslated
> previously.)
> * error.cc (gfc_diagnostic_build_locus_prefix): Likewise.
> * f95-lang.cc (gfc_init): Likewise.
> ---
>  gcc/c-family/c-opts.cc  |  2 +-
>  gcc/diagnostic.cc   |  2 +-
>  gcc/fortran/cpp.cc  |  2 +-
>  gcc/fortran/error.cc    |  4 ++--
>  gcc/fortran/f95-lang.cc |  2 +-
>  gcc/input.cc    | 10 --
>  gcc/input.h |  3 +++
>  7 files changed, 17 insertions(+), 8 deletions(-)
> 
> diff --git a/gcc/c-family/c-opts.cc b/gcc/c-family/c-opts.cc
> index 32b929e3ece..521797fb7eb 100644
> --- a/gcc/c-family/c-opts.cc
> +++ b/gcc/c-family/c-opts.cc
> @@ -1476,7 +1476,7 @@ c_finish_options (void)
>  {
>    const line_map_ordinary *bltin_map
> = linemap_check_ordinary (linemap_add (line_table, LC_RENAME,
> 0,
> -  _(""), 0));
> +  special_fname_builtin
> (), 0));
>    cb_file_change (parse_in, bltin_map);
>    linemap_line_start (line_table, 0, 1);
>  
> diff --git a/gcc/diagnostic.cc b/gcc/diagnostic.cc
> index 22f7b0b6d6e..7c7ee6da746 100644
> --- a/gcc/diagnostic.cc
> +++ b/gcc/diagnostic.cc
> @@ -470,7 +470,7 @@ diagnostic_get_location_text (diagnostic_context
> *context,
>    const char *file = s.file ? s.file : progname;
>    int line = 0;
>    int col = -1;
> -  if (strcmp (file, N_("")))
> +  if (strcmp (file, special_fname_builtin ()))
>  {
>    line = s.line;
>    if (context->show_column)
> diff --git a/gcc/fortran/cpp.cc b/gcc/fortran/cpp.cc
> index 364bd0d2a85..0b5755edbb4 100644
> --- a/gcc/fortran/cpp.cc
> +++ b/gcc/fortran/cpp.cc
> @@ -605,7 +605,7 @@ gfc_cpp_init (void)
>    if (gfc_option.flag_preprocessed)
>  return;
>  
> -  cpp_change_file (cpp_in, LC_RENAME, _(""));
> +  cpp_change_file (cpp_in, LC_RENAME, special_fname_builtin ());
>    if (!gfc_cpp_option.no_predefined)
>  {
>    /* Make sure all of the builtins about to be declared have
> diff --git a/gcc/fortran/error.cc b/gcc/fortran/error.cc
> index c9d6edbb923..214fb78ba7b 100644
> --- a/gcc/fortran/error.cc
> +++ b/gcc/fortran/error.cc
> @@ -1147,7 +1147,7 @@ gfc_diagnostic_build_locus_prefix
> (diagnostic_context *context,
>    const char *locus_ce = colorize_stop (pp_show_color (pp));
>    return (s.file == NULL
>   ? build_message_string ("%s%s:%s", locus_cs, progname,
> locus_ce )
> - : !strcmp (s.file, N_(""))
> + : !strcmp (s.file, special_fname_builtin ())
>   ? build_message_string ("%s%s:%s", locus_cs, s.file,
> locus_ce)
>   : context->show_column
>   ? build_message_string ("%s%s:%d:%d:%s", locus_cs, s.file,
> s.line,
> @@ -1167,7 +1167,7 @@ gfc_diagnostic_build_locus_prefix
> (diagnostic_context *context,
>  
>    return (s.file == NULL
>   ? build_message_string ("%s%s:%s", locus_cs, progname,
> locus_ce )
> - : !strcmp (s.file, N_(""))
> + : !strcmp (s.file, special_fname_builtin ())
>   ? build_message_string ("%s%s:%s", locus_cs, s.file,
> locus_ce)
>   : context->show_column
>   ? build_message_string ("%s%s:%d:%d-%d:%s", locus_cs,
> s.file, s.line,
> diff --git a/gcc/fortran/f95-lang.cc b/gcc/fortran/f95-lang.cc
> index a6750bea787..0d83f3f8b69 100644
> --- a/gcc/fortran/f95-lang.cc
> +++ b/gcc/fortran/f95-lang.cc
> @@ -259,7 +259,7 @@ gfc_init (void)
>    if (!gfc_cpp_enabled ())
>  {
>    linemap_add (line_table, LC_ENTER, false, gfc_source_file, 1);
> -  linemap_add (line_table, LC_RENAME, false, "", 0);
> +  linemap_add 

Re: [PATCH 1/6] diagnostics: Fix macro tracking for ad-hoc locations

2022-11-04 Thread David Malcolm via Gcc-patches
On Fri, 2022-11-04 at 09:44 -0400, Lewis Hyatt via Gcc-patches wrote:
> The result of linemap_resolve_location() can be an ad-hoc location,
> if that is
> what was stored in a relevant macro map. 
> maybe_unwind_expanded_macro_loc()
> did not previously handle this case, causing it to print the wrong
> tracking
> information for an example such as the new testcase macro-trace-1.c. 
> Fix that
> by checking for ad-hoc locations where needed.

Thanks; looks good to me.
Dave

> 
> gcc/ChangeLog:
> 
> * tree-diagnostic.cc (maybe_unwind_expanded_macro_loc):
> Handle ad-hoc
> location in return value of linemap_resolve_location().
> 
> gcc/testsuite/ChangeLog:
> 
> * c-c++-common/cpp/macro-trace-1.c: New test.
> ---
>  gcc/testsuite/c-c++-common/cpp/macro-trace-1.c | 4 
>  gcc/tree-diagnostic.cc | 7 +--
>  2 files changed, 9 insertions(+), 2 deletions(-)
>  create mode 100644 gcc/testsuite/c-c++-common/cpp/macro-trace-1.c
> 
> diff --git a/gcc/testsuite/c-c++-common/cpp/macro-trace-1.c
> b/gcc/testsuite/c-c++-common/cpp/macro-trace-1.c
> new file mode 100644
> index 000..34cfbb3dad3
> --- /dev/null
> +++ b/gcc/testsuite/c-c++-common/cpp/macro-trace-1.c
> @@ -0,0 +1,4 @@
> +/* This token is long enough to require an ad-hoc location. Make
> sure that
> +   the macro trace still prints properly.  */
> +#define X "0123456789012345678901234567689" /* { dg-error {expected
> .* before string constant} } */
> +X /* { dg-note {in expansion of macro 'X'} } */
> diff --git a/gcc/tree-diagnostic.cc b/gcc/tree-diagnostic.cc
> index 0d79fe3c3c1..5cf3a1c17d2 100644
> --- a/gcc/tree-diagnostic.cc
> +++ b/gcc/tree-diagnostic.cc
> @@ -190,14 +190,17 @@ maybe_unwind_expanded_macro_loc
> (diagnostic_context *context,
>  location_t l = 
>    linemap_resolve_location (line_table, resolved_def_loc,
>  LRK_SPELLING_LOCATION,  );
> -    if (l < RESERVED_LOCATION_COUNT || LINEMAP_SYSP (m))
> +   location_t l0 = l;
> +   if (IS_ADHOC_LOC (l0))
> + l0 = get_location_from_adhoc_loc (line_table, l0);
> +   if (l0 < RESERVED_LOCATION_COUNT || LINEMAP_SYSP (m))
>    continue;
>  
> /* We need to print the context of the macro definition only
>    when the locus of the first displayed diagnostic
> (displayed
>    before this trace) was inside the definition of the
>    macro.  */
> -    int resolved_def_loc_line = SOURCE_LINE (m, l);
> +   const int resolved_def_loc_line = SOURCE_LINE (m, l0);
>  if (ix == 0 && saved_location_line != resolved_def_loc_line)
>    {
>  diagnostic_append_note (context, resolved_def_loc, 
> 



Re: [PATCH 2/2] libstdc++: Move stream initialization into compiled library [PR44952]

2022-11-04 Thread Jonathan Wakely via Gcc-patches
On Fri, 4 Nov 2022 at 15:08, Patrick Palka via Libstdc++
 wrote:
>
> This patch moves the global object for constructing the standard streams
> out from  and into the compiled library on targets that support
> the init_priority attribute.  This means that  no longer
> introduces a separate global constructor in each TU that includes it.
>
> We can do this only if the init_priority attribute is supported because
> we need to force that the stream initialization runs first before any
> user-defined global initializer in programs that that use a static
> libstdc++.a.
>
> Bootstrapped and regtested on x86_64-pc-linux-gnu, does this look right?
> Unfortunately I don't have access to a system that truly doesn't support
> init priorities, so I instead tested that situation by artificially
> disabling the init_priority attribute on x86_64.
>
> PR libstdc++/44952
> PR libstdc++/98108
>
> libstdc++-v3/ChangeLog:
>
> * include/bits/c++config (_GLIBCXX_HAS_ATTRIBUTE): Define.
> (_GLIBCXX_HAVE_ATTRIBUTE_INIT_PRIORITY): Define.
> * include/std/iostream (__ioinit): Define only if init_priority
> attribute isn't usable.
> * src/c++98/ios_init.cc (__ioinit): Define here instead if
> the init_priority is usable.
> * src/c++98/ios_base_init.h: New file.
> ---
>  libstdc++-v3/include/bits/c++config| 12 
>  libstdc++-v3/include/std/iostream  |  4 
>  libstdc++-v3/src/c++98/ios_base_init.h |  9 +
>  libstdc++-v3/src/c++98/ios_init.cc |  4 
>  4 files changed, 29 insertions(+)
>  create mode 100644 libstdc++-v3/src/c++98/ios_base_init.h
>
> diff --git a/libstdc++-v3/include/bits/c++config 
> b/libstdc++-v3/include/bits/c++config
> index 50406066afe..f93076191d9 100644
> --- a/libstdc++-v3/include/bits/c++config
> +++ b/libstdc++-v3/include/bits/c++config
> @@ -837,6 +837,18 @@ namespace __gnu_cxx
>
>  #undef _GLIBCXX_HAS_BUILTIN
>
> +#ifdef __has_attribute

Do we need this?
I think all the compilers we support implemented this long ago (clang
had it before gcc, and Intel has it for gcc compat, and any others had
better have it by now too).

So we can just use #if __has_attribute directly, instead of defining
these extra macros.

> +# define _GLIBCXX_HAS_ATTRIBUTE(B) __has_attribute(B)
> +#else
> +# define _GLIBCXX_HAS_ATTRIBUTE(B) 0
> +#endif
> +
> +#if _GLIBCXX_HAS_ATTRIBUTE(init_priority)
> +# define _GLIBCXX_HAVE_ATTRIBUTE_INIT_PRIORITY 1
> +#endif
> +
> +#undef _GLIBCXX_HAS_ATTRIBUTE
> +
>  // Mark code that should be ignored by the compiler, but seen by Doxygen.
>  #define _GLIBCXX_DOXYGEN_ONLY(X)
>
> diff --git a/libstdc++-v3/include/std/iostream 
> b/libstdc++-v3/include/std/iostream
> index 70318a45891..5eaa9755d9a 100644
> --- a/libstdc++-v3/include/std/iostream
> +++ b/libstdc++-v3/include/std/iostream
> @@ -73,7 +73,11 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
>///@}
>
>// For construction of filebuffers for cout, cin, cerr, clog et. al.
> +  // When the init_priority attribute is usable, we do this initialization
> +  // in the compiled library instead (see src/c++98/ios_init.cc).
> +#if !_GLIBCXX_HAVE_ATTRIBUTE_INIT_PRIORITY
>static ios_base::Init __ioinit;
> +#endif
>
>  _GLIBCXX_END_NAMESPACE_VERSION
>  } // namespace
> diff --git a/libstdc++-v3/src/c++98/ios_base_init.h 
> b/libstdc++-v3/src/c++98/ios_base_init.h
> new file mode 100644
> index 000..f3087d1da3c
> --- /dev/null
> +++ b/libstdc++-v3/src/c++98/ios_base_init.h
> @@ -0,0 +1,9 @@
> +// This is only in a header so we can use the system_header pragma,
> +// to suppress the warning caused by using a reserved init_priority.
> +#pragma GCC system_header

Ugh, that's annoying.

> +
> +#if !_GLIBCXX_HAVE_ATTRIBUTE_INIT_PRIORITY
> +# error "This file should not be included for this build"
> +#endif
> +
> +static ios_base::Init __ioinit __attribute__((init_priority(90)));
> diff --git a/libstdc++-v3/src/c++98/ios_init.cc 
> b/libstdc++-v3/src/c++98/ios_init.cc
> index 1b5132f1c2d..954fa9f29cf 100644
> --- a/libstdc++-v3/src/c++98/ios_init.cc
> +++ b/libstdc++-v3/src/c++98/ios_init.cc
> @@ -75,6 +75,10 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
>extern wostream wclog;
>  #endif
>
> +#if _GLIBCXX_HAVE_ATTRIBUTE_INIT_PRIORITY
> +# include "ios_base_init.h"
> +#endif
> +
>ios_base::Init::Init()
>{
>  if (__gnu_cxx::__exchange_and_add_dispatch(&_S_refcount, 1) == 0)
> --
> 2.38.1.385.g3b08839926
>



Re: [PATCH RFA] input: add get_source_text_between

2022-11-04 Thread David Malcolm via Gcc-patches
On Fri, 2022-11-04 at 10:27 -0400, Jason Merrill wrote:
> On 11/3/22 19:06, David Malcolm wrote:
> > On Thu, 2022-11-03 at 15:59 -0400, Jason Merrill via Gcc-patches
> > wrote:

[...snip...]

> > 
> > 
> > Do you have test coverage for this from the DejaGnu side?  If not,
> > you
> > could add selftest coverage for this; see input.cc's
> > test_reading_source_line for something similar.
> 
> There is test coverage for the output of the the contract violation 
> handler, which involves printing the result of this function.

Thanks.   Is this test posted somwehere?  I was looking in:
 https://gcc.gnu.org/pipermail/gcc-patches/2022-November/604974.html
but I'm not seeing it.  Sorry if I'm missing something here.

Ideally we should have coverage for the three cases of:
(a) bails out and returns NULL
(b) single-line case
(c) multi-line case


> index a28abfac5ac..04d0809bfdf 100644
> --- a/gcc/input.cc
> +++ b/gcc/input.cc
> @@ -949,6 +949,97 @@ location_get_source_line (const char *file_path, int 
> line)
>return char_span (buffer, len);
>  }

Strings in input.cc are not always NUL-terminated, so...

>  
> +/* Return a copy of the source text between two locations.  The caller is
> +   responsible for freeing the return value.  */

...please note in the comment that if non-NULL, the copy is NUL-
terminated (I checked both exit paths that can return non-NULL, and
they do NUL-terminate their buffers).

OK with that nit fixed.

Thanks
Dave



[PATCH 2/2] libstdc++: Move stream initialization into compiled library [PR44952]

2022-11-04 Thread Patrick Palka via Gcc-patches
This patch moves the global object for constructing the standard streams
out from  and into the compiled library on targets that support
the init_priority attribute.  This means that  no longer
introduces a separate global constructor in each TU that includes it.

We can do this only if the init_priority attribute is supported because
we need to force that the stream initialization runs first before any
user-defined global initializer in programs that that use a static
libstdc++.a.

Bootstrapped and regtested on x86_64-pc-linux-gnu, does this look right?
Unfortunately I don't have access to a system that truly doesn't support
init priorities, so I instead tested that situation by artificially
disabling the init_priority attribute on x86_64.

PR libstdc++/44952
PR libstdc++/98108

libstdc++-v3/ChangeLog:

* include/bits/c++config (_GLIBCXX_HAS_ATTRIBUTE): Define.
(_GLIBCXX_HAVE_ATTRIBUTE_INIT_PRIORITY): Define.
* include/std/iostream (__ioinit): Define only if init_priority
attribute isn't usable.
* src/c++98/ios_init.cc (__ioinit): Define here instead if
the init_priority is usable.
* src/c++98/ios_base_init.h: New file.
---
 libstdc++-v3/include/bits/c++config| 12 
 libstdc++-v3/include/std/iostream  |  4 
 libstdc++-v3/src/c++98/ios_base_init.h |  9 +
 libstdc++-v3/src/c++98/ios_init.cc |  4 
 4 files changed, 29 insertions(+)
 create mode 100644 libstdc++-v3/src/c++98/ios_base_init.h

diff --git a/libstdc++-v3/include/bits/c++config 
b/libstdc++-v3/include/bits/c++config
index 50406066afe..f93076191d9 100644
--- a/libstdc++-v3/include/bits/c++config
+++ b/libstdc++-v3/include/bits/c++config
@@ -837,6 +837,18 @@ namespace __gnu_cxx
 
 #undef _GLIBCXX_HAS_BUILTIN
 
+#ifdef __has_attribute
+# define _GLIBCXX_HAS_ATTRIBUTE(B) __has_attribute(B)
+#else
+# define _GLIBCXX_HAS_ATTRIBUTE(B) 0
+#endif
+
+#if _GLIBCXX_HAS_ATTRIBUTE(init_priority)
+# define _GLIBCXX_HAVE_ATTRIBUTE_INIT_PRIORITY 1
+#endif
+
+#undef _GLIBCXX_HAS_ATTRIBUTE
+
 // Mark code that should be ignored by the compiler, but seen by Doxygen.
 #define _GLIBCXX_DOXYGEN_ONLY(X)
 
diff --git a/libstdc++-v3/include/std/iostream 
b/libstdc++-v3/include/std/iostream
index 70318a45891..5eaa9755d9a 100644
--- a/libstdc++-v3/include/std/iostream
+++ b/libstdc++-v3/include/std/iostream
@@ -73,7 +73,11 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
   ///@}
 
   // For construction of filebuffers for cout, cin, cerr, clog et. al.
+  // When the init_priority attribute is usable, we do this initialization
+  // in the compiled library instead (see src/c++98/ios_init.cc).
+#if !_GLIBCXX_HAVE_ATTRIBUTE_INIT_PRIORITY
   static ios_base::Init __ioinit;
+#endif
 
 _GLIBCXX_END_NAMESPACE_VERSION
 } // namespace
diff --git a/libstdc++-v3/src/c++98/ios_base_init.h 
b/libstdc++-v3/src/c++98/ios_base_init.h
new file mode 100644
index 000..f3087d1da3c
--- /dev/null
+++ b/libstdc++-v3/src/c++98/ios_base_init.h
@@ -0,0 +1,9 @@
+// This is only in a header so we can use the system_header pragma,
+// to suppress the warning caused by using a reserved init_priority.
+#pragma GCC system_header
+
+#if !_GLIBCXX_HAVE_ATTRIBUTE_INIT_PRIORITY
+# error "This file should not be included for this build"
+#endif
+
+static ios_base::Init __ioinit __attribute__((init_priority(90)));
diff --git a/libstdc++-v3/src/c++98/ios_init.cc 
b/libstdc++-v3/src/c++98/ios_init.cc
index 1b5132f1c2d..954fa9f29cf 100644
--- a/libstdc++-v3/src/c++98/ios_init.cc
+++ b/libstdc++-v3/src/c++98/ios_init.cc
@@ -75,6 +75,10 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
   extern wostream wclog;
 #endif
 
+#if _GLIBCXX_HAVE_ATTRIBUTE_INIT_PRIORITY
+# include "ios_base_init.h"
+#endif
+
   ios_base::Init::Init()
   {
 if (__gnu_cxx::__exchange_and_add_dispatch(&_S_refcount, 1) == 0)
-- 
2.38.1.385.g3b08839926



[PATCH 1/2] c++: correct __has_attribute(init_priority)

2022-11-04 Thread Patrick Palka via Gcc-patches
Currently __has_attribute(init_priority) always returns true, even on
targets that don't actually support init priorities, and when using
the attribute on such targets, we issue a hard error that init
priorities are unsupported.  This makes it impossible to conditionally
use the attribute by querying __has_attribute.

This patch fixes this by adding the attribute to the attribute table
only if the target supports init priorities, so that __has_attribute
returns false appropriately.  Thus on such targets we'll now treat it as
just another unrecognized attribute, so using it gives a -Wattribute
warning instead of an error.

gcc/cp/ChangeLog:

* tree.cc (cxx_attribute_table): Add entry for init_priority
only if SUPPORTS_INIT_PRIORITY.
(handle_init_priority_attribute): Assert SUPPORTS_INIT_PRIORITY
is true.

gcc/testsuite/ChangeLog:

* g++.dg/special/initpri3.C: New test.
---
 gcc/cp/tree.cc  | 20 +++-
 gcc/testsuite/g++.dg/special/initpri3.C |  9 +
 2 files changed, 16 insertions(+), 13 deletions(-)
 create mode 100644 gcc/testsuite/g++.dg/special/initpri3.C

diff --git a/gcc/cp/tree.cc b/gcc/cp/tree.cc
index 45348c58bb6..c30bbeb0839 100644
--- a/gcc/cp/tree.cc
+++ b/gcc/cp/tree.cc
@@ -5010,8 +5010,10 @@ const struct attribute_spec cxx_attribute_table[] =
 {
   /* { name, min_len, max_len, decl_req, type_req, fn_type_req,
affects_type_identity, handler, exclude } */
+#if SUPPORTS_INIT_PRIORITY
   { "init_priority",  1, 1, true,  false, false, false,
 handle_init_priority_attribute, NULL },
+#endif
   { "abi_tag", 1, -1, false, false, false, true,
 handle_abi_tag_attribute, NULL },
   { NULL, 0, 0, false, false, false, false, NULL, NULL }
@@ -5039,7 +5041,7 @@ const struct attribute_spec std_attribute_table[] =
 
 /* Handle an "init_priority" attribute; arguments as in
struct attribute_spec.handler.  */
-static tree
+ATTRIBUTE_UNUSED static tree
 handle_init_priority_attribute (tree* node,
tree name,
tree args,
@@ -5103,18 +5105,10 @@ handle_init_priority_attribute (tree* node,
 pri);
 }
 
-  if (SUPPORTS_INIT_PRIORITY)
-{
-  SET_DECL_INIT_PRIORITY (decl, pri);
-  DECL_HAS_INIT_PRIORITY_P (decl) = 1;
-  return NULL_TREE;
-}
-  else
-{
-  error ("%qE attribute is not supported on this platform", name);
-  *no_add_attrs = true;
-  return NULL_TREE;
-}
+  gcc_assert (SUPPORTS_INIT_PRIORITY);
+  SET_DECL_INIT_PRIORITY (decl, pri);
+  DECL_HAS_INIT_PRIORITY_P (decl) = 1;
+  return NULL_TREE;
 }
 
 /* DECL is being redeclared; the old declaration had the abi tags in OLD,
diff --git a/gcc/testsuite/g++.dg/special/initpri3.C 
b/gcc/testsuite/g++.dg/special/initpri3.C
new file mode 100644
index 000..a181abdd0b1
--- /dev/null
+++ b/gcc/testsuite/g++.dg/special/initpri3.C
@@ -0,0 +1,9 @@
+// Verify __has_attribute(init_priority) is false whenever the platform
+// doesn't support it, and is treated as an unrecognized attribute.
+
+#if !__has_attribute(init_priority)
+#error init_priority /* { dg-error "" "" { target { ! init_priority } } } */
+#endif
+
+struct A { A(); } a __attribute__((init_priority(500)));
+// { dg-warning "attribute directive ignored" "" { target { ! init_priority } 
} .-1 }
-- 
2.38.1.385.g3b08839926



[PATCH] LoongArch: Add fcopysign instructions

2022-11-04 Thread Xi Ruoyao via Gcc-patches
Add fcopysign.{s,d} with the names copysign{sf,df}3 so GCC will expand
__builtin_copysign{f,} to a single instruction.

Link: https://sourceware.org/pipermail/libc-alpha/2022-November/143177.html

gcc/ChangeLog:

* config/loongarch/loongarch.md (UNSPEC_FCOPYSIGN): New unspec.
(type): Add fcopysign.
(copysign3): New instruction template.

gcc/testsuite/ChangeLog:

* gcc.target/loongarch/fcopysign.c: New test.
---

Bootstrapped and regtested on loongarch64-linux-gnu.  Ok for trunk?

 gcc/config/loongarch/loongarch.md | 22 ++-
 .../gcc.target/loongarch/fcopysign.c  | 16 ++
 2 files changed, 37 insertions(+), 1 deletion(-)
 create mode 100644 gcc/testsuite/gcc.target/loongarch/fcopysign.c

diff --git a/gcc/config/loongarch/loongarch.md 
b/gcc/config/loongarch/loongarch.md
index 214b14bddd3..042e6e74491 100644
--- a/gcc/config/loongarch/loongarch.md
+++ b/gcc/config/loongarch/loongarch.md
@@ -37,6 +37,7 @@ (define_c_enum "unspec" [
   UNSPEC_FCLASS
   UNSPEC_FMAX
   UNSPEC_FMIN
+  UNSPEC_FCOPYSIGN
 
   ;; Override return address for exception handling.
   UNSPEC_EH_RETURN
@@ -214,6 +215,7 @@ (define_attr "qword_mode" "no,yes"
 ;; fabsfloating point absolute value
 ;; fnegfloating point negation
 ;; fcmpfloating point compare
+;; fcopysign   floating point copysign
 ;; fcvtfloating point convert
 ;; fsqrt   floating point square root
 ;; frsqrt   floating point reciprocal square root
@@ -226,7 +228,7 @@ (define_attr "type"
   "unknown,branch,jump,call,load,fpload,fpidxload,store,fpstore,fpidxstore,
prefetch,prefetchx,condmove,mgtf,mftg,const,arith,logical,
shift,slt,signext,clz,trap,imul,idiv,move,
-   fmove,fadd,fmul,fmadd,fdiv,frdiv,fabs,fneg,fcmp,fcvt,fsqrt,
+   fmove,fadd,fmul,fmadd,fdiv,frdiv,fabs,fneg,fcmp,fcopysign,fcvt,fsqrt,
frsqrt,accext,accmod,multi,atomic,syncloop,nop,ghost"
   (cond [(eq_attr "jirl" "!unset") (const_string "call")
 (eq_attr "got" "load") (const_string "load")
@@ -976,6 +978,24 @@ (define_insn "abs2"
(set_attr "mode" "")])
 
 ;;
+;;  
+;;
+;; FLOATING POINT COPYSIGN
+;;
+;;  
+
+(define_insn "copysign3"
+  [(set (match_operand:ANYF 0 "register_operand" "=f")
+   (unspec:ANYF [(match_operand:ANYF 1 "register_operand" "f")
+ (match_operand:ANYF 2 "register_operand" "f")]
+UNSPEC_FCOPYSIGN))]
+  ""
+  "fcopysign.\t%0,%1,%2"
+  [(set_attr "type" "fcopysign")
+   (set_attr "mode" "")])
+
+
+;;
 ;;  ...
 ;;
 ;;  Count leading zeroes.
diff --git a/gcc/testsuite/gcc.target/loongarch/fcopysign.c 
b/gcc/testsuite/gcc.target/loongarch/fcopysign.c
new file mode 100644
index 000..058ba2cf573
--- /dev/null
+++ b/gcc/testsuite/gcc.target/loongarch/fcopysign.c
@@ -0,0 +1,16 @@
+/* { dg-do compile } */
+/* { dg-options "-mdouble-float" } */
+/* { dg-final { scan-assembler "fcopysign\\.s" } } */
+/* { dg-final { scan-assembler "fcopysign\\.d" } } */
+
+double
+my_copysign (double a, double b)
+{
+  return __builtin_copysign (a, b);
+}
+
+float
+my_copysignf (float a, float b)
+{
+  return __builtin_copysignf (a, b);
+}
-- 
2.38.1



Re: [PATCH RFA] input: add get_source_text_between

2022-11-04 Thread Jason Merrill via Gcc-patches

On 11/3/22 19:06, David Malcolm wrote:

On Thu, 2022-11-03 at 15:59 -0400, Jason Merrill via Gcc-patches wrote:

Tested x86_64-pc-linux-gnu, OK for trunk?

-- >8 --

The c++-contracts branch uses this to retrieve the source form of the
contract predicate, to be returned by contract_violation::comment().

gcc/ChangeLog:

 * input.cc (get_source_text_between): New fn.
 * input.h (get_source_text_between): Declare.
---
  gcc/input.h  |  1 +
  gcc/input.cc | 76

  2 files changed, 77 insertions(+)

diff --git a/gcc/input.h b/gcc/input.h
index 11c571d076f..f18769950b5 100644
--- a/gcc/input.h
+++ b/gcc/input.h
@@ -111,6 +111,7 @@ class char_span
  };
  
  extern char_span location_get_source_line (const char *file_path,

int line);
+extern char *get_source_text_between (location_t, location_t);
  
  extern bool location_missing_trailing_newline (const char

*file_path);
  
diff --git a/gcc/input.cc b/gcc/input.cc

index a28abfac5ac..9b36356338a 100644
--- a/gcc/input.cc
+++ b/gcc/input.cc
@@ -949,6 +949,82 @@ location_get_source_line (const char *file_path,
int line)
    return char_span (buffer, len);
  }
  
+/* Return a copy of the source text between two locations.  The

caller is
+   responsible for freeing the return value.  */
+
+char *
+get_source_text_between (location_t start, location_t end)
+{
+  expanded_location expstart =
+    expand_location_to_spelling_point (start,
LOCATION_ASPECT_START);
+  expanded_location expend =
+    expand_location_to_spelling_point (end, LOCATION_ASPECT_FINISH);
+
+  /* If the locations are in different files or the end comes before
the
+ start, abort and return nothing.  */


I don't like the use of the term "abort" here, as it suggests to me the
use of abort(3).  Maybe "bail out" instead?


I went with "give up".


+  if (!expstart.file || !expend.file)
+    return NULL;
+  if (strcmp (expstart.file, expend.file) != 0)
+    return NULL;
+  if (expstart.line > expend.line)
+    return NULL;
+  if (expstart.line == expend.line
+  && expstart.column > expend.column)
+    return NULL;


We occasionally use the convention that
   (column == 0)
means "the whole line".  Probably should detect that case and bail out
early for it.


Done.


+
+  /* For a single line we need to trim both edges.  */
+  if (expstart.line == expend.line)
+    {
+  char_span line = location_get_source_line (expstart.file,
expstart.line);
+  if (line.length () < 1)
+   return NULL;
+  int s = expstart.column - 1;
+  int l = expend.column - s;


Can we please avoid lower-case L "ell" for variable names, as it looks
so similar to the numeral for one.  "len" would be more descriptive
here.


Done.


+  if (line.length () < (size_t)expend.column)
+   return NULL;
+  return line.subspan (s, l).xstrdup ();
+    }
+
+  struct obstack buf_obstack;
+  obstack_init (_obstack);
+
+  /* Loop through all lines in the range and append each to buf; may
trim
+ parts of the start and end lines off depending on column
values.  */
+  for (int l = expstart.line; l <= expend.line; ++l)


Again, please let's not have a var named "l".  Maybe "iter_line" as
that's what is being done?


+    {
+  char_span line = location_get_source_line (expstart.file, l);
+  if (line.length () < 1 && (l != expstart.line && l !=
expend.line))


...especially as I *think* the first comparison is against numeral one,
whereas comparisons two and three are against lower-case ell, but I'm
having to squint at the font in my email client to be sure :-/


Done.  But also allow me to recommend

https://nodnod.net/posts/inconsolata-dz/


+   continue;
+
+  /* For the first line in the range, only start at
expstart.column */
+  if (l == expstart.line)
+   {
+ if (expstart.column == 0)
+   return NULL;
+ if (line.length () < (size_t)expstart.column - 1)
+   return NULL;
+ line = line.subspan (expstart.column - 1,
+  line.length() - expstart.column + 1);
+   }
+  /* For the last line, don't go past expend.column */
+  else if (l == expend.line)
+   {
+ if (line.length () < (size_t)expend.column)
+   return NULL;
+ line = line.subspan (0, expend.column);
+   }
+
+  obstack_grow (_obstack, line.get_buffer (), line.length
());


Is this accumulating the trailing newline characters into the
buf_obstack?  I *think* it is, but it seems worth a comment for each of
the three cases (first line, intermediate line, last line).


It is not; I've added a comment to that effect, and also implemented the 
TODO of collapsing a series of whitespace.



+    }
+
+  /* NUL-terminate and finish the buf obstack.  */
+  obstack_1grow (_obstack, 0);
+  const char *buf = (const char *) obstack_finish (_obstack);
+
+  /* TODO should we collapse/trim newlines and runs of spaces?  */
+  return xstrdup (buf);
+}
+


Do you have 

[COMMITTED] Set nonzero bits for multiplication and divisions by a power of 2.

2022-11-04 Thread Aldy Hernandez via Gcc-patches
We're missing a lot of TLC in keeping track of nonzero bits across
range-ops.  It isn't an oversight, but just limited amount of hours to
implement stuff.

This patch keeps better track of the nonzero mask (really
maybe_nonzero bits as discussed) across multiplication and division
when the RHS is a power of 2.

It fixes PR107342 and also touches on PR55157.  In the latter, the
nonzero mask is being set quite late (CCP2) but could be set by evrp
time if we enhanced range-ops.  I have added tests from both PRs.

Tested

PR tree-optimization/107342

gcc/ChangeLog:

* range-op.cc (operator_mult::fold_range): New.
(operator_div::fold_range): New.

gcc/testsuite/ChangeLog:

* gcc.dg/tree-ssa/vrp122.c: New test.
* gcc.dg/tree-ssa/vrp123.c: New test.
---
 gcc/range-op.cc| 59 ++
 gcc/testsuite/gcc.dg/tree-ssa/vrp122.c | 19 +
 gcc/testsuite/gcc.dg/tree-ssa/vrp123.c | 18 
 3 files changed, 96 insertions(+)
 create mode 100644 gcc/testsuite/gcc.dg/tree-ssa/vrp122.c
 create mode 100644 gcc/testsuite/gcc.dg/tree-ssa/vrp123.c

diff --git a/gcc/range-op.cc b/gcc/range-op.cc
index 49ee7be3d3b..25c004d8287 100644
--- a/gcc/range-op.cc
+++ b/gcc/range-op.cc
@@ -1742,9 +1742,13 @@ cross_product_operator::wi_cross_product (irange , 
tree type,
 
 class operator_mult : public cross_product_operator
 {
+  using range_operator::fold_range;
   using range_operator::op1_range;
   using range_operator::op2_range;
 public:
+  virtual bool fold_range (irange , tree type,
+  const irange , const irange ,
+  relation_trio = TRIO_VARYING) const final override;
   virtual void wi_fold (irange , tree type,
const wide_int _lb,
const wide_int _ub,
@@ -1762,6 +1766,32 @@ public:
  relation_trio) const;
 } op_mult;
 
+bool
+operator_mult::fold_range (irange , tree type,
+  const irange , const irange ,
+  relation_trio trio) const
+{
+  if (!cross_product_operator::fold_range (r, type, lh, rh, trio))
+return false;
+
+  if (lh.undefined_p ())
+return true;
+
+  tree t;
+  if (rh.singleton_p ())
+{
+  wide_int w = wi::to_wide (t);
+  int shift = wi::exact_log2 (w);
+  if (shift != -1)
+   {
+ wide_int nz = lh.get_nonzero_bits ();
+ nz = wi::lshift (nz, shift);
+ r.set_nonzero_bits (nz);
+   }
+}
+  return true;
+}
+
 bool
 operator_mult::op1_range (irange , tree type,
  const irange , const irange ,
@@ -1902,10 +1932,39 @@ public:
const wide_int _ub) const;
   virtual bool wi_op_overflows (wide_int , tree type,
const wide_int &, const wide_int &) const;
+  virtual bool fold_range (irange , tree type,
+  const irange , const irange ,
+  relation_trio trio) const final override;
 private:
   enum tree_code code;
 };
 
+bool
+operator_div::fold_range (irange , tree type,
+ const irange , const irange ,
+ relation_trio trio) const
+{
+  if (!cross_product_operator::fold_range (r, type, lh, rh, trio))
+return false;
+
+  if (lh.undefined_p ())
+return true;
+
+  tree t;
+  if (rh.singleton_p ())
+{
+  wide_int wi = wi::to_wide (t);
+  int shift = wi::exact_log2 (wi);
+  if (shift != -1)
+   {
+ wide_int nz = lh.get_nonzero_bits ();
+ nz = wi::rshift (nz, shift, TYPE_SIGN (type));
+ r.set_nonzero_bits (nz);
+   }
+}
+  return true;
+}
+
 bool
 operator_div::wi_op_overflows (wide_int , tree type,
   const wide_int , const wide_int ) const
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/vrp122.c 
b/gcc/testsuite/gcc.dg/tree-ssa/vrp122.c
new file mode 100644
index 000..b2ddcda023c
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/tree-ssa/vrp122.c
@@ -0,0 +1,19 @@
+// { dg-do compile }
+// { dg-options "-O2 -fdump-tree-evrp-details" }
+
+void gg(void);
+int f(unsigned t)
+{
+  unsigned g = t*16;
+  if (g==0)  return 1;
+  gg();
+  gg();
+  gg();
+  gg();
+  gg();
+  gg();
+  if (g<=4)  return 1;
+  return 0;
+}
+
+// { dg-final { scan-tree-dump "Global Exported: g_.* NONZERO 0x.*fff0" "evrp" 
} }
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/vrp123.c 
b/gcc/testsuite/gcc.dg/tree-ssa/vrp123.c
new file mode 100644
index 000..1ad3caa4384
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/tree-ssa/vrp123.c
@@ -0,0 +1,18 @@
+// { dg-options "-O1 -fdump-tree-dom3-raw" }
+
+extern int
+__attribute__((const))
+foo4b (int);
+
+int f4b (unsigned int r)
+{
+  if (foo4b (r))
+r *= 8U;
+
+  if ((r / 2U) & 2U)
+r += foo4b (r);
+
+  return r;
+}
+
+// { dg-final { scan-tree-dump-times {gimple_call 

[committed] libstdc++: Simplify lifetime of eh_globals variable [PR107500]

2022-11-04 Thread Jonathan Wakely via Gcc-patches
Tested powerpc64le-linux. Pushed to trunk.

-- >8 --

Since this is a trivial type, we probably don't need to do anything to
ensure it's still accessible after other static dtors.

libstdc++-v3/ChangeLog:

PR libstdc++/107500
* libsupc++/eh_globals.cc (eh_globals): Remove immortalizing
wrapper.
(__cxxabiv1::__cxa_get_globals_fast): Adjust.
(__cxxabiv1::__cxa_get_globals): Adjust.
---
 libstdc++-v3/libsupc++/eh_globals.cc | 20 +---
 1 file changed, 5 insertions(+), 15 deletions(-)

diff --git a/libstdc++-v3/libsupc++/eh_globals.cc 
b/libstdc++-v3/libsupc++/eh_globals.cc
index 12abfc10521..74e8a454ecc 100644
--- a/libstdc++-v3/libsupc++/eh_globals.cc
+++ b/libstdc++-v3/libsupc++/eh_globals.cc
@@ -70,18 +70,8 @@ __cxxabiv1::__cxa_get_globals() _GLIBCXX_NOTHROW
 
 namespace
 {
-  struct constant_init
-  {
-union {
-  __cxa_eh_globals obj;
-};
-constexpr constant_init() : obj() { }
-
-~constant_init() { /* do nothing, union member is not destroyed */ }
-  };
-
   // Single-threaded fallback buffer.
-  __constinit constant_init eh_globals;
+  __constinit __cxa_eh_globals eh_globals;
 }
 
 #if __GTHREADS
@@ -142,7 +132,7 @@ __cxxabiv1::__cxa_get_globals_fast() _GLIBCXX_NOTHROW
   if (init._S_init)
 g = static_cast<__cxa_eh_globals*>(__gthread_getspecific(init._M_key));
   else
-g = _globals.obj;
+g = _globals;
   return g;
 }
 
@@ -167,7 +157,7 @@ __cxxabiv1::__cxa_get_globals() _GLIBCXX_NOTHROW
}
 }
   else
-g = _globals.obj;
+g = _globals;
   return g;
 }
 
@@ -175,11 +165,11 @@ __cxxabiv1::__cxa_get_globals() _GLIBCXX_NOTHROW
 
 extern "C" __cxa_eh_globals*
 __cxxabiv1::__cxa_get_globals_fast() _GLIBCXX_NOTHROW
-{ return _globals.obj; }
+{ return _globals; }
 
 extern "C" __cxa_eh_globals*
 __cxxabiv1::__cxa_get_globals() _GLIBCXX_NOTHROW
-{ return _globals.obj; }
+{ return _globals; }
 
 #endif
 
-- 
2.38.1



[committed] libstdc++: Define _GNU_SOURCE for secure_getenv on Cygwin [PR107511]

2022-11-04 Thread Jonathan Wakely via Gcc-patches
Tested powerpc64le-linux. Pushed to trunk.

-- >8 --

As in r12-6867-ge20486d508afdf we need to define _GNU_SOURCE explicitly
for Cygwin, because configure finds it in libc but it isn't declared
unless we request it.

libstdc++-v3/ChangeLog:

PR libstdc++/107511
* libsupc++/eh_alloc.cc (_GNU_SOURCE): Define.
---
 libstdc++-v3/libsupc++/eh_alloc.cc | 5 +
 1 file changed, 5 insertions(+)

diff --git a/libstdc++-v3/libsupc++/eh_alloc.cc 
b/libstdc++-v3/libsupc++/eh_alloc.cc
index e93f14c887b..83d15f39ca4 100644
--- a/libstdc++-v3/libsupc++/eh_alloc.cc
+++ b/libstdc++-v3/libsupc++/eh_alloc.cc
@@ -25,6 +25,11 @@
 // This is derived from the C++ ABI for IA-64.  Where we diverge
 // for cross-architecture compatibility are noted with "@@@".
 
+#ifndef _GNU_SOURCE
+// Cygwin needs this for secure_getenv
+# define _GNU_SOURCE 1
+#endif
+
 #include// std::exception
 #include  // std::terminate
 #include  // std::malloc, std::free, std::strtoul
-- 
2.38.1



[COMMITTED] ada: Cleanup code for unreferenced variables

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Piotr Trojanek 

Further cleanups related to warnings about unreferenced objects.

gcc/ada/

* sem_warn.adb (Check_References): Remove useless query for "spec"
of a variable; refactor nested if-statements into a single
condition.

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

---
 gcc/ada/sem_warn.adb | 29 ++---
 1 file changed, 10 insertions(+), 19 deletions(-)

diff --git a/gcc/ada/sem_warn.adb b/gcc/ada/sem_warn.adb
index 423754f5df8..a7f220bfbc7 100644
--- a/gcc/ada/sem_warn.adb
+++ b/gcc/ada/sem_warn.adb
@@ -1221,7 +1221,7 @@ package body Sem_Warn is
elsif Warn_On_Constant
  and then Ekind (E1) = E_Variable
  and then Has_Initial_Value (E1)
- and then Never_Set_In_Source_Check_Spec (E1)
+ and then Never_Set_In_Source (E1)
  and then not Generic_Package_Spec_Entity (E1)
then
   --  A special case, if this variable is volatile and not
@@ -1248,24 +1248,15 @@ package body Sem_Warn is
   --  Here we give the warning if referenced and no pragma
   --  Unreferenced or Unmodified is present.
 
-  else
- --  Variable case
-
- if Ekind (E1) = E_Variable then
-if Referenced_Check_Spec (E1)
-  and then not Has_Pragma_Unreferenced_Check_Spec (E1)
-  and then not Has_Pragma_Unmodified_Check_Spec (E1)
-then
-   if not Warnings_Off_E1
- and then not Has_Junk_Name (E1)
-   then
-  Error_Msg_N -- CODEFIX
-("?k?& is not modified, "
- & "could be declared constant!",
- E1);
-   end if;
-end if;
- end if;
+  elsif Referenced (E1)
+and then not Has_Unreferenced (E1)
+and then not Has_Unmodified (E1)
+and then not Warnings_Off_E1
+and then not Has_Junk_Name (E1)
+  then
+ Error_Msg_N -- CODEFIX
+   ("?k?& is not modified, could be declared constant!",
+E1);
   end if;
 
--  Other cases of a variable or parameter never set in source
-- 
2.34.1



[COMMITTED] ada: Fix for validity checks combined with aliasing checks

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Justin Squirek 

Attribute Overlaps_Storage, which can appear implicitly in expansion of
aliasing checks, is now excluded from operand validity checks. Likewise
for attribute Has_Same_Storage.

gcc/ada/

* exp_attr.adb (Expand_N_Attribute_Reference): Skip operand
validity checks for attributes Has_Same_Storage and
Overlaps_Storage.

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

---
 gcc/ada/exp_attr.adb | 16 +++-
 1 file changed, 11 insertions(+), 5 deletions(-)

diff --git a/gcc/ada/exp_attr.adb b/gcc/ada/exp_attr.adb
index 3c3f725cf27..1ef30656496 100644
--- a/gcc/ada/exp_attr.adb
+++ b/gcc/ada/exp_attr.adb
@@ -1998,16 +1998,22 @@ package body Exp_Attr is
--  Start of processing for Expand_N_Attribute_Reference
 
begin
-  --  Do required validity checking, if enabled. Do not apply check to
-  --  output parameters of an Asm instruction, since the value of this
-  --  is not set till after the attribute has been elaborated, and do
-  --  not apply the check to the arguments of a 'Read or 'Input attribute
-  --  reference since the scalar argument is an OUT scalar.
+  --  Do required validity checking, if enabled.
+  --
+  --  Skip check for output parameters of an Asm instruction (since their
+  --  valuesare not set till after the attribute has been elaborated),
+  --  for the arguments of a 'Read or 'Input attribute reference (since
+  --  the scalar argument is an OUT scalar) and for the arguments of a
+  --  'Has_Same_Storage or 'Overlaps_Storage attribute reference (which not
+  --  considered to be reads of their prefixes and expressions, see Ada RM
+  --  13.3(73.10/3)).
 
   if Validity_Checks_On and then Validity_Check_Operands
 and then Id /= Attribute_Asm_Output
 and then Id /= Attribute_Read
 and then Id /= Attribute_Input
+and then Id /= Attribute_Has_Same_Storage
+and then Id /= Attribute_Overlaps_Storage
   then
  declare
 Expr : Node_Id;
-- 
2.34.1



[COMMITTED] ada: Cleanup code for warnings about unset references

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Piotr Trojanek 

Cleanup related to new checks for unset references.

gcc/ada/

* sem_util.adb
(In_Pragma_Expression): Add standard guard against searching too
far.
(In_Quantified_Expression): Likewise.
* sem_warn.adb
(May_Need_Initialized_Actual): Remove redundant parens.
(Check_References): Remove guard that duplicates a condition from
the enclosing if-statement; only assign E1T variable when
necessary.
(Within_Postcondition): Fix layout.
(No_Warn_On_In_Out): Balance parens in comment.

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

---
 gcc/ada/sem_util.adb | 13 +
 gcc/ada/sem_warn.adb | 18 ++
 2 files changed, 19 insertions(+), 12 deletions(-)

diff --git a/gcc/ada/sem_util.adb b/gcc/ada/sem_util.adb
index 80d07eb0023..5c495761df1 100644
--- a/gcc/ada/sem_util.adb
+++ b/gcc/ada/sem_util.adb
@@ -14794,8 +14794,15 @@ package body Sem_Util is
   loop
  if No (P) then
 return False;
+
+ --  Prevent the search from going too far
+
+ elsif Is_Body_Or_Package_Declaration (P) then
+return False;
+
  elsif Nkind (P) = N_Pragma and then Pragma_Name (P) = Nam then
 return True;
+
  else
 P := Parent (P);
  end if;
@@ -14871,6 +14878,12 @@ package body Sem_Util is
   loop
  if No (P) then
 return False;
+
+ --  Prevent the search from going too far
+
+ elsif Is_Body_Or_Package_Declaration (P) then
+return False;
+
  elsif Nkind (P) = N_Quantified_Expression then
 return True;
  else
diff --git a/gcc/ada/sem_warn.adb b/gcc/ada/sem_warn.adb
index 509efa50af3..423754f5df8 100644
--- a/gcc/ada/sem_warn.adb
+++ b/gcc/ada/sem_warn.adb
@@ -928,7 +928,7 @@ package body Sem_Warn is
  if not Is_Generic_Type (T) then
 null;
 
- elsif (Nkind (Par)) = N_Private_Extension_Declaration then
+ elsif Nkind (Par) = N_Private_Extension_Declaration then
 
 --  We only indicate the first such variable in the generic.
 
@@ -936,7 +936,7 @@ package body Sem_Warn is
Set_Uninitialized_Variable (Par, Ent);
 end if;
 
- elsif (Nkind (Par)) = N_Formal_Type_Declaration
+ elsif Nkind (Par) = N_Formal_Type_Declaration
and then Nkind (Formal_Type_Definition (Par)) =
  N_Formal_Private_Type_Definition
  then
@@ -1151,8 +1151,6 @@ package body Sem_Warn is
 
   E1 := First_Entity (E);
   while Present (E1) loop
- E1T := Etype (E1);
-
  --  We are only interested in source entities. We also don't issue
  --  warnings within instances, since the proper place for such
  --  warnings is on the template when it is compiled, and we don't
@@ -1161,6 +1159,8 @@ package body Sem_Warn is
  if Comes_From_Source (E1)
and then Instantiation_Location (Sloc (E1)) = No_Location
  then
+E1T := Etype (E1);
+
 --  We are interested in variables and out/in-out parameters, but
 --  we exclude protected types, too complicated to worry about.
 
@@ -1648,11 +1648,6 @@ package body Sem_Warn is
not Is_Package_Or_Generic_Package
  (Cunit_Entity (Current_Sem_Unit
 
-  --  Exclude instantiations, since there is no reason why every
-  --  entity in an instantiation should be referenced.
-
-  and then Instantiation_Location (Sloc (E1)) = No_Location
-
   --  Exclude formal parameters from bodies if the corresponding
   --  spec entity has been referenced in the case where there is
   --  a separate spec.
@@ -2001,8 +1996,7 @@ package body Sem_Warn is
   P := Parent (Nod);
 
   if Nkind (P) = N_Pragma
-and then Pragma_Name (P) =
-  Name_Test_Case
+and then Pragma_Name (P) = Name_Test_Case
 and then Nod = Test_Case_Arg (P, Name_Ensures)
   then
  return True;
@@ -3028,7 +3022,7 @@ package body Sem_Warn is
   --  if we have seen the address of the subprogram being taken, or if the
   --  subprogram is used as a generic actual (in the latter cases the
   --  context may force use of IN OUT, even if the parameter is not
-  --  modified for this particular case.
+  --  modified for this particular case).
 
   ---
   -- No_Warn_On_In_Out --
-- 
2.34.1



[COMMITTED] ada: Fix couple of issues with arrays indexed by enumeration type

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Eric Botcazou 

The first one is that Remove_Warning_Messages reinstates the Original_Node
of an N_Raise_Constraint_Error node in the tree for no clear reasons, and
the Original_Node may contain constructs whose expansion has been stopped
when the Constraint_Error was asserted, eventually causing gigi to stop.

The second one is that a path in Build_Array_Aggr_Code.Gen_Loop does not
copy the loop bounds, unlike other paths, thus triggering a sharing issue.

gcc/ada/

* errout.adb (Remove_Warning_Messages.Check_For_Warning): Do not
reinstate the Original_Node in the tree.
* exp_aggr.adb (Build_Array_Aggr_Code.Gen_Loop): Copy the bounds
on all paths.

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

---
 gcc/ada/errout.adb   | 16 +++-
 gcc/ada/exp_aggr.adb |  4 ++--
 2 files changed, 5 insertions(+), 15 deletions(-)

diff --git a/gcc/ada/errout.adb b/gcc/ada/errout.adb
index 85931552970..5730a543ee1 100644
--- a/gcc/ada/errout.adb
+++ b/gcc/ada/errout.adb
@@ -3383,23 +3383,13 @@ package body Errout is
 E := Errors.Table (E).Next;
  end loop;
 
+ --  Warnings may have been posted on subexpressions of original tree
+
  if Nkind (N) = N_Raise_Constraint_Error
and then Is_Rewrite_Substitution (N)
and then No (Condition (N))
  then
---  Warnings may have been posted on subexpressions of the original
---  tree. We place the original node back on the tree to remove
---  those warnings, whose sloc do not match those of any node in
---  the current tree. Given that we are in unreachable code, this
---  modification to the tree is harmless.
-
-if Is_List_Member (N) then
-   Set_Condition (N, Original_Node (N));
-   Check_All_Warnings (Condition (N));
-else
-   Rewrite (N, Original_Node (N));
-   Check_All_Warnings (N);
-end if;
+Check_All_Warnings (Original_Node (N));
  end if;
 
  return OK;
diff --git a/gcc/ada/exp_aggr.adb b/gcc/ada/exp_aggr.adb
index 185705544e9..dde49d1e289 100644
--- a/gcc/ada/exp_aggr.adb
+++ b/gcc/ada/exp_aggr.adb
@@ -2058,7 +2058,7 @@ package body Exp_Aggr is
  --  to do that if we already have the base type at hand.
 
  if Etype (L) = Index_Base then
-L_L := L;
+L_L := New_Copy_Tree (L);
  else
 L_L :=
   Make_Qualified_Expression (Loc,
@@ -2067,7 +2067,7 @@ package body Exp_Aggr is
  end if;
 
  if Etype (H) = Index_Base then
-L_H := H;
+L_H := New_Copy_Tree (H);
  else
 L_H :=
   Make_Qualified_Expression (Loc,
-- 
2.34.1



[COMMITTED] ada: Fix various typos in GNAT User's Guide

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Piotr Trojanek 

Fix uncontroversial typos.

gcc/ada/

* doc/gnat_ugn/building_executable_programs_with_gnat.rst: Fix
typos.
* doc/gnat_ugn/elaboration_order_handling_in_gnat.rst: Fix typos
and refill as necessary; remove trailing whitespace.
* doc/gnat_ugn/gnat_and_program_execution.rst: Fix typos.
* gnat_ugn.texi: Regenerate.

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

---
 .../building_executable_programs_with_gnat.rst|  2 +-
 .../elaboration_order_handling_in_gnat.rst| 15 ---
 .../doc/gnat_ugn/gnat_and_program_execution.rst   |  4 ++--
 gcc/ada/gnat_ugn.texi | 13 +++--
 4 files changed, 18 insertions(+), 16 deletions(-)

diff --git a/gcc/ada/doc/gnat_ugn/building_executable_programs_with_gnat.rst 
b/gcc/ada/doc/gnat_ugn/building_executable_programs_with_gnat.rst
index 49cfc7477af..83bc50f7e91 100644
--- a/gcc/ada/doc/gnat_ugn/building_executable_programs_with_gnat.rst
+++ b/gcc/ada/doc/gnat_ugn/building_executable_programs_with_gnat.rst
@@ -7403,7 +7403,7 @@ development environments much more flexible.
 Examples of ``gnatbind`` Usage
 --
 
-Here are some examples of ``gnatbind`` invovations:
+Here are some examples of ``gnatbind`` invocations:
 
   ::
 
diff --git a/gcc/ada/doc/gnat_ugn/elaboration_order_handling_in_gnat.rst 
b/gcc/ada/doc/gnat_ugn/elaboration_order_handling_in_gnat.rst
index 4982ebf4b10..76a1461777e 100644
--- a/gcc/ada/doc/gnat_ugn/elaboration_order_handling_in_gnat.rst
+++ b/gcc/ada/doc/gnat_ugn/elaboration_order_handling_in_gnat.rst
@@ -265,7 +265,7 @@ respect to control and data flow.
 Checking the Elaboration Order
 ==
 
-To avoid placing the entire elaboration-order burden on the programmer, Ada 
+To avoid placing the entire elaboration-order burden on the programmer, Ada
 provides three lines of defense:
 
 * *Static semantics*
@@ -931,9 +931,9 @@ Resolving Elaboration Circularities
 ===
 
 The most desirable option from the point of view of long-term maintenance is to
-rearrange the program so that the elaboration problems are avoided. One useful 
-technique is to place the elaboration code into separate child packages. 
-Another is to move some of the initialization code to explicitly invoked 
+rearrange the program so that the elaboration problems are avoided. One useful
+technique is to place the elaboration code into separate child packages.
+Another is to move some of the initialization code to explicitly invoked
 subprograms, where the program controls the order of initialization explicitly.
 Although this is the most desirable option, it may be impractical and involve
 too much modification, especially in the case of complex legacy code.
@@ -990,8 +990,9 @@ following tactics to eliminate the circularity:
  change pragma Elaborate_All for unit "..." to Elaborate in unit "..."
 
   This tactic is always suggested with the pragma ``Elaborate_All`` elimination
-  tactic. It offers a different alernative of guaranteeing that the argument of
-  the pragma will still be elaborated prior to the unit containing the pragma.
+  tactic. It offers a different alternative of guaranteeing that the argument
+  of the pragma will still be elaborated prior to the unit containing the
+  pragma.
 
   The programmer should update the pragma as advised, and rebuild the program.
 
@@ -1281,7 +1282,7 @@ Summary of Procedures for Elaboration Control
 
 A programmer should first compile the program with the default options, using
 none of the binder or compiler switches. If the binder succeeds in finding an
-elaboration order, then apart from possible cases involing dispatching calls
+elaboration order, then apart from possible cases involving dispatching calls
 and access-to-subprogram types, the program is free of elaboration errors.
 
 If it is important for the program to be portable to compilers other than GNAT,
diff --git a/gcc/ada/doc/gnat_ugn/gnat_and_program_execution.rst 
b/gcc/ada/doc/gnat_ugn/gnat_and_program_execution.rst
index 0d78e433e73..e827d1f9841 100644
--- a/gcc/ada/doc/gnat_ugn/gnat_and_program_execution.rst
+++ b/gcc/ada/doc/gnat_ugn/gnat_and_program_execution.rst
@@ -2321,7 +2321,7 @@ erroneous, and the compiler would be entitled to assume 
that
 
 However, in practice, this would cause some existing code that
 seems to work with no optimization to start failing at high
-levels of optimzization.
+levels of optimization.
 
 What the compiler does for such cases is to assume that marking
 a variable as aliased indicates that some "funny business" may
@@ -2728,7 +2728,7 @@ To deal with the portability issue, and with the problem 
of
 mathematical versus run-time interpretation of the expressions in
 assertions, GNAT provides comprehensive control over the handling
 of intermediate overflow. GNAT can operate in three modes, and
-furthemore, permits separate 

[COMMITTED] ada: Fix typo in comment referring to pragma Restrictions

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Piotr Trojanek 

Comment cleanup only.

gcc/ada/

* libgnat/g-excact.ads
(Register_Global_Action): Refill comment.
(Name_To_Id): Change pragma Restriction from singular to plural.

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

---
 gcc/ada/libgnat/g-excact.ads | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)

diff --git a/gcc/ada/libgnat/g-excact.ads b/gcc/ada/libgnat/g-excact.ads
index 110154651e0..c2e0b30b1da 100644
--- a/gcc/ada/libgnat/g-excact.ads
+++ b/gcc/ada/libgnat/g-excact.ads
@@ -71,8 +71,7 @@ package GNAT.Exception_Actions is
--  If Action is null, this will in effect cancel all exception actions.
 
procedure Register_Global_Unhandled_Action (Action : Exception_Action);
-   --  Similar to Register_Global_Action, called on unhandled exceptions
-   --  only.
+   --  Similar to Register_Global_Action, called on unhandled exceptions only
 
procedure Register_Id_Action
  (Id : Exception_Id;
@@ -90,7 +89,7 @@ package GNAT.Exception_Actions is
--  an exception that is declared within an unlabeled block.
--
--  Note: All non-predefined exceptions will return Null_Id for programs
-   --  compiled with pragma Restriction (No_Exception_Registration)
+   --  compiled with pragma Restrictions (No_Exception_Registration).
 
function Is_Foreign_Exception (E : Exception_Occurrence) return Boolean;
--  Tell whether the exception occurrence E represents a foreign exception,
-- 
2.34.1



[COMMITTED] ada: Fix repeated killing of private entity values

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Piotr Trojanek 

When killing known values of assignable entities we iterated from
First_Entity and then again from First_Private_Entity. This second
iteration was unnecessary, because the entity chain that starts with
First_Entity contains all entities, including the private ones.

This is just a performance improvement; the behavior is unchanged.

gcc/ada/

* sem_util.adb (Kill_Current_Values): Only iterate from
First_Entity through Next_Entity.

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

---
 gcc/ada/sem_util.adb | 38 +-
 1 file changed, 9 insertions(+), 29 deletions(-)

diff --git a/gcc/ada/sem_util.adb b/gcc/ada/sem_util.adb
index 9eeaf7cc05b..28396a4c34b 100644
--- a/gcc/ada/sem_util.adb
+++ b/gcc/ada/sem_util.adb
@@ -22287,25 +22287,6 @@ package body Sem_Util is
procedure Kill_Current_Values (Last_Assignment_Only : Boolean := False) is
   S : Entity_Id;
 
-  procedure Kill_Current_Values_For_Entity_Chain (E : Entity_Id);
-  --  Clear current value for entity E and all entities chained to E
-
-  --
-  -- Kill_Current_Values_For_Entity_Chain --
-  --
-
-  procedure Kill_Current_Values_For_Entity_Chain (E : Entity_Id) is
- Ent : Entity_Id;
-  begin
- Ent := E;
- while Present (Ent) loop
-Kill_Current_Values (Ent, Last_Assignment_Only);
-Next_Entity (Ent);
- end loop;
-  end Kill_Current_Values_For_Entity_Chain;
-
-   --  Start of processing for Kill_Current_Values
-
begin
   --  Kill all saved checks, a special case of killing saved values
 
@@ -22321,16 +22302,15 @@ package body Sem_Util is
 
  --  Clear current values of all entities in current scope
 
- Kill_Current_Values_For_Entity_Chain (First_Entity (S));
-
- --  If scope is a package, also clear current values of all private
- --  entities in the scope.
-
- if Is_Package_Or_Generic_Package (S)
-   or else Is_Concurrent_Type (S)
- then
-Kill_Current_Values_For_Entity_Chain (First_Private_Entity (S));
- end if;
+ declare
+Ent : Entity_Id;
+ begin
+Ent := First_Entity (S);
+while Present (Ent) loop
+   Kill_Current_Values (Ent, Last_Assignment_Only);
+   Next_Entity (Ent);
+end loop;
+ end;
 
  --  If this is a not a subprogram, deal with parents
 
-- 
2.34.1



[COMMITTED] ada: Flag unsupported dispatching constructor calls

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Javier Miranda 

gcc/ada/

* exp_intr.adb
(Expand_Dispatching_Constructor_Call): Report an error on
unsupported dispatching constructor calls and report a warning on
calls that may fail at run time.

gcc/testsuite/

* gnat.dg/abstract1.ads: Cleanup whitespaces.
* gnat.dg/abstract1.adb: Likewise and add -gnatws to silence new
warning.

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

---
 gcc/ada/exp_intr.adb| 44 +
 gcc/testsuite/gnat.dg/abstract1.adb | 14 +
 gcc/testsuite/gnat.dg/abstract1.ads |  6 ++--
 3 files changed, 55 insertions(+), 9 deletions(-)

diff --git a/gcc/ada/exp_intr.adb b/gcc/ada/exp_intr.adb
index bd987f089e1..cb9b5be1090 100644
--- a/gcc/ada/exp_intr.adb
+++ b/gcc/ada/exp_intr.adb
@@ -24,13 +24,16 @@
 --
 
 with Atree;  use Atree;
+with Aspects;use Aspects;
 with Checks; use Checks;
 with Einfo;  use Einfo;
 with Einfo.Entities; use Einfo.Entities;
 with Einfo.Utils;use Einfo.Utils;
 with Elists; use Elists;
+with Errout; use Errout;
 with Expander;   use Expander;
 with Exp_Atag;   use Exp_Atag;
+with Exp_Ch6;use Exp_Ch6;
 with Exp_Ch7;use Exp_Ch7;
 with Exp_Ch11;   use Exp_Ch11;
 with Exp_Code;   use Exp_Code;
@@ -277,6 +280,47 @@ package body Exp_Intr is
   Result_Typ : Entity_Id;
 
begin
+  pragma Assert (Is_Class_Wide_Type (Etype (Entity (Name (N);
+
+  --  Report case where we know that the generated code is wrong; that
+  --  is a dispatching constructor call whose controlling type has tasks
+  --  but its root type does not have tasks. In such case the constructor
+  --  subprogram of the root type does not have extra formals but the
+  --  constructor of the derivation must have extra formals.
+
+  if not Global_No_Tasking
+and then not No_Run_Time_Mode
+and then Is_Build_In_Place_Function (Entity (Name (N)))
+and then not Has_Task (Root_Type (Etype (Entity (Name (N)
+and then not Has_Aspect (Root_Type (Etype (Entity (Name (N,
+   Aspect_No_Task_Parts)
+  then
+ --  Case 1: Explicit tag reference (which allows static check)
+
+ if Nkind (Tag_Arg) = N_Identifier
+   and then Present (Entity (Tag_Arg))
+   and then Is_Tag (Entity (Tag_Arg))
+ then
+if Has_Task (Related_Type (Entity (Tag_Arg))) then
+   Error_Msg_N ("unsupported dispatching constructor call", N);
+   Error_Msg_NE
+ ("\work around this problem by defining task component "
+  & "type& using access-to-task-type",
+  N, Related_Type (Entity (Tag_Arg)));
+end if;
+
+ --  Case 2: Dynamic tag which may fail at run time
+
+ else
+Error_Msg_N
+  ("unsupported dispatching constructor call if the type "
+   & "of the built object has task components??", N);
+Error_Msg_N
+  ("\work around this problem by replacing task components "
+   & "with access-to-task-type components??", N);
+ end if;
+  end if;
+
   --  Remove side effects from tag argument early, before rewriting
   --  the dispatching constructor call, as Remove_Side_Effects relies
   --  on Tag_Arg's Parent link properly attached to the tree (once the
diff --git a/gcc/testsuite/gnat.dg/abstract1.adb 
b/gcc/testsuite/gnat.dg/abstract1.adb
index 97508fac2b8..36f75e9d495 100644
--- a/gcc/testsuite/gnat.dg/abstract1.adb
+++ b/gcc/testsuite/gnat.dg/abstract1.adb
@@ -1,18 +1,20 @@
 --  { dg-do compile }
+--  { dg-options "-gnatws" }
+
 with Ada.Tags.Generic_Dispatching_Constructor;  use Ada.Tags;
 package body abstract1 is
-   
+
function New_T (Stream : not null access Root_Stream_Type'Class)
   return T'Class is
   function Construct is
  new Generic_Dispatching_Constructor (T, Root_Stream_Type'Class, 
Input);
   E : constant String := String'Input (Stream);
   I : constant Tag := Internal_Tag (E);
-   
+
begin
   return Construct (I, Stream);
end New_T;
-   
+
function Input (Stream : not null access Root_Stream_Type'Class)
  return IT is
begin
@@ -20,12 +22,12 @@ package body abstract1 is
 Integer'Read (Stream, O.I);
   end return;
end Input;
-   
+
function Input (Stream : not null access Root_Stream_Type'Class)
   return FT is
begin
   return O : FT do
 Float'Read (Stream, O.F);
-  end return;  
-   end Input;  
+  end return;
+   end Input;
 end abstract1;
diff --git a/gcc/testsuite/gnat.dg/abstract1.ads 
b/gcc/testsuite/gnat.dg/abstract1.ads
index 

[COMMITTED] ada: Cleanup code for warnings about unreferenced formal parameters

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Piotr Trojanek 

Cleanup related to new checks for unset references.

gcc/ada/

* sem_warn.adb (Check_References): Remove redundant guard, as it
is implied by a preceding call to Referenced_Check_Spec.

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

---
 gcc/ada/sem_warn.adb | 9 -
 1 file changed, 9 deletions(-)

diff --git a/gcc/ada/sem_warn.adb b/gcc/ada/sem_warn.adb
index a7f220bfbc7..77d58211b50 100644
--- a/gcc/ada/sem_warn.adb
+++ b/gcc/ada/sem_warn.adb
@@ -1639,15 +1639,6 @@ package body Sem_Warn is
not Is_Package_Or_Generic_Package
  (Cunit_Entity (Current_Sem_Unit
 
-  --  Exclude formal parameters from bodies if the corresponding
-  --  spec entity has been referenced in the case where there is
-  --  a separate spec.
-
-  and then not (Is_Formal (E1)
- and then Ekind (Scope (E1)) = E_Subprogram_Body
- and then Present (Spec_Entity (E1))
- and then Referenced (Spec_Entity (E1)))
-
   --  Consider private type referenced if full view is referenced.
   --  If there is not full view, this is a generic type on which
   --  warnings are also useful.
-- 
2.34.1



[COMMITTED] ada: Remove sa_messages

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Ghjuvan Lacambre 

Spark and CodePeer do not depend on this unit anymore.

gcc/ada/

* sa_messages.ads, sa_messages.adb: Remove files.

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

---
 gcc/ada/sa_messages.adb | 539 
 gcc/ada/sa_messages.ads | 267 
 2 files changed, 806 deletions(-)
 delete mode 100644 gcc/ada/sa_messages.adb
 delete mode 100644 gcc/ada/sa_messages.ads

diff --git a/gcc/ada/sa_messages.adb b/gcc/ada/sa_messages.adb
deleted file mode 100644
index b9b4e932b43..000
--- a/gcc/ada/sa_messages.adb
+++ /dev/null
@@ -1,539 +0,0 @@
---
---   C O D E P E E R / S P A R K--
---  --
--- Copyright (C) 2015-2022, AdaCore --
---  --
--- This is free software;  you can redistribute it  and/or modify it  under --
--- terms of the  GNU General Public License as published  by the Free Soft- --
--- ware  Foundation;  either version 3,  or (at your option) any later ver- --
--- sion.  This software is distributed in the hope  that it will be useful, --
--- but WITHOUT ANY WARRANTY;  without even the implied warranty of MERCHAN- --
--- TABILITY 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  distributed  with  this  software;   see  file --
--- COPYING3.  If not, go to http://www.gnu.org/licenses for a complete copy --
--- of the license.  --
---  --
---
-
-pragma Ada_2012;
-
-with Ada.Directories; use Ada.Directories;
-with Ada.Strings.Unbounded.Hash;
-
-with Ada.Text_IO; use Ada.Text_IO;
-with GNATCOLL.JSON;   use GNATCOLL.JSON;
-
-package body SA_Messages is
-
-   ---
-   -- Local subprograms --
-   ---
-
-   function "<" (Left, Right : SA_Message) return Boolean is
- (if Left.Kind /= Right.Kind then
- Left.Kind < Right.Kind
-  else
- Left.Kind in Check_Kind
-   and then Left.Check_Result < Right.Check_Result);
-
-   function "<" (Left, Right : Simple_Source_Location) return Boolean is
-  (if Left.File_Name /= Right.File_Name then
-  Left.File_Name < Right.File_Name
-   elsif Left.Line /= Right.Line then
-  Left.Line < Right.Line
-   else
-  Left.Column < Right.Column);
-
-   function "<" (Left, Right : Source_Locations) return Boolean is
- (if Left'Length /= Right'Length then
- Left'Length < Right'Length
-  elsif Left'Length = 0 then
- False
-  elsif Left (Left'Last) /= Right (Right'Last) then
- Left (Left'Last) < Right (Right'Last)
-  else
- Left (Left'First .. Left'Last - 1) <
-   Right (Right'First .. Right'Last - 1));
-
-   function "<" (Left, Right : Source_Location) return Boolean is
- (Left.Locations < Right.Locations);
-
-   function Base_Location
- (Location : Source_Location) return Simple_Source_Location is
- (Location.Locations (1));
-
-   function Hash (Key : SA_Message) return Hash_Type;
-   function Hash (Key : Source_Location) return Hash_Type;
-
-   -
-   -- "<" --
-   -
-
-   function "<" (Left, Right : Message_And_Location) return Boolean is
- (if Left.Message = Right.Message
-  then Left.Location < Right.Location
-  else Left.Message < Right.Message);
-
-   
-   -- Column --
-   
-
-   function Column (Location : Source_Location) return Column_Number is
- (Base_Location (Location).Column);
-
-   ---
-   -- File_Name --
-   ---
-
-   function File_Name (Location : Source_Location) return String is
- (To_String (Base_Location (Location).File_Name));
-
-   function File_Name (Location : Source_Location) return Unbounded_String is
- (Base_Location (Location).File_Name);
-
-   
-   -- Enclosing_Instance --
-   
-
-   function Enclosing_Instance
- (Location : Source_Location) return Source_Location_Or_Null is
- (Count => Location.Count - 1,
-  Locations => Location.Locations (2 .. Location.Count));
-
-   --
-   -- Hash --
-   --
-
-   function Hash (Key : Message_And_Location) return Hash_Type is
- (Hash (Key.Message) + Hash (Key.Location));
-
-   function Hash (Key : SA_Message) return Hash_Type is
-   begin
-  return Result : Hash_Type :=
-Hash_Type'Mod (Message_Kind'Pos (Key.Kind))
-  do
- if 

[COMMITTED] ada: Simplify detection of controlling formals

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Piotr Trojanek 

When detecting controlling formals we are only interested in formal
parameters and not in other entities.

gcc/ada/

* sem_ch6.adb (Controlling_Formal): Iterate with First/Next_Formal
and not with First/Next_Entity.

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

---
 gcc/ada/sem_ch6.adb | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/gcc/ada/sem_ch6.adb b/gcc/ada/sem_ch6.adb
index 228adcff5cd..d28de10d3d6 100644
--- a/gcc/ada/sem_ch6.adb
+++ b/gcc/ada/sem_ch6.adb
@@ -10711,13 +10711,13 @@ package body Sem_Ch6 is
  E : Entity_Id;
 
   begin
- E := First_Entity (Prim);
+ E := First_Formal (Prim);
  while Present (E) loop
-if Is_Formal (E) and then Is_Controlling_Formal (E) then
+if Is_Controlling_Formal (E) then
return E;
 end if;
 
-Next_Entity (E);
+Next_Formal (E);
  end loop;
 
  return Empty;
-- 
2.34.1



[COMMITTED] ada: Avoid repeated iteration over private protected components

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Piotr Trojanek 

The First_Entity/Next_Entity chain includes private entities, so there
it no need to iterate starting both from First_Entity and
First_Private_Entity.

Code cleanup related to improved detection of references to
uninitialized objects; behavior is unaffected.

gcc/ada/

* sem_util.adb
(Check_Components): Iterate using
First/Next_Component_Or_Discriminant.
(Has_Preelaborable_Initialization): Avoid repeated iteration with
calls to Check_Components with First_Entity and
First_Private_Entity.
(Is_Independent_Object_Entity): Tune indentation.

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

---
 gcc/ada/sem_util.adb | 25 +++--
 1 file changed, 11 insertions(+), 14 deletions(-)

diff --git a/gcc/ada/sem_util.adb b/gcc/ada/sem_util.adb
index 9a7640b3147..536d5fadefb 100644
--- a/gcc/ada/sem_util.adb
+++ b/gcc/ada/sem_util.adb
@@ -13679,15 +13679,12 @@ package body Sem_Util is
  Exp : Node_Id;
 
   begin
- --  Loop through entities of record or protected type
+ --  Loop through components and discriminants of record or protected
+ --  type.
 
- Ent := E;
+ Ent := First_Component_Or_Discriminant (E);
  while Present (Ent) loop
 
---  We are interested only in components and discriminants
-
-Exp := Empty;
-
 case Ekind (Ent) is
when E_Component =>
 
@@ -13698,6 +13695,8 @@ package body Sem_Util is
 
   if Present (Declaration_Node (Ent)) then
  Exp := Expression (Declaration_Node (Ent));
+  else
+ Exp := Empty;
   end if;
 
when E_Discriminant =>
@@ -13710,7 +13709,7 @@ package body Sem_Util is
   Exp := Discriminant_Default_Value (Ent);
 
when others =>
-  goto Check_Next_Entity;
+  raise Program_Error;
 end case;
 
 --  A component has PI if it has no default expression and the
@@ -13731,8 +13730,7 @@ package body Sem_Util is
exit;
 end if;
 
- <>
-Next_Entity (Ent);
+Next_Component_Or_Discriminant (Ent);
  end loop;
   end Check_Components;
 
@@ -13842,7 +13840,7 @@ package body Sem_Util is
  --  If OK, check extension components (if any)
 
  if Has_PE and then Is_Record_Type (E) then
-Check_Components (First_Entity (E));
+Check_Components (E);
  end if;
 
  --  Check specifically for 10.2.1(11.4/2) exception: a controlled type
@@ -13882,7 +13880,7 @@ package body Sem_Util is
 
   elsif Is_Record_Type (E) then
  Has_PE := True;
- Check_Components (First_Entity (E));
+ Check_Components (E);
 
   --  Protected types must not have entries, and components must meet
   --  same set of rules as for record components.
@@ -13892,8 +13890,7 @@ package body Sem_Util is
 Has_PE := False;
  else
 Has_PE := True;
-Check_Components (First_Entity (E));
-Check_Components (First_Private_Entity (E));
+Check_Components (E);
  end if;
 
   --  Type System.Address always has preelaborable initialization
@@ -18305,7 +18302,7 @@ package body Sem_Util is
Is_Object (Id)
  and then (Is_Independent (Id)
 or else
-  Is_Independent (Etype (Id)));
+   Is_Independent (Etype (Id)));
   end Is_Independent_Object_Entity;
 
   -
-- 
2.34.1



[COMMITTED] ada: Static intrinsic functions are a core language extension.

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Steve Baird 

GNAT-defined Ada extensions are divided into two categories: those that are
enabled by either -gnatX or -gnatX0 and those which require -gnatX0.
Move static intrinsic functions from the second category into the first.

gcc/ada/

* doc/gnat_rm/implementation_defined_pragmas.rst: Add the standard
'... "On" enables this extension.' sentence to the description of
static intrinsic functions.
* sem_ch13.adb
(Analyze_Aspect_Spec): In the call to Error_Msg_GNAT_Extension for
a Static aspect specification for an intrinsic function, specify
Is_Core_Extension => True.
* sem_eval.adb
(Eval_Intrinsic_Call): Test Core_Extensions_Allowed instead of
testing All_Extensions_Allowed.
* gnat_rm.texi: Regenerate.

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

---
 gcc/ada/doc/gnat_rm/implementation_defined_pragmas.rst | 2 ++
 gcc/ada/gnat_rm.texi   | 2 ++
 gcc/ada/sem_ch13.adb   | 3 ++-
 gcc/ada/sem_eval.adb   | 5 +++--
 4 files changed, 9 insertions(+), 3 deletions(-)

diff --git a/gcc/ada/doc/gnat_rm/implementation_defined_pragmas.rst 
b/gcc/ada/doc/gnat_rm/implementation_defined_pragmas.rst
index 100d79e69b1..7e5fb700691 100644
--- a/gcc/ada/doc/gnat_rm/implementation_defined_pragmas.rst
+++ b/gcc/ada/doc/gnat_rm/implementation_defined_pragmas.rst
@@ -2200,6 +2200,8 @@ are identified below.
   functions and the compiler will evaluate some of these intrinsic statically,
   in particular the ``Shift_Left`` and ``Shift_Right`` intrinsics.
 
+  An Extensions_Allowed pragma argument of "On" enables this extension.
+
 * ``[]`` aggregates
 
   This new aggregate syntax for arrays and containers is provided under -gnatX
diff --git a/gcc/ada/gnat_rm.texi b/gcc/ada/gnat_rm.texi
index 6fcaca76571..fbd8bb8d6b2 100644
--- a/gcc/ada/gnat_rm.texi
+++ b/gcc/ada/gnat_rm.texi
@@ -3639,6 +3639,8 @@ The Ada 202x @code{Static} aspect can be specified on 
Intrinsic imported
 functions and the compiler will evaluate some of these intrinsic statically,
 in particular the @code{Shift_Left} and @code{Shift_Right} intrinsics.
 
+An Extensions_Allowed pragma argument of “On” enables this extension.
+
 @item 
 @code{[]} aggregates
 
diff --git a/gcc/ada/sem_ch13.adb b/gcc/ada/sem_ch13.adb
index 6f4d33b6d55..2eb1a69e764 100644
--- a/gcc/ada/sem_ch13.adb
+++ b/gcc/ada/sem_ch13.adb
@@ -2408,7 +2408,8 @@ package body Sem_Ch13 is
 
   elsif Is_Imported_Intrinsic then
  Error_Msg_GNAT_Extension
-   ("aspect % on intrinsic function", Sloc (Aspect));
+   ("aspect % on intrinsic function", Sloc (Aspect),
+Is_Core_Extension => True);
 
   else
  Error_Msg_N
diff --git a/gcc/ada/sem_eval.adb b/gcc/ada/sem_eval.adb
index 6339cfe3b04..195f27e14d6 100644
--- a/gcc/ada/sem_eval.adb
+++ b/gcc/ada/sem_eval.adb
@@ -2856,10 +2856,11 @@ package body Sem_Eval is
  return;
   end if;
 
-  --  Intrinsic calls as part of a static function is a language extension.
+  --  Intrinsic calls as part of a static function is a (core)
+  --  language extension.
 
   if Checking_Potentially_Static_Expression
-and then not All_Extensions_Allowed
+and then not Core_Extensions_Allowed
   then
  return;
   end if;
-- 
2.34.1



[COMMITTED] ada: Fix various typos in GNAT RM

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Piotr Trojanek 

List of unknown words in files can be produced with:

  $ cat *.rst | ispell -l |
tr '[:upper:]' '[:lower:]' | sort | uniq | less

and can be easily filtered with eyes.

gcc/ada/

* doc/gnat_rm/implementation_defined_aspects.rst: Fix typos.
* doc/gnat_rm/implementation_defined_attributes.rst: Likewise
* doc/gnat_rm/implementation_defined_characteristics.rst: Likewise
* doc/gnat_rm/implementation_defined_pragmas.rst: Likewise
* doc/gnat_rm/standard_library_routines.rst: Likewise.
* gnat_rm.texi: Regenerate.

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

---
 .../implementation_defined_aspects.rst|  2 +-
 .../implementation_defined_attributes.rst |  4 ++--
 ...implementation_defined_characteristics.rst |  2 +-
 .../implementation_defined_pragmas.rst| 12 +-
 .../doc/gnat_rm/standard_library_routines.rst |  2 +-
 gcc/ada/gnat_rm.texi  | 22 +--
 6 files changed, 22 insertions(+), 22 deletions(-)

diff --git a/gcc/ada/doc/gnat_rm/implementation_defined_aspects.rst 
b/gcc/ada/doc/gnat_rm/implementation_defined_aspects.rst
index 4541f2bc70b..960c505c9ae 100644
--- a/gcc/ada/doc/gnat_rm/implementation_defined_aspects.rst
+++ b/gcc/ada/doc/gnat_rm/implementation_defined_aspects.rst
@@ -422,7 +422,7 @@ This aspect is equivalent to :ref:`attribute 
Object_Size`
 
 Aspect Obsolescent
 ==
-.. index:: Obsolsecent
+.. index:: Obsolescent
 
 This aspect is equivalent to :ref:`pragma Obsolescent`. 
Note that the
 evaluation of this aspect happens at the point of occurrence, it is not
diff --git a/gcc/ada/doc/gnat_rm/implementation_defined_attributes.rst 
b/gcc/ada/doc/gnat_rm/implementation_defined_attributes.rst
index d839b1fd2e7..22dae06cefe 100644
--- a/gcc/ada/doc/gnat_rm/implementation_defined_attributes.rst
+++ b/gcc/ada/doc/gnat_rm/implementation_defined_attributes.rst
@@ -589,7 +589,7 @@ Attribute Library_Level
 ``P'Library_Level``, where P is an entity name,
 returns a Boolean value which is True if the entity is declared
 at the library level, and False otherwise. Note that within a
-generic instantition, the name of the generic unit denotes the
+generic instantiation, the name of the generic unit denotes the
 instance, which means that this attribute can be used to test
 if a generic is instantiated at the library level, as shown
 in this example:
@@ -1231,7 +1231,7 @@ Attribute System_Allocator_Alignment
 .. index:: System_Allocator_Alignment
 
 ``Standard'System_Allocator_Alignment`` (``Standard`` is the only
-allowed prefix) provides the observable guaranted to be honored by
+allowed prefix) provides the observable guaranteed to be honored by
 the system allocator (malloc). This is a static value that can be used
 in user storage pools based on malloc either to reject allocation
 with alignment too large or to enable a realignment circuitry if the
diff --git a/gcc/ada/doc/gnat_rm/implementation_defined_characteristics.rst 
b/gcc/ada/doc/gnat_rm/implementation_defined_characteristics.rst
index 095d04b5a26..fb6a63ced2c 100644
--- a/gcc/ada/doc/gnat_rm/implementation_defined_characteristics.rst
+++ b/gcc/ada/doc/gnat_rm/implementation_defined_characteristics.rst
@@ -1215,7 +1215,7 @@ a distributed application.
 *
   "The range of type System.RPC.Partition_Id.  See E.5(14)."
 
-System.RPC.Partion_ID'Last is Integer'Last. See source file :file:`s-rpc.ads`.
+System.RPC.Partition_ID'Last is Integer'Last. See source file 
:file:`s-rpc.ads`.
 
 *
   "Implementation-defined interfaces in the PCS.  See E.5(26)."
diff --git a/gcc/ada/doc/gnat_rm/implementation_defined_pragmas.rst 
b/gcc/ada/doc/gnat_rm/implementation_defined_pragmas.rst
index 1f371a50168..100d79e69b1 100644
--- a/gcc/ada/doc/gnat_rm/implementation_defined_pragmas.rst
+++ b/gcc/ada/doc/gnat_rm/implementation_defined_pragmas.rst
@@ -1389,7 +1389,7 @@ Pragma CPP_Virtual
 This pragma is now obsolete and, other than generating a warning if warnings
 on obsolescent features are enabled, is completely ignored.
 It is retained for compatibility
-purposes. It used to be required to ensure compoatibility with C++, but
+purposes. It used to be required to ensure compatibility with C++, but
 is no longer required for that purpose because GNAT generates
 the same object layout as the G++ compiler by default.
 
@@ -3870,7 +3870,7 @@ decrease or increase in successive iterations of the 
loop. In its simplest
 form, just one expression is specified, whose value must increase or decrease
 on each iteration of the loop.
 
-In a more complex form, multiple arguments can be given which are intepreted
+In a more complex form, multiple arguments can be given which are interpreted
 in a nesting lexicographic manner. For example:
 
 .. code-block:: ada
@@ -4951,7 +4951,7 @@ appear at the start of the declarations in a subprogram 
body
 Note: This pragma is called ``Post_Class`` rather than
 ``Post'Class`` because 

[COMMITTED] ada: Skip dynamic interface conversion under configurable runtime

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Javier Miranda 

gcc/ada/

* exp_disp.adb
(Expand_Interface_Conversion): Fix typo in comment.

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

---
 gcc/ada/exp_disp.adb | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/gcc/ada/exp_disp.adb b/gcc/ada/exp_disp.adb
index d8a45ffb7c9..41da7a23ee5 100644
--- a/gcc/ada/exp_disp.adb
+++ b/gcc/ada/exp_disp.adb
@@ -1308,7 +1308,7 @@ package body Exp_Disp is
  --  When the target type is an interface type that is an ancestor of
  --  the operand type, it is generally safe to skip generating code to
  --  displace the pointer to the object to reference the secondary
- --  dispatch table of the target interface type. Two scenaries are
+ --  dispatch table of the target interface type. Two scenarios are
  --  possible here:
  --1) The operand type is a regular tagged type
  --2) The operand type is an interface type
-- 
2.34.1



[COMMITTED] ada: Cleanup clearing flags on package variables

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Piotr Trojanek 

When killing flags on assignable entities we iterated from First_Entity
and then again from First_Private_Entity. This second iteration was
unnecessary, because the entity chain that starts with First_Entity
contains all entities, including the private ones.

This is just a performance improvement; the behavior is unchanged.

gcc/ada/

* sem_ch7.adb (Clear_Constants): Only iterate from First_Entity
through Next_Entity; only examine variables because packages have
no assignable formal parameters.

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

---
 gcc/ada/sem_ch7.adb | 21 +
 1 file changed, 9 insertions(+), 12 deletions(-)

diff --git a/gcc/ada/sem_ch7.adb b/gcc/ada/sem_ch7.adb
index 5c347bd8b4f..77d1b38b827 100644
--- a/gcc/ada/sem_ch7.adb
+++ b/gcc/ada/sem_ch7.adb
@@ -1317,11 +1317,10 @@ package body Sem_Ch7 is
   --  private_with_clauses, and remove them at the end of the nested
   --  package.
 
-  procedure Clear_Constants (Id : Entity_Id; FE : Entity_Id);
-  --  Clears constant indications (Never_Set_In_Source, Constant_Value, and
-  --  Is_True_Constant) on all variables that are entities of Id, and on
-  --  the chain whose first element is FE. A recursive call is made for all
-  --  packages and generic packages.
+  procedure Clear_Constants (Id : Entity_Id);
+  --  Clears constant indications (Never_Set_In_Source, Constant_Value,
+  --  and Is_True_Constant) on all variables that are entities of Id.
+  --  A recursive call is made for all packages and generic packages.
 
   procedure Generate_Parent_References;
   --  For a child unit, generate references to parent units, for
@@ -1352,7 +1351,7 @@ package body Sem_Ch7 is
   -- Clear_Constants --
   -
 
-  procedure Clear_Constants (Id : Entity_Id; FE : Entity_Id) is
+  procedure Clear_Constants (Id : Entity_Id) is
  E : Entity_Id;
 
   begin
@@ -1368,9 +1367,9 @@ package body Sem_Ch7 is
  --  package can contain a renaming declaration to itself, and such
  --  renamings are generated automatically within package instances.
 
- E := FE;
+ E := First_Entity (Id);
  while Present (E) and then E /= Id loop
-if Is_Assignable (E) then
+if Ekind (E) = E_Variable then
Set_Never_Set_In_Source (E, False);
Set_Is_True_Constant(E, False);
Set_Current_Value   (E, Empty);
@@ -1382,8 +1381,7 @@ package body Sem_Ch7 is
end if;
 
 elsif Is_Package_Or_Generic_Package (E) then
-   Clear_Constants (E, First_Entity (E));
-   Clear_Constants (E, First_Private_Entity (E));
+   Clear_Constants (E);
 end if;
 
 Next_Entity (E);
@@ -2009,8 +2007,7 @@ package body Sem_Ch7 is
   if Is_Library_Level_Entity (Id)
 or else Is_Generic_Instance (Id)
   then
- Clear_Constants (Id, First_Entity (Id));
- Clear_Constants (Id, First_Private_Entity (Id));
+ Clear_Constants (Id);
   end if;
 
   --  Output relevant information as to why the package requires a body.
-- 
2.34.1



[COMMITTED] ada: Remove redundant calls in handling of aspect specifications

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Piotr Trojanek 

Routine Set_Aspect_Specifications sets the Has_Aspect flag, so there is
no need to set this flag again afterwards.

Code cleanup; semantics is unaffected.

gcc/ada/

* aspects.adb (Relocate_Aspect): Remove call to Set_Has_Aspects.
* sem_ch12.adb (Analyze_Formal_Package_Declaration): Likewise.
* sem_util.adb (Copy_Ghost_Aspect, Copy_SPARK_Mode_Aspect):
Likewise.

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

---
 gcc/ada/aspects.adb  | 1 -
 gcc/ada/sem_ch12.adb | 1 -
 gcc/ada/sem_util.adb | 2 --
 3 files changed, 4 deletions(-)

diff --git a/gcc/ada/aspects.adb b/gcc/ada/aspects.adb
index 3471a81f176..81c9c284048 100644
--- a/gcc/ada/aspects.adb
+++ b/gcc/ada/aspects.adb
@@ -373,7 +373,6 @@ package body Aspects is
  else
 Asps := New_List;
 Set_Aspect_Specifications (To, Asps);
-Set_Has_Aspects (To);
  end if;
 
  --  Remove the aspect from its original owner and relocate it to node
diff --git a/gcc/ada/sem_ch12.adb b/gcc/ada/sem_ch12.adb
index 6781e5ee5b6..0b7b7c904d3 100644
--- a/gcc/ada/sem_ch12.adb
+++ b/gcc/ada/sem_ch12.adb
@@ -3121,7 +3121,6 @@ package body Sem_Ch12 is
   if Present (Aspect_Specifications (Gen_Decl)) then
  if No (Aspect_Specifications (N)) then
 Set_Aspect_Specifications (N, New_List);
-Set_Has_Aspects (N);
  end if;
 
  declare
diff --git a/gcc/ada/sem_util.adb b/gcc/ada/sem_util.adb
index 536d5fadefb..80d07eb0023 100644
--- a/gcc/ada/sem_util.adb
+++ b/gcc/ada/sem_util.adb
@@ -7049,7 +7049,6 @@ package body Sem_Util is
 
  if Present (Asp) then
 Set_Aspect_Specifications (To, New_List (New_Copy_Tree (Asp)));
-Set_Has_Aspects (To, True);
  end if;
   end if;
end Copy_Ghost_Aspect;
@@ -7101,7 +7100,6 @@ package body Sem_Util is
 
  if Present (Asp) then
 Set_Aspect_Specifications (To, New_List (New_Copy_Tree (Asp)));
-Set_Has_Aspects (To, True);
  end if;
   end if;
end Copy_SPARK_Mode_Aspect;
-- 
2.34.1



[COMMITTED] ada: Improve efficiency of scope stack restoration

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Piotr Trojanek 

We save/restore visibility by setting the Is_Immediately_Visible flag
and appending entities to / removing them from the tail of an element
list.

However, the Is_Immediately_Visible flag can be restored in any order,
while the element list is singly-linked and removal from the tail is
inefficient. This change removes a performance hot spot, which accounted
for up to 10% of compilation time of complex applications (e.g. QGen),
at least as measured on GNAT built with profiling support.

gcc/ada/

* sem_ch8.adb (Restore_Scope_Stack): Remove elements from the head
and not the tail of an element list.

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

---
 gcc/ada/sem_ch8.adb | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/gcc/ada/sem_ch8.adb b/gcc/ada/sem_ch8.adb
index c4812e2a563..e555de915e6 100644
--- a/gcc/ada/sem_ch8.adb
+++ b/gcc/ada/sem_ch8.adb
@@ -9717,10 +9717,10 @@ package body Sem_Ch8 is
   --  we saved (we use Remove, since this list will not be used again).
 
   loop
- Elmt := Last_Elmt (List);
+ Elmt := First_Elmt (List);
  exit when Elmt = No_Elmt;
  Set_Is_Immediately_Visible (Node (Elmt));
- Remove_Last_Elmt (List);
+ Remove_Elmt (List, Elmt);
   end loop;
 
   --  Restore use clauses
-- 
2.34.1



[COMMITTED] ada: Skip dynamic interface conversion under configurable runtime

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Javier Miranda 

gcc/ada/

* exp_disp.adb
(Expand_Interface_Conversion): Under configurable runtime, when
the target type is an interface that is an ancestor of the operand
type, skip generating code to displace the pointer to reference
the target dispatch table.
* sem_disp.adb
(Propagate_Tag): Handle class-wide types when checking for the
addition of an implicit interface conversion.

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

---
 gcc/ada/exp_disp.adb | 32 +---
 gcc/ada/sem_disp.adb | 15 ---
 2 files changed, 33 insertions(+), 14 deletions(-)

diff --git a/gcc/ada/exp_disp.adb b/gcc/ada/exp_disp.adb
index 43ae2e0f34d..d8a45ffb7c9 100644
--- a/gcc/ada/exp_disp.adb
+++ b/gcc/ada/exp_disp.adb
@@ -1304,17 +1304,24 @@ package body Exp_Disp is
and then Is_Ancestor (Iface_Typ, Opnd, Use_Full_View => True)
  then
 return;
- end if;
 
- --  When the type of the operand and the target interface type match,
- --  it is generally safe to skip generating code to displace the
- --  pointer to the object to reference the secondary dispatch table
- --  associated with the target interface type. The exception to this
- --  general rule is when the underlying object of the type conversion
- --  is an object built by means of a dispatching constructor (since in
- --  such case the expansion of the constructor call is a direct call
- --  to an object primitive, i.e. without thunks, and the expansion of
- --  the constructor call adds an explicit conversion to the target
+ --  When the target type is an interface type that is an ancestor of
+ --  the operand type, it is generally safe to skip generating code to
+ --  displace the pointer to the object to reference the secondary
+ --  dispatch table of the target interface type. Two scenaries are
+ --  possible here:
+ --1) The operand type is a regular tagged type
+ --2) The operand type is an interface type
+ --  In the former case the target interface and the regular tagged
+ --  type share the primary dispatch table of the object; in the latter
+ --  case the operand interface has all the primitives of the ancestor
+ --  interface type (and exactly in the same dispatch table slots).
+ --
+ --  The exception to this general rule is when the underlying object
+ --  is built by means of a dispatching constructor (since in such case
+ --  the expansion of the constructor call is a direct call to an
+ --  object primitive, i.e. without thunks, and the expansion of
+ --  the constructor call adds this explicit conversion to the target
  --  interface type to force the displacement of the pointer to the
  --  object to reference the corresponding secondary dispatch table
  --  (cf. Make_DT and Expand_Dispatching_Constructor_Call)).
@@ -1326,7 +1333,10 @@ package body Exp_Disp is
  --  to the object, because generic dispatching constructors are not
  --  supported.
 
- if Opnd = Iface_Typ and then not RTE_Available (RE_Displace) then
+ elsif Is_Interface (Iface_Typ)
+   and then Is_Ancestor (Iface_Typ, Opnd, Use_Full_View => True)
+   and then not RTE_Available (RE_Displace)
+ then
 return;
  end if;
   end;
diff --git a/gcc/ada/sem_disp.adb b/gcc/ada/sem_disp.adb
index ee1d96ec389..af260136bc0 100644
--- a/gcc/ada/sem_disp.adb
+++ b/gcc/ada/sem_disp.adb
@@ -3072,18 +3072,27 @@ package body Sem_Disp is
 
   if Tagged_Type_Expansion then
  declare
-Call_Typ : constant Entity_Id := Etype (Call_Node);
+Call_Typ : Entity_Id := Etype (Call_Node);
+Ctrl_Typ : Entity_Id := Etype (Control);
 
  begin
 Expand_Dispatching_Call (Call_Node);
 
+if Is_Class_Wide_Type (Call_Typ) then
+   Call_Typ := Root_Type (Call_Typ);
+end if;
+
+if Is_Class_Wide_Type (Ctrl_Typ) then
+   Ctrl_Typ := Root_Type (Ctrl_Typ);
+end if;
+
 --  If the controlling argument is an interface type and the type
 --  of Call_Node differs then we must add an implicit conversion to
 --  force displacement of the pointer to the object to reference
 --  the secondary dispatch table of the interface.
 
-if Is_Interface (Etype (Control))
-  and then Etype (Control) /= Call_Typ
+if Is_Interface (Ctrl_Typ)
+  and then Ctrl_Typ /= Call_Typ
 then
--  Cannot use Convert_To because the previous call to
--  Expand_Dispatching_Call leaves decorated the Call_Node
-- 
2.34.1



[COMMITTED] ada: Fix typo

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Ronan Desplanques 

Fix typo in documentation.

gcc/ada/

* doc/gnat_rm/standard_library_routines.rst: Fix typo.
* gnat_rm.texi: Regenerate.

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

---
 gcc/ada/doc/gnat_rm/standard_library_routines.rst | 2 +-
 gcc/ada/gnat_rm.texi  | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/gcc/ada/doc/gnat_rm/standard_library_routines.rst 
b/gcc/ada/doc/gnat_rm/standard_library_routines.rst
index f9749e07e4f..27659a40463 100644
--- a/gcc/ada/doc/gnat_rm/standard_library_routines.rst
+++ b/gcc/ada/doc/gnat_rm/standard_library_routines.rst
@@ -157,7 +157,7 @@ the unit is not implemented.
 
 ``Ada.Directories.Hierarchical_File_Names`` *(A.16.1)*
   This package provides additional directory operations handling
-  hiearchical file names.
+  hierarchical file names.
 
 
 ``Ada.Directories.Information`` *(A.16)*
diff --git a/gcc/ada/gnat_rm.texi b/gcc/ada/gnat_rm.texi
index ad6a8adbde4..6fcaca76571 100644
--- a/gcc/ada/gnat_rm.texi
+++ b/gcc/ada/gnat_rm.texi
@@ -20877,7 +20877,7 @@ This package provides operations on directories.
 @item @code{Ada.Directories.Hierarchical_File_Names} `(A.16.1)'
 
 This package provides additional directory operations handling
-hiearchical file names.
+hierarchical file names.
 
 @item @code{Ada.Directories.Information} `(A.16)'
 
-- 
2.34.1



[COMMITTED] ada: Fix loop unnesting issue.

2022-11-04 Thread Marc Poulhiès via Gcc-patches
During loop unnesting, when the loop statements are wrapped in a code
block, the newly created block's scope must be set to the loop
scope (instead of the previous 'Current_Scope' that would point to an
upper scope).

gcc/ada/

* sem_util.ads (Add_Block_Identifier): Add new extra Scope
argument.
* sem_util.adb (Add_Block_Identifier): Likewise and use this scope
variable instead of Current_Scope.
* exp_util.adb (Wrap_Statements_In_Block): Add new scope argument
to Add_Block_Identifier call.

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

---
 gcc/ada/exp_util.adb |  2 +-
 gcc/ada/sem_util.adb |  8 ++--
 gcc/ada/sem_util.ads | 14 +-
 3 files changed, 16 insertions(+), 8 deletions(-)

diff --git a/gcc/ada/exp_util.adb b/gcc/ada/exp_util.adb
index 6c87debe456..35667028df1 100644
--- a/gcc/ada/exp_util.adb
+++ b/gcc/ada/exp_util.adb
@@ -11367,7 +11367,7 @@ package body Exp_Util is
  --  Create a label for the block in case the block needs to manage the
  --  secondary stack. A label allows for flag Uses_Sec_Stack to be set.
 
- Add_Block_Identifier (Block_Nod, Block_Id);
+ Add_Block_Identifier (Block_Nod, Block_Id, Scop);
 
  --  When wrapping the statements of an iterator loop, check whether
  --  the loop requires secondary stack management and if so, propagate
diff --git a/gcc/ada/sem_util.adb b/gcc/ada/sem_util.adb
index 28396a4c34b..9a7640b3147 100644
--- a/gcc/ada/sem_util.adb
+++ b/gcc/ada/sem_util.adb
@@ -1044,7 +1044,11 @@ package body Sem_Util is
-- Add_Block_Identifier --
--
 
-   procedure Add_Block_Identifier (N : Node_Id; Id : out Entity_Id) is
+   procedure Add_Block_Identifier
+   (N : Node_Id;
+Id : out Entity_Id;
+Scope : Entity_Id := Current_Scope)
+   is
   Loc : constant Source_Ptr := Sloc (N);
begin
   pragma Assert (Nkind (N) = N_Block_Statement);
@@ -1057,7 +1061,7 @@ package body Sem_Util is
   --  Create a new block label and set its attributes
 
   else
- Id := New_Internal_Entity (E_Block, Current_Scope, Loc, 'B');
+ Id := New_Internal_Entity (E_Block, Scope, Loc, 'B');
  Set_Etype  (Id, Standard_Void_Type);
  Set_Parent (Id, N);
 
diff --git a/gcc/ada/sem_util.ads b/gcc/ada/sem_util.ads
index c23d358e2fb..88bfbfc2086 100644
--- a/gcc/ada/sem_util.ads
+++ b/gcc/ada/sem_util.ads
@@ -88,11 +88,6 @@ package Sem_Util is
--  Add A to the list of access types to process when expanding the
--  freeze node of E.
 
-   procedure Add_Block_Identifier (N : Node_Id; Id : out Entity_Id);
-   --  Given a block statement N, generate an internal E_Block label and make
-   --  it the identifier of the block. Id denotes the generated entity. If the
-   --  block already has an identifier, Id returns the entity of its label.
-
procedure Add_Global_Declaration (N : Node_Id);
--  These procedures adds a declaration N at the library level, to be
--  elaborated before any other code in the unit. It is used for example
@@ -678,6 +673,15 @@ package Sem_Util is
function Current_Scope return Entity_Id;
--  Get entity representing current scope
 
+   procedure Add_Block_Identifier
+   (N : Node_Id;
+Id : out Entity_Id;
+Scope : Entity_Id := Current_Scope);
+   --  Given a block statement N, generate an internal E_Block label and make
+   --  it the identifier of the block. Scope denotes the scope in which the
+   --  generated entity Id is created and defaults to the current scope. If the
+   --  block already has an identifier, Id returns the entity of its label.
+
function Current_Scope_No_Loops return Entity_Id;
--  Return the current scope ignoring internally generated loops
 
-- 
2.34.1



[COMMITTED] ada: Small editorial changes to documentation comments

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Ronan Desplanques 

gcc/ada/

* sinfo.ads: Small editorial changes.

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

---
 gcc/ada/sinfo.ads | 8 
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/gcc/ada/sinfo.ads b/gcc/ada/sinfo.ads
index 53880c5dfce..abea84c2533 100644
--- a/gcc/ada/sinfo.ads
+++ b/gcc/ada/sinfo.ads
@@ -440,7 +440,7 @@ package Sinfo is
--  documents the restriction.
 
--  Note that most of these restrictions apply only to trees generated when
-   --  code is being generated, since they involved expander actions that
+   --  code is being generated, since they involve expander actions that
--  destroy the tree.
 

@@ -528,7 +528,7 @@ package Sinfo is
--  function.
--
--  If the mode of a Ghost region is Ignore, any newly created nodes as well
-   --  as source entities are marked as ignored Ghost. In additon, the marking
+   --  as source entities are marked as ignored Ghost. In addition, the marking
--  process signals all enclosing scopes that an ignored Ghost node resides
--  within. The compilation unit where the node resides is also added to an
--  auxiliary table for post processing.
@@ -715,9 +715,9 @@ package Sinfo is
--This flag is set if the node comes directly from an explicit construct
--in the source. It is normally on for any nodes built by the scanner or
--parser from the source program, with the exception that in a few cases
-   --the parser adds nodes to normalize the representation (in particular
+   --the parser adds nodes to normalize the representation (in particular,
--a null statement is added to a package body if there is no begin/end
-   --initialization section.
+   --initialization section).
--
--Most nodes inserted by the analyzer or expander are not considered
--as coming from source, so the flag is off for such nodes. In a few
-- 
2.34.1



[COMMITTED] ada: Refactor: replace uses of `not Present(X)` with `No (X)`

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Ghjuvan Lacambre 

`No (X)` is essentially `not Present (X)`, there's no reason for not
using this shorter form.

gcc/ada/

* checks.adb, exp_atag.adb, exp_attr.adb, exp_ch4.adb, exp_ch6.adb,
exp_ch7.adb, exp_dbug.adb, exp_disp.adb, exp_unst.adb, exp_util.adb,
freeze.adb, layout.adb, pprint.adb, rtsfind.adb, sem_aggr.adb,
sem_attr.adb, sem_case.adb, sem_ch12.adb, sem_ch13.adb, sem_ch3.adb,
sem_ch5.adb, sem_ch6.adb, sem_ch8.adb, sem_dim.adb, sem_prag.adb,
sem_util.adb, sem_warn.adb:
Replace uses of `not Present (X)` with `No (X)`.

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

---
 gcc/ada/checks.adb   |  4 ++--
 gcc/ada/exp_atag.adb |  2 +-
 gcc/ada/exp_attr.adb |  2 +-
 gcc/ada/exp_ch4.adb  |  4 ++--
 gcc/ada/exp_ch6.adb  |  4 ++--
 gcc/ada/exp_ch7.adb  |  2 +-
 gcc/ada/exp_dbug.adb |  2 +-
 gcc/ada/exp_disp.adb | 16 +++-
 gcc/ada/exp_unst.adb |  2 +-
 gcc/ada/exp_util.adb |  8 
 gcc/ada/freeze.adb   | 12 ++--
 gcc/ada/layout.adb   |  2 +-
 gcc/ada/pprint.adb   |  4 ++--
 gcc/ada/rtsfind.adb  |  4 ++--
 gcc/ada/sem_aggr.adb |  4 ++--
 gcc/ada/sem_attr.adb |  2 +-
 gcc/ada/sem_case.adb |  2 +-
 gcc/ada/sem_ch12.adb |  2 +-
 gcc/ada/sem_ch13.adb | 14 +++---
 gcc/ada/sem_ch3.adb  |  8 
 gcc/ada/sem_ch5.adb  |  3 +--
 gcc/ada/sem_ch6.adb  | 16 
 gcc/ada/sem_ch8.adb  |  8 
 gcc/ada/sem_dim.adb  |  2 +-
 gcc/ada/sem_prag.adb |  4 ++--
 gcc/ada/sem_util.adb | 16 
 gcc/ada/sem_warn.adb |  2 +-
 27 files changed, 74 insertions(+), 77 deletions(-)

diff --git a/gcc/ada/checks.adb b/gcc/ada/checks.adb
index 8fa16b802de..47412948b78 100644
--- a/gcc/ada/checks.adb
+++ b/gcc/ada/checks.adb
@@ -593,7 +593,7 @@ package body Checks is
   pragma Assert (not No_Dynamic_Accessibility_Checks_Enabled (N));
 
   if Ada_Version >= Ada_2012
- and then not Present (Param_Ent)
+ and then No (Param_Ent)
  and then Is_Entity_Name (N)
  and then Ekind (Entity (N)) in E_Constant | E_Variable
  and then Present (Effective_Extra_Accessibility (Entity (N)))
@@ -778,7 +778,7 @@ package body Checks is
  --  Note: Expr is empty if the address-clause is applied to in-mode
  --  actuals (allowed by 13.1(22)).
 
- if not Present (Expr)
+ if No (Expr)
or else
  (Is_Entity_Name (Expression (AC))
and then Ekind (Entity (Expression (AC))) = E_Constant
diff --git a/gcc/ada/exp_atag.adb b/gcc/ada/exp_atag.adb
index 787136346c6..074ab4e9093 100644
--- a/gcc/ada/exp_atag.adb
+++ b/gcc/ada/exp_atag.adb
@@ -312,7 +312,7 @@ package body Exp_Atag is
 
  if not Is_Predefined_Dispatching_Operation (Prim)
and then not Is_Predefined_Dispatching_Operation (E)
-   and then not Present (Interface_Alias (Prim))
+   and then No (Interface_Alias (Prim))
and then not Is_Abstract_Subprogram (E)
and then not Is_Eliminated (E)
and then Prim_Pos <= CPP_Nb_Prims
diff --git a/gcc/ada/exp_attr.adb b/gcc/ada/exp_attr.adb
index 0e79b5d10cd..3c3f725cf27 100644
--- a/gcc/ada/exp_attr.adb
+++ b/gcc/ada/exp_attr.adb
@@ -6575,7 +6575,7 @@ package body Exp_Attr is
--  If Storage_Size wasn't found (can only occur in the simple
--  storage pool case), then simply use zero for the result.
 
-   if not Present (Alloc_Op) then
+   if No (Alloc_Op) then
   Rewrite (N, Make_Integer_Literal (Loc, 0));
 
--  Otherwise, rewrite the allocator as a call to pool type's
diff --git a/gcc/ada/exp_ch4.adb b/gcc/ada/exp_ch4.adb
index 0b7e3911c6a..7a3a414ca0d 100644
--- a/gcc/ada/exp_ch4.adb
+++ b/gcc/ada/exp_ch4.adb
@@ -6733,7 +6733,7 @@ package body Exp_Ch4 is
 --  Skip this for predicated types, where such expressions are a
 --  reasonable way of testing if something meets the predicate.
 
-and then not Present (Predicate_Function (Ltyp))
+and then No (Predicate_Function (Ltyp))
   then
  Substitute_Valid_Check;
  return;
@@ -7148,7 +7148,7 @@ package body Exp_Ch4 is
   if Is_Entity_Name (Lop) then
  Expr_Entity := Param_Entity (Lop);
 
- if not Present (Expr_Entity) then
+ if No (Expr_Entity) then
 Expr_Entity := Entity (Lop);
  end if;
   end if;
diff --git a/gcc/ada/exp_ch6.adb b/gcc/ada/exp_ch6.adb
index ce1a7525fa2..cf64e82bc99 100644
--- a/gcc/ada/exp_ch6.adb
+++ b/gcc/ada/exp_ch6.adb
@@ -376,7 +376,7 @@ package body Exp_Ch6 is
 
   --  If no return object is provided, then pass null
 
-  if not Present (Return_Object) then
+  if No (Return_Object) then
  Obj_Address := Make_Null (Loc);
  Set_Parent (Obj_Address, Function_Call);
 
@@ -3223,7 +3223,7 @@ 

[COMMITTED] ada: Fix various typos in node and entity description comments

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Piotr Trojanek 

Fix typos in units that describe GNAT abstract syntax tree.

gcc/ada/

* einfo.ads: Fix typos in comments; refill as necessary.
* sinfo.ads: Likewise.

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

---
 gcc/ada/einfo.ads | 13 +++--
 gcc/ada/sinfo.ads | 13 +++--
 2 files changed, 14 insertions(+), 12 deletions(-)

diff --git a/gcc/ada/einfo.ads b/gcc/ada/einfo.ads
index e350f137ee7..2a1a406850e 100644
--- a/gcc/ada/einfo.ads
+++ b/gcc/ada/einfo.ads
@@ -874,7 +874,7 @@ package Einfo is
 --   are generated (subprograms, package declarations and package
 --   bodies). Defined if there are pending generic body instantiations
 --   for the corresponding entity. If this flag is set, then generation
---   of the subprogram descriptor for the corresponding enities must
+--   of the subprogram descriptor for the corresponding entities must
 --   be delayed, since the insertion of the generic body may add entries
 --   to the list of handlers.
 --
@@ -2570,7 +2570,7 @@ package Einfo is
 
 --Is_Elaboration_Checks_OK_Id
 --   Defined in elaboration targets (see terminology in Sem_Elab). Set when
---   the target appears in a region which is subject to elabled elaboration
+--   the target appears in a region which is subject to enabled elaboration
 --   checks. Such targets are allowed to generate run-time conditional ABE
 --   checks or guaranteed ABE failures.
 
@@ -3114,7 +3114,7 @@ package Einfo is
 --   Defined in all entities, set in E_Package and E_Generic_Package
 --   entities to which a pragma Preelaborate is applied, and also in
 --   all entities within such packages. Note that the fact that this
---   flag is set does not necesarily mean that no elaboration code is
+--   flag is set does not necessarily mean that no elaboration code is
 --   generated for the package.
 
 --Is_Primitive
@@ -3228,7 +3228,7 @@ package Einfo is
 --   Defined in all entities, set only for a variable or constant for
 --   which the Renamed_Object field is non-empty and for which the
 --   renaming is handled by the front end, by macro substitution of
---   a copy of the (evaluated) name tree whereever the variable is used.
+--   a copy of the (evaluated) name tree wherever the variable is used.
 
 --Is_Return_Object
 --   Defined in all object entities. True if the object is the return
@@ -3964,7 +3964,8 @@ package Einfo is
 --   Present in variable entities. Contains all references to the variable
 --   when it is subject to pragma Part_Of. If the variable is a constituent
 --   of a single protected/task type, the references are examined as they
---   must appear only within the type defintion and the corresponding body.
+--   must appear only within the type definition and the corresponding
+--   body.
 
 --Partial_DIC_Procedure (synthesized)
 --   Defined in type entities. Set for a private type and its full view
@@ -4058,7 +4059,7 @@ package Einfo is
 
 --Prev_Entity
 --   Defined in all entities. The entities of a scope are chained, and this
---   field is used as a backward pointer for this entity list - effectivly
+--   field is used as a backward pointer for this entity list - effectively
 --   making the entity chain doubly-linked.
 
 --Primitive_Operations (synthesized)
diff --git a/gcc/ada/sinfo.ads b/gcc/ada/sinfo.ads
index abea84c2533..c41b0f24742 100644
--- a/gcc/ada/sinfo.ads
+++ b/gcc/ada/sinfo.ads
@@ -629,7 +629,7 @@ package Sinfo is
--  specified by means of an aspect or a pragma.
 
--  The following entities may be subject to a SPARK mode. Entities marked
-   --  with * may possess two differente SPARK modes.
+   --  with * may possess two different SPARK modes.
 
-- E_Entry
-- E_Entry_Family
@@ -1549,7 +1549,7 @@ package Sinfo is
 
--  Is_Analyzed_Pragma
--Present in N_Pragma nodes. Set for delayed pragmas that require a two
-   --step analysis. The initial step is peformed by routine Analyze_Pragma
+   --step analysis. The initial step is performed by routine Analyze_Pragma
--and verifies the overall legality of the pragma. The second step takes
--place in the various Analyze_xxx_In_Decl_Part routines which perform
--full analysis. The flag prevents the reanalysis of a delayed pragma.
@@ -1641,8 +1641,9 @@ package Sinfo is
--  variable reference marker
--
--Set when the node appears within a context which allows the generation
-   --of run-time ABE checks. This flag detemines whether the ABE Processing
-   --phase generates conditional ABE checks and guaranteed ABE failures.
+   --of run-time ABE checks. This flag determines whether the ABE
+   --Processing phase generates conditional ABE checks and guaranteed ABE
+   --failures.
 
--  Is_Elaboration_Code
--Present in 

[COMMITTED] ada: Allow enabling a restricted set of language extensions.

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Steve Baird 

The -gnatX switch (and the related Extensions_Allowed pragma) is currently a
two-valued all-or-nothing option. Add support for enabling a curated subset
of language extensions without enabling others via the -gnatX switch
and for enabling all language extensions via the new -gnatX0 switch.
Similarly, the existing "ON" argument for the Extensions_Allowed pragma
now only enables the curated subset; the new argument "ALL" enables all
language extensions. The subset of language extensions currently includes
prefixed-view notation with an untagged prefix, fixed-low-bound array
subtypes, and casing on composite values.

gcc/ada/

* opt.ads: Replace Ada_Version_Type enumeration literal
Ada_With_Extensions with two literals, Ada_With_Core_Extensions
and Ada_With_All_Extensions. Update uses of the deleted literal.
Replace Extensions_Allowed function with two functions:
All_Extensions_Allowed and Core_Extensions_Allowed.
* errout.ads, errout.adb: Add Boolean parameter to
Error_Msg_GNAT_Extension to indicate whether the construct in
question belongs to the curated subset.
* exp_ch5.adb, par-ch4.adb, sem_case.adb, sem_ch3.adb:
* sem_ch4.adb, sem_ch5.adb, sem_ch8.adb: Replace calls to
Extensions_Allowed with calls to Core_Extensions_Allowed for
constructs that are in the curated subset.
* sem_attr.adb, sem_ch13.adb, sem_eval.adb, sem_util.adb: Replace
calls to Extensions_Allowed with calls to All_Extensions_Allowed
for constructs that are not in the curated subset.
* par-ch3.adb: Override default for new parameter in calls to
Error_Msg_GNAT_Extension for constructs in the curated subset.
* par-prag.adb: Add Boolean parameter to Check_Arg_Is_On_Or_Off to
also allow ALL. Set Opt.Ada_Version appropriately for ALL or ON
arguments.
* sem_prag.adb: Allowed ALL argument for an Extensions_Allowed
pragma. Set Opt.Ada_Version appropriately for ALL or ON arguments.
* switch-c.adb: The -gnatX switch now enables only the curated
subset of language extensions (formerly it enabled all of them);
the new -gnatX0 switch enables all of them.
* doc/gnat_ugn/building_executable_programs_with_gnat.rst:
Document new "-gnatX0" switch and update documentation for
"-gnatX" switch.
* doc/gnat_rm/implementation_defined_pragmas.rst: Document new ALL
argument for pragma Extensions_Allowed and update documentation
for the ON argument. Delete mention of Ada 2022 Reduce attribute
as an extension.
* gnat_rm.texi, gnat_ugn.texi: Regenerate.

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

---
 .../implementation_defined_pragmas.rst| 28 +++--
 ...building_executable_programs_with_gnat.rst | 23 +--
 gcc/ada/errout.adb| 40 ++-
 gcc/ada/errout.ads| 17 +---
 gcc/ada/exp_ch5.adb   |  4 +-
 gcc/ada/gnat_rm.texi  | 29 --
 gcc/ada/gnat_ugn.texi | 34 ++--
 gcc/ada/opt.ads   | 18 ++---
 gcc/ada/par-ch3.adb   |  9 +++--
 gcc/ada/par-ch4.adb   |  4 +-
 gcc/ada/par-prag.adb  | 35 +++-
 gcc/ada/sem_attr.adb  |  2 +-
 gcc/ada/sem_case.adb  |  4 +-
 gcc/ada/sem_ch13.adb  |  8 ++--
 gcc/ada/sem_ch3.adb   |  4 +-
 gcc/ada/sem_ch4.adb   | 11 ++---
 gcc/ada/sem_ch5.adb   |  6 +--
 gcc/ada/sem_ch8.adb   |  4 +-
 gcc/ada/sem_eval.adb  |  2 +-
 gcc/ada/sem_prag.adb  |  8 ++--
 gcc/ada/sem_util.adb  |  2 +-
 gcc/ada/switch-c.adb  | 15 +--
 22 files changed, 212 insertions(+), 95 deletions(-)

diff --git a/gcc/ada/doc/gnat_rm/implementation_defined_pragmas.rst 
b/gcc/ada/doc/gnat_rm/implementation_defined_pragmas.rst
index 5c26b3a55c9..1f371a50168 100644
--- a/gcc/ada/doc/gnat_rm/implementation_defined_pragmas.rst
+++ b/gcc/ada/doc/gnat_rm/implementation_defined_pragmas.rst
@@ -2174,16 +2174,19 @@ Syntax:
 
 .. code-block:: ada
 
-  pragma Extensions_Allowed (On | Off);
+  pragma Extensions_Allowed (On | Off | All);
 
 
-This configuration pragma enables or disables the implementation
-extension mode (the use of Off as a parameter cancels the effect
-of the *-gnatX* command switch).
+This configuration pragma enables (via the "On" or "All" argument) or disables
+(via the "Off" argument) the implementation extension mode; the pragma takes
+precedence over the *-gnatX* and *-gnatX0* command switches.
 
-In extension mode, the 

[COMMITTED] ada: Generate missing object decls for adainit/adafinal registration calls

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Steve Baird 

A previous change on this ticket introduced calls to CUDA_Register_Function
for adainit and adafinal, but failed to introduce declarations for the
C string variables that are initialized and then passed as actual parameters
in this call. Provide the missing declarations (and, incidentally, change
the names of the two variables).

gcc/ada/

* bindgen.adb: Introduce two new string constants for the names of
the C-String variables that are assigned the names for adainit and
adafinal. Replace string literals in Gen_CUDA_Init with references
to these constants. In Gen_CUDA_Defs, generate C-String variable
declarations where these constants are the names of the variables.

Tested on x86_64-pc-linux-gnu, committed on master.
---
 gcc/ada/bindgen.adb | 19 ++-
 1 file changed, 14 insertions(+), 5 deletions(-)

diff --git a/gcc/ada/bindgen.adb b/gcc/ada/bindgen.adb
index 1daa03dd7b8..4e89918b51d 100644
--- a/gcc/ada/bindgen.adb
+++ b/gcc/ada/bindgen.adb
@@ -114,6 +114,11 @@ package body Bindgen is
--  For CodePeer, introduce a wrapper subprogram which calls the
--  user-defined main subprogram.
 
+   --  Names for local C-String variables
+
+   Adainit_String_Obj_Name  : constant String := "Adainit_Name_C_String";
+   Adafinal_String_Obj_Name : constant String := "Adafinal_Name_C_String";
+
--  Names and link_names for CUDA device adainit/adafinal procs.
 
Device_Subp_Name_Prefix : constant String := "imported_device_";
@@ -131,9 +136,6 @@ package body Bindgen is
function Device_Ada_Init_Subp_Name return String is
  (Device_Subp_Name_Prefix & Ada_Init_Name.all);
 
-   --  Text for aspect specifications (if any) given as part of the
-   --  Adainit and Adafinal spec declarations.
-
--
-- Interface_State Pragma Table --
--
@@ -1366,6 +1368,13 @@ package body Bindgen is
   WBI ("   pragma Import (C, " & Device_Ada_Final_Subp_Name &
  ", Link_Name => """ & Device_Ada_Final_Link_Name & """);");
 
+  --  C-string declarations for adainit and adafinal
+  WBI ("   " & Adainit_String_Obj_Name
+& " : Interfaces.C.Strings.Chars_Ptr;");
+  WBI ("   " & Adafinal_String_Obj_Name
+& " : Interfaces.C.Strings.Chars_Ptr;");
+  WBI ("");
+
   WBI ("");
end Gen_CUDA_Defs;
 
@@ -1449,11 +1458,11 @@ package body Bindgen is
   --  Register device-side Adainit and Adafinal
   Gen_CUDA_Register_Function_Call
 (Kernel_Name   => Device_Ada_Init_Link_Name,
- Kernel_String => "Adainit_Name_String",
+ Kernel_String => Adainit_String_Obj_Name,
  Kernel_Proc   => Device_Ada_Init_Subp_Name);
   Gen_CUDA_Register_Function_Call
 (Kernel_Name   => Device_Ada_Final_Link_Name,
- Kernel_String => "Adafinal_Name_String",
+ Kernel_String => Adafinal_String_Obj_Name,
  Kernel_Proc   => Device_Ada_Final_Subp_Name);
 
   WBI ("  CUDA_Register_Fat_Binary_End (Fat_Binary_Handle);");
-- 
2.34.1



[COMMITTED] ada: Remove VxWorks 6 and VxWorks 653 2.x content from the UGX

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Cedric Landet 

Because they are not supported anymore.

gcc/ada/

* doc/gnat_rm/implementation_defined_pragmas.rst: Remove VxWorks
version 6.
* gnat_rm.texi, gnat_ugn.texi: Regenerate.

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

---
 gcc/ada/doc/gnat_rm/implementation_defined_pragmas.rst | 2 +-
 gcc/ada/gnat_rm.texi   | 4 ++--
 gcc/ada/gnat_ugn.texi  | 6 +++---
 3 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/gcc/ada/doc/gnat_rm/implementation_defined_pragmas.rst 
b/gcc/ada/doc/gnat_rm/implementation_defined_pragmas.rst
index 6752d48d159..5c26b3a55c9 100644
--- a/gcc/ada/doc/gnat_rm/implementation_defined_pragmas.rst
+++ b/gcc/ada/doc/gnat_rm/implementation_defined_pragmas.rst
@@ -6869,7 +6869,7 @@ Syntax:
 This pragma specifies that the specified entity, which must be
 a variable declared in a library-level package, is to be marked as
 "Thread Local Storage" (``TLS``). On systems supporting this (which
-include Windows, Solaris, GNU/Linux, and VxWorks 6), this causes each
+include Windows, Solaris, GNU/Linux, and VxWorks), this causes each
 thread (and hence each Ada task) to see a distinct copy of the variable.
 
 The variable must not have default initialization, and if there is
diff --git a/gcc/ada/gnat_rm.texi b/gcc/ada/gnat_rm.texi
index e79cdeeacfe..3b9f2cfc098 100644
--- a/gcc/ada/gnat_rm.texi
+++ b/gcc/ada/gnat_rm.texi
@@ -19,7 +19,7 @@
 
 @copying
 @quotation
-GNAT Reference Manual , Oct 04, 2022
+GNAT Reference Manual , Oct 27, 2022
 
 AdaCore
 
@@ -8407,7 +8407,7 @@ pragma Thread_Local_Storage ([Entity =>] LOCAL_NAME);
 This pragma specifies that the specified entity, which must be
 a variable declared in a library-level package, is to be marked as
 “Thread Local Storage” (@code{TLS}). On systems supporting this (which
-include Windows, Solaris, GNU/Linux, and VxWorks 6), this causes each
+include Windows, Solaris, GNU/Linux, and VxWorks), this causes each
 thread (and hence each Ada task) to see a distinct copy of the variable.
 
 The variable must not have default initialization, and if there is
diff --git a/gcc/ada/gnat_ugn.texi b/gcc/ada/gnat_ugn.texi
index 7d96dbe6aa1..25aa72bc27e 100644
--- a/gcc/ada/gnat_ugn.texi
+++ b/gcc/ada/gnat_ugn.texi
@@ -3,7 +3,7 @@
 @setfilename gnat_ugn.info
 @documentencoding UTF-8
 @ifinfo
-@*Generated by Sphinx 5.1.1.@*
+@*Generated by Sphinx 5.2.3.@*
 @end ifinfo
 @settitle GNAT User's Guide for Native Platforms
 @defindex ge
@@ -19,7 +19,7 @@
 
 @copying
 @quotation
-GNAT User's Guide for Native Platforms , Sep 26, 2022
+GNAT User's Guide for Native Platforms , Oct 27, 2022
 
 AdaCore
 
@@ -29319,8 +29319,8 @@ to permit their use in free software.
 
 @printindex ge
 
-@anchor{gnat_ugn/gnat_utility_programs switches-related-to-project-files}@w{   
   }
 @anchor{cf}@w{  }
+@anchor{gnat_ugn/gnat_utility_programs switches-related-to-project-files}@w{   
   }
 
 @c %**end of body
 @bye
-- 
2.34.1



[COMMITTED] ada: Support lock-free protected objects with pragma Initialize_Scalars

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Piotr Trojanek 

In general, protected subprograms are only eligible for a lock-free
expansion if they do not reference global assignable objects.

However, it seems reasonable to ignore references to variables in
System.Scalar_Values, which are generated when pragma Initialize_Scalars
is active. Such references appear, for example, when protected
subprogram has formal parameters of mode out.

gcc/ada/

* sem_ch9.adb (Satisfies_Lock_Free_Requirements): Ignore
references to global variables inserted due to pragma
Initialize_Scalars.

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

---
 gcc/ada/sem_ch9.adb | 9 +
 1 file changed, 9 insertions(+)

diff --git a/gcc/ada/sem_ch9.adb b/gcc/ada/sem_ch9.adb
index 5dee216256c..e43e3ae0b41 100644
--- a/gcc/ada/sem_ch9.adb
+++ b/gcc/ada/sem_ch9.adb
@@ -474,6 +474,12 @@ package body Sem_Ch9 is
  begin
 --  Prohibit references to non-constant entities
 --  outside the protected subprogram scope.
+--
+--  References to variables in System.Scalar_Values
+--  generated because of pragma Initialize_Scalars are
+--  allowed, because once those variables are
+--  initialized by the binder-generated code, they
+--  behave like constants.
 
 if Is_Assignable (Id)
   and then not
@@ -482,6 +488,9 @@ package body Sem_Ch9 is
 Scope_Within_Or_Same
   (Scope (Id),
Protected_Body_Subprogram (Sub_Id))
+  and then not
+(Is_RTU (Scope (Id), System_Scalar_Values)
+   and then not Comes_From_Source (N))
 then
if Lock_Free_Given then
   Error_Msg_NE
-- 
2.34.1



[COMMITTED] ada: Reject expanded global names in lock-free protected objects

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Piotr Trojanek 

Lock-free expansion of protected subprograms is only possible when there
are no references to global assignable objects. We only detected such
references when they appeared as direct names, but we must similarly
detect expanded names.

gcc/ada/

* sem_ch9.adb (Satisfies_Lock_Free_Requirements): Detect
references via expanded names.

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

---
 gcc/ada/sem_ch9.adb | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/gcc/ada/sem_ch9.adb b/gcc/ada/sem_ch9.adb
index f2a59017865..5dee216256c 100644
--- a/gcc/ada/sem_ch9.adb
+++ b/gcc/ada/sem_ch9.adb
@@ -463,7 +463,7 @@ package body Sem_Ch9 is
 
   --  References
 
-  elsif Kind = N_Identifier
+  elsif Kind in N_Identifier | N_Expanded_Name
 and then Present (Entity (N))
   then
  declare
@@ -564,7 +564,7 @@ package body Sem_Ch9 is
   --  reference only one component of the protected type, plus
   --  the type of the component must support atomic operation.
 
-  if Kind = N_Identifier
+  if Kind in N_Identifier | N_Expanded_Name
 and then Present (Entity (N))
   then
  declare
-- 
2.34.1



[COMMITTED] ada: Generate host-side CUDA_Register_Function calls for device's adainit/adafinal

2022-11-04 Thread Marc Poulhiès via Gcc-patches
From: Steve Baird 

To invoke a device-side subprogram from the host (via a CUDA_execute pragma),
the subprogram also has to be registered by calling CUDA_Register_Function.
The host-side adainit and adafinal procedures need to invoke the corresponding
device-side procedures, so corresponding CUDA_Register_Function calls need
to be generated.

gcc/ada/

* bindgen.adb
(Gen_CUDA_Init): Move existing loop body into a new local
procedure, Gen_CUDA_Register_Function_Call, and replace that loop
body with a call to this procedure. This first part is just
semantics-preserving refactoring. The second part is to add
Gen_CUDA_Register_Function_Call calls after the loop for the
device-side adainit and adafinal procedures.

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

---
 gcc/ada/bindgen.adb | 66 +
 1 file changed, 49 insertions(+), 17 deletions(-)

diff --git a/gcc/ada/bindgen.adb b/gcc/ada/bindgen.adb
index f2aaa2dea92..1daa03dd7b8 100644
--- a/gcc/ada/bindgen.adb
+++ b/gcc/ada/bindgen.adb
@@ -1374,6 +1374,41 @@ package body Bindgen is
---
 
procedure Gen_CUDA_Init is
+  --  Generate call to register one function
+  procedure Gen_CUDA_Register_Function_Call
+(Kernel_Name   : String;
+ Kernel_String : String;
+ Kernel_Proc   : String);
+
+  -
+  -- Gen_CUDA_Register_Function_Call --
+  -
+
+  procedure Gen_CUDA_Register_Function_Call
+(Kernel_Name   : String;
+ Kernel_String : String;
+ Kernel_Proc   : String) is
+  begin
+ WBI ("  " & Kernel_String & " :=");
+ WBI ("Interfaces.C.Strings.New_Char_Array ("""
+   & Kernel_Name
+   & """);");
+
+ --  Generate call to CUDA runtime to register function.
+ WBI ("  CUDA_Register_Function (");
+ WBI ("Fat_Binary_Handle, ");
+ WBI ("" & Kernel_Proc & "'Address,");
+ WBI ("" & Kernel_String & ",");
+ WBI ("" & Kernel_String & ",");
+ WBI ("-1,");
+ WBI ("System.Null_Address,");
+ WBI ("System.Null_Address,");
+ WBI ("System.Null_Address,");
+ WBI ("System.Null_Address,");
+ WBI ("System.Null_Address);");
+ WBI ("");
+  end Gen_CUDA_Register_Function_Call;
+
begin
   if not Enable_CUDA_Expansion then
  return;
@@ -1404,26 +1439,23 @@ package body Bindgen is
Get_Name_String (CUDA_Kernels.Table (K).Kernel_Name);
 --  Kernel_Name is the name of the kernel, after package expansion.
  begin
-WBI ("  " & Kernel_String & " :=");
-WBI ("Interfaces.C.Strings.New_Char_Array ("""
-  & Kernel_Name
-  & """);");
---  Generate call to CUDA runtime to register function.
-WBI ("  CUDA_Register_Function (");
-WBI ("Fat_Binary_Handle, ");
-WBI ("" & Kernel_Proc & "'Address,");
-WBI ("" & Kernel_String & ",");
-WBI ("" & Kernel_String & ",");
-WBI ("-1,");
-WBI ("System.Null_Address,");
-WBI ("System.Null_Address,");
-WBI ("System.Null_Address,");
-WBI ("System.Null_Address,");
-WBI ("System.Null_Address);");
-WBI ("");
+Gen_CUDA_Register_Function_Call
+  (Kernel_Name   => Kernel_Name,
+   Kernel_String => Kernel_String,
+   Kernel_Proc   => Kernel_Proc);
  end;
   end loop;
 
+  --  Register device-side Adainit and Adafinal
+  Gen_CUDA_Register_Function_Call
+(Kernel_Name   => Device_Ada_Init_Link_Name,
+ Kernel_String => "Adainit_Name_String",
+ Kernel_Proc   => Device_Ada_Init_Subp_Name);
+  Gen_CUDA_Register_Function_Call
+(Kernel_Name   => Device_Ada_Final_Link_Name,
+ Kernel_String => "Adafinal_Name_String",
+ Kernel_Proc   => Device_Ada_Final_Subp_Name);
+
   WBI ("  CUDA_Register_Fat_Binary_End (Fat_Binary_Handle);");
 
   --  perform device (as opposed to host) elaboration
-- 
2.34.1



Re: [PATCH v2] tree-object-size: Support strndup and strdup

2022-11-04 Thread Siddhesh Poyarekar

On 2022-11-04 09:43, Prathamesh Kulkarni wrote:

On Fri, 4 Nov 2022 at 18:18, Siddhesh Poyarekar  wrote:


Use string length of input to strdup to determine the usable size of the
resulting object.  Avoid doing the same for strndup since there's a
chance that the input may be too large, resulting in an unnecessary
overhead or worse, the input may not be NULL terminated, resulting in a
crash where there would otherwise have been none.

gcc/ChangeLog:

 * tree-object-size.cc (todo): New variable.
 (object_sizes_execute): Use it.
 (strdup_object_size): New function.
 (call_object_size): Use it.

gcc/testsuite/ChangeLog:

 * gcc.dg/builtin-dynamic-object-size-0.c (test_strdup,
 test_strndup, test_strdup_min, test_strndup_min): New tests.
 (main): Call them.
 * gcc.dg/builtin-dynamic-object-size-1.c: Silence overread
 warnings.
 * gcc.dg/builtin-dynamic-object-size-2.c: Likewise.
 * gcc.dg/builtin-dynamic-object-size-3.c: Likewise.
 * gcc.dg/builtin-dynamic-object-size-4.c: Likewise.
 * gcc.dg/builtin-object-size-1.c: Silence overread warnings.
 Declare free, strdup and strndup.
 (test11): New test.
 (main): Call it.
 * gcc.dg/builtin-object-size-2.c: Silence overread warnings.
 Declare free, strdup and strndup.
 (test9): New test.
 (main): Call it.
 * gcc.dg/builtin-object-size-3.c: Silence overread warnings.
 Declare free, strdup and strndup.
 (test11): New test.
 (main): Call it.
 * gcc.dg/builtin-object-size-4.c: Silence overread warnings.
 Declare free, strdup and strndup.
 (test9): New test.
 (main): Call it.
---
Tested:

- x86_64 bootstrap and testsuite run
- i686 build and testsuite run
- ubsan bootstrap

  .../gcc.dg/builtin-dynamic-object-size-0.c| 43 +
  .../gcc.dg/builtin-dynamic-object-size-1.c|  2 +-
  .../gcc.dg/builtin-dynamic-object-size-2.c|  2 +-
  .../gcc.dg/builtin-dynamic-object-size-3.c|  2 +-
  .../gcc.dg/builtin-dynamic-object-size-4.c|  2 +-
  gcc/testsuite/gcc.dg/builtin-object-size-1.c  | 94 +-
  gcc/testsuite/gcc.dg/builtin-object-size-2.c  | 94 +-
  gcc/testsuite/gcc.dg/builtin-object-size-3.c  | 95 ++-
  gcc/testsuite/gcc.dg/builtin-object-size-4.c  | 94 +-
  gcc/tree-object-size.cc   | 84 +++-
  10 files changed, 502 insertions(+), 10 deletions(-)

diff --git a/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-0.c 
b/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-0.c
index 01a280b2d7b..4f1606a486b 100644
--- a/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-0.c
+++ b/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-0.c
@@ -479,6 +479,40 @@ test_loop (int *obj, size_t sz, size_t start, size_t end, 
int incr)
return __builtin_dynamic_object_size (ptr, 0);
  }

+/* strdup/strndup.  */
+
+size_t
+__attribute__ ((noinline))
+test_strdup (const char *in)
+{
+  char *res = __builtin_strdup (in);
+  return __builtin_dynamic_object_size (res, 0);
+}
+
+size_t
+__attribute__ ((noinline))
+test_strndup (const char *in, size_t bound)
+{
+  char *res = __builtin_strndup (in, bound);
+  return __builtin_dynamic_object_size (res, 0);
+}
+
+size_t
+__attribute__ ((noinline))
+test_strdup_min (const char *in)
+{
+  char *res = __builtin_strdup (in);
+  return __builtin_dynamic_object_size (res, 2);
+}
+
+size_t
+__attribute__ ((noinline))
+test_strndup_min (const char *in, size_t bound)
+{
+  char *res = __builtin_strndup (in, bound);
+  return __builtin_dynamic_object_size (res, 2);
+}
+
  /* Other tests.  */

  struct TV4
@@ -651,6 +685,15 @@ main (int argc, char **argv)
int *t = test_pr105736 ();
if (__builtin_dynamic_object_size (t, 0) != -1)
  FAIL ();
+  const char *str = "hello world";
+  if (test_strdup (str) != __builtin_strlen (str) + 1)
+FAIL ();
+  if (test_strndup (str, 4) != 5)
+FAIL ();
+  if (test_strdup_min (str) != __builtin_strlen (str) + 1)
+FAIL ();
+  if (test_strndup_min (str, 4) != 1)
+FAIL ();

if (nfails > 0)
  __builtin_abort ();
diff --git a/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-1.c 
b/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-1.c
index 7cc8b1c9488..8f17c8edcaf 100644
--- a/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-1.c
+++ b/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-1.c
@@ -1,5 +1,5 @@
  /* { dg-do run } */
-/* { dg-options "-O2" } */
+/* { dg-options "-O2 -Wno-stringop-overread" } */
  /* { dg-require-effective-target alloca } */

  #define __builtin_object_size __builtin_dynamic_object_size
diff --git a/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-2.c 
b/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-2.c
index 267dbf48ca7..3677782ff1c 100644
--- a/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-2.c
+++ 

[PATCH 6/6] diagnostics: libcpp: Assign real locations to the tokens inside _Pragma strings

2022-11-04 Thread Lewis Hyatt via Gcc-patches
Currently, the tokens obtained from a destringified _Pragma string do not get
assigned proper locations while they are being lexed.  After the tokens have
been obtained, they are reassigned the same location as the _Pragma token,
which is sufficient to make things like _Pragma("GCC diagnostic ignored...")
operate correctly, but this still results in inferior diagnostics, since the
diagnostics do not point to the problematic tokens.  Further, if a diagnostic
is issued by libcpp during the lexing of the tokens, as opposed to being
issued by the frontend during the processing of the pragma, then the
patched-up location is not yet in place, and the user rather sees an invalid
location that is near to the location of the _Pragma string in some cases, or
potentially very far away, depending on the macro expansion history.  For
example:

=
_Pragma("GCC diagnostic ignored \"oops")
=

produces the diagnostic:

file.cpp:1:24: warning: missing terminating " character
1 | _Pragma("GCC diagnostic ignored \"oops")
  |^

with the caret in a nonsensical location, while this one:

=
 #define S "GCC diagnostic ignored \"oops"
_Pragma(S)
=

produces:

file.cpp:2:24: warning: missing terminating " character
2 | _Pragma(S)
  |^

with both the caret in a nonsensical location, and the actual relevant context
completely absent.

Fix this by assigning proper locations using the new LC_GEN type of linemap.
Now the tokens are given locations inside a generated content buffer, and the
macro expansion stack is modified to be aware that these tokens logically
belong to the "expansion" of the _Pragma directive. For the above examples we
now output:

==
In buffer generated from file.cpp:1:
:1:24: warning: missing terminating " character
1 | GCC diagnostic ignored "oops
  |^
file.cpp:1:1: note: in <_Pragma directive>
1 | _Pragma("GCC diagnostic ignored \"oops")
  | ^~~
==

and

==
:1:24: warning: missing terminating " character
1 | GCC diagnostic ignored "oops
  |^
file.cpp:2:1: note: in <_Pragma directive>
2 | _Pragma(S)
  | ^~~
==

So that carets are pointing to something meaningful and all relevant context
appears in the diagnostic.  For the second example, it would be nice if the
macro expansion also output "in expansion of macro S", however doing that for
a general case of macro expansions makes the logic very complicated, since it
has to be done after the fact when the macro maps have already been
constructed.  It doesn't seem worth it for this case, given that the _Pragma
string has already been output once on the first line.

gcc/ChangeLog:

* tree-diagnostic.cc (maybe_unwind_expanded_macro_loc): Add awareness
of _Pragma directive to the macro expansion trace.

libcpp/ChangeLog:

* directives.cc (get_token_no_padding): Add argument to receive the
virtual location of the token.
(get__Pragma_string): Likewise.
(do_pragma): Set pfile->directive_result->src_loc properly, it should
not be a virtual location.
(destringize_and_run): Update to provide proper locations for the
_Pragma string tokens.  Support raw strings.
(_cpp_do__Pragma): Adapt to changes to the helper functions.
* errors.cc (cpp_diagnostic_at): Support
cpp_reader::diagnostic_rebase_loc.
(cpp_diagnostic_with_line): Likewise.
* include/line-map.h (class rich_location): Add new member
forget_cached_expanded_locations().
* internal.h (struct _cpp__Pragma_state): Define new struct.
(_cpp_rebase_diagnostic_location): Declare new function.
(struct cpp_reader): Add diagnostic_rebase_loc member.
(_cpp_push__Pragma_token_context): Declare new function.
(_cpp_do__Pragma): Adjust prototype.
* macro.cc (pragma_str): New static var.
(builtin_macro): Adapt to new implementation of _Pragma processing.
(_cpp_pop_context): Fix the logic for resetting
pfile->top_most_macro_node, which previously was never triggered,
although the error seems to have been harmless.
(_cpp_push__Pragma_token_context): New function.
(_cpp_rebase_diagnostic_location): New function.

gcc/c-family/ChangeLog:

* c-ppoutput.cc (token_streamer::stream): Pass the virtual location of
the _Pragma token to maybe_print_line(), not the spelling location.

libgomp/ChangeLog:

* testsuite/libgomp.oacc-c-c++-common/reduction-5.c: Adjust for new
macro tracking output for _Pragma directives.
* testsuite/libgomp.oacc-c-c++-common/vred2d-128.c: Likewise.

gcc/testsuite/ChangeLog:

* c-c++-common/cpp/diagnostic-pragma-1.c: Adjust for new macro
tracking output for _Pragma directives.
* c-c++-common/cpp/pr57580.c: Likewise.
* c-c++-common/gomp/pragma-3.c: Likewise.

[PATCH 5/6] diagnostics: Support generated data in additional contexts

2022-11-04 Thread Lewis Hyatt via Gcc-patches
Add awareness that diagnostic locations may be in generated buffers rather
than an actual file to other places in the diagnostics code that may care,
most notably SARIF output (which needs to obtain its own snapshots of the code
involved). For edit context output, which outputs fixit hints as diffs, for
now just make sure we ignore generated data buffers. At the moment, there is
no ability for a fixit hint to be generated in such a buffer.

Because SARIF uses JSON as well, also add the ability to the json::string
class to handle a buffer with nulls in the middle (since we place no
restriction on LC_GEN content) by providing the option to specify the data
length.

gcc/ChangeLog:

* diagnostic-format-sarif.cc (sarif_builder::xloc_to_fb): New function.
(sarif_builder::maybe_make_physical_location_object): Support
generated data locations.
(sarif_builder::make_artifact_location_object): Likewise.
(sarif_builder::maybe_make_region_object_for_context): Likewise.
(sarif_builder::make_artifact_object): Likewise.
(sarif_builder::maybe_make_artifact_content_object): Likewise.
(get_source_lines): Likewise.
* edit-context.cc (edit_context::apply_fixit): Ignore generated
locations if one should make its way this far.
* json.cc (string::string): Support non-null-terminated string.
(string::print): Likewise.
* json.h (class string): Likewise.
---
 gcc/diagnostic-format-sarif.cc | 86 +-
 gcc/edit-context.cc|  4 ++
 gcc/json.cc| 17 +--
 gcc/json.h |  5 +-
 4 files changed, 75 insertions(+), 37 deletions(-)

diff --git a/gcc/diagnostic-format-sarif.cc b/gcc/diagnostic-format-sarif.cc
index 7110db4edd6..c2d18a1a16e 100644
--- a/gcc/diagnostic-format-sarif.cc
+++ b/gcc/diagnostic-format-sarif.cc
@@ -125,7 +125,10 @@ private:
   json::array *maybe_make_kinds_array (diagnostic_event::meaning m) const;
   json::object *maybe_make_physical_location_object (location_t loc);
   json::object *make_artifact_location_object (location_t loc);
-  json::object *make_artifact_location_object (const char *filename);
+
+  typedef std::pair filename_or_buffer;
+  json::object *make_artifact_location_object (filename_or_buffer fb);
+
   json::object *make_artifact_location_object_for_pwd () const;
   json::object *maybe_make_region_object (location_t loc) const;
   json::object *maybe_make_region_object_for_context (location_t loc) const;
@@ -146,16 +149,17 @@ private:
   json::object *make_reporting_descriptor_object_for_cwe_id (int cwe_id) const;
   json::object *
   make_reporting_descriptor_reference_object_for_cwe_id (int cwe_id);
-  json::object *make_artifact_object (const char *filename);
-  json::object *maybe_make_artifact_content_object (const char *filename) 
const;
-  json::object *maybe_make_artifact_content_object (const char *filename,
-   int start_line,
+  json::object *make_artifact_object (filename_or_buffer fb);
+  json::object *
+  maybe_make_artifact_content_object (filename_or_buffer fb) const;
+  json::object *maybe_make_artifact_content_object (expanded_location xloc,
int end_line) const;
   json::object *make_fix_object (const rich_location _loc);
   json::object *make_artifact_change_object (const rich_location );
   json::object *make_replacement_object (const fixit_hint ) const;
   json::object *make_artifact_content_object (const char *text) const;
   int get_sarif_column (expanded_location exploc) const;
+  static filename_or_buffer xloc_to_fb (expanded_location xloc);
 
   diagnostic_context *m_context;
 
@@ -166,7 +170,11 @@ private:
  diagnostic group.  */
   sarif_result *m_cur_group_result;
 
-  hash_set  m_filenames;
+  /* If the second member is >0, then this is a buffer of generated content,
+ with that length, not a filename.  */
+  hash_set ,
+  int_hash  >
+   > m_filenames;
   bool m_seen_any_relative_paths;
   hash_set  m_rule_id_set;
   json::array *m_rules_arr;
@@ -588,6 +596,15 @@ sarif_builder::make_location_object (const 
diagnostic_event )
   return location_obj;
 }
 
+/* Populate a filename_or_buffer pair from an expanded location.  */
+sarif_builder::filename_or_buffer
+sarif_builder::xloc_to_fb (expanded_location xloc)
+{
+  if (xloc.generated_data_len)
+return filename_or_buffer (xloc.generated_data, xloc.generated_data_len);
+  return filename_or_buffer (xloc.file, 0);
+}
+
 /* Make a physicalLocation object (SARIF v2.1.0 section 3.29) for LOC,
or return NULL;
Add any filename to the m_artifacts.  */
@@ -603,7 +620,7 @@ sarif_builder::maybe_make_physical_location_object 
(location_t loc)
   /* "artifactLocation" property (SARIF v2.1.0 section 3.29.3).  */
   json::object *artifact_loc_obj = make_artifact_location_object (loc);
   phys_loc_obj->set 

[PATCH 4/6] diagnostics: libcpp: Add LC_GEN linemaps to support in-memory buffers

2022-11-04 Thread Lewis Hyatt via Gcc-patches
Add a new linemap reason LC_GEN which enables encoding the location of data
that was generated during compilation and does not appear in any source file.
There could be many use cases, such as, for instance, referring to the content
of builtin macros (not yet implemented, but an easy lift after this one.) The
first intended application is to create a place to store the input to a
_Pragma directive, so that proper locations can be assigned to those
tokens. This will be done in a subsequent commit.

The actual change needed to the line-maps API in libcpp is very minimal and
requires no space overhead in the line map data structures (on 64-bit systems
that is; one newly added data member to class line_map_ordinary sits inside
former padding bytes.) An LC_GEN map is just an ordinary map like any other,
but the TO_FILE member that normally points to the file name points instead to
the actual data.  This works automatically with PCH as well, for the same
reason that the file name makes its way into a PCH.

Outside libcpp, there are many small changes but most of them are to
selftests, which are necessarily more sensitive to implementation
details. From the perspective of the user (the "user", here, being a frontend
using line maps or else the diagnostics infrastructure), the chief visible
change is that the function location_get_source_line() should be passed an
expanded_location object instead of a separate filename and line number.  This
is not a big change because in most cases, this information came anyway from a
call to expand_location and the needed expanded_location object is readily
available. The new overload of location_get_source_line() uses the extra
information in the expanded_location object to obtain the data from the
in-memory buffer when it originated from an LC_GEN map.

Until the subsequent patch that starts using LC_GEN maps, none are yet
generated within GCC, hence nothing is added to the testsuite here; but all
relevant selftests have been extended to cover generated data maps in
addition to normal files.

libcpp/ChangeLog:

* include/line-map.h (enum lc_reason): Add LC_GEN.
(struct line_map_ordinary): Add new member to_file_len and update the
GTY markup on to_file to support embedded null bytes.
(class expanded_location): Add new members to store generated content.
* line-map.cc (linemap_add): Add new argument to_file_len to support
generated content. Implement LC_GEN maps.
(linemap_line_start): Pass new to_file_len argument to linemap_add.
(linemap_expand_location): Support LC_GEN locations.
(linemap_dump): Likewise.

gcc/ChangeLog:

* diagnostic-show-locus.cc (make_range): Initialize new fields in
expanded_location.
(layout::calculate_x_offset_display): Use the new expanded_location
overload of location_get_source_line(), so as to support LC_GEN maps.
(layout::print_line): Likewise.
(source_line::source_line): Likewise.
(line_corrections::add_hint): Likewise.
(class line_corrections): Store the location as an exploc rather than
individual filename, so as to support LC_GEN maps.
(layout::print_trailing_fixits): Use the new exploc constructor for
class line_corrections.
(test_layout_x_offset_display_utf8): Test LC_GEN maps as well as normal.
(test_layout_x_offset_display_tab): Likewise.
(test_diagnostic_show_locus_one_liner): Likewise.
(test_diagnostic_show_locus_one_liner_utf8): Likewise.
(test_add_location_if_nearby): Likewise.
(test_diagnostic_show_locus_fixit_lines): Likewise.
(test_fixit_consolidation): Likewise.
(test_overlapped_fixit_printing): Likewise.
(test_overlapped_fixit_printing_utf8): Likewise.
(test_overlapped_fixit_printing_2): Likewise.
(test_fixit_insert_containing_newline): Likewise.
(test_fixit_insert_containing_newline_2): Likewise.
(test_fixit_replace_containing_newline): Likewise.
(test_fixit_deletion_affecting_newline): Likewise.
(test_tab_expansion): Likewise.
(test_escaping_bytes_1): Likewise.
(test_escaping_bytes_2): Likewise.
(test_line_numbers_multiline_range): Likewise.
(diagnostic_show_locus_cc_tests): Likewise.
* diagnostic.cc (diagnostic_report_current_module): Support LC_GEN
maps when outputting include trace.
(assert_location_text): Zero-initialize the expanded_location so as to
cover all fields, including the newly added ones.
* gcc-rich-location.cc (blank_line_before_p): Use the new
expanded_location overload of location_get_source_line().
* input.cc (class file_cache_slot): Add new member m_data_active.
(file_cache_slot::file_cache_slot): Initialize new member.
(special_fname_generated): New function.
(expand_location_1): Recognize LC_GEN locations and output the 

[PATCH 2/6] diagnostics: Use an inline function rather than hardcoding string

2022-11-04 Thread Lewis Hyatt via Gcc-patches
The string "" is hard-coded in several places throughout the
diagnostics code, and in some of those places, it is used incorrectly with
respect to internationalization. (Comparing a translated string to an
untranslated string.) The error is not currently observable in any output GCC
actually produces, hence no testcase added here, but it's worth fixing, and
also, I am shortly going to add a new such string and want to avoid hardcoding
that one in similar places.

gcc/c-family/ChangeLog:

* c-opts.cc (c_finish_options): Use special_fname_builtin () rather
than a hard-coded string.

gcc/ChangeLog:

* diagnostic.cc (diagnostic_get_location_text): Use
special_fname_builtin () rather than a hardcoded string (which was
also incorrectly left untranslated previously.)
* input.cc (special_fname_builtin): New function.
(expand_location_1): Use special_fname_builtin () rather than a
hard-coded string.
(test_builtins): Likewise.
* input.h (special_fname_builtin): Declare.

gcc/fortran/ChangeLog:

* cpp.cc (gfc_cpp_init): Use special_fname_builtin () rather than a
hardcoded string (which was also incorrectly left untranslated
previously.)
* error.cc (gfc_diagnostic_build_locus_prefix): Likewise.
* f95-lang.cc (gfc_init): Likewise.
---
 gcc/c-family/c-opts.cc  |  2 +-
 gcc/diagnostic.cc   |  2 +-
 gcc/fortran/cpp.cc  |  2 +-
 gcc/fortran/error.cc|  4 ++--
 gcc/fortran/f95-lang.cc |  2 +-
 gcc/input.cc| 10 --
 gcc/input.h |  3 +++
 7 files changed, 17 insertions(+), 8 deletions(-)

diff --git a/gcc/c-family/c-opts.cc b/gcc/c-family/c-opts.cc
index 32b929e3ece..521797fb7eb 100644
--- a/gcc/c-family/c-opts.cc
+++ b/gcc/c-family/c-opts.cc
@@ -1476,7 +1476,7 @@ c_finish_options (void)
 {
   const line_map_ordinary *bltin_map
= linemap_check_ordinary (linemap_add (line_table, LC_RENAME, 0,
-  _(""), 0));
+  special_fname_builtin (), 0));
   cb_file_change (parse_in, bltin_map);
   linemap_line_start (line_table, 0, 1);
 
diff --git a/gcc/diagnostic.cc b/gcc/diagnostic.cc
index 22f7b0b6d6e..7c7ee6da746 100644
--- a/gcc/diagnostic.cc
+++ b/gcc/diagnostic.cc
@@ -470,7 +470,7 @@ diagnostic_get_location_text (diagnostic_context *context,
   const char *file = s.file ? s.file : progname;
   int line = 0;
   int col = -1;
-  if (strcmp (file, N_("")))
+  if (strcmp (file, special_fname_builtin ()))
 {
   line = s.line;
   if (context->show_column)
diff --git a/gcc/fortran/cpp.cc b/gcc/fortran/cpp.cc
index 364bd0d2a85..0b5755edbb4 100644
--- a/gcc/fortran/cpp.cc
+++ b/gcc/fortran/cpp.cc
@@ -605,7 +605,7 @@ gfc_cpp_init (void)
   if (gfc_option.flag_preprocessed)
 return;
 
-  cpp_change_file (cpp_in, LC_RENAME, _(""));
+  cpp_change_file (cpp_in, LC_RENAME, special_fname_builtin ());
   if (!gfc_cpp_option.no_predefined)
 {
   /* Make sure all of the builtins about to be declared have
diff --git a/gcc/fortran/error.cc b/gcc/fortran/error.cc
index c9d6edbb923..214fb78ba7b 100644
--- a/gcc/fortran/error.cc
+++ b/gcc/fortran/error.cc
@@ -1147,7 +1147,7 @@ gfc_diagnostic_build_locus_prefix (diagnostic_context 
*context,
   const char *locus_ce = colorize_stop (pp_show_color (pp));
   return (s.file == NULL
  ? build_message_string ("%s%s:%s", locus_cs, progname, locus_ce )
- : !strcmp (s.file, N_(""))
+ : !strcmp (s.file, special_fname_builtin ())
  ? build_message_string ("%s%s:%s", locus_cs, s.file, locus_ce)
  : context->show_column
  ? build_message_string ("%s%s:%d:%d:%s", locus_cs, s.file, s.line,
@@ -1167,7 +1167,7 @@ gfc_diagnostic_build_locus_prefix (diagnostic_context 
*context,
 
   return (s.file == NULL
  ? build_message_string ("%s%s:%s", locus_cs, progname, locus_ce )
- : !strcmp (s.file, N_(""))
+ : !strcmp (s.file, special_fname_builtin ())
  ? build_message_string ("%s%s:%s", locus_cs, s.file, locus_ce)
  : context->show_column
  ? build_message_string ("%s%s:%d:%d-%d:%s", locus_cs, s.file, s.line,
diff --git a/gcc/fortran/f95-lang.cc b/gcc/fortran/f95-lang.cc
index a6750bea787..0d83f3f8b69 100644
--- a/gcc/fortran/f95-lang.cc
+++ b/gcc/fortran/f95-lang.cc
@@ -259,7 +259,7 @@ gfc_init (void)
   if (!gfc_cpp_enabled ())
 {
   linemap_add (line_table, LC_ENTER, false, gfc_source_file, 1);
-  linemap_add (line_table, LC_RENAME, false, "", 0);
+  linemap_add (line_table, LC_RENAME, false, special_fname_builtin (), 0);
 }
   else
 gfc_cpp_init_0 ();
diff --git a/gcc/input.cc b/gcc/input.cc
index a28abfac5ac..483cb6e940d 100644
--- a/gcc/input.cc
+++ b/gcc/input.cc
@@ -29,6 +29,12 @@ along with GCC; see the file COPYING3.  If not see
 #define HAVE_ICONV 0
 #endif
 
+const char *
+special_fname_builtin ()
+{
+  

[PATCH 3/6] libcpp: Fix paste error with unknown pragma after macro expansion

2022-11-04 Thread Lewis Hyatt via Gcc-patches
In directives.cc, do_pragma() contains logic to handle a case such as the new
testcase pragma-omp-unknown.c, where an unknown pragma was the result of macro
expansion (for pragma namespaces that permit expansion). This no longer works
correctly as shown by the testcase, fixed by adding PREV_WHITE to the flags on
the second token to prevent an unwanted paste.  Also fixed the memory leak,
since the temporary tokens are pushed on their own context, nothing prevents
freeing of the buffer that holds them when the context is eventually popped.

libcpp/ChangeLog:

* directives.cc (do_pragma): Fix memory leak in token buffer.  Fix
unwanted paste between two tokens.

gcc/testsuite/ChangeLog:

* c-c++-common/gomp/pragma-omp-unknown.c: New test.
---
 gcc/testsuite/c-c++-common/gomp/pragma-omp-unknown.c | 10 ++
 libcpp/directives.cc | 10 +-
 2 files changed, 15 insertions(+), 5 deletions(-)
 create mode 100644 gcc/testsuite/c-c++-common/gomp/pragma-omp-unknown.c

diff --git a/gcc/testsuite/c-c++-common/gomp/pragma-omp-unknown.c 
b/gcc/testsuite/c-c++-common/gomp/pragma-omp-unknown.c
new file mode 100644
index 000..04881f786ab
--- /dev/null
+++ b/gcc/testsuite/c-c++-common/gomp/pragma-omp-unknown.c
@@ -0,0 +1,10 @@
+/* { dg-do preprocess } */
+/* { dg-options "-fopenmp" } */
+
+#define X UNKNOWN1
+#pragma omp X
+/* { dg-final { scan-file pragma-omp-unknown.i "#pragma omp UNKNOWN1" } } */
+
+#define Y UNKNOWN2
+_Pragma("omp Y")
+/* { dg-final { scan-file pragma-omp-unknown.i "#pragma omp UNKNOWN2" } } */
diff --git a/libcpp/directives.cc b/libcpp/directives.cc
index 918752f6b1f..9dc4363c65a 100644
--- a/libcpp/directives.cc
+++ b/libcpp/directives.cc
@@ -1565,15 +1565,15 @@ do_pragma (cpp_reader *pfile)
{
  /* Invalid name comes from macro expansion, _cpp_backup_tokens
 won't allow backing 2 tokens.  */
- /* ??? The token buffer is leaked.  Perhaps if def_pragma hook
-reads both tokens, we could perhaps free it, but if it doesn't,
-we don't know the exact lifespan.  */
- cpp_token *toks = XNEWVEC (cpp_token, 2);
+ const auto tok_buff = _cpp_get_buff (pfile, 2 * sizeof (cpp_token));
+ const auto toks = (cpp_token *)tok_buff->base;
  toks[0] = ns_token;
  toks[0].flags |= NO_EXPAND;
  toks[1] = *token;
- toks[1].flags |= NO_EXPAND;
+ toks[1].flags |= NO_EXPAND | PREV_WHITE;
  _cpp_push_token_context (pfile, NULL, toks, 2);
+ /* Arrange to free this buffer when no longer needed.  */
+ pfile->context->buff = tok_buff;
}
   pfile->cb.def_pragma (pfile, pfile->directive_line);
 }


[PATCH 1/6] diagnostics: Fix macro tracking for ad-hoc locations

2022-11-04 Thread Lewis Hyatt via Gcc-patches
The result of linemap_resolve_location() can be an ad-hoc location, if that is
what was stored in a relevant macro map.  maybe_unwind_expanded_macro_loc()
did not previously handle this case, causing it to print the wrong tracking
information for an example such as the new testcase macro-trace-1.c.  Fix that
by checking for ad-hoc locations where needed.

gcc/ChangeLog:

* tree-diagnostic.cc (maybe_unwind_expanded_macro_loc): Handle ad-hoc
location in return value of linemap_resolve_location().

gcc/testsuite/ChangeLog:

* c-c++-common/cpp/macro-trace-1.c: New test.
---
 gcc/testsuite/c-c++-common/cpp/macro-trace-1.c | 4 
 gcc/tree-diagnostic.cc | 7 +--
 2 files changed, 9 insertions(+), 2 deletions(-)
 create mode 100644 gcc/testsuite/c-c++-common/cpp/macro-trace-1.c

diff --git a/gcc/testsuite/c-c++-common/cpp/macro-trace-1.c 
b/gcc/testsuite/c-c++-common/cpp/macro-trace-1.c
new file mode 100644
index 000..34cfbb3dad3
--- /dev/null
+++ b/gcc/testsuite/c-c++-common/cpp/macro-trace-1.c
@@ -0,0 +1,4 @@
+/* This token is long enough to require an ad-hoc location. Make sure that
+   the macro trace still prints properly.  */
+#define X "0123456789012345678901234567689" /* { dg-error {expected .* before 
string constant} } */
+X /* { dg-note {in expansion of macro 'X'} } */
diff --git a/gcc/tree-diagnostic.cc b/gcc/tree-diagnostic.cc
index 0d79fe3c3c1..5cf3a1c17d2 100644
--- a/gcc/tree-diagnostic.cc
+++ b/gcc/tree-diagnostic.cc
@@ -190,14 +190,17 @@ maybe_unwind_expanded_macro_loc (diagnostic_context 
*context,
 location_t l = 
   linemap_resolve_location (line_table, resolved_def_loc,
 LRK_SPELLING_LOCATION,  );
-if (l < RESERVED_LOCATION_COUNT || LINEMAP_SYSP (m))
+   location_t l0 = l;
+   if (IS_ADHOC_LOC (l0))
+ l0 = get_location_from_adhoc_loc (line_table, l0);
+   if (l0 < RESERVED_LOCATION_COUNT || LINEMAP_SYSP (m))
   continue;
 
/* We need to print the context of the macro definition only
   when the locus of the first displayed diagnostic (displayed
   before this trace) was inside the definition of the
   macro.  */
-int resolved_def_loc_line = SOURCE_LINE (m, l);
+   const int resolved_def_loc_line = SOURCE_LINE (m, l0);
 if (ix == 0 && saved_location_line != resolved_def_loc_line)
   {
 diagnostic_append_note (context, resolved_def_loc, 


[PATCH 0/6] diagnostics: libcpp: Overhaul locations for _Pragma tokens

2022-11-04 Thread Lewis Hyatt via Gcc-patches
Hello-

In the past couple years there has been a ton of progress in fixing bugs
related to _Pragma, especially its use in the type of macros that many
projects like to implement for manipulating GCC diagnostic pragmas more
easily. For GCC 13 I have been going through the remaining open PRs, fixing a
couple and adding testcases for several that were already fixed. I felt that
made it a good time to overhaul one of the last remaining issues with _Pragma
processing, which is that we do not currently assign good locations to the
tokens involved. The locations are very important, however, because that is
how GCC diagnostic pragmas will ultimately determine whether a given warning
should or should not apply at a given point. Currently, the tokens inside a
_Pragma string are all assigned the same location as the _Pragma token itself,
which is sufficient to make diagnostic pragmas work correctly. It does produce
somewhat inferior diagnostics, though, since we do not point the user to which
part of the _Pragma string caused the problem; and if the _Pragma string was
expanded from a macro, we do not even point them to the string at all.

Further, the assignment of the fake location to the tokens inside the _Pragma
string takes place after all the tokens have been lexed -- consequently, if a
diagnostic is issued by libcpp during that process, it doesn't benefit from the
patched-up location and instead uses a bogus location. As a quick example,
compiling:

=
_Pragma("GCC diagnostic ignored \"oops")
=

produces:

=
file:1:24: warning: missing terminating " character
1 | _Pragma("GCC diagnostic ignored \"oops")
  |^
=

It is surprisingly involved to make that caret point to something
reasonable. The reason it points to the middle of nowhere is that the current
implementation of _Pragma in directives.cc:destringize_and_run() does not
touch the line_maps instance at all, and so does not inform it where the
tokens are coming from. But the line_maps API in fact does not provide any way
to handle this case, so this needs to be added first. With all the changes in
this patch set, we would output instead:

==
In buffer generated from file:1:
:1:24: warning: missing terminating " character
1 | GCC diagnostic ignored "oops
  |^
file:1:1: note: in <_Pragma directive>
1 | _Pragma("GCC diagnostic ignored \"oops")
  | ^~~
==

Treating the _Pragma like a macro expansion makes everything consistent and
solves a ton of problems; all the locations involved will just make sense from
the user's point of view.

Patches 1-3 are tiny bug fixes that I came across while working on the new
testcases. I was a bit surprised that #1 and #3 especially did not have PRs
open, but I guess these small glitches have gone unnoticed so far.

Patch 4 is the largest one. It adds a new reason=LC_GEN for ordinary line
maps. These maps are just like normal ones, except the file name pointer
points not to a file name, but to the actual data in memory instead. This is
how we can issue diagnostics for code that did not appear in the user's input,
such as the de-stringized _Pragma string. The changes needed in libcpp to
support this concept are pretty small and straightforward. Most of the changes
outside of libcpp are in input.cc and diagnostic-show-locus.cc, which need to
learn how to obtain code from LC_GEN maps, and also a lot of the changes are
in selftests that are pretty sensitive to the internal implementation.

Patch 5 is a continuation of 4 that supports LC_GEN maps in less commonly used
places, such as the new SARIF output format, that also need to know how to
read source back from in-memory buffers in addition to files.

Patch 6 updates the implementation of _Pragma handling to use LC_GEN maps and
to create virtual locations for the tokens as in the example above. I have
also added support for the argument of the _Pragma to be a raw string, as
requested by PR83473, since this was easy to do while I was there.

1/6: diagnostics: Fix macro tracking for ad-hoc locations
2/6: diagnostics: Use an inline function rather than hardcoding 
 string
3/6: libcpp: Fix paste error with unknown pragma after macro expansion
4/6: diagnostics: libcpp: Add LC_GEN linemaps to support in-memory buffers
5/6: diagnostics: Support generated data in additional contexts
6/6: diagnostics: libcpp: Assign real locations to the tokens inside
 _Pragma strings

Bootstrap and regtest all languages on x86-64 Linux looks good.

I realize it's near the end of stage 1 now. It would still be great and I
would appreciate very much if this patch could get reviewed please? For GCC 13,
there have been several _Pragma-related bugs fixed (especially PR53431), and
addressing this location issue would tie it together nicely. Thanks very much!

-Lewis


Re: [PATCH v2] tree-object-size: Support strndup and strdup

2022-11-04 Thread Prathamesh Kulkarni via Gcc-patches
On Fri, 4 Nov 2022 at 18:18, Siddhesh Poyarekar  wrote:
>
> Use string length of input to strdup to determine the usable size of the
> resulting object.  Avoid doing the same for strndup since there's a
> chance that the input may be too large, resulting in an unnecessary
> overhead or worse, the input may not be NULL terminated, resulting in a
> crash where there would otherwise have been none.
>
> gcc/ChangeLog:
>
> * tree-object-size.cc (todo): New variable.
> (object_sizes_execute): Use it.
> (strdup_object_size): New function.
> (call_object_size): Use it.
>
> gcc/testsuite/ChangeLog:
>
> * gcc.dg/builtin-dynamic-object-size-0.c (test_strdup,
> test_strndup, test_strdup_min, test_strndup_min): New tests.
> (main): Call them.
> * gcc.dg/builtin-dynamic-object-size-1.c: Silence overread
> warnings.
> * gcc.dg/builtin-dynamic-object-size-2.c: Likewise.
> * gcc.dg/builtin-dynamic-object-size-3.c: Likewise.
> * gcc.dg/builtin-dynamic-object-size-4.c: Likewise.
> * gcc.dg/builtin-object-size-1.c: Silence overread warnings.
> Declare free, strdup and strndup.
> (test11): New test.
> (main): Call it.
> * gcc.dg/builtin-object-size-2.c: Silence overread warnings.
> Declare free, strdup and strndup.
> (test9): New test.
> (main): Call it.
> * gcc.dg/builtin-object-size-3.c: Silence overread warnings.
> Declare free, strdup and strndup.
> (test11): New test.
> (main): Call it.
> * gcc.dg/builtin-object-size-4.c: Silence overread warnings.
> Declare free, strdup and strndup.
> (test9): New test.
> (main): Call it.
> ---
> Tested:
>
> - x86_64 bootstrap and testsuite run
> - i686 build and testsuite run
> - ubsan bootstrap
>
>  .../gcc.dg/builtin-dynamic-object-size-0.c| 43 +
>  .../gcc.dg/builtin-dynamic-object-size-1.c|  2 +-
>  .../gcc.dg/builtin-dynamic-object-size-2.c|  2 +-
>  .../gcc.dg/builtin-dynamic-object-size-3.c|  2 +-
>  .../gcc.dg/builtin-dynamic-object-size-4.c|  2 +-
>  gcc/testsuite/gcc.dg/builtin-object-size-1.c  | 94 +-
>  gcc/testsuite/gcc.dg/builtin-object-size-2.c  | 94 +-
>  gcc/testsuite/gcc.dg/builtin-object-size-3.c  | 95 ++-
>  gcc/testsuite/gcc.dg/builtin-object-size-4.c  | 94 +-
>  gcc/tree-object-size.cc   | 84 +++-
>  10 files changed, 502 insertions(+), 10 deletions(-)
>
> diff --git a/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-0.c 
> b/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-0.c
> index 01a280b2d7b..4f1606a486b 100644
> --- a/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-0.c
> +++ b/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-0.c
> @@ -479,6 +479,40 @@ test_loop (int *obj, size_t sz, size_t start, size_t 
> end, int incr)
>return __builtin_dynamic_object_size (ptr, 0);
>  }
>
> +/* strdup/strndup.  */
> +
> +size_t
> +__attribute__ ((noinline))
> +test_strdup (const char *in)
> +{
> +  char *res = __builtin_strdup (in);
> +  return __builtin_dynamic_object_size (res, 0);
> +}
> +
> +size_t
> +__attribute__ ((noinline))
> +test_strndup (const char *in, size_t bound)
> +{
> +  char *res = __builtin_strndup (in, bound);
> +  return __builtin_dynamic_object_size (res, 0);
> +}
> +
> +size_t
> +__attribute__ ((noinline))
> +test_strdup_min (const char *in)
> +{
> +  char *res = __builtin_strdup (in);
> +  return __builtin_dynamic_object_size (res, 2);
> +}
> +
> +size_t
> +__attribute__ ((noinline))
> +test_strndup_min (const char *in, size_t bound)
> +{
> +  char *res = __builtin_strndup (in, bound);
> +  return __builtin_dynamic_object_size (res, 2);
> +}
> +
>  /* Other tests.  */
>
>  struct TV4
> @@ -651,6 +685,15 @@ main (int argc, char **argv)
>int *t = test_pr105736 ();
>if (__builtin_dynamic_object_size (t, 0) != -1)
>  FAIL ();
> +  const char *str = "hello world";
> +  if (test_strdup (str) != __builtin_strlen (str) + 1)
> +FAIL ();
> +  if (test_strndup (str, 4) != 5)
> +FAIL ();
> +  if (test_strdup_min (str) != __builtin_strlen (str) + 1)
> +FAIL ();
> +  if (test_strndup_min (str, 4) != 1)
> +FAIL ();
>
>if (nfails > 0)
>  __builtin_abort ();
> diff --git a/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-1.c 
> b/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-1.c
> index 7cc8b1c9488..8f17c8edcaf 100644
> --- a/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-1.c
> +++ b/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-1.c
> @@ -1,5 +1,5 @@
>  /* { dg-do run } */
> -/* { dg-options "-O2" } */
> +/* { dg-options "-O2 -Wno-stringop-overread" } */
>  /* { dg-require-effective-target alloca } */
>
>  #define __builtin_object_size __builtin_dynamic_object_size
> diff --git a/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-2.c 
> 

Re: [PATCH] libcpp: Update to Unicode 15

2022-11-04 Thread Marek Polacek via Gcc-patches
On Fri, Nov 04, 2022 at 09:55:55AM +0100, Jakub Jelinek wrote:
> Hi!
> 
> The following patch (included in the mail is for uname2c.h part
> just a pseudo patch with a lot of changes replaced with ...
> because it is too large but the important changes like
> -static const char uname2c_dict[59418] =
> +static const char uname2c_dict[59891] =
> -static const unsigned char uname2c_tree[208765] = {
> +static const unsigned char uname2c_tree[210697] = {
> are shown, full patch xz compressed attached) regenerates the
> libcpp tables with Unicode 15.0.0 which added 4489 new characters.
> 
> As mentioned previously, this isn't just a matter of running the
> two libcpp/make*.cc programs on the new Unicode files, but one needs
> to manually update a table inside of makeuname2c.cc according to
> a table in Unicode text (which is partially reflected in the text
> files, but e.g. in Unicode 14.0.0 not 100% accurately, in 15.0.0
> actually accurately).
> I've also added some randomly chosen subset of those 4489 new
> characters to a testcase.
> 
> Bootstrapped/regtested on x86_64-linux and i686-linux, ok for trunk?

OK, thanks.
 
> 2022-11-04  Jakub Jelinek  
> 
> gcc/testsuite/
>   * c-c++-common/cpp/named-universal-char-escape-1.c: Add tests for some
>   characters newly added in Unicode 15.0.0.

Cool, thanks for updating the test as well.

> libcpp/
>   * makeuname2c.cc (struct generated): Update from Unicode 15.0.0
>   table 4-8.
>   * ucnid.h: Regenerated for Unicode 15.0.0.
>   * uname2c.h: Likewise.
> 
> --- gcc/testsuite/c-c++-common/cpp/named-universal-char-escape-1.c.jj 
> 2022-08-27 23:01:28.319565957 +0200
> +++ gcc/testsuite/c-c++-common/cpp/named-universal-char-escape-1.c
> 2022-11-04 09:41:45.908527440 +0100
> @@ -117,6 +117,27 @@ typedef __CHAR32_TYPE__ char32_t;
>  || U'\u0FD0' != U'\N{TIBETAN MARK BSKA- SHOG GI MGO RGYAN}' \
>  || U'\uFE18' != U'\N{PRESENTATION FORM FOR VERTICAL RIGHT WHITE 
> LENTICULAR BRAKCET}' \
>  || U'\uFE18' != U'\N{PRESENTATION FORM FOR VERTICAL RIGHT WHITE 
> LENTICULAR BRACKET}' \
> +|| U'\u0CF3' != U'\N{KANNADA SIGN COMBINING ANUSVARA ABOVE RIGHT}' \
> +|| U'\u0ECE' != U'\N{LAO YAMAKKAN}' \
> +|| U'\U00010EFE' != U'\N{ARABIC SMALL LOW WORD QASR}' \
> +|| U'\U00011241' != U'\N{KHOJKI VOWEL SIGN VOCALIC R}' \
> +|| U'\U00011B06' != U'\N{DEVANAGARI SIGN WESTERN FIVE-LIKE BHALE}' \
> +|| U'\U00011F0B' != U'\N{KAWI LETTER VOCALIC RR}' \
> +|| U'\U0001342F' != U'\N{EGYPTIAN HIEROGLYPH V011D}' \
> +|| U'\U00013451' != U'\N{EGYPTIAN HIEROGLYPH MODIFIER DAMAGED AT START 
> AND BOTTOM}' \
> +|| U'\U0001B132' != U'\N{HIRAGANA LETTER SMALL KO}' \
> +|| U'\U0001B155' != U'\N{KATAKANA LETTER SMALL KO}' \
> +|| U'\U0001D2C4' != U'\N{KAKTOVIK NUMERAL FOUR}' \
> +|| U'\U0001DF27' != U'\N{LATIN SMALL LETTER N WITH MID-HEIGHT LEFT 
> HOOK}' \
> +|| U'\U0001E036' != U'\N{MODIFIER LETTER CYRILLIC SMALL ZHE}' \
> +|| U'\U0001E05B' != U'\N{CYRILLIC SUBSCRIPT SMALL LETTER EL}' \
> +|| U'\U0001E4E5' != U'\N{NAG MUNDARI LETTER ENN}' \
> +|| U'\U0001F6DC' != U'\N{WIRELESS}' \
> +|| U'\U0001F77E' != U'\N{QUAOAR}' \
> +|| U'\U0001F7D9' != U'\N{NINE POINTED WHITE STAR}' \
> +|| U'\U0001FA76' != U'\N{GREY HEART}' \
> +|| U'\U0001FA88' != U'\N{FLUTE}' \
> +|| U'\U0001FABC' != U'\N{JELLYFISH}' \
>  || U'\uAC00' != U'\N{HANGUL SYLLABLE GA}' \
>  || U'\uAC02' != U'\N{HANGUL SYLLABLE GAGG}' \
>  || U'\uAD8D' != U'\N{HANGUL SYLLABLE GWEONJ}' \
> @@ -134,6 +155,7 @@ typedef __CHAR32_TYPE__ char32_t;
>  || U'\U0002A6DD' != U'\N{CJK UNIFIED IDEOGRAPH-2A6DD}' \
>  || U'\U00020700' != U'\N{CJK UNIFIED IDEOGRAPH-20700}' \
>  || U'\U0002B734' != U'\N{CJK UNIFIED IDEOGRAPH-2B734}' \
> +|| U'\U0002B739' != U'\N{CJK UNIFIED IDEOGRAPH-2B739}' \
>  || U'\U0002B740' != U'\N{CJK UNIFIED IDEOGRAPH-2B740}' \
>  || U'\U0002B81D' != U'\N{CJK UNIFIED IDEOGRAPH-2B81D}' \
>  || U'\U0002B820' != U'\N{CJK UNIFIED IDEOGRAPH-2B820}' \
> @@ -142,6 +164,8 @@ typedef __CHAR32_TYPE__ char32_t;
>  || U'\U0002EBE0' != U'\N{CJK UNIFIED IDEOGRAPH-2EBE0}' \
>  || U'\U0003' != U'\N{CJK UNIFIED IDEOGRAPH-3}' \
>  || U'\U0003134A' != U'\N{CJK UNIFIED IDEOGRAPH-3134A}' \
> +|| U'\U00031350' != U'\N{CJK UNIFIED IDEOGRAPH-31350}' \
> +|| U'\U000323AF' != U'\N{CJK UNIFIED IDEOGRAPH-323AF}' \
>  || U'\U00017000' != U'\N{TANGUT IDEOGRAPH-17000}' \
>  || U'\U000187F7' != U'\N{TANGUT IDEOGRAPH-187F7}' \
>  || U'\U00018D00' != U'\N{TANGUT IDEOGRAPH-18D00}' \
> --- libcpp/makeuname2c.cc.jj  2022-08-31 10:22:33.439166029 +0200
> +++ libcpp/makeuname2c.cc 2022-11-03 10:38:03.341964913 +0100
> @@ -69,7 +69,7 @@ struct entry { const char *name; unsigne
>  static struct entry *entries;
>  static unsigned long num_allocated, num_entries;
>  
> -/* Unicode 14 Table 4-8.  */
> +/* Unicode 15 Table 4-8.  */
>  struct generated {
>const char *prefix;
>/* 

Re: [PATCH] [PR24021] Implement PLUS_EXPR range-op entry for floats.

2022-11-04 Thread Jakub Jelinek via Gcc-patches
On Mon, Oct 17, 2022 at 08:21:01AM +0200, Aldy Hernandez wrote:
> --- a/gcc/range-op-float.cc
> +++ b/gcc/range-op-float.cc
> @@ -200,6 +200,116 @@ frelop_early_resolve (irange , tree type,
> && relop_early_resolve (r, type, op1, op2, rel, my_rel));
>  }
>  
> +// If R contains a NAN of unknown sign, update the NAN's signbit
> +// depending on two operands.
> +
> +inline void
> +update_nan_sign (frange , const frange , const frange )
> +{
> +  if (!r.maybe_isnan ())
> +return;
> +
> +  bool op1_nan = op1.maybe_isnan ();
> +  bool op2_nan = op2.maybe_isnan ();
> +  bool sign1, sign2;
> +
> +  gcc_checking_assert (!r.nan_signbit_p (sign1));
> +  if (op1_nan && op2_nan)
> +{
> +  if (op1.nan_signbit_p (sign1) && op2.nan_signbit_p (sign2))
> + r.update_nan (sign1 | sign2);
> +}
> +  else if (op1_nan)
> +{
> +  if (op1.nan_signbit_p (sign1))
> + r.update_nan (sign1);
> +}
> +  else if (op2_nan)
> +{
> +  if (op2.nan_signbit_p (sign2))
> + r.update_nan (sign2);
> +}
> +}

IEEE 754-2008 says:
"When either an input or result is NaN, this standard does not interpret the 
sign of a NaN. Note, however,
that operations on bit strings — copy, negate, abs, copySign — specify the sign 
bit of a NaN result,
sometimes based upon the sign bit of a NaN operand. The logical predicate 
totalOrder is also affected by
the sign bit of a NaN operand. For all other operations, this standard does not 
specify the sign bit of a NaN
result, even when there is only one input NaN, or when the NaN is produced from 
an invalid
operation."
so, while one can e.g. see on x86_64 that in simple -O0
int
main ()
{
  volatile float f1 = __builtin_nansf ("");
  volatile float f2 = __builtin_copysignf (__builtin_nansf (""), -1.0f);
  volatile float f3 = __builtin_nanf ("");
  volatile float f4 = __builtin_copysignf (__builtin_nanf (""), -1.0f);
  volatile float fzero = 0.0f;
  __builtin_printf ("%08x %08x\n", *(unsigned *), *(unsigned *));
  __builtin_printf ("%08x %08x\n", *(unsigned *), *(unsigned *));
  f1 = -f1;
  f2 = -f2;
  f3 = -f3;
  f4 = -f4;
  __builtin_printf ("%08x %08x\n", *(unsigned *), *(unsigned *));
  __builtin_printf ("%08x %08x\n", *(unsigned *), *(unsigned *));
  volatile float f5 = f1 + fzero;
  volatile float f6 = fzero + f1;
  __builtin_printf ("%08x %08x\n", *(unsigned *), *(unsigned *));
  f5 = f2 + fzero;
  f6 = fzero + f2;
  __builtin_printf ("%08x %08x\n", *(unsigned *), *(unsigned *));
  f5 = f3 + fzero;
  f6 = fzero + f3;
  __builtin_printf ("%08x %08x\n", *(unsigned *), *(unsigned *));
  f5 = f4 + fzero;
  f6 = fzero + f4;
  __builtin_printf ("%08x %08x\n", *(unsigned *), *(unsigned *));
  f5 = f1 + f2;
  f6 = f2 + f1;
  __builtin_printf ("%08x %08x\n", *(unsigned *), *(unsigned *));
  f5 = f2 + f3;
  f6 = f3 + f2;
  __builtin_printf ("%08x %08x\n", *(unsigned *), *(unsigned *));
  f5 = f3 + f4;
  f6 = f4 + f3;
  __builtin_printf ("%08x %08x\n", *(unsigned *), *(unsigned *));
  f5 = f4 + f1;
  f6 = f1 + f4;
  __builtin_printf ("%08x %08x\n", *(unsigned *), *(unsigned *));
  return 0;
}
result of:
7fa0 ffa0
7fc0 ffc0
ffa0 7fa0
ffc0 7fc0
ffe0 ffe0
7fe0 7fe0
ffc0 ffc0
7fc0 7fc0
7fe0 ffe0
ffc0 7fe0
7fc0 ffc0
ffe0 7fc0
which basically shows that copysign copies sign bit, negation toggles it,
binary operation with a single NaN (quiet or signaling) get that NaN
with its sign and for binary operation on 2 NaNs (again quiet or signaling)
one gets sign from the second? operand, I think the above IEEE text
doesn't guarantee it except for a simple assignment (but with no mode
conversion; that one copies the bit), NEGATE_EXPR (toggles it),
ABS_EXPR (clears it), __builtin_copysign*/IFN_COPYSIGN (copies it from
the second operand).  Everything else, including invalid operation cases,
should set the possible sign bit values of NANs to 0/1 rather than just
one of them.  Perhaps COND_EXPR 2nd/3rd operand is a move too.

As you are adding a binary operation, that should be one of those cases
where we drop the NAN sign to VARYING.

> +
> +// If either operand is a NAN, set R to the combination of both NANs
> +// signwise and return TRUE.
> +
> +inline bool
> +propagate_nans (frange , const frange , const frange )
> +{
> +  if (op1.known_isnan () || op2.known_isnan ())
> +{
> +  r.set_nan (op1.type ());
> +  update_nan_sign (r, op1, op2);
> +  return true;
> +}
> +  return false;
> +}
> +
> +// Set VALUE to its next real value, or INF if the operation overflows.
> +
> +inline void
> +frange_nextafter (enum machine_mode mode,
> +   REAL_VALUE_TYPE ,
> +   const REAL_VALUE_TYPE )
> +{
> +  const real_format *fmt = REAL_MODE_FORMAT (mode);
> +  REAL_VALUE_TYPE tmp;
> +  bool overflow = real_nextafter (, fmt, , );
> +  if (overflow)
> +value = inf;
> +  else
> +value = tmp;
> +}
> +
> +// Like real_arithmetic, but round the result to INF 

Re: [PATCH v2] libgcc: Mostly vectorize CIE encoding extraction for FDEs

2022-11-04 Thread Florian Weimer via Gcc-patches
* Jakub Jelinek:

>> +#undef C
>> +
>> +  /* Validate the augmentation length, and return the enconding after
>> + it.  No check for the return address column because it is
>> + byte-encoded with CIE version 1.  */
>> +  if (__builtin_expect ((value & mask) == expected
>> +&& (cie->augmentation[8] & 0x80) == 0, 1))
>> +  return cie->augmentation[9];
>
> And the above line is indented too much, should be just tab.
>
> But more importantly, I don't see how it can work at all correctly.
> For the "zR" case:
>   Version:   1
>   Augmentation:  "zR"
>   Code alignment factor: 1
>   Data alignment factor: -8
>   Return address column: 16
>   Augmentation data: 1b
> I believe the function wants to return 0x1b, we have
> 1 z R 0 c d r l X
> and we want to return the X, which is indeed at >version + 8
> aka cie->augmentation[7].
> But with "zPLR"
>   Version:   1
>   Augmentation:  "zPLR"
>   Code alignment factor: 1
>   Data alignment factor: -8
>   Return address column: 16
>   Augmentation data: 03 00 00 00 00 03 1b
> we have
> 1 z P L R 0 c d r l M N N N N O X 
> and still want to return the X, while you return the M in there.
> How large the N is depends on the M value.  The "P" data
> is  + , "L" takes just 
> and so does "R".
> So, you'd need in addition to your (cie->augmentation[8] & 0x80) == 0
> check (that augmentation data length is single byte uleb128) verify
> that cie->augmentation[9] is DW_EH_PE_udata4, then you can skip
> the 4 bytes after it and the one byte for "L" and return
> cie->augmentation[15];  But you'd need to verify what different
> DW_EH_PE_* values are used in the wild.

Meh, right.  I think what I'm doing is pretty pointless.  We call
extract_cie_info immediately after calling _Unwind_Find_FDE in
uw_frame_state_for.  That already gives us the FDE encoding.  So it
seems to make more sense to do the PC range check in uw_frame_state_for,
and _Unwind_Find_FDE won't need the FDE encoding anymore.

My testing doesn't catch this problem unfortunately.

> BTW, version 1 is there just because binutils emit those,
> if one uses -fno-dwarf2-cfi-asm, there is:
>   Version:   3
>   Augmentation:  "zR"
>   Code alignment factor: 1
>   Data alignment factor: -8
>   Return address column: 16
>   Augmentation data: 03
> and
>   Version:   3
>   Augmentation:  "zPLR"
>   Code alignment factor: 1
>   Data alignment factor: -8
>   Return address column: 16
>   Augmentation data: 03 00 00 00 00 03 03
> instead (so 3 instead of 1, and leb128 RA instead of byte;
> 1 vs. 3 can be handled by mask and checking if top byte of the
> RA isn't set could work too).  One should trie what one gets
> with -fpic/-fpie/-fno-pie on various arches though.
> E.g. doesn't aarch64 use augmentations with B in it?

I haven't seen those, and I also can't find the GCC code to emit it.  I
think it's now handled via aarch64_frob_update_context, not an
augmentation flag.  Perhaps we should remove the 'B' cases.



[PATCH v2] tree-object-size: Support strndup and strdup

2022-11-04 Thread Siddhesh Poyarekar
Use string length of input to strdup to determine the usable size of the
resulting object.  Avoid doing the same for strndup since there's a
chance that the input may be too large, resulting in an unnecessary
overhead or worse, the input may not be NULL terminated, resulting in a
crash where there would otherwise have been none.

gcc/ChangeLog:

* tree-object-size.cc (todo): New variable.
(object_sizes_execute): Use it.
(strdup_object_size): New function.
(call_object_size): Use it.

gcc/testsuite/ChangeLog:

* gcc.dg/builtin-dynamic-object-size-0.c (test_strdup,
test_strndup, test_strdup_min, test_strndup_min): New tests.
(main): Call them.
* gcc.dg/builtin-dynamic-object-size-1.c: Silence overread
warnings.
* gcc.dg/builtin-dynamic-object-size-2.c: Likewise.
* gcc.dg/builtin-dynamic-object-size-3.c: Likewise.
* gcc.dg/builtin-dynamic-object-size-4.c: Likewise.
* gcc.dg/builtin-object-size-1.c: Silence overread warnings.
Declare free, strdup and strndup.
(test11): New test.
(main): Call it.
* gcc.dg/builtin-object-size-2.c: Silence overread warnings.
Declare free, strdup and strndup.
(test9): New test.
(main): Call it.
* gcc.dg/builtin-object-size-3.c: Silence overread warnings.
Declare free, strdup and strndup.
(test11): New test.
(main): Call it.
* gcc.dg/builtin-object-size-4.c: Silence overread warnings.
Declare free, strdup and strndup.
(test9): New test.
(main): Call it.
---
Tested:

- x86_64 bootstrap and testsuite run
- i686 build and testsuite run
- ubsan bootstrap

 .../gcc.dg/builtin-dynamic-object-size-0.c| 43 +
 .../gcc.dg/builtin-dynamic-object-size-1.c|  2 +-
 .../gcc.dg/builtin-dynamic-object-size-2.c|  2 +-
 .../gcc.dg/builtin-dynamic-object-size-3.c|  2 +-
 .../gcc.dg/builtin-dynamic-object-size-4.c|  2 +-
 gcc/testsuite/gcc.dg/builtin-object-size-1.c  | 94 +-
 gcc/testsuite/gcc.dg/builtin-object-size-2.c  | 94 +-
 gcc/testsuite/gcc.dg/builtin-object-size-3.c  | 95 ++-
 gcc/testsuite/gcc.dg/builtin-object-size-4.c  | 94 +-
 gcc/tree-object-size.cc   | 84 +++-
 10 files changed, 502 insertions(+), 10 deletions(-)

diff --git a/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-0.c 
b/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-0.c
index 01a280b2d7b..4f1606a486b 100644
--- a/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-0.c
+++ b/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-0.c
@@ -479,6 +479,40 @@ test_loop (int *obj, size_t sz, size_t start, size_t end, 
int incr)
   return __builtin_dynamic_object_size (ptr, 0);
 }
 
+/* strdup/strndup.  */
+
+size_t
+__attribute__ ((noinline))
+test_strdup (const char *in)
+{
+  char *res = __builtin_strdup (in);
+  return __builtin_dynamic_object_size (res, 0);
+}
+
+size_t
+__attribute__ ((noinline))
+test_strndup (const char *in, size_t bound)
+{
+  char *res = __builtin_strndup (in, bound);
+  return __builtin_dynamic_object_size (res, 0);
+}
+
+size_t
+__attribute__ ((noinline))
+test_strdup_min (const char *in)
+{
+  char *res = __builtin_strdup (in);
+  return __builtin_dynamic_object_size (res, 2);
+}
+
+size_t
+__attribute__ ((noinline))
+test_strndup_min (const char *in, size_t bound)
+{
+  char *res = __builtin_strndup (in, bound);
+  return __builtin_dynamic_object_size (res, 2);
+}
+
 /* Other tests.  */
 
 struct TV4
@@ -651,6 +685,15 @@ main (int argc, char **argv)
   int *t = test_pr105736 ();
   if (__builtin_dynamic_object_size (t, 0) != -1)
 FAIL ();
+  const char *str = "hello world";
+  if (test_strdup (str) != __builtin_strlen (str) + 1)
+FAIL ();
+  if (test_strndup (str, 4) != 5)
+FAIL ();
+  if (test_strdup_min (str) != __builtin_strlen (str) + 1)
+FAIL ();
+  if (test_strndup_min (str, 4) != 1)
+FAIL ();
 
   if (nfails > 0)
 __builtin_abort ();
diff --git a/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-1.c 
b/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-1.c
index 7cc8b1c9488..8f17c8edcaf 100644
--- a/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-1.c
+++ b/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-1.c
@@ -1,5 +1,5 @@
 /* { dg-do run } */
-/* { dg-options "-O2" } */
+/* { dg-options "-O2 -Wno-stringop-overread" } */
 /* { dg-require-effective-target alloca } */
 
 #define __builtin_object_size __builtin_dynamic_object_size
diff --git a/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-2.c 
b/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-2.c
index 267dbf48ca7..3677782ff1c 100644
--- a/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-2.c
+++ b/gcc/testsuite/gcc.dg/builtin-dynamic-object-size-2.c
@@ -1,5 +1,5 @@
 /* { dg-do run } */
-/* { dg-options "-O2" } */
+/* { dg-options "-O2 -Wno-stringop-overread" } */
 /* { 

[PATCH] doc: Document correct -fwide-exec-charset defaults [PR41041]

2022-11-04 Thread Jonathan Wakely via Gcc-patches
OK for trunk and release branches?

-- >8 --

As shown in the PR, the default is not UTF-32 but rather UTF-32BE or
UTF-32LE, avoiding the need for a byte order mark in literals.

gcc/ChangeLog:

PR c/41041
* doc/cppopts.texi: Document -fwide-exec-charset defaults
correctly.
---
 gcc/doc/cppopts.texi | 7 ---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/gcc/doc/cppopts.texi b/gcc/doc/cppopts.texi
index 75c56a368ca..c0a92b37018 100644
--- a/gcc/doc/cppopts.texi
+++ b/gcc/doc/cppopts.texi
@@ -318,9 +318,10 @@ supported by the system's @code{iconv} library routine.
 @opindex fwide-exec-charset
 @cindex character set, wide execution
 Set the wide execution character set, used for wide string and
-character constants.  The default is UTF-32 or UTF-16, whichever
-corresponds to the width of @code{wchar_t}.  As with
-@option{-fexec-charset}, @var{charset} can be any encoding supported
+character constants.  The default is one of UTF-32BE, UTF-32LE, UTF-16BE,
+or UTF-16LE, whichever corresponds to the width of @code{wchar_t} and the
+big-endian or little-endian byte order being used for code generation.  As
+with @option{-fexec-charset}, @var{charset} can be any encoding supported
 by the system's @code{iconv} library routine; however, you will have
 problems with encodings that do not fit exactly in @code{wchar_t}.
 
-- 
2.38.1



Re: [PATCH] cgraph_node: Remove redundant section clearing

2022-11-04 Thread Jan Hubicka via Gcc-patches
> Ok for trunk if testing passes?
> 
> gcc/ChangeLog:
> 
>   * cgraph.cc (cgraph_node::make_local): Remove redundant set_section.
>   * multiple_target.cc (create_dispatcher_calls): Likewise.
OK (not sure how this slipped in)
The code in create_dispatcher_calls is clearly cut of make_local. I
wonder if we should clean up the FIXME :)
thanks!
Honza
> 
> Signed-off-by: Bernhard Reutner-Fischer 
> ---
>  gcc/cgraph.cc  | 1 -
>  gcc/multiple_target.cc | 1 -
>  2 files changed, 2 deletions(-)
> 
> diff --git a/gcc/cgraph.cc b/gcc/cgraph.cc
> index 8d6ed38efa2..36afa6f33f6 100644
> --- a/gcc/cgraph.cc
> +++ b/gcc/cgraph.cc
> @@ -2488,15 +2488,14 @@ cgraph_node::make_local (cgraph_node *node, void *)
>  {
>node->make_decl_local ();
>node->set_section (NULL);
>node->set_comdat_group (NULL);
>node->externally_visible = false;
>node->forced_by_abi = false;
>node->local = true;
> -  node->set_section (NULL);
>node->unique_name = ((node->resolution == LDPR_PREVAILING_DEF_IRONLY
>  || node->resolution == 
> LDPR_PREVAILING_DEF_IRONLY_EXP)
>  && !flag_incremental_link);
>node->resolution = LDPR_PREVAILING_DEF_IRONLY;
>gcc_assert (node->get_availability () == AVAIL_LOCAL);
>  }
>return false;
> diff --git a/gcc/multiple_target.cc b/gcc/multiple_target.cc
> index 3e2d26882c8..67866a7c963 100644
> --- a/gcc/multiple_target.cc
> +++ b/gcc/multiple_target.cc
> @@ -174,15 +174,14 @@ create_dispatcher_calls (struct cgraph_node *node)
>/* FIXME: copy of cgraph_node::make_local that should be cleaned up
>   in next stage1.  */
>node->make_decl_local ();
>node->set_section (NULL);
>node->set_comdat_group (NULL);
>node->externally_visible = false;
>node->forced_by_abi = false;
> -  node->set_section (NULL);
>  
>DECL_ARTIFICIAL (node->decl) = 1;
>node->force_output = true;
>  }
>  }
>  
>  /* Create string with attributes separated by comma.
> -- 
> 2.38.1
> 


Re: GCC 13: OpenMP offloading to Intel MIC has been removed (was: Remove support for Intel MIC offloading)

2022-11-04 Thread Jakub Jelinek via Gcc-patches
On Fri, Nov 04, 2022 at 11:05:13AM +0100, Thomas Schwinge wrote:
> Hi!
> 
> On 2022-10-20T13:34:41+0200, Jakub Jelinek via Gcc-patches 
>  wrote:
> > we'll need to update the offloading wiki
> 
> I'll look into that.  I assume we just remove any "Intel MIC" text,
> unless historically or otherwise still relevant, of course.

Well, e.g. at the start
GCC 5 and later support two offloading configurations:

OpenMP to Intel MIC targets (upcoming Intel Xeon Phi products codenamed 
KNL) as well as MIC emulation on host. 
should be kept, and in the GCC 13 entry say that the support has been
removed.  Or perhaps better split the GCC 5 entry to say that
GCC 5 and later support OpenACC to NVidia PTX and another entry
that GCC 5 to GCC 12 support OpenMP to Intel MIC.

As there is just one wiki for all the GCC versions, I think we
should keep the MIC stuff in there for now but add notes to the various
spots that it isn't there for GCC 13 anymore (repeat the info).
And when GCC 12.5 is released and branch 12 closes we can drop it
except from the first part of the wiki.

Jakub



Re: Remove support for Intel MIC offloading

2022-11-04 Thread Thomas Schwinge
Hi Jakub!

On 2022-11-04T11:30:04+0100, Jakub Jelinek  wrote:
> On Fri, Nov 04, 2022 at 10:54:02AM +0100, Thomas Schwinge wrote:
>> On 2022-10-20T22:56:57+0200, I wrote:
>> > Hi Jakub, Tobias!
>> >
>> > On 2022-10-20T13:15:43+0200, I wrote:
>> >> I'm proposing the attached "Remove support for Intel MIC offloading"
>> >
>> > Can you please confirm:
>>
>> Taking your non-response as silent approval, I've now pushed to master
>
> I have responded in
> https://gcc.gnu.org/pipermail/gcc-patches/2022-October/603988.html

That's correct, but later I sent this other email where I asked "Can you
please confirm: [...]", which had not gotten a response.  (..., but I
convinced myself that my thinking was correct, so I now did proceed
understanding "non-response as silent approval".)


Grüße
 Thomas
-
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


Re: Remove support for Intel MIC offloading

2022-11-04 Thread Jakub Jelinek via Gcc-patches
On Fri, Nov 04, 2022 at 10:54:02AM +0100, Thomas Schwinge wrote:
> Hi!
> 
> On 2022-10-20T22:56:57+0200, I wrote:
> > Hi Jakub, Tobias!
> >
> > On 2022-10-20T13:15:43+0200, I wrote:
> >> I'm proposing the attached "Remove support for Intel MIC offloading"
> >
> > Can you please confirm:
> 
> Taking your non-response as silent approval, I've now pushed to master

I have responded in
https://gcc.gnu.org/pipermail/gcc-patches/2022-October/603988.html

> branch commit e4cba49413ca429dc82f6aa2e88129ecb3fdd943
> "Remove support for Intel MIC offloading", see attached (generated with
> 'git format-patch --irreversible-delete', 'xz -9').

Jakub



Re: [PATCH v2] libgcc: Mostly vectorize CIE encoding extraction for FDEs

2022-11-04 Thread Jakub Jelinek via Gcc-patches
On Fri, Nov 04, 2022 at 10:37:56AM +0100, Florian Weimer via Gcc-patches wrote:
> "zR" and "zPLR" are the most common augmentations.  Use a simple
> SIMD-with-in-a-register technique to check for both augmentations,
> and that the following variable-length integers have length 1, to
> get more quickly at the encoding field.
> 
> libgcc/
> 
>   * unwind-dw2-fde.c (get_cie_encoding_slow): Rename from
>   get_cie_encoding.  Mark as noinline.
>   (get_cie_encoding): Add fast path for "zR" and "zPLR"
>   augmentations.  Call get_cie_encoding_slow as a fall-back.
> 
> ---
> v2: Use memcpy to avoid a potential aliasing violation.
> 
>  libgcc/unwind-dw2-fde.c | 62 
> +++--
>  1 file changed, 60 insertions(+), 2 deletions(-)
> 
> diff --git a/libgcc/unwind-dw2-fde.c b/libgcc/unwind-dw2-fde.c
> index 3c0cc654ec0..21eee77882e 100644
> --- a/libgcc/unwind-dw2-fde.c
> +++ b/libgcc/unwind-dw2-fde.c
> @@ -333,8 +333,10 @@ base_from_object (unsigned char encoding, const struct 
> object *ob)
>  /* Return the FDE pointer encoding from the CIE.  */
>  /* ??? This is a subset of extract_cie_info from unwind-dw2.c.  */
>  
> -static int
> -get_cie_encoding (const struct dwarf_cie *cie)
> +/* Disable inlining because the function is only used as a slow path in
> +   get_cie_encoding below.  */
> +static int __attribute__ ((noinline))
> +get_cie_encoding_slow (const struct dwarf_cie *cie)
>  {
>const unsigned char *aug, *p;
>_Unwind_Ptr dummy;
> @@ -389,6 +391,62 @@ get_cie_encoding (const struct dwarf_cie *cie)
>  }
>  }
>  
> +static inline int
> +get_cie_encoding (const struct dwarf_cie *cie)
> +{
> +  /* Fast path for some augmentations and single-byte variable-length
> + integers.  Do this only for targets that align struct dwarf_cie to 8
> + bytes, which ensures that at least 8 bytes are available starting at
> + cie->version.  */
> +#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ \
> +  || __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
> +  if (__alignof (*cie) == 8 && sizeof (unsigned long long) == 8)
> +{
> +  unsigned long long value;
> +  memcpy (, >version, sizeof (value));
> +
> +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
> +#define C(x) __builtin_bswap64 (x)
> +#else
> +#define C(x) x
> +#endif
> +
> +  /* Fast path for "zR".  Check for version 1, the "zR" string and that
> +  the sleb128/uleb128 values are single bytes.  In the comments
> +  below, '1', 'c', 'd', 'r', 'l' are version, code alignment, data
> +  alignment, return address column, augmentation length.  Note that
> +  with CIE version 1, the return address column is byte-encoded.  */
> +  unsigned long long expected =
> + /*   1 z R 0 c d r l.  */
> + C (0x017a5200ULL);
> +  unsigned long long mask =
> + /*   1 z R 0 c d r l.  */
> + C (0x80800080ULL);
> +
> +  if ((value & mask) == expected)
> + return cie->augmentation[7];
> +
> +  /* Fast path for "zPLR".  */
> +  expected =
> + /*   1 z P L R 0 c d.  */
> + C (0x017a504c5200ULL);
> +  mask =
> + /*   1 z P L R 0 c d.  */
> + C (0x8080ULL);

The formatting is all wrong, = should go before C, not at the end of lines.

> +#undef C
> +
> +  /* Validate the augmentation length, and return the enconding after
> +  it.  No check for the return address column because it is
> +  byte-encoded with CIE version 1.  */
> +  if (__builtin_expect ((value & mask) == expected
> + && (cie->augmentation[8] & 0x80) == 0, 1))
> +   return cie->augmentation[9];

And the above line is indented too much, should be just tab.

But more importantly, I don't see how it can work at all correctly.
For the "zR" case:
  Version:   1
  Augmentation:  "zR"
  Code alignment factor: 1
  Data alignment factor: -8
  Return address column: 16
  Augmentation data: 1b
I believe the function wants to return 0x1b, we have
1 z R 0 c d r l X
and we want to return the X, which is indeed at >version + 8
aka cie->augmentation[7].
But with "zPLR"
  Version:   1
  Augmentation:  "zPLR"
  Code alignment factor: 1
  Data alignment factor: -8
  Return address column: 16
  Augmentation data: 03 00 00 00 00 03 1b
we have
1 z P L R 0 c d r l M N N N N O X 
and still want to return the X, while you return the M in there.
How large the N is depends on the M value.  The "P" data
is  + , "L" takes just 
and so does "R".
So, you'd need in addition to your (cie->augmentation[8] & 0x80) == 0
check (that augmentation data length is single byte uleb128) verify
that cie->augmentation[9] is DW_EH_PE_udata4, then you can skip
the 4 bytes after it and the one byte for "L" and return
cie->augmentation[15];  But you'd need to verify what different
DW_EH_PE_* values are used in the wild.

BTW, version 1 is there just because binutils emit those,
if one uses -fno-dwarf2-cfi-asm, 

[PATCH][committed] aarch64: Fix typo in aarch64-sve.md comment

2022-11-04 Thread Kyrylo Tkachov via Gcc-patches
Pushing as obvious.
Thanks,
Kyrill

gcc/ChangeLog:

* config/aarch64/aarch64-sve2.md: Fix typo in Cryptographic extensions
comment.


typo.patch
Description: typo.patch


GCC 13: OpenMP offloading to Intel MIC has been removed (was: Remove support for Intel MIC offloading)

2022-11-04 Thread Thomas Schwinge
Hi!

On 2022-10-20T13:34:41+0200, Jakub Jelinek via Gcc-patches 
 wrote:
> we'll need to update the offloading wiki

I'll look into that.  I assume we just remove any "Intel MIC" text,
unless historically or otherwise still relevant, of course.

Likewise I'll look through open PRs to see if any can be closed now.

And, I've pushed to wwwdocs master branch
commit c59054dae1319cd21e8198733a63d60111681d1b
"GCC 13: OpenMP offloading to Intel MIC has been removed", see attached,
borrowing both the position in the notes and wording from the GCC 12
deprecation.


Now, looking forward to the day when someone introduces support for (new)
Intel GPU offloading!  (See initial/inconclusive discussion in thread at

"GCC/OpenMP offloading for Intel GPUs?".


Grüße
 Thomas


-
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
>From c59054dae1319cd21e8198733a63d60111681d1b Mon Sep 17 00:00:00 2001
From: Thomas Schwinge 
Date: Fri, 4 Nov 2022 10:18:38 +0100
Subject: [PATCH] GCC 13: OpenMP offloading to Intel MIC has been removed

---
 htdocs/gcc-13/changes.html | 1 +
 1 file changed, 1 insertion(+)

diff --git a/htdocs/gcc-13/changes.html b/htdocs/gcc-13/changes.html
index f5fa97e5..8b4bf7f3 100644
--- a/htdocs/gcc-13/changes.html
+++ b/htdocs/gcc-13/changes.html
@@ -28,6 +28,7 @@ a work-in-progress.
 
 Caveats
 
+OpenMP offloading to Intel MIC has been removed.
 The support for the cr16-elf, tilegx*-linux, tilepro*-linux,
   hppa[12]*-*-hpux10*, hppa[12]*-*-hpux11*
   and m32c-rtems configurations has been removed.
-- 
2.35.1



Remove support for Intel MIC offloading

2022-11-04 Thread Thomas Schwinge
Hi!

On 2022-10-20T22:56:57+0200, I wrote:
> Hi Jakub, Tobias!
>
> On 2022-10-20T13:15:43+0200, I wrote:
>> I'm proposing the attached "Remove support for Intel MIC offloading"
>
> Can you please confirm:

Taking your non-response as silent approval, I've now pushed to master
branch commit e4cba49413ca429dc82f6aa2e88129ecb3fdd943
"Remove support for Intel MIC offloading", see attached (generated with
'git format-patch --irreversible-delete', 'xz -9').


Grüße
 Thomas


>> --- a/gcc/config/i386/i386-options.cc
>> +++ b/gcc/config/i386/i386-options.cc
>> @@ -307,10 +307,6 @@ ix86_omp_device_kind_arch_isa (enum 
>> omp_device_kind_arch_isa trait,
>>  case omp_device_kind:
>>return strcmp (name, "cpu") == 0;
>>  case omp_device_arch:
>> -#ifdef ACCEL_COMPILER
>> -  if (strcmp (name, "intel_mic") == 0)
>> - return 1;
>> -#endif
>>if (strcmp (name, "x86") == 0)
>>   return 1;
>>if (TARGET_64BIT)
>
> Only remove this bit as quoted, or actually remove the whole function
> (used for 'gcc/config/i386/i386.cc:TARGET_OMP_DEVICE_KIND_ARCH_ISA')?
> But if I do the latter, I get a few FAILs in compiler-side
> '[...]/gomp/declare-variant-[...]' test cases, and
> 'libgomp.c/declare-variant-1.c'.
>
> You, Jakub, had originally added that in
> Subversion r277662 (Git commit 9ba66bf5b9c69e0e2bcd1b2ab88160bf9b2aa417)
> "targetm.omp.device_kind_arch_isa and OpenMP declare variant kind/arch/isa 
> handling".
> Reading these emails, and the discussion in
> 
> "[OpenMP] Context selectors missing for PowerPC", I infer that we
> generally would like to keep this stuff, for non-offloading OpenMP use,
> and thus indeed just remove the Intel MIC parts (as quoted above).
>
> Thus:
>
>> --- a/libgomp/libgomp.texi
>> +++ b/libgomp/libgomp.texi
>> @@ -4303,10 +4303,6 @@ offloading devices (it's not clear if they should be):
>>
>>  @multitable @columnfractions .60 .10 .25
>>  @headitem @code{arch} @tab @code{kind} @tab @code{isa}
>> -@item @code{intel_mic}, @code{x86}, @code{x86_64}, @code{i386}, @code{i486},
>> -  @code{i586}, @code{i686}, @code{ia32}
>> -  @tab @code{host}
>> -  @tab See @code{-m...} flags in ``x86 Options'' (without @code{-m})
>>  @item @code{amdgcn}, @code{gcn}
>>@tab @code{gpu}
>>@tab See @code{-march=} in ``AMD GCN Options''
>
> ..., I should also restore this, and only remove the Intel MIC mention.
>
> On the other hand:
>
>> diff --git a/gcc/config/i386/t-omp-device b/gcc/config/i386/t-omp-device
>> deleted file mode 100644
> | index cfb41ed71ce..000
> | --- gcc/config/i386/t-omp-device
> | +++ /dev/null
> | @@ -1,6 +0,0 @@
> | -omp-device-properties-i386: $(srcdir)/config/i386/i386-options.cc
> | - echo kind: cpu > $@
> | - echo arch: intel_mic x86 x86_64 i386 i486 i586 i686 ia32 >> $@
> | - echo isa: sse4 `sed -n '/^static struct ix86_target_opts 
> isa2\?_opts\[\] =/,/^};/p' \
> | -   $(srcdir)/config/i386/i386-options.cc | \
> | -   sed -n 's/",.*$$//;s/^  { "-m//p'` >> $@
>
> Indeed remove this whole file, or just Intel MIC, again?  Here, as I
> understand, this is fine to remove completely, as is only used if there
> is an actual offload compiler (which now there isn't anymore); unused as
> of here:
>
>> --- a/gcc/configure.ac
>> +++ b/gcc/configure.ac
>
>> @@ -1153,10 +1147,6 @@ for tgt in `echo $enable_offload_targets | sed 's/,/ 
>> /g'`; do
>>
>>enable_offloading=1
>>case "$tgt" in
>> -*-intelmic-* | *-intelmicemul-*)
>> - omp_device_property=omp-device-properties-i386
>> - omp_device_property_tmake_file="${omp_device_property_tmake_file} 
>> \$(srcdir)/config/i386/t-omp-device"
>> - ;;
>>  amdgcn*)
>>   omp_device_property=omp-device-properties-gcn
>>   omp_device_property_tmake_file="${omp_device_property_tmake_file} 
>> \$(srcdir)/config/gcn/t-omp-device"
>
> So I assume that is OK the way I had it prepared.
>
>
> Grüße
>  Thomas


-
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


0001-Remove-support-for-Intel-MIC-offloading.patch.xz
Description: application/xz


Re: [PATCH, v2] Fortran: ordering of hidden procedure arguments [PR107441]

2022-11-04 Thread Mikael Morin

Le 03/11/2022 à 23:03, Harald Anlauf a écrit :

Am 03.11.22 um 11:06 schrieb Mikael Morin:

Le 02/11/2022 à 22:19, Harald Anlauf via Fortran a écrit :

I do see what needs to be done in gfc_get_function_type, which seems
in fact very simple.  But I get really lost in create_function_arglist
when trying to get the typelist right.

One thing is I really don't understand how the (hidden_)typelist is
managed here.  How does that macro TREE_CHAIN work?  Can we somehow
chain two typelists the same way we chain arguments?


TREE_CHAIN is just a linked list "next" pointer like there is in the
fortran frontend a "next" pointer in gfc_ref or gfc_actual_arglist
structures.
Yes, we can chain typelists; the implementation of chainon in tree.cc is
just TREE_CHAIN appending under the hood.


(Failing that, I tried to split the loop over the dummy arguments in
create_function_arglist into two passes, one for the optional+value
variant, and one for the rest.  It turned out to be a bad idea...)


Not necessarily a bad idea, but one has to be careful to keep linked
lists synchronized with argument walking.

The most simple, I think, is to move the hidden_typelist advancement for
optional, value presence arguments from the main loop to a preliminary
loop.

I hope it helps.



I've spent some time not only staring at create_function_arglist,
but trying several variations handling the declared hidden parms,
and applying the necessary adjustments to gfc_get_function_type.
(Managing linked trees is not the issue, just understanding them.)
I've been unable to get the declarations in sync, and would need
help how to debug the mess I've created.  Dropping my patch for
the time being.


If you want, we can meet on IRC somewhen (tonight?).


Update Affiliation.

2022-11-04 Thread Ramana Radhakrishnan via Gcc-patches
Update affiliation as I'm moving on from Arm. More from me in a month or so.

Pushed to trunk

regards
Ramana
commit 4e5f373406ed5da42c4a7c4b7f650d92195f2984
Author: Ramana Radhakrishnan 
Date:   Fri Nov 4 09:30:00 2022 +

Update affiliation

diff --git a/htdocs/steering.html b/htdocs/steering.html
index 3a38346d..95d6a4a8 100644
--- a/htdocs/steering.html
+++ b/htdocs/steering.html
@@ -38,7 +38,7 @@ place to reach them is the gcc mailing 
list.
 Toon Moene (Koninklijk Nederlands Meteorologisch Instituut)
 Joseph Myers (CodeSourcery / Mentor Graphics) [co-Release Manager]
 Gerald Pfeifer (SUSE)
-Ramana Radhakrishnan (ARM)
+Ramana Radhakrishnan 
 Joel Sherrill (OAR Corporation)
 Ian Lance Taylor (Google)
 Jim Wilson (SiFive)


Re: [PATCH] Fix recent thinko in operand_equal_p

2022-11-04 Thread Richard Biener via Gcc-patches



> Am 04.11.2022 um 10:29 schrieb Eric Botcazou via Gcc-patches 
> :
> 
> Hi,
> 
> there is a thinko in the recent improvement by Jan:
> 
> 2020-11-19  Jan Hubicka  
> 
>* fold-const.c (operand_compare::operand_equal_p): Fix thinko in
>COMPONENT_REF handling and guard types_same_for_odr by
>virtual_method_call_p.
>(operand_compare::hash_operand): Likewise.
> 
> where the code just looks at operand 2 of COMPONENT_REF, if it is present, to 
> compare addresses.  That's wrong because operand 2 contains the number of 
> DECL_OFFSET_ALIGN-bit-sized words so, when DECL_OFFSET_ALIGN > 8, not all the 
> bytes are included and some of them are in DECL_FIELD_BIT_OFFSET instead, see 
> get_inner_reference for the model computation.
> 
> In other words, you would need to compare operand 2 and DECL_OFFSET_ALIGN and 
> DECL_FIELD_BIT_OFFSET in this situation, but I'm not sure this is worth the 
> hassle in practice so the attached fix just removes this alternate handling.

> Tested on x86-64/Linux, OK for mainline, 12 and 11 branches?

Ok.

Thanks,
Richard 

> 
> 2022-11-04  Eric Botcazou  
> 
>* fold-const.cc (operand_compare::operand_equal_p) :
>Do not take into account operand 2.
>(operand_compare::hash_operand) : Likewise.
> 
> 
> 2022-11-04  Eric Botcazou  
> 
>* gnat.dg/opt99.adb: New test.
>* gnat.dg/opt99_pkg1.ads, gnat.dg/opt99_pkg1.adb: New helper.
>* gnat.dg/opt99_pkg2.ads: Likewise.
> 
> -- 
> Eric Botcazou
> 
> 
> 
> 
> 


[PATCH v2] libgcc: Mostly vectorize CIE encoding extraction for FDEs

2022-11-04 Thread Florian Weimer via Gcc-patches
"zR" and "zPLR" are the most common augmentations.  Use a simple
SIMD-with-in-a-register technique to check for both augmentations,
and that the following variable-length integers have length 1, to
get more quickly at the encoding field.

libgcc/

* unwind-dw2-fde.c (get_cie_encoding_slow): Rename from
get_cie_encoding.  Mark as noinline.
(get_cie_encoding): Add fast path for "zR" and "zPLR"
augmentations.  Call get_cie_encoding_slow as a fall-back.

---
v2: Use memcpy to avoid a potential aliasing violation.

 libgcc/unwind-dw2-fde.c | 62 +++--
 1 file changed, 60 insertions(+), 2 deletions(-)

diff --git a/libgcc/unwind-dw2-fde.c b/libgcc/unwind-dw2-fde.c
index 3c0cc654ec0..21eee77882e 100644
--- a/libgcc/unwind-dw2-fde.c
+++ b/libgcc/unwind-dw2-fde.c
@@ -333,8 +333,10 @@ base_from_object (unsigned char encoding, const struct 
object *ob)
 /* Return the FDE pointer encoding from the CIE.  */
 /* ??? This is a subset of extract_cie_info from unwind-dw2.c.  */
 
-static int
-get_cie_encoding (const struct dwarf_cie *cie)
+/* Disable inlining because the function is only used as a slow path in
+   get_cie_encoding below.  */
+static int __attribute__ ((noinline))
+get_cie_encoding_slow (const struct dwarf_cie *cie)
 {
   const unsigned char *aug, *p;
   _Unwind_Ptr dummy;
@@ -389,6 +391,62 @@ get_cie_encoding (const struct dwarf_cie *cie)
 }
 }
 
+static inline int
+get_cie_encoding (const struct dwarf_cie *cie)
+{
+  /* Fast path for some augmentations and single-byte variable-length
+ integers.  Do this only for targets that align struct dwarf_cie to 8
+ bytes, which ensures that at least 8 bytes are available starting at
+ cie->version.  */
+#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ \
+  || __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+  if (__alignof (*cie) == 8 && sizeof (unsigned long long) == 8)
+{
+  unsigned long long value;
+  memcpy (, >version, sizeof (value));
+
+#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+#define C(x) __builtin_bswap64 (x)
+#else
+#define C(x) x
+#endif
+
+  /* Fast path for "zR".  Check for version 1, the "zR" string and that
+the sleb128/uleb128 values are single bytes.  In the comments
+below, '1', 'c', 'd', 'r', 'l' are version, code alignment, data
+alignment, return address column, augmentation length.  Note that
+with CIE version 1, the return address column is byte-encoded.  */
+  unsigned long long expected =
+   /*   1 z R 0 c d r l.  */
+   C (0x017a5200ULL);
+  unsigned long long mask =
+   /*   1 z R 0 c d r l.  */
+   C (0x80800080ULL);
+
+  if ((value & mask) == expected)
+   return cie->augmentation[7];
+
+  /* Fast path for "zPLR".  */
+  expected =
+   /*   1 z P L R 0 c d.  */
+   C (0x017a504c5200ULL);
+  mask =
+   /*   1 z P L R 0 c d.  */
+   C (0x8080ULL);
+#undef C
+
+  /* Validate the augmentation length, and return the enconding after
+it.  No check for the return address column because it is
+byte-encoded with CIE version 1.  */
+  if (__builtin_expect ((value & mask) == expected
+   && (cie->augmentation[8] & 0x80) == 0, 1))
+ return cie->augmentation[9];
+}
+#endif
+
+  return get_cie_encoding_slow (cie);
+}
+
 static inline int
 get_fde_encoding (const struct dwarf_fde *f)
 {

base-commit: e724b0480bfa5ec04f39be8c7290330b495c59de



Re: [PATCH 1/3] STABS: remove -gstabs and -gxcoff functionality

2022-11-04 Thread Thomas Schwinge
Hi!

On 2022-09-01T12:05:23+0200, Martin Liška  wrote:
> gcc/ChangeLog:

> --- a/gcc/system.h
> +++ b/gcc/system.h
> @@ -1009,8 +1009,7 @@ extern void fancy_abort (const char *, int, const char 
> *)
>   ASM_OUTPUT_DEFINE_LABEL_DIFFERENCE_SYMBOL HOST_WORDS_BIG_ENDIAN\
>   OBJC_PROLOGUE ALLOCATE_TRAMPOLINE HANDLE_PRAGMA ROUND_TYPE_SIZE\
>   ROUND_TYPE_SIZE_UNIT CONST_SECTION_ASM_OP CRT_GET_RFIB_TEXT\
> - DBX_LBRAC_FIRST DBX_OUTPUT_ENUM DBX_OUTPUT_SOURCE_FILENAME \
> - DBX_WORKING_DIRECTORY INSN_CACHE_DEPTH INSN_CACHE_SIZE \
> + INSN_CACHE_DEPTH INSN_CACHE_SIZE   \
>   INSN_CACHE_LINE_WIDTH INIT_SECTION_PREAMBLE NEED_ATEXIT ON_EXIT\
>   EXIT_BODY OBJECT_FORMAT_ROSE MULTIBYTE_CHARS MAP_CHARACTER \
>   LIBGCC_NEEDS_DOUBLE FINAL_PRESCAN_LABEL DEFAULT_CALLER_SAVES   \
> @@ -1023,15 +1022,14 @@ extern void fancy_abort (const char *, int, const 
> char *)
>   MAX_WCHAR_TYPE_SIZE SHARED_SECTION_ASM_OP INTEGRATE_THRESHOLD  \
>   FINAL_REG_PARM_STACK_SPACE MAYBE_REG_PARM_STACK_SPACE  \
>   TRADITIONAL_PIPELINE_INTERFACE DFA_PIPELINE_INTERFACE  \
> - DBX_OUTPUT_STANDARD_TYPES BUILTIN_SETJMP_FRAME_VALUE   \
> + BUILTIN_SETJMP_FRAME_VALUE \
>   SUNOS4_SHARED_LIBRARIES PROMOTE_FOR_CALL_ONLY  \
>   SPACE_AFTER_L_OPTION NO_RECURSIVE_FUNCTION_CSE \
>   DEFAULT_MAIN_RETURN TARGET_MEM_FUNCTIONS EXPAND_BUILTIN_VA_ARG \
>   COLLECT_PARSE_FLAG DWARF2_GENERATE_TEXT_SECTION_LABEL WINNING_GDB  \
>   ASM_OUTPUT_FILENAME ASM_OUTPUT_SOURCE_LINE FILE_NAME_JOINER\
> - GDB_INV_REF_REGPARM_STABS_LETTER DBX_MEMPARM_STABS_LETTER  \
> - PUT_SDB_SRC_FILE STABS_GCC_MARKER DBX_OUTPUT_FUNCTION_END  \
> - DBX_OUTPUT_GCC_MARKER DBX_FINISH_SYMBOL SDB_GENERATE_FAKE  \
> + GDB_INV_REF_REGPARM_STABS_LETTER   \
> + PUT_SDB_SRC_FILE STABS_GCC_MARKER SDB_GENERATE_FAKE\
>   NON_SAVING_SETJMP TARGET_LATE_RTL_PROLOGUE_EPILOGUE\
>   CASE_DROPS_THROUGH TARGET_BELL TARGET_BS TARGET_CR TARGET_DIGIT0   \
>  TARGET_ESC TARGET_FF TARGET_NEWLINE TARGET_TAB TARGET_VT\
> @@ -1056,8 +1054,8 @@ extern void fancy_abort (const char *, int, const char 
> *)
>   PREFERRED_OUTPUT_RELOAD_CLASS SYSTEM_INCLUDE_DIR   \
>   STANDARD_INCLUDE_DIR STANDARD_INCLUDE_COMPONENT\
>   LINK_ELIMINATE_DUPLICATE_LDIRECTORIES MIPS_DEBUGGING_INFO  \
> - IDENT_ASM_OP ALL_COP_ADDITIONAL_REGISTER_NAMES DBX_OUTPUT_LBRAC\
> - DBX_OUTPUT_NFUN DBX_OUTPUT_RBRAC RANGE_TEST_NON_SHORT_CIRCUIT  \
> + IDENT_ASM_OP ALL_COP_ADDITIONAL_REGISTER_NAMES \
> + RANGE_TEST_NON_SHORT_CIRCUIT   \
>   REAL_VALUE_TRUNCATE REVERSE_CONDEXEC_PREDICATES_P  \
>   TARGET_ALIGN_ANON_BITFIELDS TARGET_NARROW_VOLATILE_BITFIELDS   \
>   IDENT_ASM_OP UNALIGNED_SHORT_ASM_OP UNALIGNED_INT_ASM_OP   \

These changes are part of
commit r13-2361-g7e0db0cdf01e9c885a29cb37415f5bc00d90c029
"STABS: remove -gstabs and -gxcoff functionality".  What this does is
remove these identifiers from "poisoning":

/* As the last action in this file, we poison the identifiers that
   shouldn't be used.
[...]
/* Other obsolete target macros, or macros that used to be in target
   headers and were not used, and may be obsolete or may never have
   been used.  */
 #pragma GCC poison [...]

Shouldn't these identifiers actually stay (so that any accidental future
use gets flagged, as I understand this machinery), and instead more
identifiers be added potentially: those where their definition/use got
removed with "STABS: remove -gstabs and -gxcoff functionality"?  (I've
not checked.)


Grüße
 Thomas
-
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


[PATCH] Fix recent thinko in operand_equal_p

2022-11-04 Thread Eric Botcazou via Gcc-patches
Hi,

there is a thinko in the recent improvement by Jan:

2020-11-19  Jan Hubicka  

* fold-const.c (operand_compare::operand_equal_p): Fix thinko in
COMPONENT_REF handling and guard types_same_for_odr by
virtual_method_call_p.
(operand_compare::hash_operand): Likewise.

where the code just looks at operand 2 of COMPONENT_REF, if it is present, to 
compare addresses.  That's wrong because operand 2 contains the number of 
DECL_OFFSET_ALIGN-bit-sized words so, when DECL_OFFSET_ALIGN > 8, not all the 
bytes are included and some of them are in DECL_FIELD_BIT_OFFSET instead, see 
get_inner_reference for the model computation.

In other words, you would need to compare operand 2 and DECL_OFFSET_ALIGN and 
DECL_FIELD_BIT_OFFSET in this situation, but I'm not sure this is worth the 
hassle in practice so the attached fix just removes this alternate handling.

Tested on x86-64/Linux, OK for mainline, 12 and 11 branches?


2022-11-04  Eric Botcazou  

* fold-const.cc (operand_compare::operand_equal_p) :
Do not take into account operand 2.
(operand_compare::hash_operand) : Likewise.


2022-11-04  Eric Botcazou  

* gnat.dg/opt99.adb: New test.
* gnat.dg/opt99_pkg1.ads, gnat.dg/opt99_pkg1.adb: New helper.
* gnat.dg/opt99_pkg2.ads: Likewise.

-- 
Eric Botcazoudiff --git a/gcc/fold-const.cc b/gcc/fold-const.cc
index 9f7beae14e5..e7a9d5215a5 100644
--- a/gcc/fold-const.cc
+++ b/gcc/fold-const.cc
@@ -3351,9 +3351,6 @@ operand_compare::operand_equal_p (const_tree arg0, const_tree arg1,
 		if (compare_address
 		&& (flags & OEP_ADDRESS_OF_SAME_FIELD) == 0)
 		  {
-		if (TREE_OPERAND (arg0, 2)
-			|| TREE_OPERAND (arg1, 2))
-		  return OP_SAME_WITH_NULL (2);
 		tree field0 = TREE_OPERAND (arg0, 1);
 		tree field1 = TREE_OPERAND (arg1, 1);
 
@@ -3864,17 +3861,10 @@ operand_compare::hash_operand (const_tree t, inchash::hash ,
 	  if (sflags & OEP_ADDRESS_OF)
 		{
 		  hash_operand (TREE_OPERAND (t, 0), hstate, flags);
-		  if (TREE_OPERAND (t, 2))
-		hash_operand (TREE_OPERAND (t, 2), hstate,
-  flags & ~OEP_ADDRESS_OF);
-		  else
-		{
-		  tree field = TREE_OPERAND (t, 1);
-		  hash_operand (DECL_FIELD_OFFSET (field),
-hstate, flags & ~OEP_ADDRESS_OF);
-		  hash_operand (DECL_FIELD_BIT_OFFSET (field),
-hstate, flags & ~OEP_ADDRESS_OF);
-		}
+		  hash_operand (DECL_FIELD_OFFSET (TREE_OPERAND (t, 1)),
+hstate, flags & ~OEP_ADDRESS_OF);
+		  hash_operand (DECL_FIELD_BIT_OFFSET (TREE_OPERAND (t, 1)),
+hstate, flags & ~OEP_ADDRESS_OF);
 		  return;
 		}
 	  break;
-- { dg-do run }
-- { dg-options "-O" }

with Opt99_Pkg1; use Opt99_Pkg1;

procedure Opt99 is
  C : constant My_Character := (D => True, C => ' ');
  D : Derived;

begin
  Set (D, C, C);
  if not D.C2.D then
raise Program_Error;
  end if;
end;
package body Opt99_Pkg1 is

  procedure Set (D: in out Derived; C1, C2 : My_Character) is
  begin
D.I  := 0;
D.C1 := C1;
D.C2 := C2;
  end;

end Opt99_Pkg1;
package Opt99_Pkg2 is

  function Get_Max return Positive is (4);

  C : constant Positive := Get_Max;

  type Arr is array (1 .. C) of Integer;

  type Root is tagged record
Data : Arr;
  end record;

end Opt99_Pkg2;
with Opt99_Pkg2;

package Opt99_Pkg1 is

  type My_Character (D : Boolean := False) is record
case D is
  when False => null;
  when True  => C : Character;
end case;
  end record;

  type Derived is new Opt99_Pkg2.Root with record
I : Integer;
C1, C2 : My_Character;
  end record;

  procedure Set (D: in out Derived; C1, C2 : My_Character);

end Opt99_Pkg1;


[PATCH] testsuite: Add testcase from C++23 P2314R4 - Character sets and encodings

2022-11-04 Thread Jakub Jelinek via Gcc-patches
Hi!

I've read the paper and I believe we just implement it with no changes
needed (at least since PR67224 and similar libcpp changes in GCC 10),
but I could be wrong.

The following patch at least adds a testcase from the start of the paper.

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

Do you agree that we can mark the paper as implemented or do you think
we need to change something (what?)?

2022-11-04  Jakub Jelinek  

* g++.dg/cpp23/charset1.C: New testcase from C++23 P2314R4.

--- gcc/testsuite/g++.dg/cpp23/charset1.C.jj2022-11-03 10:56:48.114588796 
+0100
+++ gcc/testsuite/g++.dg/cpp23/charset1.C   2022-11-03 10:56:39.162711201 
+0100
@@ -0,0 +1,10 @@
+// P2314R4
+// { dg-do compile { target c++23 } }
+// { dg-options "-finput-charset=UTF-8 -fexec-charset=UTF-8" }
+
+#define S(x) # x
+const char s1[] = S(Köppe);   // "Köppe"
+const char s2[] = S(K\u00f6ppe);  // "Köppe"
+
+static_assert (sizeof (s1) == 7);
+static_assert (sizeof (s2) == 7);

Jakub



Better integrate default 'sorry' 'TARGET_ASM_CONSTRUCTOR', 'TARGET_ASM_DESTRUCTOR' (was: Restore default 'sorry' 'TARGET_ASM_CONSTRUCTOR', 'TARGET_ASM_DESTRUCTOR')

2022-11-04 Thread Thomas Schwinge
Hi!

On 2022-10-11T08:40:02+0200, Richard Biener via Gcc-patches 
 wrote:
> On Mon, Oct 10, 2022 at 4:23 PM Tom de Vries  wrote:
>> FWIW, nvptx change looks in the obvious category to me.

I hadn't put you on CC for approval of the one-line '#include' change,
but rather to inform you about the GCC/nvptx breakage generally.  ;-)


> Can you rename the functions as default_asm_out_* and instead of
> reviving dbxout.cc
> put them into targhooks.cc?

ACK.

Pushed to master branch commit a05d8e1d15ea08526639ba154e59b6822b704f4c
"Better integrate default 'sorry' 'TARGET_ASM_CONSTRUCTOR', 
'TARGET_ASM_DESTRUCTOR'",
see attached.

With that, the actual 'diff' is simply:

 gcc/target-def.h |  4 
 gcc/targhooks.cc | 20 
 gcc/targhooks.h  |  2 ++
 3 files changed, 26 insertions(+)

diff --git gcc/target-def.h gcc/target-def.h
index f81f8fe3bb3..5e5cc3b767e 100644
--- gcc/target-def.h
+++ gcc/target-def.h
@@ -62,6 +62,8 @@
 # else
 #  ifdef TARGET_ASM_NAMED_SECTION
 #   define TARGET_ASM_CONSTRUCTOR default_named_section_asm_out_constructor
+#  else
+#   define TARGET_ASM_CONSTRUCTOR default_asm_out_constructor
 #  endif
 # endif
 #endif
@@ -72,6 +74,8 @@
 # else
 #  ifdef TARGET_ASM_NAMED_SECTION
 #   define TARGET_ASM_DESTRUCTOR default_named_section_asm_out_destructor
+#  else
+#   define TARGET_ASM_DESTRUCTOR default_asm_out_destructor
 #  endif
 # endif
 #endif
diff --git gcc/targhooks.cc gcc/targhooks.cc
index d17d393baed..12a58456b39 100644
--- gcc/targhooks.cc
+++ gcc/targhooks.cc
@@ -1405,6 +1405,26 @@ default_generate_pic_addr_diff_vec (void)
   return flag_pic;
 }

+/* Record an element in the table of global constructors.  SYMBOL is
+   a SYMBOL_REF of the function to be called; PRIORITY is a number
+   between 0 and MAX_INIT_PRIORITY.  */
+
+void
+default_asm_out_constructor (rtx symbol ATTRIBUTE_UNUSED,
+int priority ATTRIBUTE_UNUSED)
+{
+  sorry ("global constructors not supported on this target");
+}
+
+/* Likewise for global destructors.  */
+
+void
+default_asm_out_destructor (rtx symbol ATTRIBUTE_UNUSED,
+   int priority ATTRIBUTE_UNUSED)
+{
+  sorry ("global destructors not supported on this target");
+}
+
 /* By default, do no modification. */
 tree default_mangle_decl_assembler_name (tree decl ATTRIBUTE_UNUSED,
 tree id)
diff --git gcc/targhooks.h gcc/targhooks.h
index ecce55ebe79..a6a423c1abb 100644
--- gcc/targhooks.h
+++ gcc/targhooks.h
@@ -178,6 +178,8 @@ extern void default_target_option_override (void);
 extern void hook_void_bitmap (bitmap);
 extern int default_reloc_rw_mask (void);
 extern bool default_generate_pic_addr_diff_vec (void);
+extern void default_asm_out_constructor (rtx, int);
+extern void default_asm_out_destructor (rtx, int);
 extern tree default_mangle_decl_assembler_name (tree, tree);
 extern tree default_emutls_var_fields (tree, tree *);
 extern tree default_emutls_var_init (tree, tree, tree);


Grüße
 Thomas


-
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
>From a05d8e1d15ea08526639ba154e59b6822b704f4c Mon Sep 17 00:00:00 2001
From: Thomas Schwinge 
Date: Thu, 3 Nov 2022 17:29:13 +0100
Subject: [PATCH] Better integrate default 'sorry' 'TARGET_ASM_CONSTRUCTOR',
 'TARGET_ASM_DESTRUCTOR'

... after commit 4ee35c11fd328728c12f3e086ae016ca94624bf8
"Restore default 'sorry' 'TARGET_ASM_CONSTRUCTOR', 'TARGET_ASM_DESTRUCTOR'".
No functional change.

	gcc/
	* Makefile.in (OBJS): Remove 'dbxout.o'.
	* config/nvptx/nvptx.cc: Don't '#include "dbxout.h"'.
	* dbxout.cc: Remove.
	* dbxout.h: Likewise.
	* target-def.h (TARGET_ASM_CONSTRUCTOR, TARGET_ASM_DESTRUCTOR):
	Default to 'default_asm_out_constructor',
	'default_asm_out_destructor'.
	* targhooks.cc (default_asm_out_constructor)
	(default_asm_out_destructor): New.
	* targhooks.h (default_asm_out_constructor)
	(default_asm_out_destructor): Declare.
---
 gcc/Makefile.in   |  1 -
 gcc/config/nvptx/nvptx.cc |  1 -
 gcc/dbxout.cc | 43 ---
 gcc/dbxout.h  | 25 ---
 gcc/target-def.h  |  4 ++--
 gcc/targhooks.cc  | 20 ++
 gcc/targhooks.h   |  2 ++
 7 files changed, 24 insertions(+), 72 deletions(-)
 delete mode 100644 gcc/dbxout.cc
 delete mode 100644 gcc/dbxout.h

diff --git a/gcc/Makefile.in b/gcc/Makefile.in
index c4072d06a936..f672e6ea5498 100644
--- a/gcc/Makefile.in
+++ b/gcc/Makefile.in
@@ -1355,7 +1355,6 @@ OBJS = \
 	

Re: [PATCH 1/2] gcc/file-prefix-map: Allow remapping of relative paths

2022-11-04 Thread Eric Botcazou via Gcc-patches
> gcc/ChangeLog:
> 
> * file-prefix-map.cc (remap_filename): Allow remapping of relative paths

Small regression in Ada though, probably a missing guard somewhere:

=== gnat tests ===


Running target unix
FAIL: gnat.dg/specs/coverage1.ads (test for excess errors)

In order to reproduce, configure the compiler with Ada enabled, build it, and 
copy $[srcdir)/gcc/testsuite/gnat.dg/specs/coverage1.ads into the build 
directory, then just issue:

gcc/gnat1 -quiet coverage1.ads -ftest-coverage -Igcc/ada/rts

raised STORAGE_ERROR : stack overflow or erroneous memory access

-- 
Eric Botcazou




Re: Restore default 'sorry' 'TARGET_ASM_CONSTRUCTOR', 'TARGET_ASM_DESTRUCTOR' (was: [PATCH 1/3] STABS: remove -gstabs and -gxcoff functionality)

2022-11-04 Thread Thomas Schwinge
Hi!

On 2022-11-04T10:04:59+0100,  wrote:
> On 2022-10-12T11:21:19+0200, Martin Liška  wrote:
>> On 10/10/22 16:19, Thomas Schwinge wrote:
>>> attached
>>> "Restore default 'sorry' 'TARGET_ASM_CONSTRUCTOR', 'TARGET_ASM_DESTRUCTOR'".
>
>> Thanks for the fix, really appreciated!
>
> Pushed to master branch commit 4ee35c11fd328728c12f3e086ae016ca94624bf8
> "Restore default 'sorry' 'TARGET_ASM_CONSTRUCTOR', 'TARGET_ASM_DESTRUCTOR'"

..., see attached now.  ;-)


Grüße
 Thomas


-
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
>From 4ee35c11fd328728c12f3e086ae016ca94624bf8 Mon Sep 17 00:00:00 2001
From: Thomas Schwinge 
Date: Sun, 9 Oct 2022 22:39:02 +0200
Subject: [PATCH] Restore default 'sorry' 'TARGET_ASM_CONSTRUCTOR',
 'TARGET_ASM_DESTRUCTOR'

... that got lost in commit 7e0db0cdf01e9c885a29cb37415f5bc00d90c029
"STABS: remove -gstabs and -gxcoff functionality".

Previously, if a back end was not 'USE_COLLECT2', nor manually defined
'TARGET_ASM_CONSTRUCTOR', 'TARGET_ASM_DESTRUCTOR', or got pointed to the
respective 'default_[...]' functions due to 'CTORS_SECTION_ASM_OP',
'DTORS_SECTION_ASM_OP', or 'TARGET_ASM_NAMED_SECTION', it got pointed to
'default_stabs_asm_out_constructor', 'default_stabs_asm_out_destructor'.
These would emit 'sorry' for any global constructor/destructor they're
run into.

This is now gone, and thus in such a back end configuration case
'TARGET_ASM_CONSTRUCTOR', 'TARGET_ASM_DESTRUCTOR' don't get defined
anymore, and thus the subsequently following:

#if !defined(TARGET_HAVE_CTORS_DTORS)
# if defined(TARGET_ASM_CONSTRUCTOR) && defined(TARGET_ASM_DESTRUCTOR)
# define TARGET_HAVE_CTORS_DTORS true
# endif
#endif

... doesn't define 'TARGET_HAVE_CTORS_DTORS' anymore, and thus per my
understanding, 'gcc/final.cc:rest_of_handle_final':

if (DECL_STATIC_CONSTRUCTOR (current_function_decl)
&& targetm.have_ctors_dtors)
  targetm.asm_out.constructor (XEXP (DECL_RTL (current_function_decl), 0),
   decl_init_priority_lookup
 (current_function_decl));
if (DECL_STATIC_DESTRUCTOR (current_function_decl)
&& targetm.have_ctors_dtors)
  targetm.asm_out.destructor (XEXP (DECL_RTL (current_function_decl), 0),
  decl_fini_priority_lookup
(current_function_decl));

... simply does nothing anymore for a 'DECL_STATIC_CONSTRUCTOR',
'DECL_STATIC_DESTRUCTOR'.

This, effectively, means that GCC/nvptx now suddenly appears to "support"
global constructors/destructors, which means that a ton of test cases now
erroneously PASS that previously used to FAIL:

sorry, unimplemented: global constructors not supported on this target

Of course, such support didn't magically happen due to
"STABS: remove -gstabs and -gxcoff functionality", so this is bad.  And,
corresponding execution testing then regularly FAILs (due to the global
constructor/destructor functions never being invoked), for example:

[-UNSUPPORTED:-]{+PASS:+} gcc.dg/initpri1.c {+(test for excess errors)+}
{+FAIL: gcc.dg/initpri1.c execution test+}

[-UNSUPPORTED:-]{+PASS:+} g++.dg/special/conpr-1.C {+(test for excess errors)+}
{+FAIL: g++.dg/special/conpr-1.C execution test+}

To restore the previous GCC/nvptx behavior, for traceability, this simply
restores the previous code, stripped down to the bare minimum.

	gcc/
	* Makefile.in (OBJS): Add 'dbxout.o'.
	* config/nvptx/nvptx.cc: '#include "dbxout.h"'.
	* dbxout.cc: New.
	* dbxout.h: Likewise.
	* target-def.h (TARGET_ASM_CONSTRUCTOR, TARGET_ASM_DESTRUCTOR):
	Default to 'default_stabs_asm_out_constructor',
	'default_stabs_asm_out_destructor'.
---
 gcc/Makefile.in   |  1 +
 gcc/config/nvptx/nvptx.cc |  1 +
 gcc/dbxout.cc | 43 +++
 gcc/dbxout.h  | 25 +++
 gcc/target-def.h  |  4 
 5 files changed, 74 insertions(+)
 create mode 100644 gcc/dbxout.cc
 create mode 100644 gcc/dbxout.h

diff --git a/gcc/Makefile.in b/gcc/Makefile.in
index f672e6ea5498..c4072d06a936 100644
--- a/gcc/Makefile.in
+++ b/gcc/Makefile.in
@@ -1355,6 +1355,7 @@ OBJS = \
 	data-streamer.o \
 	data-streamer-in.o \
 	data-streamer-out.o \
+	dbxout.o \
 	dbgcnt.o \
 	dce.o \
 	ddg.o \
diff --git a/gcc/config/nvptx/nvptx.cc b/gcc/config/nvptx/nvptx.cc
index 2fe120b38730..4cb5d02d40cd 100644
--- a/gcc/config/nvptx/nvptx.cc
+++ b/gcc/config/nvptx/nvptx.cc
@@ -52,6 +52,7 @@
 #include "tm-preds.h"
 #include "tm-constrs.h"
 #include "langhooks.h"
+#include "dbxout.h"
 #include "cfgrtl.h"
 #include "gimple.h"
 #include "stor-layout.h"
diff --git a/gcc/dbxout.cc b/gcc/dbxout.cc
new file mode 100644
index ..161eeb196537
--- 

Restore default 'sorry' 'TARGET_ASM_CONSTRUCTOR', 'TARGET_ASM_DESTRUCTOR' (was: [PATCH 1/3] STABS: remove -gstabs and -gxcoff functionality)

2022-11-04 Thread Thomas Schwinge
Hi!

On 2022-10-12T11:21:19+0200, Martin Liška  wrote:
> On 10/10/22 16:19, Thomas Schwinge wrote:
>> attached
>> "Restore default 'sorry' 'TARGET_ASM_CONSTRUCTOR', 'TARGET_ASM_DESTRUCTOR'".

> Thanks for the fix, really appreciated!

Pushed to master branch commit 4ee35c11fd328728c12f3e086ae016ca94624bf8
"Restore default 'sorry' 'TARGET_ASM_CONSTRUCTOR', 'TARGET_ASM_DESTRUCTOR'",
see attached.


Grüße
 Thomas
-
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


[PATCH] libcpp: Update to Unicode 15

2022-11-04 Thread Jakub Jelinek via Gcc-patches
Hi!

The following pseudo-patch (for uname2c.h part
just a pseudo patch with a lot of changes replaced with ...
because it is too large but the important changes like
-static const char uname2c_dict[59418] =
+static const char uname2c_dict[59891] =
-static const unsigned char uname2c_tree[208765] = {
+static const unsigned char uname2c_tree[210697] = {
are shown, full patch xz compressed will be posted separately
due to mail limit) regenerates the libcpp tables with Unicode 15.0.0
which added 4489 new characters.

As mentioned previously, this isn't just a matter of running the
two libcpp/make*.cc programs on the new Unicode files, but one needs
to manually update a table inside of makeuname2c.cc according to
a table in Unicode text (which is partially reflected in the text
files, but e.g. in Unicode 14.0.0 not 100% accurately, in 15.0.0
actually accurately).
I've also added some randomly chosen subset of those 4489 new
characters to a testcase.

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

2022-11-04  Jakub Jelinek  

gcc/testsuite/
* c-c++-common/cpp/named-universal-char-escape-1.c: Add tests for some
characters newly added in Unicode 15.0.0.
libcpp/
* makeuname2c.cc (struct generated): Update from Unicode 15.0.0
table 4-8.
* ucnid.h: Regenerated for Unicode 15.0.0.
* uname2c.h: Likewise.

--- gcc/testsuite/c-c++-common/cpp/named-universal-char-escape-1.c.jj   
2022-08-27 23:01:28.319565957 +0200
+++ gcc/testsuite/c-c++-common/cpp/named-universal-char-escape-1.c  
2022-11-04 09:41:45.908527440 +0100
@@ -117,6 +117,27 @@ typedef __CHAR32_TYPE__ char32_t;
 || U'\u0FD0' != U'\N{TIBETAN MARK BSKA- SHOG GI MGO RGYAN}' \
 || U'\uFE18' != U'\N{PRESENTATION FORM FOR VERTICAL RIGHT WHITE LENTICULAR 
BRAKCET}' \
 || U'\uFE18' != U'\N{PRESENTATION FORM FOR VERTICAL RIGHT WHITE LENTICULAR 
BRACKET}' \
+|| U'\u0CF3' != U'\N{KANNADA SIGN COMBINING ANUSVARA ABOVE RIGHT}' \
+|| U'\u0ECE' != U'\N{LAO YAMAKKAN}' \
+|| U'\U00010EFE' != U'\N{ARABIC SMALL LOW WORD QASR}' \
+|| U'\U00011241' != U'\N{KHOJKI VOWEL SIGN VOCALIC R}' \
+|| U'\U00011B06' != U'\N{DEVANAGARI SIGN WESTERN FIVE-LIKE BHALE}' \
+|| U'\U00011F0B' != U'\N{KAWI LETTER VOCALIC RR}' \
+|| U'\U0001342F' != U'\N{EGYPTIAN HIEROGLYPH V011D}' \
+|| U'\U00013451' != U'\N{EGYPTIAN HIEROGLYPH MODIFIER DAMAGED AT START AND 
BOTTOM}' \
+|| U'\U0001B132' != U'\N{HIRAGANA LETTER SMALL KO}' \
+|| U'\U0001B155' != U'\N{KATAKANA LETTER SMALL KO}' \
+|| U'\U0001D2C4' != U'\N{KAKTOVIK NUMERAL FOUR}' \
+|| U'\U0001DF27' != U'\N{LATIN SMALL LETTER N WITH MID-HEIGHT LEFT HOOK}' \
+|| U'\U0001E036' != U'\N{MODIFIER LETTER CYRILLIC SMALL ZHE}' \
+|| U'\U0001E05B' != U'\N{CYRILLIC SUBSCRIPT SMALL LETTER EL}' \
+|| U'\U0001E4E5' != U'\N{NAG MUNDARI LETTER ENN}' \
+|| U'\U0001F6DC' != U'\N{WIRELESS}' \
+|| U'\U0001F77E' != U'\N{QUAOAR}' \
+|| U'\U0001F7D9' != U'\N{NINE POINTED WHITE STAR}' \
+|| U'\U0001FA76' != U'\N{GREY HEART}' \
+|| U'\U0001FA88' != U'\N{FLUTE}' \
+|| U'\U0001FABC' != U'\N{JELLYFISH}' \
 || U'\uAC00' != U'\N{HANGUL SYLLABLE GA}' \
 || U'\uAC02' != U'\N{HANGUL SYLLABLE GAGG}' \
 || U'\uAD8D' != U'\N{HANGUL SYLLABLE GWEONJ}' \
@@ -134,6 +155,7 @@ typedef __CHAR32_TYPE__ char32_t;
 || U'\U0002A6DD' != U'\N{CJK UNIFIED IDEOGRAPH-2A6DD}' \
 || U'\U00020700' != U'\N{CJK UNIFIED IDEOGRAPH-20700}' \
 || U'\U0002B734' != U'\N{CJK UNIFIED IDEOGRAPH-2B734}' \
+|| U'\U0002B739' != U'\N{CJK UNIFIED IDEOGRAPH-2B739}' \
 || U'\U0002B740' != U'\N{CJK UNIFIED IDEOGRAPH-2B740}' \
 || U'\U0002B81D' != U'\N{CJK UNIFIED IDEOGRAPH-2B81D}' \
 || U'\U0002B820' != U'\N{CJK UNIFIED IDEOGRAPH-2B820}' \
@@ -142,6 +164,8 @@ typedef __CHAR32_TYPE__ char32_t;
 || U'\U0002EBE0' != U'\N{CJK UNIFIED IDEOGRAPH-2EBE0}' \
 || U'\U0003' != U'\N{CJK UNIFIED IDEOGRAPH-3}' \
 || U'\U0003134A' != U'\N{CJK UNIFIED IDEOGRAPH-3134A}' \
+|| U'\U00031350' != U'\N{CJK UNIFIED IDEOGRAPH-31350}' \
+|| U'\U000323AF' != U'\N{CJK UNIFIED IDEOGRAPH-323AF}' \
 || U'\U00017000' != U'\N{TANGUT IDEOGRAPH-17000}' \
 || U'\U000187F7' != U'\N{TANGUT IDEOGRAPH-187F7}' \
 || U'\U00018D00' != U'\N{TANGUT IDEOGRAPH-18D00}' \
--- libcpp/makeuname2c.cc.jj2022-08-31 10:22:33.439166029 +0200
+++ libcpp/makeuname2c.cc   2022-11-03 10:38:03.341964913 +0100
@@ -69,7 +69,7 @@ struct entry { const char *name; unsigne
 static struct entry *entries;
 static unsigned long num_allocated, num_entries;
 
-/* Unicode 14 Table 4-8.  */
+/* Unicode 15 Table 4-8.  */
 struct generated {
   const char *prefix;
   /* max_high is a workaround for UnicodeData.txt inconsistencies
@@ -81,13 +81,14 @@ struct generated {
 static struct generated generated_ranges[] =
 { { "HANGUL SYLLABLE ", 0xac00, 0xd7a3, 0, 0, 0 }, /* NR1 rule */
   { "CJK UNIFIED IDEOGRAPH-", 0x3400, 0x4dbf, 0, 1, 0 }, /* NR2 

Re: Extend fold_vec_perm to fold VEC_PERM_EXPR in VLA manner

2022-11-04 Thread Prathamesh Kulkarni via Gcc-patches
On Mon, 31 Oct 2022 at 15:27, Richard Sandiford
 wrote:
>
> Prathamesh Kulkarni  writes:
> > On Wed, 26 Oct 2022 at 21:07, Richard Sandiford
> >  wrote:
> >>
> >> Sorry for the slow response.  I wanted to find some time to think
> >> about this a bit more.
> >>
> >> Prathamesh Kulkarni  writes:
> >> > On Fri, 30 Sept 2022 at 21:38, Richard Sandiford
> >> >  wrote:
> >> >>
> >> >> Richard Sandiford via Gcc-patches  writes:
> >> >> > Prathamesh Kulkarni  writes:
> >> >> >> Sorry to ask a silly question but in which case shall we select 2nd 
> >> >> >> vector ?
> >> >> >> For num_poly_int_coeffs == 2,
> >> >> >> a1 /trunc n1 == (a1 + 0x) / (n1.coeffs[0] + n1.coeffs[1]*x)
> >> >> >> If a1/trunc n1 succeeds,
> >> >> >> 0 / n1.coeffs[1] == a1/n1.coeffs[0] == 0.
> >> >> >> So, a1 has to be < n1.coeffs[0] ?
> >> >> >
> >> >> > Remember that a1 is itself a poly_int.  It's not necessarily a 
> >> >> > constant.
> >> >> >
> >> >> > E.g. the TRN1 .D instruction maps to a VEC_PERM_EXPR with the 
> >> >> > selector:
> >> >> >
> >> >> >   { 0, 2 + 2x, 1, 4 + 2x, 2, 6 + 2x, ... }
> >> >>
> >> >> Sorry, should have been:
> >> >>
> >> >>   { 0, 2 + 2x, 2, 4 + 2x, 4, 6 + 2x, ... }
> >> > Hi Richard,
> >> > Thanks for the clarifications, and sorry for late reply.
> >> > I have attached POC patch that tries to implement the above approach.
> >> > Passes bootstrap+test on x86_64-linux-gnu and aarch64-linux-gnu for VLS 
> >> > vectors.
> >> >
> >> > For VLA vectors, I have only done limited testing so far.
> >> > It seems to pass couple of tests written in the patch for
> >> > nelts_per_pattern == 3,
> >> > and folds the following svld1rq test:
> >> > int32x4_t v = {1, 2, 3, 4};
> >> > return svld1rq_s32 (svptrue_b8 (), [0])
> >> > into:
> >> > return {1, 2, 3, 4, ...};
> >> > I will try to bootstrap+test it on SVE machine to test further for VLA 
> >> > folding.
> >> >
> >> > I have a couple of questions:
> >> > 1] When mask selects elements from same vector but from different 
> >> > patterns:
> >> > For eg:
> >> > arg0 = {1, 11, 2, 12, 3, 13, ...},
> >> > arg1 = {21, 31, 22, 32, 23, 33, ...},
> >> > mask = {0, 0, 0, 1, 0, 2, ... },
> >> > All have npatterns = 2, nelts_per_pattern = 3.
> >> >
> >> > With above mask,
> >> > Pattern {0, ...} selects arg0[0], ie {1, ...}
> >> > Pattern {0, 1, 2, ...} selects arg0[0], arg0[1], arg0[2], ie {1, 11, 2, 
> >> > ...}
> >> > While arg0[0] and arg0[2] belong to same pattern, arg0[1] belongs to 
> >> > different
> >> > pattern in arg0.
> >> > The result is:
> >> > res = {1, 1, 1, 11, 1, 2, ...}
> >> > In this case, res's 2nd pattern {1, 11, 2, ...} is encoded with:
> >> > with a0 = 1, a1 = 11, S = -9.
> >> > Is that expected tho ? It seems to create a new encoding which
> >> > wasn't present in the input vector. For instance, the next elem in
> >> > sequence would be -7,
> >> > which is not present originally in arg0.
> >>
> >> Yeah, you're right, sorry.  Going back to:
> >>
> >> (2) The explicit encoding can be used to produce a sequence of N*Ex*Px
> >> elements for any integer N.  This extended sequence can be reencoded
> >> as having N*Px patterns, with Ex staying the same.
> >>
> >> I guess we need to pick an N for the selector such that each new
> >> selector pattern (each one out of the N*Px patterns) selects from
> >> the *same pattern* of the same data input.
> >>
> >> So if a particular pattern in the selector has a step S, and the data
> >> input it selects from has Pi patterns, N*S must be a multiple of Pi.
> >> N must be a multiple of least_common_multiple(S,Pi)/S.
> >>
> >> I think that means that the total number of patterns in the result
> >> (Pr from previous messages) can safely be:
> >>
> >>   Ps * least_common_multiple(
> >> least_common_multiple(S[1], P[input(1)]) / S[1],
> >> ...
> >> least_common_multiple(S[Ps], P[input(Ps)]) / S[Ps]
> >>   )
> >>
> >> where:
> >>
> >>   Ps = the number of patterns in the selector
> >>   S[I] = the step for selector pattern I (I being 1-based)
> >>   input(I) = the data input selected by selector pattern I (I being 
> >> 1-based)
> >>   P[I] = the number of patterns in data input I
> >>
> >> That's getting quite complicated :-)  If we allow arbitrary P[...]
> >> and S[...] then it could also get large.  Perhaps we should finally
> >> give up on the general case and limit this to power-of-2 patterns and
> >> power-of-2 steps, so that least_common_multiple becomes MAX.  Maybe that
> >> simplifies other things as well.
> >>
> >> What do you think?
> > Hi Richard,
> > Thanks for the suggestions. Yeah I suppose we can initially add support for
> > power-of-2 patterns and power-of-2 steps and try to generalize it in
> > follow up patches if possible.
> >
> > Sorry if this sounds like a silly ques -- if we are going to have
> > pattern in selector, select *same pattern from same input vector*,
> > instead of re-encoding the selector to have N * Ps patterns, would it
> > make sense for elements in selector to denote 

Re: c: tree: target: C2x (...) function prototypes and va_start relaxation

2022-11-04 Thread Eric Botcazou via Gcc-patches
> And also:
> 
> FAIL: gcc.dg/torture/c2x-stdarg-split-1a.c   -O0  execution test
> FAIL: gcc.dg/torture/c2x-stdarg-split-1a.c   -O1  execution test
> FAIL: gcc.dg/torture/c2x-stdarg-split-1a.c   -O2  execution test
> FAIL: gcc.dg/torture/c2x-stdarg-split-1a.c   -O3 -g  execution test
> FAIL: gcc.dg/torture/c2x-stdarg-split-1a.c   -Os  execution test
> FAIL: gcc.dg/torture/c2x-stdarg-split-1a.c   -O2 -flto
> -fno-use-linker-plugin -flto-partition=none  execution test FAIL:
> gcc.dg/torture/c2x-stdarg-split-1a.c   -O2 -flto -fuse-linker-plugin
> -fno-fat-lto-objects  execution test

The implementation does not work on some targets, see PR target/107453.

-- 
Eric Botcazou




[PATCH] Initial Granite Rapids support

2022-11-04 Thread Haochen Jiang via Gcc-patches
From: "Hu, Lin1" 

Hi all,

This patch aimed to add initial Granite Rapids support for GCC.
It needs to be checked in after prefetchit0/t1 patch.

The information for Granite Rapids comes following:
https://www.intel.com/content/www/us/en/develop/download/intel-architecture-instruction-set-extensions-programming-reference.html

Regtested on x86_64-pc-linux-gnu. Ok for trunk?

BRs,
Haochen

gcc/Changelog:

* common/config/i386/cpuinfo.h:
(get_intel_cpu): Handle Granite Rapids.
* common/config/i386/i386-common.cc:
(processor_names): Add graniterapids.
(processor_alias_table): Ditto.
* common/config/i386/i386-cpuinfo.h:
(enum processor_types): Add INTEL_GRANITERAPIDS.
* config.gcc: Add -march=graniterapids.
* config/i386/driver-i386.cc (host_detect_local_cpu):
Handle graniterapids.
* config/i386/i386-c.cc (ix86_target_macros_internal):
Ditto.
* config/i386/i386-options.cc (m_GRANITERAPIDS): New define.
(processor_cost_table): Add graniterapids.
* config/i386/i386.h (enum processor_type):
Add PROCESSOR_GRANITERAPIDS.
(PTA_GRANITERAPIDS): Ditto.
* doc/extend.texi: Add graniterapids.
* doc/invoke.texi: Ditto.

gcc/testsuite/ChangeLog:

* gcc/testsuite/g++.target/i386/mv16.C: Add graniterapids.
* gcc.target/i386/funcspec-56.inc: Handle new march.
---
 gcc/common/config/i386/cpuinfo.h  |  9 +
 gcc/common/config/i386/i386-common.cc |  3 +++
 gcc/common/config/i386/i386-cpuinfo.h |  1 +
 gcc/config.gcc|  2 +-
 gcc/config/i386/driver-i386.cc|  5 -
 gcc/config/i386/i386-c.cc |  7 +++
 gcc/config/i386/i386-options.cc   |  4 +++-
 gcc/config/i386/i386.h|  3 +++
 gcc/doc/extend.texi   |  3 +++
 gcc/doc/invoke.texi   | 11 +++
 gcc/testsuite/g++.target/i386/mv16.C  |  6 ++
 gcc/testsuite/gcc.target/i386/funcspec-56.inc |  1 +
 12 files changed, 52 insertions(+), 3 deletions(-)

diff --git a/gcc/common/config/i386/cpuinfo.h b/gcc/common/config/i386/cpuinfo.h
index ac7761699af..42c25b8a636 100644
--- a/gcc/common/config/i386/cpuinfo.h
+++ b/gcc/common/config/i386/cpuinfo.h
@@ -564,6 +564,15 @@ get_intel_cpu (struct __processor_model *cpu_model,
   CHECK___builtin_cpu_is ("sierraforest");
   cpu_model->__cpu_type = INTEL_SIERRAFOREST;
   break;
+case 0xad:
+case 0xae:
+  /* Granite Rapids.  */
+  cpu = "graniterapids";
+  CHECK___builtin_cpu_is ("corei7");
+  CHECK___builtin_cpu_is ("graniterapids");
+  cpu_model->__cpu_type = INTEL_COREI7;
+  cpu_model->__cpu_subtype = INTEL_COREI7_GRANITERAPIDS;
+  break;
 case 0x17:
 case 0x1d:
   /* Penryn.  */
diff --git a/gcc/common/config/i386/i386-common.cc 
b/gcc/common/config/i386/i386-common.cc
index 9bcae020a00..c828ae5b7d7 100644
--- a/gcc/common/config/i386/i386-common.cc
+++ b/gcc/common/config/i386/i386-common.cc
@@ -1918,6 +1918,7 @@ const char *const processor_names[] =
   "sapphirerapids",
   "alderlake",
   "rocketlake",
+  "graniterapids",
   "intel",
   "lujiazui",
   "geode",
@@ -2037,6 +2038,8 @@ const pta processor_alias_table[] =
 M_CPU_SUBTYPE (INTEL_COREI7_ALDERLAKE), P_PROC_AVX2},
   {"meteorlake", PROCESSOR_ALDERLAKE, CPU_HASWELL, PTA_ALDERLAKE,
 M_CPU_SUBTYPE (INTEL_COREI7_ALDERLAKE), P_PROC_AVX2},
+  {"graniterapids", PROCESSOR_GRANITERAPIDS, CPU_HASWELL, PTA_GRANITERAPIDS,
+M_CPU_SUBTYPE (INTEL_COREI7_GRANITERAPIDS), P_PROC_AVX512F},
   {"bonnell", PROCESSOR_BONNELL, CPU_ATOM, PTA_BONNELL,
 M_CPU_TYPE (INTEL_BONNELL), P_PROC_SSSE3},
   {"atom", PROCESSOR_BONNELL, CPU_ATOM, PTA_BONNELL,
diff --git a/gcc/common/config/i386/i386-cpuinfo.h 
b/gcc/common/config/i386/i386-cpuinfo.h
index 68eda7a8696..c06f089b0c5 100644
--- a/gcc/common/config/i386/i386-cpuinfo.h
+++ b/gcc/common/config/i386/i386-cpuinfo.h
@@ -96,6 +96,7 @@ enum processor_subtypes
   INTEL_COREI7_ROCKETLAKE,
   ZHAOXIN_FAM7H_LUJIAZUI,
   AMDFAM19H_ZNVER4,
+  INTEL_COREI7_GRANITERAPIDS,
   CPU_SUBTYPE_MAX
 };
 
diff --git a/gcc/config.gcc b/gcc/config.gcc
index 5c782b2f298..03c1523f7af 100644
--- a/gcc/config.gcc
+++ b/gcc/config.gcc
@@ -668,7 +668,7 @@ silvermont knl knm skylake-avx512 cannonlake icelake-client 
icelake-server \
 skylake goldmont goldmont-plus tremont cascadelake tigerlake cooperlake \
 sapphirerapids alderlake rocketlake eden-x2 nano nano-1000 nano-2000 nano-3000 
\
 nano-x2 eden-x4 nano-x4 lujiazui x86-64 x86-64-v2 x86-64-v3 x86-64-v4 \
-sierraforest native"
+sierraforest graniterapids native"
 
 # Additional x86 processors supported by --with-cpu=.  Each processor
 # MUST be separated by exactly one space.
diff --git a/gcc/config/i386/driver-i386.cc b/gcc/config/i386/driver-i386.cc
index a265b1c39f9..3117d83de00 100644
--- 

  1   2   >