[PATCH][pushed] contrib: add 'contrib' to default dirs in update-copyright.py

2023-01-05 Thread Martin Liška
Hi.

I forgot to include contrib folder in default dir, thus the copyright in the 
folder
haven't been updated by Jakub.

However, I noticed when I run ./contrib/update-copyright.py --this-year
I get much more modifications out of contrib folder:

$ git diff --stat
...
 951 files changed, 976 insertions(+), 979 deletions(-)

where the are not updated files is:
gcc/analyzer/*
gcc/common/config/*
gcc/m2/*
gcc/objc/*

Jakub, can you please re-run the script?

Cheers,
Martin

contrib/ChangeLog:

* update-copyright.py: Add contrib as a default dir.
---
 contrib/update-copyright.py | 1 +
 1 file changed, 1 insertion(+)

diff --git a/contrib/update-copyright.py b/contrib/update-copyright.py
index fcae846fb1e..06e6fb61757 100755
--- a/contrib/update-copyright.py
+++ b/contrib/update-copyright.py
@@ -785,6 +785,7 @@ class GCCCmdLine (CmdLine):
 
 self.default_dirs = [
 'c++tools',
+'contrib',
 'gcc',
 'include',
 'libada',
-- 
2.39.0



Re: [PATCH] xtensa: Optimize stack frame adjustment more

2023-01-05 Thread Takayuki 'January June' Suwa via Gcc-patches
On 2023/01/06 15:26, Max Filippov wrote:
> On Thu, Jan 5, 2023 at 7:35 PM Takayuki 'January June' Suwa
>  wrote:
>> On second thought, it cannot be a good idea to split addition/subtraction to 
>> the stack pointer.
>>
>>> -4aaf:  b0a192  movia9, 0x1b0
>>> -4ab2:  1f9aadd.n   a1, a15, a9
>>
>>> +4aaf:  02df12  addmi   a1, a15, 0x200
>>> +4ab2:  b0c112  addia1, a1, -80
>>
>> Because the former is atomic, but the latter is not. (may be interrupted 
>> between the two add instructions)
> 
> Oh, right, there are two issues: one is interruption in the absence of
> detailed stack tracking in the DWARF info, which can be fixed by emitting
> a separate note for each a1 change, the other is interruption when
> a1 is in the parent frame, which can be fixed by always moving a1
> down first, e.g. with the following change:
> 
> diff --git a/gcc/config/xtensa/xtensa.cc b/gcc/config/xtensa/xtensa.cc
> index 3b8a7bcda371..29cb91fa7de5 100644
> --- a/gcc/config/xtensa/xtensa.cc
> +++ b/gcc/config/xtensa/xtensa.cc
> @@ -2539,7 +2539,10 @@ xtensa_split_imm_two_addends (HOST_WIDE_INT
> imm, HOST_WIDE_INT v[2])
> 
>   if (xtensa_simm8 (v1) || xtensa_simm8x256 (v1))
> {
> -  v[0] = v0, v[1] = v1;
> +  if (v0 < 0)
> +   v[0] = v0, v[1] = v1;
> +  else
> +   v[0] = v1, v[1] = v0;
>   return true;
> }
> 
> Or both can be fixed by using a scratch register in the middle of the
> addi/addmi sequence.
> 
>> I'll wait for the results of your investigation, but it may be better to 
>> withdraw the patch.
> 
> The issue was in the unwinding code in the libgcc_s.so. I haven't figured
> out the exact mechanism, but found that emitting a separate note for each
> a1 change fixes it.
> 

Oh, thank you very much for your detailed investigation.  I will try to correct 
what you pointed out ASAP.


[PATCH] [RISCV] Change the generation mode of `adjust_sp_rtx` from gen_insn to gen_SET.

2023-01-05 Thread jinma via Gcc-patches
From 35c1f22d3c9a6910103cf9688c5c2bc3d5b75c68 Mon Sep 17 00:00:00 2001
From: Jin Ma 
Date: Fri, 6 Jan 2023 14:47:37 +0800
Subject: [PATCH] [RISCV] Change the generation mode of `adjust_sp_rtx` from 
gen_insn to gen_SET.

The gen_insn method is used to generate `adjust_sp_rtx` here, which has certain
potential risks:

When the architecture adds pre-processing to `define_insn "adddi3"`, such as
`define_expend "adddi3"`, the gen_expand will be automatically called here,
causing the patern to emit directly, which will cause insn to enter REG_NOTE
for `DWARF` instead of patern.

The following error REG_NOTE occurred:
error: invalid rtl sharing found in the insn:
(insn 19 3 20 2 (parallel [
...
])
(expr_list:REG_CFA_ADJUST_CFA
(insn 18 0 0 (set (reg/f:DI 2 sp)
(plus:DI (reg/f:DI 2 sp)
(const_int -16 [0xfff0]))) -1
(nil

In fact, the correct one should be the following:
(insn 19 3 20 2 (parallel [
...
])
(expr_list:REG_CFA_ADJUST_CFA
(set (reg/f:DI 2 sp)
(plus:DI (reg/f:DI 2 sp)
(const_int -16 [0xfff0])

Following the treatment of arm or other architectures, it is more reasonable to
use gen_SET here.

gcc/ChangeLog:

* config/riscv/riscv.cc (riscv_adjust_libcall_cfi_prologue):
(riscv_adjust_libcall_cfi_epilogue):
---
 gcc/config/riscv/riscv.cc | 10 ++
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/gcc/config/riscv/riscv.cc b/gcc/config/riscv/riscv.cc
index 9a53999a39d..eab0500262f 100644
--- a/gcc/config/riscv/riscv.cc
+++ b/gcc/config/riscv/riscv.cc
@@ -5044,8 +5044,9 @@ riscv_adjust_libcall_cfi_prologue ()
   }

   /* Debug info for adjust sp.  */
-  adjust_sp_rtx = gen_add3_insn (stack_pointer_rtx,
-stack_pointer_rtx, GEN_INT (-saved_size));
+  adjust_sp_rtx =
+gen_rtx_SET (stack_pointer_rtx,
+gen_rtx_PLUS (GET_MODE(stack_pointer_rtx), stack_pointer_rtx, 
GEN_INT (-saved_size)));
   dwarf = alloc_reg_note (REG_CFA_ADJUST_CFA, adjust_sp_rtx,
  dwarf);
   return dwarf;
@@ -5166,8 +5167,9 @@ riscv_adjust_libcall_cfi_epilogue ()
   int saved_size = cfun->machine->frame.save_libcall_adjustment;

   /* Debug info for adjust sp.  */
-  adjust_sp_rtx = gen_add3_insn (stack_pointer_rtx,
-stack_pointer_rtx, GEN_INT (saved_size));
+  adjust_sp_rtx =
+gen_rtx_SET (stack_pointer_rtx,
+gen_rtx_PLUS (GET_MODE(stack_pointer_rtx), stack_pointer_rtx, 
GEN_INT (saved_size)));
   dwarf = alloc_reg_note (REG_CFA_ADJUST_CFA, adjust_sp_rtx,
  dwarf);

--
2.17.1

Re: [PATCH] xtensa: Optimize stack frame adjustment more

2023-01-05 Thread Max Filippov via Gcc-patches
On Thu, Jan 5, 2023 at 7:35 PM Takayuki 'January June' Suwa
 wrote:
> On second thought, it cannot be a good idea to split addition/subtraction to 
> the stack pointer.
>
> > -4aaf:  b0a192  movia9, 0x1b0
> > -4ab2:  1f9aadd.n   a1, a15, a9
>
> > +4aaf:  02df12  addmi   a1, a15, 0x200
> > +4ab2:  b0c112  addia1, a1, -80
>
> Because the former is atomic, but the latter is not. (may be interrupted 
> between the two add instructions)

Oh, right, there are two issues: one is interruption in the absence of
detailed stack tracking in the DWARF info, which can be fixed by emitting
a separate note for each a1 change, the other is interruption when
a1 is in the parent frame, which can be fixed by always moving a1
down first, e.g. with the following change:

diff --git a/gcc/config/xtensa/xtensa.cc b/gcc/config/xtensa/xtensa.cc
index 3b8a7bcda371..29cb91fa7de5 100644
--- a/gcc/config/xtensa/xtensa.cc
+++ b/gcc/config/xtensa/xtensa.cc
@@ -2539,7 +2539,10 @@ xtensa_split_imm_two_addends (HOST_WIDE_INT
imm, HOST_WIDE_INT v[2])

  if (xtensa_simm8 (v1) || xtensa_simm8x256 (v1))
{
-  v[0] = v0, v[1] = v1;
+  if (v0 < 0)
+   v[0] = v0, v[1] = v1;
+  else
+   v[0] = v1, v[1] = v0;
  return true;
}

Or both can be fixed by using a scratch register in the middle of the
addi/addmi sequence.

> I'll wait for the results of your investigation, but it may be better to 
> withdraw the patch.

The issue was in the unwinding code in the libgcc_s.so. I haven't figured
out the exact mechanism, but found that emitting a separate note for each
a1 change fixes it.

-- 
Thanks.
-- Max


Re: [PATCH] xtensa: Optimize stack frame adjustment more

2023-01-05 Thread Takayuki 'January June' Suwa via Gcc-patches
On 2023/01/06 6:32, Max Filippov wrote:
> Hi Suwa-san,
Hi!

> 
> On Thu, Jan 5, 2023 at 3:57 AM Takayuki 'January June' Suwa
>  wrote:
>>
>> This patch introduces a convenient helper function for integer immediate
>> addition with scratch register as needed, that splits and emits either
>> up to two ADDI/ADDMI machine instructions or an addition by register
>> following an immediate integer load (which may later be transformed by
>> constantsynth).
>>
>> By using the helper function, it makes stack frame adjustment logic
>> simplified and instruction count less in some cases.
>>
>> gcc/ChangeLog:
>>
>> * config/xtensa/xtensa.cc
>> (xtensa_split_imm_two_addends, xtensa_emit_add_imm):
>> New helper functions.
>> (xtensa_emit_adjust_stack_ptr, xtensa_set_return_address,
>> xtensa_output_mi_thunk): Change to use the helper function.
>> ---
>>  gcc/config/xtensa/xtensa.cc | 139 +++-
>>  1 file changed, 88 insertions(+), 51 deletions(-)
> 
> This change introduces a bunch of failures in the g++ testsuite,
> but the culprit is apparently somewhere in the libstdc++.so, I'm
> still looking for it.
> 
> I see the following pattern change in the generated epilogue code:
> 
> -4aaf:  b0a192  movia9, 0x1b0
> -4ab2:  1f9aadd.n   a1, a15, a9
> ...
> -4abe:  20c112  addia1, a1, 32
> -4ac1:  f00dret.n
> +4aaf:  02df12  addmi   a1, a15, 0x200
> +4ab2:  b0c112  addia1, a1, -80
> ...
> +4abf:  20c112  addia1, a1, 32
> +4ac2:  f00dret.n
> 
> I.e. a1 is first moved into the parent stack frame, then back to the right
> spot. This does not look correct, especially for bare-metal targets.
> 

On second thought, it cannot be a good idea to split addition/subtraction to 
the stack pointer.

> -4aaf:  b0a192  movia9, 0x1b0
> -4ab2:  1f9aadd.n   a1, a15, a9

> +4aaf:  02df12  addmi   a1, a15, 0x200
> +4ab2:  b0c112  addia1, a1, -80

Because the former is atomic, but the latter is not. (may be interrupted 
between the two add instructions)

I'll wait for the results of your investigation, but it may be better to 
withdraw the patch.


Re: [RFA] choosing __platform_wait_t on targets without lock-free 64 atomics

2023-01-05 Thread Jonathan Wakely via Gcc-patches
How about this?

I don't think we should worry about targets without atomic int, so don't
bother using types smaller than int.


-- >8 --

For non-futex targets the __platform_wait_t type is currently uint64_t,
but that requires a lock in libatomic for some 32-bit targets. We don't
really need a 64-bit type, so use unsigned long if that is lock-free,
and int otherwise. This should mean it's lock-free on a wider set of
targets.

libstdc++-v3/ChangeLog:

* include/bits/atomic_wait.h (__detail::__platform_wait_t):
Define as unsigned long if always lock-free, and unsigned int
otherwise.
---
 libstdc++-v3/include/bits/atomic_wait.h | 6 +-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/libstdc++-v3/include/bits/atomic_wait.h 
b/libstdc++-v3/include/bits/atomic_wait.h
index bd1ed56d157..46f39f10cbc 100644
--- a/libstdc++-v3/include/bits/atomic_wait.h
+++ b/libstdc++-v3/include/bits/atomic_wait.h
@@ -64,7 +64,11 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
 // and __platform_notify() if there is a more efficient primitive supported
 // by the platform (e.g. __ulock_wait()/__ulock_wake()) which is better than
 // a mutex/condvar based wait.
-using __platform_wait_t = uint64_t;
+# if  ATOMIC_LONG_LOCK_FREE == 2
+using __platform_wait_t = unsigned long;
+# else
+using __platform_wait_t = unsigned int;
+# endif
 inline constexpr size_t __platform_wait_alignment
   = __alignof__(__platform_wait_t);
 #endif
-- 
2.39.0



Re: [PATCH] libgccjit: Fix a failing test

2023-01-05 Thread Guillaume Gomez via Gcc-patches
Ping David.

Le sam. 24 déc. 2022 à 21:01, Guillaume Gomez 
a écrit :

> Ping David
>
> Le jeu. 15 déc. 2022 à 11:34, Guillaume Gomez 
> a écrit :
>
>> Forgot it indeed, thanks for notifying me!
>>
>> I modified the commit message to add it and added it into this email.
>>
>> Le mer. 14 déc. 2022 à 16:12, Antoni Boucher  a écrit :
>>
>>> Thanks!
>>>
>>> In your patch, you're missing this line at the end of the commit
>>> message:
>>>
>>>Signed-off-by: Guillaume Gomez 
>>>
>>> On Wed, 2022-12-14 at 14:39 +0100, Guillaume Gomez via Jit wrote:
>>> > Hi,
>>> >
>>> > This fixes bug 107999.
>>> >
>>> > Thanks in advance for the review.
>>>
>>>


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

2023-01-05 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 v2 1/4] diagnostics: libcpp: Add LC_GEN linemaps to support in-memory buffers

2023-01-05 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 not too large 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.  In order to avoid
confusion, the member has been renamed from TO_FILE to DATA, and associated
accessors adjusted.

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 members to support LC_GEN concept.
(ORDINARY_MAP_FILE_NAME): Assert that map really does encode a file
and not generated data.
(ORDINARY_MAP_GENERATED_DATA_P): New function.
(ORDINARY_MAP_GENERATED_DATA): New function.
(ORDINARY_MAP_GENERATED_DATA_LEN): New function.
(ORDINARY_MAP_FILE_NAME_OR_DATA): New function.
(ORDINARY_MAPS_SAME_FILE_P): Declare new function.
(ORDINARY_MAP_CONTAINING_FILE_NAME): Declare new function.
(LINEMAP_FILE): This was always a synonym for ORDINARY_MAP_FILE_NAME;
make this explicit.
(linemap_get_file_highest_location): Adjust prototype.
(linemap_add): Adjust prototype.
(class expanded_location): Add new members to store generated content.
* line-map.cc (ORDINARY_MAP_CONTAINING_FILE_NAME): New function.
(ORDINARY_MAPS_SAME_FILE_P): New function.
(linemap_add): Add new argument DATA_LEN. Support generated data in
LC_GEN maps.
(linemap_check_files_exited): Adapt to API changes supporting LC_GEN.
(linemap_line_start): Likewise.
(linemap_position_for_loc_and_offset): Likewise.
(linemap_get_expansion_filename): Likewise.
(linemap_expand_location): Likewise.
(linemap_dump): Likewise.
(linemap_dump_location): Likewise.
(linemap_get_file_highest_location): Likewise.
* directives.cc (_cpp_do_file_change): Likewise.

gcc/ChangeLog:

* diagnostic-show-locus.cc (make_range): Initialize new fields in
expanded_location.
(compatible_locations_p): Use new ORDINARY_MAPS_SAME_FILE_P ()
function.
(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.

[PATCH v2 4/4] diagnostics: Support generated data locations in SARIF output

2023-01-05 Thread Lewis Hyatt via Gcc-patches
The diagnostics routines for SARIF output need to read the source code back
in, so that they can generate "snippet" and "content" records, so they need to
be able to cope with generated data locations.  Add support for that in
diagnostic-format-sarif.cc.

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.

gcc/testsuite/ChangeLog:

* c-c++-common/diagnostic-format-sarif-file-5.c: New test.
---
 gcc/diagnostic-format-sarif.cc| 102 +++---
 .../diagnostic-format-sarif-file-5.c  |  31 ++
 2 files changed, 93 insertions(+), 40 deletions(-)
 create mode 100644 gcc/testsuite/c-c++-common/diagnostic-format-sarif-file-5.c

diff --git a/gcc/diagnostic-format-sarif.cc b/gcc/diagnostic-format-sarif.cc
index f8fdd586ff0..99aba1414ea 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 ("artifactLocation", artifact_loc_obj);
-  m_filenames.add (LOCATION_FILE (loc));
+  m_filenames.add (xloc_to_fb (expand_location (loc)));
 
   /* "region" property (SARIF v2.1.0 section 3.29.4).  */
   if (json::object *region_obj = maybe_make_region_object (loc))
@@ -627,7 +644,7 @@ sarif_builder::maybe_make_physical_location_object 
(location_t loc)
 json::object *
 sarif_builder::make_artifact_location_object (location_t loc)
 {
-  return make_artifact_location_object (LOCATION_FILE (loc));
+  return make_artifact_location_object (xloc_to_fb (expand_location (loc)));
 }
 
 /* 

[PATCH v2 2/4] diagnostics: Handle generated data locations in edit_context

2023-01-05 Thread Lewis Hyatt via Gcc-patches
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.
---
 gcc/edit-context.cc | 4 
 1 file changed, 4 insertions(+)

diff --git a/gcc/edit-context.cc b/gcc/edit-context.cc
index 6f5bc6b9d8f..ae11b6f2e00 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 v2 0/4] diagnostics: libcpp: Overhaul locations for _Pragma tokens

2023-01-05 Thread Lewis Hyatt via Gcc-patches
Hello-

This series contains the four remaining patches in the series originally
sent here:

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

which implements improved locations for tokens lexed from a string inside a
_Pragma directive.

v2 1/4: diagnostics: libcpp: Add LC_GEN linemaps to support in-memory buffers

This was formerly v1 4/6. It has been rewritten in line with that review,
most recently discussed here:
https://gcc.gnu.org/pipermail/gcc-patches/2022-November/606616.html

v2 2/4: diagnostics: Handle generated data locations in edit_context

This was formerly v1 5a/6. It has been approved already conditional on
v2 1/4 as a prerequisite.

v2 3/4: diagnostics: libcpp: Assign real locations to the tokens inside
_Pragma strings

This was formerly v1 6/6 and is unchanged from that one. It has not been
reviewed yet.

v2 4/4: diagnostics: Support generated data locations in SARIF output

This was formerly v1 5c/6. It has not been fully reviewed yet.

Thanks for taking a look!

-Lewis


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

2023-01-05 Thread Lewis Hyatt via Gcc-patches
On Thu, Nov 17, 2022 at 4:21 PM Lewis Hyatt  wrote:
>
> On Sat, Nov 05, 2022 at 12:23:28PM -0400, David Malcolm wrote:
> > On Fri, 2022-11-04 at 09:44 -0400, Lewis Hyatt via Gcc-patches wrote:
> > [...snip...]
> > >
> > > diff --git a/gcc/c-family/c-common.cc b/gcc/c-family/c-common.cc
> > > index 5890c18bdc3..2935d7fb236 100644
> > > --- a/gcc/c-family/c-common.cc
> > > +++ b/gcc/c-family/c-common.cc
> > > @@ -9183,11 +9183,14 @@ try_to_locate_new_include_insertion_point (const 
> > > char *file, location_t loc)
> > >const line_map_ordinary *ord_map
> > > = LINEMAPS_ORDINARY_MAP_AT (line_table, i);
> > >
> > > +  if (ord_map->reason == LC_GEN)
> > > +   continue;
> > > +
> > >if (const line_map_ordinary *from
> > >   = linemap_included_from_linemap (line_table, ord_map))
> > > /* We cannot use pointer equality, because with preprocessed
> > >input all filename strings are unique.  */
> > > -   if (0 == strcmp (from->to_file, file))
> > > +   if (from->reason != LC_GEN && 0 == strcmp (from->to_file, file))
> > >   {
> > > last_include_ord_map = from;
> > > last_ord_map_after_include = NULL;
> >
> > [...snip...]
> >
> > I'm not a fan of having the "to_file" field change meaning based on
> > whether reason is LC_GEN.
> >
> > How involved would it be to split line_map_ordinary into two
> > subclasses, so that we'd have this hierarchy (with indentation showing
> > inheritance):
> >
> > line_map
> >   line_map_ordinary
> > line_map_ordinary_file
> > line_map_ordinary_generated
> >   line_map_macro
> >
> > Alternatively, how about renaming "to_file" to be "data" (or "m_data"),
> > to emphasize that it might not be a filename, and that we have to check
> > everywhere we access that field.
> >
> > Please can all those checks for LC_GEN go into an inline function so we
> > can write e.g.
> >   map->generated_p ()
> > or somesuch.
> >
> > If I reading things right, patch 6 adds the sole usage of this in
> > destringize_and_run.  Would we ever want to discriminate between
> > different kinds of generated buffers?
> >
> > [...snip...]
> >
> > > @@ -796,10 +798,13 @@ diagnostic_report_current_module 
> > > (diagnostic_context *context, location_t where)
> > >  N_("of module"),
> > >  N_("In module imported at"),   /* 6 */
> > >  N_("imported at"),
> > > +N_("In buffer generated from"),   /* 8 */
> > > };
> >
> > We use the wording "destringized" in:
> >
> > so maybe this should be "In buffer destringized from" ???  (I'm not
> > sure)
> >
> > [...snip...]
> >
> > > diff --git a/gcc/input.cc b/gcc/input.cc
> > > index 483cb6e940d..3cf5480551d 100644
> > > --- a/gcc/input.cc
> > > +++ b/gcc/input.cc
> >
> > [..snip...]
> >
> > > @@ -58,7 +64,7 @@ public:
> > >~file_cache_slot ();
> >
> > My initial thought reading the input.cc part of this patch was that I
> > want it to be very clear when a file_cache_slot is for a real file vs
> > when we're replaying generated data.  I'd hoped that this could have
> > been expressed via inheritance, but we preallocate all the cache slots
> > once in an array in file_cache's ctor and the slots get reused over
> > time.  So instead of that, can we please have some kind of:
> >
> >bool file_slot_p () const;
> >bool generated_slot_p () const;
> >
> > or somesuch, so that we can have clear assertions and conditionals
> > about the current state of a slot (I think the discriminating condition
> > is that generated_data_len > 0, right?)
> >
> > If I'm reading things right, it looks like file_cache_slot::m_file_path
> > does double duty after this patch, and is either a filename, or a
> > pointer to the generated data.  If so, please can the patch rename it,
> > and have all usage guarded appropriately.  Can it be a union? (or does
> > the ctor prevent that?)
> >
> > [...snip...]
> >
> > > @@ -445,16 +461,23 @@ file_cache::evicted_cache_tab_entry (unsigned 
> > > *highest_use_count)
> > > num_file_slots files are cached.  */
> > >
> > >  file_cache_slot*
> > > -file_cache::add_file (const char *file_path)
> > > +file_cache::add_file (const char *file_path, unsigned int 
> > > generated_data_len)
> >
> > Can we split this into two functions: one for files, and one for
> > generated data?  (add_file vs add_generated_data?)
> >
> > >  {
> > >
> > > -  FILE *fp = fopen (file_path, "r");
> > > -  if (fp == NULL)
> > > -return NULL;
> > > +  FILE *fp;
> > > +  if (generated_data_len)
> > > +fp = NULL;
> > > +  else
> > > +{
> > > +  fp = fopen (file_path, "r");
> > > +  if (fp == NULL)
> > > +   return NULL;
> > > +}
> > >
> > >unsigned highest_use_count = 0;
> > >file_cache_slot *r = evicted_cache_tab_entry (_use_count);
> > > -  if (!r->create (in_context, file_path, fp, highest_use_count))
> > > +  if (!r->create (in_context, file_path, fp, highest_use_count,

Re: [PATCH] xtensa: Optimize stack frame adjustment more

2023-01-05 Thread Max Filippov via Gcc-patches
Hi Suwa-san,

On Thu, Jan 5, 2023 at 3:57 AM Takayuki 'January June' Suwa
 wrote:
>
> This patch introduces a convenient helper function for integer immediate
> addition with scratch register as needed, that splits and emits either
> up to two ADDI/ADDMI machine instructions or an addition by register
> following an immediate integer load (which may later be transformed by
> constantsynth).
>
> By using the helper function, it makes stack frame adjustment logic
> simplified and instruction count less in some cases.
>
> gcc/ChangeLog:
>
> * config/xtensa/xtensa.cc
> (xtensa_split_imm_two_addends, xtensa_emit_add_imm):
> New helper functions.
> (xtensa_emit_adjust_stack_ptr, xtensa_set_return_address,
> xtensa_output_mi_thunk): Change to use the helper function.
> ---
>  gcc/config/xtensa/xtensa.cc | 139 +++-
>  1 file changed, 88 insertions(+), 51 deletions(-)

This change introduces a bunch of failures in the g++ testsuite,
but the culprit is apparently somewhere in the libstdc++.so, I'm
still looking for it.

I see the following pattern change in the generated epilogue code:

-4aaf:  b0a192  movia9, 0x1b0
-4ab2:  1f9aadd.n   a1, a15, a9
...
-4abe:  20c112  addia1, a1, 32
-4ac1:  f00dret.n
+4aaf:  02df12  addmi   a1, a15, 0x200
+4ab2:  b0c112  addia1, a1, -80
...
+4abf:  20c112  addia1, a1, 32
+4ac2:  f00dret.n

I.e. a1 is first moved into the parent stack frame, then back to the right
spot. This does not look correct, especially for bare-metal targets.

-- 
Thanks.
-- Max


Re: [x86_64 PATCH] Introduce insvti_highpart define_insn_and_split.

2023-01-05 Thread Uros Bizjak via Gcc-patches
On Thu, Jan 5, 2023 at 3:10 PM Roger Sayle  wrote:
>
>
> This patch adds a convenient post-reload splitter for setting/updating
> the highpart of a TImode variable, using the recently added
> split_double_concat infrastructure.
>
> For the new test case below:
>
> __int128 foo(__int128 x, unsigned long long y)
> {
>   __int128 t = (__int128)y << 64;
>   __int128 r = (x & ~0ull) | t;
>   return r;
> }
>
> mainline GCC with -O2 currently generates:
>
> foo:movq%rdi, %rcx
> xorl%eax, %eax
> xorl%edi, %edi
> orq %rcx, %rax
> orq %rdi, %rdx
> ret
>
> with this patch, GCC instead now generates the much better:
>
> foo:movq%rdi, %rcx
> movq%rcx, %rax
> ret
>
> [which interestingly shows the deeper (ABI) issue that I'm trying
> to fix, this new define_insn_and_split being the next piece].
>
> It turns out that the -m32 equivalent of this testcase, already
> avoids using explict orl/xor instructions, as it gets optimized
> (in combine) by a completely different path.  Given that this idiom
> isn't seen in 32-bit code (and therefore this pattern wouldn't match),
> and also that the shorter 32-bit AND bitmask is represented as a
> CONST_INT rather than a CONST_WIDE_INT, this new define_insn_and_split
> is implemented for just TARGET_64BIT rather than contort a "generic"
> implementation using DWI mode iterators.
>
> This patch has been tested on x86_64-pc-linux-gnu with make bootstrap
> and make -k check, both with and without --target_board=unix{-m32},
> with no new failures.  Ok for mainline?  Please let me know if you'd
> prefer a different pattern name [insv seemed better than mov].
>
>
> 2023-01-05  Roger Sayle  
>
> gcc/ChangeLog
> * config/i386/i386.md (any_or_plus): Move definition earlier.
> (*insvti_highpart_1): New define_insn_and_split to overwrite
> (insv) the highpart of a TImode register/memory.
>
> gcc/testsuite/ChangeLog
> * gcc.target/i386/insvti_highpart-1.c: New test case.

LGTM, but the new pattern looks complex enough to make me a bit
nervous at this development stage. If the patch just extended the
existing SI/DI mode pattern to also handle DI/TI case for 64-bit
targets, I would approve it without hesitation, but since 128 bit
types are not that common ATM, I'd rather postpone introduction of
complex new pattern to the next stage 1.

Target specific part of the compiler does have some more freedom to
introduce new functionality during "general bugfixing" development
stage, so simple patches that extend existing patterns to handle new
modes or constraints should be OK, but let's not stretch this rule too
much.

To follow with the example, your recent extendditi2 splitter patch was
OK even at this development stage, because it just extended existing
patterns and existing approach to also handle 64bit instructions (that
are actually same as 32bit ones).

Uros.


Re: [PATCH] wwwdocs: Note that old reload is deprecated

2023-01-05 Thread Segher Boessenkool
On Thu, Jan 05, 2023 at 02:54:04PM -0500, Paul Koning wrote:
> > On Jan 5, 2023, at 2:27 PM, Segher Boessenkool  
> > wrote:
> > +Support for old reload is deprecated. It will be removed in a 
> > future
> > +  release. Every target will always use LRA from then on.

> Does this mean that targets that have an option to use LRA or not should now 
> default to LRA?  Some currently default to old reload.

It would be a good idea to do that in GCC 13 already, yes.


Segher


[Committed] PR rtl-optimization/108292: Revert "Improve ix86_expand_int_movcc to allow condition (mask) sharing"

2023-01-05 Thread Roger Sayle


I agree with Uros that it's best to revert my recent patch that caused PR
rtl-optimization/108292.
Sorry for the inconvenience.

This reverts commit d0558f420b2a5692fd38ac76ffa97ae6c1726ed9.


2023-01-05  Roger Sayle  

gcc/ChangeLog
PR rtl-optimization/108292
* config/i386/i386-expand.cc (ix86_expand_int_movcc): Revert
previous change.

gcc/testsuite/ChangeLog
PR rtl-optimization/108292
* gcc.target/i386/cmov10.c: Remove test case.

Roger
--




Re: [PATCH] wwwdocs: Note that old reload is deprecated

2023-01-05 Thread Paul Koning via Gcc-patches
Does this mean that targets that have an option to use LRA or not should now 
default to LRA?  Some currently default to old reload.

paul


> On Jan 5, 2023, at 2:27 PM, Segher Boessenkool  
> wrote:
> 
> Hi!
> 
> Happy new year everyone.
> 
> Is this patch okay to commit?
> 
> 
> Segher
> 
> ---
> htdocs/gcc-13/changes.html | 2 ++
> 1 file changed, 2 insertions(+)
> 
> diff --git a/htdocs/gcc-13/changes.html b/htdocs/gcc-13/changes.html
> index 3876ad77543a..954469cdcfa4 100644
> --- a/htdocs/gcc-13/changes.html
> +++ b/htdocs/gcc-13/changes.html
> @@ -39,6 +39,8 @@ a work-in-progress.
> Legacy debug info compression option -gz=zlib-gnu was 
> removed
>   and the option is ignored right now.
> New debug info compression option value -gz=zstd has 
> been added.
> +Support for old reload is deprecated. It will be removed in a future
> +  release. Every target will always use LRA from then on.
> 
> 
> 
> -- 
> 1.8.3.1
> 



Re: [PATCH] rs6000: Make P10_FUSION honour tuning setting

2023-01-05 Thread Pat Haugen via Gcc-patches

On 1/4/23 3:20 AM, Kewen.Lin via Gcc-patches wrote:

diff --git a/gcc/config/rs6000/rs6000.cc b/gcc/config/rs6000/rs6000.cc
index 88c865b6b4b..6fa084c0807 100644
--- a/gcc/config/rs6000/rs6000.cc
+++ b/gcc/config/rs6000/rs6000.cc
@@ -4378,9 +4378,15 @@ rs6000_option_override_internal (bool global_init_p)
rs6000_isa_flags &= ~OPTION_MASK_MMA;
  }

-  if (TARGET_POWER10
-  && (rs6000_isa_flags_explicit & OPTION_MASK_P10_FUSION) == 0)
-rs6000_isa_flags |= OPTION_MASK_P10_FUSION;
+  /* Enable power10 fusion if we are tuning for power10, even if we aren't
+ generating power10 instructions.  */
+  if (!(rs6000_isa_flags_explicit & OPTION_MASK_P10_FUSION))
+{
+  if (processor_target_table[tune_index].processor == PROCESSOR_POWER10)


You can use (rs6000_tune == PROCESSOR_POWER10) at this point.
-Pat


+   rs6000_isa_flags |= OPTION_MASK_P10_FUSION;
+  else
+   rs6000_isa_flags &= ~OPTION_MASK_P10_FUSION;
+}





[PATCH] wwwdocs: Note that old reload is deprecated

2023-01-05 Thread Segher Boessenkool
Hi!

Happy new year everyone.

Is this patch okay to commit?


Segher

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

diff --git a/htdocs/gcc-13/changes.html b/htdocs/gcc-13/changes.html
index 3876ad77543a..954469cdcfa4 100644
--- a/htdocs/gcc-13/changes.html
+++ b/htdocs/gcc-13/changes.html
@@ -39,6 +39,8 @@ a work-in-progress.
 Legacy debug info compression option -gz=zlib-gnu was 
removed
   and the option is ignored right now.
 New debug info compression option value -gz=zstd has been 
added.
+Support for old reload is deprecated. It will be removed in a future
+  release. Every target will always use LRA from then on.
 
 
 
-- 
1.8.3.1



[committed] hppa: Fix atomic operations on PA-RISC 2.0 processors

2023-01-05 Thread John David Anglin
This changes fixes the atomic operations defined for hppa processors
in libstdc++-v3.  It appears they were originally written with only
PA 1.x processors in mind.

Tested on hppa64-hp-hpux11.11.  Committed to trunk.

Dave
---

Fix atomic operations on PA-RISC 2.0 processors.

PA-RISC 2.0 supports out-of-order execution for loads and stores.
Thus, we need to synchonize memory accesses.

This change revises the lock releases in __exchange_and_add and
__atomic_add to use an ordered store with release semantics.  We
also use an ordered load in the inner spin loop.

We use the "ldcw,co" instruction instead of "ldcw" when compiled
for PA 2.0.  Most PA 2.0 processors are coherent and can execute
the ldcw instruction in cache for improved performance.

Finally, the inner spin loop is revised to immediately branch to
the ldcw instruction when it detects the lock is free.

2023-01-05  John David Anglin  

libstdc++-v3/ChangeLog:

* config/cpu/hppa/atomicity.h (_PA_LDCW_INSN): Define.
(__exchange_and_add): Use _PA_LDCW_INSN.  Use ordered store for
lock release.  Revise loop.
(__atomic_add): Likewise.

diff --git a/libstdc++-v3/config/cpu/hppa/atomicity.h 
b/libstdc++-v3/config/cpu/hppa/atomicity.h
index bb997e70c1d..658073537a4 100644
--- a/libstdc++-v3/config/cpu/hppa/atomicity.h
+++ b/libstdc++-v3/config/cpu/hppa/atomicity.h
@@ -25,6 +25,15 @@
 #include 
 #include 
 
+/* Perform ldcw operation in cache when possible.  */
+#ifndef _PA_LDCW_INSN
+# ifdef _PA_RISC2_0
+# define _PA_LDCW_INSN "ldcw,co"
+# else
+# define _PA_LDCW_INSN "ldcw"
+# endif
+#endif
+
 namespace __gnu_cxx _GLIBCXX_VISIBILITY(default)
 {
 _GLIBCXX_BEGIN_NAMESPACE_VERSION
@@ -51,19 +60,19 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
 int tmp;
 volatile int& lock = _Atomicity_lock<0>::_S_atomicity_lock;
 
-__asm__ __volatile__ ("ldcw 0(%1),%0\n\t"
+__asm__ __volatile__ (_PA_LDCW_INSN " 0(%1),%0\n\t"
  "cmpib,<>,n 0,%0,.+20\n\t"
- "ldw 0(%1),%0\n\t"
- "cmpib,= 0,%0,.-4\n\t"
+ "ldw,ma 0(%1),%0\n\t"
+ "cmpib,<> 0,%0,.-12\n\t"
  "nop\n\t"
- "b,n .-20"
+ "b,n .-12"
  : "=" (tmp)
  : "r" ()
  : "memory");
 
 result = *__mem;
 *__mem = result + __val;
-__asm__ __volatile__ ("stw %1,0(%0)"
+__asm__ __volatile__ ("stw,ma %1,0(%0)"
  : : "r" (), "r" (tmp) : "memory");
 return result;
   }
@@ -75,18 +84,18 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
 int tmp;
 volatile int& lock = _Atomicity_lock<0>::_S_atomicity_lock;
 
-__asm__ __volatile__ ("ldcw 0(%1),%0\n\t"
+__asm__ __volatile__ (_PA_LDCW_INSN " 0(%1),%0\n\t"
  "cmpib,<>,n 0,%0,.+20\n\t"
- "ldw 0(%1),%0\n\t"
- "cmpib,= 0,%0,.-4\n\t"
+ "ldw,ma 0(%1),%0\n\t"
+ "cmpib,<> 0,%0,.-12\n\t"
  "nop\n\t"
- "b,n .-20"
+ "b,n .-12"
  : "=" (tmp)
  : "r" ()
  : "memory");
 
 *__mem += __val;
-__asm__ __volatile__ ("stw %1,0(%0)"
+__asm__ __volatile__ ("stw,ma %1,0(%0)"
  : : "r" (), "r" (tmp) : "memory");
   }
 



signature.asc
Description: PGP signature


Re: [PATCH] c++: class-head parsing and CPP_TEMPLATE_ID access [PR108275]

2023-01-05 Thread Jason Merrill via Gcc-patches

On 1/5/23 12:20, Patrick Palka wrote:

When tentatively parsing what is really an elaborated-type-specifier
first as a class-specifier, we may form a CPP_TEMPLATE_ID token that
later gets reused in the fallback parse if the tentative parse fails.
These special tokens also capture the access checks that have been
deferred while parsing the template-id.  But here, we form such a token
when the access check state is dk_no_check, and so the token captures
no access checks.  This effectively bypasses access checking for the
template-id during the subsequent parse as an elaborated-type-specifier.

This patch fixes this by using dk_deferred instead of dk_no_check when
parsing the class name.

Bootstrapped and regtested on x86_64-pc-linux-gnu, does this look OK for
trunk?


OK.


PR c++/108275

gcc/cp/ChangeLog:

* parser.cc (cp_parser_class_head): Use dk_deferred instead of
dk_no_check when parsing the class name.

gcc/testsuite/ChangeLog:

* g++.dg/parse/access14.C: New test.
---
  gcc/cp/parser.cc  | 23 +--
  gcc/testsuite/g++.dg/parse/access14.C | 18 ++
  2 files changed, 35 insertions(+), 6 deletions(-)
  create mode 100644 gcc/testsuite/g++.dg/parse/access14.C

diff --git a/gcc/cp/parser.cc b/gcc/cp/parser.cc
index bfd8aeae39f..8b1658decba 100644
--- a/gcc/cp/parser.cc
+++ b/gcc/cp/parser.cc
@@ -26559,7 +26559,23 @@ cp_parser_class_head (cp_parser* parser,
if (cp_parser_global_scope_opt (parser, /*current_scope_valid_p=*/false))
  qualified_p = true;
  
-  push_deferring_access_checks (dk_no_check);

+  /* It is OK to define an inaccessible class; for example:
+
+   class A { class B; };
+   class A::B {};
+
+ So we want to ignore access when parsing the class name.
+ However, we might be tentatively parsing what is really an
+ elaborated-type-specifier naming a template-id, e.g.
+
+   struct C<::m> c;
+
+ In this case the tentative parse as a class-head will fail, but not
+ before cp_parser_template_id splices in a CPP_TEMPLATE_ID token.
+ Since dk_no_check is sticky, we must instead use dk_deferred so that
+ any such CPP_TEMPLATE_ID token created during this tentative parse
+ will correctly capture the access checks imposed by the template-id . */
+  push_deferring_access_checks (dk_deferred);
  
/* Determine the name of the class.  Begin by looking for an

   optional nested-name-specifier.  */
@@ -26586,11 +26602,6 @@ cp_parser_class_head (cp_parser* parser,
 The proposed resolution for Core Issue 180 says that wherever
 you see `class T::X' you should treat `X' as a type-name.
  
-	 It is OK to define an inaccessible class; for example:

-
-  class A { class B; };
-  class A::B {};
-
 We do not know if we will see a class-name, or a
 template-name.  We look for a class-name first, in case the
 class-name is a template-id; if we looked for the
diff --git a/gcc/testsuite/g++.dg/parse/access14.C 
b/gcc/testsuite/g++.dg/parse/access14.C
new file mode 100644
index 000..bdbc7f6ee2b
--- /dev/null
+++ b/gcc/testsuite/g++.dg/parse/access14.C
@@ -0,0 +1,18 @@
+// PR c++/108275
+
+struct A {
+  int i;
+private:
+  int j;
+};
+
+template
+struct B {
+  struct C { };
+private:
+  template struct D { };
+};
+
+struct B<::j> b;   // { dg-error "private" }
+struct B<::j>::C c;// { dg-error "private" }
+struct B<::i>::D<0> d; // { dg-error "private" }




Re: [PATCH] c++: class-head parsing and CPP_TEMPLATE_ID access [PR108275]

2023-01-05 Thread Patrick Palka via Gcc-patches
On Thu, 5 Jan 2023, Patrick Palka wrote:

> When tentatively parsing what is really an elaborated-type-specifier
> first as a class-specifier, we may form a CPP_TEMPLATE_ID token that
> later gets reused in the fallback parse if the tentative parse fails.
> These special tokens also capture the access checks that have been
> deferred while parsing the template-id.  But here, we form such a token
> when the access check state is dk_no_check, and so the token captures
> no access checks.  This effectively bypasses access checking for the
> template-id during the subsequent parse as an elaborated-type-specifier.
> 
> This patch fixes this by using dk_deferred instead of dk_no_check when
> parsing the class name.

Looks like this issue isn't specific to the CPP_TEMPLATE_ID mechanism --
using dk_no_check also means we bypass access checking during satisfaction too:

  template
requires T::value
  struct A { };

  struct B {
  private:
static constexpr bool value = true;
  };

  struct A a; // incorrectly accepted

> 
> Bootstrapped and regtested on x86_64-pc-linux-gnu, does this look OK for
> trunk?
> 
>   PR c++/108275
> 
> gcc/cp/ChangeLog:
> 
>   * parser.cc (cp_parser_class_head): Use dk_deferred instead of
>   dk_no_check when parsing the class name.
> 
> gcc/testsuite/ChangeLog:
> 
>   * g++.dg/parse/access14.C: New test.
> ---
>  gcc/cp/parser.cc  | 23 +--
>  gcc/testsuite/g++.dg/parse/access14.C | 18 ++
>  2 files changed, 35 insertions(+), 6 deletions(-)
>  create mode 100644 gcc/testsuite/g++.dg/parse/access14.C
> 
> diff --git a/gcc/cp/parser.cc b/gcc/cp/parser.cc
> index bfd8aeae39f..8b1658decba 100644
> --- a/gcc/cp/parser.cc
> +++ b/gcc/cp/parser.cc
> @@ -26559,7 +26559,23 @@ cp_parser_class_head (cp_parser* parser,
>if (cp_parser_global_scope_opt (parser, /*current_scope_valid_p=*/false))
>  qualified_p = true;
>  
> -  push_deferring_access_checks (dk_no_check);
> +  /* It is OK to define an inaccessible class; for example:
> +
> +   class A { class B; };
> +   class A::B {};
> +
> + So we want to ignore access when parsing the class name.
> + However, we might be tentatively parsing what is really an
> + elaborated-type-specifier naming a template-id, e.g.
> +
> +   struct C<::m> c;
> +
> + In this case the tentative parse as a class-head will fail, but not
> + before cp_parser_template_id splices in a CPP_TEMPLATE_ID token.
> + Since dk_no_check is sticky, we must instead use dk_deferred so that
> + any such CPP_TEMPLATE_ID token created during this tentative parse
> + will correctly capture the access checks imposed by the template-id . */
> +  push_deferring_access_checks (dk_deferred);
>  
>/* Determine the name of the class.  Begin by looking for an
>   optional nested-name-specifier.  */
> @@ -26586,11 +26602,6 @@ cp_parser_class_head (cp_parser* parser,
>The proposed resolution for Core Issue 180 says that wherever
>you see `class T::X' you should treat `X' as a type-name.
>  
> -  It is OK to define an inaccessible class; for example:
> -
> -class A { class B; };
> -class A::B {};
> -
>We do not know if we will see a class-name, or a
>template-name.  We look for a class-name first, in case the
>class-name is a template-id; if we looked for the
> diff --git a/gcc/testsuite/g++.dg/parse/access14.C 
> b/gcc/testsuite/g++.dg/parse/access14.C
> new file mode 100644
> index 000..bdbc7f6ee2b
> --- /dev/null
> +++ b/gcc/testsuite/g++.dg/parse/access14.C
> @@ -0,0 +1,18 @@
> +// PR c++/108275
> +
> +struct A {
> +  int i;
> +private:
> +  int j;
> +};
> +
> +template
> +struct B {
> +  struct C { };
> +private:
> +  template struct D { };
> +};
> +
> +struct B<::j> b;   // { dg-error "private" }
> +struct B<::j>::C c;// { dg-error "private" }
> +struct B<::i>::D<0> d; // { dg-error "private" }
> -- 
> 2.39.0.189.g4dbebc36b0
> 
> 



Re: [PATCH V2] Disable sched1 in functions that call setjmp

2023-01-05 Thread Qing Zhao via Gcc-patches
Alexander,

(Sorry for the late reply due to holiday vacation).

> On Dec 24, 2022, at 3:10 AM, Alexander Monakov  wrote:
> 
> 
> On Fri, 23 Dec 2022, Qing Zhao wrote:
> 
>> BTW, Why sched1 is not enabled on x86 by default?
> 
> Register allocation is tricky on x86 due to small number of general-purpose
> registers, and sched1 can make it even more difficult. I think before register
> pressure modeling was added, sched1 could not be enabled because then 
> allocation
> would sometimes fail, and now there's no incentive to enable it, as it is not 
> so
> important for modern x86 CPUs. Perhaps someone else has a more comprehensive
> answer.

Okay. I see. Thanks for the explanation of the history. 
> 
>> Another question is:  As discussed in the original bug PR57067:
>> https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57067 The root cause of this
>> issue related to the abnormal control flow edges (from setjmp/longjmp) cannot
>> be represented correctly at RTL stage, shall we fix this root cause instead? 
> 
> You'd need an experienced reviewer to work with you, especially on high-level
> design decisions such as "How ABNORMAL_DISPATCHER should be represented on 
> RTL".
> I'm afraid it's not just a matter of applying a small patch in one place.
I see. (And I guess so, fixing this is not a trivial work).

Qing
> 
> Alexander



[PATCH] c++: class-head parsing and CPP_TEMPLATE_ID access [PR108275]

2023-01-05 Thread Patrick Palka via Gcc-patches
When tentatively parsing what is really an elaborated-type-specifier
first as a class-specifier, we may form a CPP_TEMPLATE_ID token that
later gets reused in the fallback parse if the tentative parse fails.
These special tokens also capture the access checks that have been
deferred while parsing the template-id.  But here, we form such a token
when the access check state is dk_no_check, and so the token captures
no access checks.  This effectively bypasses access checking for the
template-id during the subsequent parse as an elaborated-type-specifier.

This patch fixes this by using dk_deferred instead of dk_no_check when
parsing the class name.

Bootstrapped and regtested on x86_64-pc-linux-gnu, does this look OK for
trunk?

PR c++/108275

gcc/cp/ChangeLog:

* parser.cc (cp_parser_class_head): Use dk_deferred instead of
dk_no_check when parsing the class name.

gcc/testsuite/ChangeLog:

* g++.dg/parse/access14.C: New test.
---
 gcc/cp/parser.cc  | 23 +--
 gcc/testsuite/g++.dg/parse/access14.C | 18 ++
 2 files changed, 35 insertions(+), 6 deletions(-)
 create mode 100644 gcc/testsuite/g++.dg/parse/access14.C

diff --git a/gcc/cp/parser.cc b/gcc/cp/parser.cc
index bfd8aeae39f..8b1658decba 100644
--- a/gcc/cp/parser.cc
+++ b/gcc/cp/parser.cc
@@ -26559,7 +26559,23 @@ cp_parser_class_head (cp_parser* parser,
   if (cp_parser_global_scope_opt (parser, /*current_scope_valid_p=*/false))
 qualified_p = true;
 
-  push_deferring_access_checks (dk_no_check);
+  /* It is OK to define an inaccessible class; for example:
+
+   class A { class B; };
+   class A::B {};
+
+ So we want to ignore access when parsing the class name.
+ However, we might be tentatively parsing what is really an
+ elaborated-type-specifier naming a template-id, e.g.
+
+   struct C<::m> c;
+
+ In this case the tentative parse as a class-head will fail, but not
+ before cp_parser_template_id splices in a CPP_TEMPLATE_ID token.
+ Since dk_no_check is sticky, we must instead use dk_deferred so that
+ any such CPP_TEMPLATE_ID token created during this tentative parse
+ will correctly capture the access checks imposed by the template-id . */
+  push_deferring_access_checks (dk_deferred);
 
   /* Determine the name of the class.  Begin by looking for an
  optional nested-name-specifier.  */
@@ -26586,11 +26602,6 @@ cp_parser_class_head (cp_parser* parser,
 The proposed resolution for Core Issue 180 says that wherever
 you see `class T::X' you should treat `X' as a type-name.
 
-It is OK to define an inaccessible class; for example:
-
-  class A { class B; };
-  class A::B {};
-
 We do not know if we will see a class-name, or a
 template-name.  We look for a class-name first, in case the
 class-name is a template-id; if we looked for the
diff --git a/gcc/testsuite/g++.dg/parse/access14.C 
b/gcc/testsuite/g++.dg/parse/access14.C
new file mode 100644
index 000..bdbc7f6ee2b
--- /dev/null
+++ b/gcc/testsuite/g++.dg/parse/access14.C
@@ -0,0 +1,18 @@
+// PR c++/108275
+
+struct A {
+  int i;
+private:
+  int j;
+};
+
+template
+struct B {
+  struct C { };
+private:
+  template struct D { };
+};
+
+struct B<::j> b;   // { dg-error "private" }
+struct B<::j>::C c;// { dg-error "private" }
+struct B<::i>::D<0> d; // { dg-error "private" }
-- 
2.39.0.189.g4dbebc36b0



[PATCH] ipa: Sort ipa_param_body_adjustments::m_replacements (PR 108110)

2023-01-05 Thread Martin Jambor
Hi,

the problem in PR 108110 is that elements describing the same base
parameter in ipa_param_body_adjustments::m_replacements are not
adjacent to each other, which is something that
ipa_param_body_adjustments::modify_call_stmt when it gathers all
replacements for a parameter.

One option would be to simply always keep looking until the end of the
vector (see bugzilla comment 15 for a one-line fix) but the correct
thing to do is to keep the elements of the vector sorted and thus make
such elements adjacent again.  This patch does that and then also
modifies the look-ups to take advantage of it.

Since the one user of ipa_param_body_adjustments that is not
tree-inline.cc, which is OpenMP declare SIMD cloning code, also
registers its own replacements and in theory pointers to elements of
the m_replacements vector can leak through public method
get_expr_replacement, I decided that in those cases it is the
responsibility of the user of the class to call the sorting method
between the replacement registrations and the first lookup.  That is
why the patch also adds a line to omp-simd-clone.cc.

Bootstrapped, tested and LTO-bootstrapped on x86_64-linux.  OK for
trunk?

Thanks,

Martin


gcc/ChangeLog:

2023-01-04  Martin Jambor  

* ipa-param-manipulation.h (ipa_param_body_adjustments): New members
sort_replacements, lookup_first_base_replacement and
m_sorted_replacements_p.
* ipa-param-manipulation.cc: Define INCLUDE_ALGORITHM.
(ipa_param_body_adjustments::register_replacement): Set
m_sorted_replacements_p to false.
(compare_param_body_replacement): New function.
(ipa_param_body_adjustments::sort_replacements): Likewise.
(ipa_param_body_adjustments::common_initialization): Call
sort_replacements.
(ipa_param_body_adjustments::ipa_param_body_adjustments): Initialize
m_sorted_replacements_p.
(ipa_param_body_adjustments::lookup_replacement_1): Rework to use
std::lower_bound.
(ipa_param_body_adjustments::lookup_first_base_replacement): New
function.
(ipa_param_body_adjustments::modify_call_stmt): Use
lookup_first_base_replacement.
* omp-simd-clone.cc (ipa_simd_modify_function_body): Call
adjustments->sort_replacements.

gcc/testsuite/ChangeLog:

2023-01-04  Martin Jambor  

* g++.dg/ipa/pr108110.C: New test.
---
 gcc/ipa-param-manipulation.cc   | 116 +---
 gcc/ipa-param-manipulation.h|   9 +++
 gcc/omp-simd-clone.cc   |   1 +
 gcc/testsuite/g++.dg/ipa/pr108110.C |  32 
 4 files changed, 132 insertions(+), 26 deletions(-)
 create mode 100644 gcc/testsuite/g++.dg/ipa/pr108110.C

diff --git a/gcc/ipa-param-manipulation.cc b/gcc/ipa-param-manipulation.cc
index a0e4098a3f1..8d78ef57c12 100644
--- a/gcc/ipa-param-manipulation.cc
+++ b/gcc/ipa-param-manipulation.cc
@@ -18,6 +18,7 @@ You should have received a copy of the GNU General Public 
License
 along with GCC; see the file COPYING3.  If not see
 .  */
 
+#define INCLUDE_ALGORITHM
 #include "config.h"
 #include "system.h"
 #include "coretypes.h"
@@ -1000,6 +1001,7 @@ ipa_param_body_adjustments::register_replacement (tree 
base,
   psr.dummy = NULL_TREE;
   psr.unit_offset = unit_offset;
   m_replacements.safe_push (psr);
+  m_sorted_replacements_p = false;
 }
 
 /* Register that REPLACEMENT should replace parameter described in APM.  */
@@ -1015,6 +1017,36 @@ ipa_param_body_adjustments::register_replacement 
(ipa_adjusted_param *apm,
replacement);
 }
 
+/* Comparator to qsort ipa_param_body_adjustments::m_replacements.  */
+
+static int
+compare_param_body_replacement (const void *va, const void *vb)
+{
+  const ipa_param_body_replacement *a = (const ipa_param_body_replacement *) 
va;
+  const ipa_param_body_replacement *b = (const ipa_param_body_replacement *) 
vb;
+
+  if (DECL_UID (a->base) < DECL_UID (b->base))
+return -1;
+  if (DECL_UID (a->base) > DECL_UID (b->base))
+return 1;
+  if (a->unit_offset < b->unit_offset)
+return -1;
+  if (a->unit_offset > b->unit_offset)
+return 1;
+  return 0;
+}
+
+/* Sort m_replacements and set m_sorted_replacements_p to true.  */
+
+void
+ipa_param_body_adjustments::sort_replacements ()
+{
+  if (m_sorted_replacements_p)
+return;
+  m_replacements.qsort (compare_param_body_replacement);
+  m_sorted_replacements_p = true;
+}
+
 /* Copy or not, as appropriate given m_id and decl context, a pre-existing
PARM_DECL T so that it can be included in the parameters of the modified
function.  */
@@ -1426,6 +1458,7 @@ ipa_param_body_adjustments::common_initialization (tree 
old_fndecl,
}
}
 }
+  sort_replacements ();
 
   if (tree_map)
 {
@@ -1503,7 +1536,7 @@ ipa_param_body_adjustments
 m_dead_stmt_debug_equiv (), m_fndecl (fndecl), m_id (NULL), m_oparms (),
 m_new_decls (), m_new_types (), 

Re: [PATCH] gccrs: avoid printing to stderr in selftest::rust_flatten_list

2023-01-05 Thread Arthur Cohen



On 1/5/23 16:36, David Malcolm wrote:

On Thu, 2023-01-05 at 15:44 +0100, Arthur Cohen wrote:

Hi David,

On 1/4/23 20:28, David Malcolm wrote:

On Mon, 2023-01-02 at 13:47 +0100, Arthur Cohen wrote:

Hi David,

Sorry for the delayed reply!

On 12/16/22 18:01, David Malcolm wrote:

Successfully bootstrapped & regrtested on x86_64-pc-linux-gnu.

OK for trunk?

gcc/rust/ChangeLog:
  * resolve/rust-ast-resolve-item.cc
(selftest::rust_flatten_list):
  Remove output to stderr.


For reference, the stderr spewage was:

foo::bar::baz
foo::bar::bul




Signed-off-by: David Malcolm 
---
    gcc/rust/resolve/rust-ast-resolve-item.cc | 3 ---
    1 file changed, 3 deletions(-)

diff --git a/gcc/rust/resolve/rust-ast-resolve-item.cc
b/gcc/rust/resolve/rust-ast-resolve-item.cc
index 0c38f28d530..1276e845acc 100644
--- a/gcc/rust/resolve/rust-ast-resolve-item.cc
+++ b/gcc/rust/resolve/rust-ast-resolve-item.cc
@@ -1202,9 +1202,6 @@ rust_flatten_list (void)
  auto paths = std::vector ();
  Rust::Resolver::flatten_list (list, paths);

-  for (auto  : paths)

-    fprintf (stderr, "%s\n", path.as_string ().c_str ());
-
  ASSERT_TRUE (!paths.empty ());
  ASSERT_EQ (paths.size (), 2);
  ASSERT_EQ (paths[0].get_segments ()[0].as_string (),
"foo");


Looks good to me. OK for trunk :)

Thanks for taking the time!


I was about to push this and
   
https://gcc.gnu.org/pipermail/gcc-patches/2022-December/608645.html

to trunk (after retesting against all the changes since before my
break), but you mentioned today on IRC something about merger
issues:

 ibuclaw: I'm looking at the remaining issues for
updating
GCC's master with our most recent gccrs commits. I've come to the
conclusion that it would be easier for me to upstream your target
changes while I'm upstreaming/submitting all of the missing commits
 would that suit you?
 it would just be me sending in your commits, but I
wouldn't be author on them or anything of course
 this would enable us to time them properly within the
rest of the commits, so there'd be no conflicts or anything of the
sort
 dmalcolm: same question to you, actually :)


Sorry for the confusion, and for disappearing from IRC before you got
a
chance to answer! In those messages, I was talking about the
`error_meta` PR you had submitted to us on Github. Since we are in
the
process of updating upstream with the current state of our dev
branch,
we have to figure out what to do with these commits that are already
present in our dev branch but not upstreamed yet. Since you and Iain
have pushed commits to our dev branch, we are wondering whether you'd
like us to upstream them during this updating process or if you'd
like
to do so on your own.


For reference, presumably this is:
   https://github.com/Rust-GCC/gccrs/pull/1408
which was kind of an experimenal proof-of-concept on my part.

As far as I can tell, that PR added some relatively trivial new stuff
to gcc/diagnostic*, and otherwise just touched the gcc/rust
subdirectory, so I hope it's relatively trivial to merge.

I'd prefer to leave the responsibility for merging that work into trunk
to you.


Sounds good!





Regarding the two new patches that you've submitted here and that
aren't
upstreamed or merged in our dev branch yet, it's a bit different. You
can either go ahead and push them to trunk if that's what you'd like,
and I'm assuming that when we merge upstream and our dev branch this
won't cause any conflict. And if these two patches do, they are easy
enough that we can fix them by hand.


Thanks.  I've gone ahead and pushed the two simple patches to trunk as:
   r13-5031-gb0edfa0ef02c0f
and:
   r13-5032-gefce0caf2d75df

Dave


Great :) Thanks a lot!

Arthur


OpenPGP_0x1B3465B044AD9C65.asc
Description: OpenPGP public key


OpenPGP_signature
Description: OpenPGP digital signature


[committed] libstdc++: Fix printers for Python 2 [PR108212]

2023-01-05 Thread Jonathan Wakely via Gcc-patches
Tested powerpc64le-linux (python 2.7) and x86_64-linux (Python 3.10).
Pushed to trunk.

-- >8 --

The datetime.timezone.utc singleton doesn't exist in Python 2, but we
can create it ourselves by deriving from datetime.tzinfo.

libstdc++-v3/ChangeLog:

PR libstdc++/108212
* python/libstdcxx/v6/printers.py (_utc_timezone): New global
variable.
(StdChronoTimePointPrinter::to_string): Use it.
---
 libstdc++-v3/python/libstdcxx/v6/printers.py | 19 +--
 1 file changed, 17 insertions(+), 2 deletions(-)

diff --git a/libstdc++-v3/python/libstdcxx/v6/printers.py 
b/libstdc++-v3/python/libstdcxx/v6/printers.py
index 7e694f48f28..8cfb4f26b0e 100644
--- a/libstdc++-v3/python/libstdcxx/v6/printers.py
+++ b/libstdc++-v3/python/libstdcxx/v6/printers.py
@@ -19,7 +19,7 @@ import gdb
 import itertools
 import re
 import sys, os, errno
-from datetime import datetime, timezone
+import datetime
 
 ### Python 2 + Python 3 compatibility code
 
@@ -45,6 +45,7 @@ if sys.version_info[0] > 2:
 izip = zip
 # Also, int subsumes long
 long = int
+_utc_timezone = datetime.timezone.utc
 else:
 ### Python 2 stuff
 class Iterator:
@@ -64,6 +65,20 @@ else:
 # In Python 2, we still need these from itertools
 from itertools import imap, izip
 
+# Python 2 does not provide the datetime.UTC singleton.
+class UTC(datetime.tzinfo):
+"""Concrete tzinfo class representing the UTC time zone"""
+
+def utcoffset(self, dt):
+return datetime.timedelta(0)
+
+def tzname(self, dt):
+return "UTC"
+
+def dst(self, dt):
+return datetime.timedelta(0)
+_utc_timezone = UTC()
+
 # Try to use the new-style pretty-printing if available.
 _use_gdb_pp = True
 try:
@@ -1955,7 +1970,7 @@ class StdChronoTimePointPrinter:
 num, den = printer._ratio()
 secs = (r * num / den) + offset
 try:
-dt = datetime.fromtimestamp(secs, timezone.utc)
+dt = datetime.fromtimestamp(secs, _utc_timezone)
 time = ' [{:%Y-%m-%d %H:%M:%S}]'.format(dt)
 except:
 pass
-- 
2.39.0



[committed] libstdc++: Reduce size of std::bind_front(empty_type) result [PR108290]

2023-01-05 Thread Jonathan Wakely via Gcc-patches
Tested powerpc64le-linux. Pushed to trunk.

-- >8 --

libstdc++-v3/ChangeLog:

PR libstdc++/108290
* include/std/functional (_Bind_front): Add no_unique_address
attribute to data members.
* testsuite/20_util/function_objects/bind_front/107784.cc: Check
size of call wrappers with empty types for targets and bound
arguments.
---
 libstdc++-v3/include/std/functional   |  6 +--
 .../function_objects/bind_front/107784.cc | 38 ++-
 2 files changed, 40 insertions(+), 4 deletions(-)

diff --git a/libstdc++-v3/include/std/functional 
b/libstdc++-v3/include/std/functional
index 22fcd04..5dff5be089d 100644
--- a/libstdc++-v3/include/std/functional
+++ b/libstdc++-v3/include/std/functional
@@ -991,8 +991,8 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
  std::forward<_CallArgs>(__call_args)...);
}
 
-  _Fd _M_fd;
-  std::tuple<_BoundArgs...> _M_bound_args;
+  [[no_unique_address]] _Fd _M_fd;
+  [[no_unique_address]] std::tuple<_BoundArgs...> _M_bound_args;
 };
 
   // Avoid the overhead of an empty tuple<> if there are no bound args.
@@ -1051,7 +1051,7 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
}
 
 private:
-  _Fd _M_fd;
+  [[no_unique_address]] _Fd _M_fd;
 };
 
   template
diff --git 
a/libstdc++-v3/testsuite/20_util/function_objects/bind_front/107784.cc 
b/libstdc++-v3/testsuite/20_util/function_objects/bind_front/107784.cc
index ec255f3ee36..f1f8cee4509 100644
--- a/libstdc++-v3/testsuite/20_util/function_objects/bind_front/107784.cc
+++ b/libstdc++-v3/testsuite/20_util/function_objects/bind_front/107784.cc
@@ -10,6 +10,42 @@ struct Foo
 
 void bar() { }
 
-// PR libstdc++/107784
+// PR libstdc++/107784 - QOI: sizeof( bind_front( Member-Function ) ) too big
 static_assert( sizeof(std::bind_front(::func)) == sizeof(::func) );
 static_assert( sizeof(std::bind_front()) == sizeof() );
+
+// PR libstdc++/108290 - QoI: bind_front captureless lambda is too big
+auto empty_lambda = [](auto, auto) { return 0; };
+
+struct {
+  void operator()(int, int, int) { }
+  template void operator()(T, T) { }
+} empty_class;
+
+static_assert(sizeof(std::bind_front(empty_lambda)) == 1);
+static_assert(sizeof(std::bind_front(empty_lambda, 1)) == sizeof(int));
+static_assert(sizeof(std::bind_front(empty_lambda, empty_lambda)) == 2);
+static_assert(sizeof(std::bind_front(empty_lambda, empty_class)) == 1);
+static_assert(sizeof(std::bind_front(empty_lambda, 1, 2)) == 2 * sizeof(int));
+static_assert(sizeof(std::bind_front(empty_lambda, '1', empty_lambda)) == 2);
+static_assert(sizeof(std::bind_front(empty_lambda, '1', empty_class)) == 1);
+
+static_assert(sizeof(std::bind_front(empty_class)) == 1);
+static_assert(sizeof(std::bind_front(empty_class, 1)) == sizeof(int));
+static_assert(sizeof(std::bind_front(empty_class, empty_lambda)) == 1);
+static_assert(sizeof(std::bind_front(empty_class, empty_class)) == 2);
+static_assert(sizeof(std::bind_front(empty_class, 1, 2)) == 2 * sizeof(int));
+static_assert(sizeof(std::bind_front(empty_class, '1', empty_lambda)) == 1);
+static_assert(sizeof(std::bind_front(empty_class, '1', empty_class)) == 2);
+
+struct derived1 : decltype(std::bind_front(empty_class))
+{
+  int i;
+};
+static_assert(sizeof(derived1) == sizeof(int));
+
+struct derived2 : decltype(std::bind_front(empty_class, empty_lambda))
+{
+  int i;
+};
+static_assert(sizeof(derived2) == sizeof(int));
-- 
2.39.0



Re: [PATCH v4 02/34] RISC-V: Add vlex_2.c

2023-01-05 Thread Joern Rennecke
On Wed, Jun 1, 2022 at 02:28:45 GMT 2022, zhongjuzhe
 wrote:
> gcc/testsuite/ChangeLog:
>
>* gcc.target/riscv/rvv/intrinsic/vlex_2.c: New test.

These intrinsic test cases look like they have been machine generated.  And if
they aren't, they probably should (have) be(en).  I've been working on
stabilizing
a tree with the rvv patches merged, and found a number of tests had diverged
in intrinsic function naming, arguments taken, and/or return type.
Fixing this all
with global replaces in dozens of files is quite messy.  It would be
preferable if
such issues could be fixed by adjusting a generator file, and just re-generating
the generated files.  That's one of the reasons why the GPL makes a point of
asking to include source code.  Even if that is not strictly required
for the testsuite
for license reasons, it makes good sense to do that for maintenance reasons.
The generator file should then also add a note where in the source
tree to find the
generator file, and, where appropriate, notes which part(s) of the
generator file
is/are responsible for generating the test case.


Re: [PATCH] gccrs: avoid printing to stderr in selftest::rust_flatten_list

2023-01-05 Thread David Malcolm via Gcc-patches
On Thu, 2023-01-05 at 15:44 +0100, Arthur Cohen wrote:
> Hi David,
> 
> On 1/4/23 20:28, David Malcolm wrote:
> > On Mon, 2023-01-02 at 13:47 +0100, Arthur Cohen wrote:
> > > Hi David,
> > > 
> > > Sorry for the delayed reply!
> > > 
> > > On 12/16/22 18:01, David Malcolm wrote:
> > > > Successfully bootstrapped & regrtested on x86_64-pc-linux-gnu.
> > > > 
> > > > OK for trunk?
> > > > 
> > > > gcc/rust/ChangeLog:
> > > >  * resolve/rust-ast-resolve-item.cc
> > > > (selftest::rust_flatten_list):
> > > >  Remove output to stderr.
> > 
> > For reference, the stderr spewage was:
> > 
> > foo::bar::baz
> > foo::bar::bul
> > > 
> > > > 
> > > > Signed-off-by: David Malcolm 
> > > > ---
> > > >    gcc/rust/resolve/rust-ast-resolve-item.cc | 3 ---
> > > >    1 file changed, 3 deletions(-)
> > > > 
> > > > diff --git a/gcc/rust/resolve/rust-ast-resolve-item.cc
> > > > b/gcc/rust/resolve/rust-ast-resolve-item.cc
> > > > index 0c38f28d530..1276e845acc 100644
> > > > --- a/gcc/rust/resolve/rust-ast-resolve-item.cc
> > > > +++ b/gcc/rust/resolve/rust-ast-resolve-item.cc
> > > > @@ -1202,9 +1202,6 @@ rust_flatten_list (void)
> > > >  auto paths = std::vector ();
> > > >  Rust::Resolver::flatten_list (list, paths);
> > > >    
> > > > -  for (auto  : paths)
> > > > -    fprintf (stderr, "%s\n", path.as_string ().c_str ());
> > > > -
> > > >  ASSERT_TRUE (!paths.empty ());
> > > >  ASSERT_EQ (paths.size (), 2);
> > > >  ASSERT_EQ (paths[0].get_segments ()[0].as_string (),
> > > > "foo");
> > > 
> > > Looks good to me. OK for trunk :)
> > > 
> > > Thanks for taking the time!
> > 
> > I was about to push this and
> >   
> > https://gcc.gnu.org/pipermail/gcc-patches/2022-December/608645.html
> > to trunk (after retesting against all the changes since before my
> > break), but you mentioned today on IRC something about merger
> > issues:
> > 
> >  ibuclaw: I'm looking at the remaining issues for
> > updating
> > GCC's master with our most recent gccrs commits. I've come to the
> > conclusion that it would be easier for me to upstream your target
> > changes while I'm upstreaming/submitting all of the missing commits
> >  would that suit you?
> >  it would just be me sending in your commits, but I
> > wouldn't be author on them or anything of course
> >  this would enable us to time them properly within the
> > rest of the commits, so there'd be no conflicts or anything of the
> > sort
> >  dmalcolm: same question to you, actually :)
> 
> Sorry for the confusion, and for disappearing from IRC before you got
> a 
> chance to answer! In those messages, I was talking about the 
> `error_meta` PR you had submitted to us on Github. Since we are in
> the 
> process of updating upstream with the current state of our dev
> branch, 
> we have to figure out what to do with these commits that are already 
> present in our dev branch but not upstreamed yet. Since you and Iain 
> have pushed commits to our dev branch, we are wondering whether you'd
> like us to upstream them during this updating process or if you'd
> like 
> to do so on your own.

For reference, presumably this is:
  https://github.com/Rust-GCC/gccrs/pull/1408
which was kind of an experimenal proof-of-concept on my part.

As far as I can tell, that PR added some relatively trivial new stuff
to gcc/diagnostic*, and otherwise just touched the gcc/rust
subdirectory, so I hope it's relatively trivial to merge.

I'd prefer to leave the responsibility for merging that work into trunk
to you.

> 
> Regarding the two new patches that you've submitted here and that
> aren't 
> upstreamed or merged in our dev branch yet, it's a bit different. You
> can either go ahead and push them to trunk if that's what you'd like,
> and I'm assuming that when we merge upstream and our dev branch this 
> won't cause any conflict. And if these two patches do, they are easy 
> enough that we can fix them by hand.

Thanks.  I've gone ahead and pushed the two simple patches to trunk as:
  r13-5031-gb0edfa0ef02c0f
and:
  r13-5032-gefce0caf2d75df

Dave



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

2023-01-05 Thread Szabolcs Nagy via Gcc-patches
The 01/03/2023 17:27, Wilco Dijkstra wrote:
> 
> > Also, if I understood correctly, the reason we use REG_UNSAVED is to
> > ensure that state from one frame isn't carried across to a parent frame,
> > in cases where the parent frame lacks any signing.  That is, each frame
> > should start out with a zero bit even if a child frame is unwound while
> > it has a set bit.
> 
> This works fine since all registers are initialized to REG_UNSAVED every 
> frame.
> 
> In v2 I've removed some clutter and encode the signing state in REG_UNSAVED/
> REG_UNDEFINED.

this looks good to me.


> @@ -1206,8 +1205,10 @@ execute_cfa_program (const unsigned char *insn_ptr,
>   /* This CFA is multiplexed with Sparc.  On AArch64 it's used to 
> toggle
>  return address signing status.  */
>   reg = DWARF_REGNUM_AARCH64_RA_STATE;
> - gcc_assert (fs->regs.how[reg] == REG_UNSAVED);
> - fs->regs.reg[reg].loc.offset ^= 1;
> + if (fs->regs.how[reg] == REG_UNSAVED)
> +   fs->regs.how[reg] = REG_UNDEFINED;
> + else
> +   fs->regs.how[reg] = REG_UNSAVED;
>  #else
>   /* ??? Hardcoded for SPARC register window configuration.  */
>   if (__LIBGCC_DWARF_FRAME_REGISTERS__ >= 32)

i would keep the assert: how[reg] must be either UNSAVED or UNDEFINED
here, other how[reg] means the toggle cfi instruction is mixed with
incompatible instructions for the pseudo reg.

and i would add a comment about this e.g. saying that UNSAVED/UNDEFINED
how[reg] is used for tracking the return address signing status and
other how[reg] is not allowed here.

otherwise the patch looks good.



[COMMITTED] ada: Minor tweak to test added in previous change

2023-01-05 Thread Marc Poulhiès via Gcc-patches
From: Eric Botcazou 

This changes the test to use the common idion of the codebase.

gcc/ada/

* exp_util.adb (Make_CW_Equivalent_Type) : Tweak.

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

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

diff --git a/gcc/ada/exp_util.adb b/gcc/ada/exp_util.adb
index 245c3cd9dc7..ab4b18da538 100644
--- a/gcc/ada/exp_util.adb
+++ b/gcc/ada/exp_util.adb
@@ -9731,7 +9731,7 @@ package body Exp_Util is
  --  identifies T.
 
  if Is_Entity_Name (Exp)
-   and then Ekind (Entity (Exp)) in Constant_Or_Variable_Kind
+   and then Ekind (Entity (Exp)) in E_Constant | E_Variable
  then
 return True;
 
-- 
2.34.1



[COMMITTED] ada: Remove unhelpful special case for renamed bodies in GNATprove mode

2023-01-05 Thread Marc Poulhiès via Gcc-patches
From: Piotr Trojanek 

This patch reverts a special-case related to inlining of renamed bodies
in GNATprove mode. Its idea was that inlining is decided in routine
Cannot_Inline, which is called much later. This didn't quite work,
because in the meantime the renamed body was prepared to inlining in
Build_Body_To_Inline, which was not designed to handle renamed bodies.

gcc/ada/

* freeze.adb (Build_Renamed_Body): Revert a special case for
GNATprove; remove unnecessary initialization of a local variable.

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

---
 gcc/ada/freeze.adb | 7 ++-
 1 file changed, 2 insertions(+), 5 deletions(-)

diff --git a/gcc/ada/freeze.adb b/gcc/ada/freeze.adb
index 97a25d10835..a3ab685f5fc 100644
--- a/gcc/ada/freeze.adb
+++ b/gcc/ada/freeze.adb
@@ -398,7 +398,7 @@ package body Freeze is
   Nam: constant Node_Id := Name (N);
   Old_S  : Entity_Id;
   Spec   : constant Node_Id := New_Copy_Tree (Specification (Decl));
-  Actuals: List_Id := No_List;
+  Actuals: List_Id;
   Call_Node  : Node_Id;
   Call_Name  : Node_Id;
   Body_Node  : Node_Id;
@@ -477,14 +477,11 @@ package body Freeze is
   --  calls to the renamed entity. The body must be generated in any case
   --  for calls that may appear elsewhere. This is not done in the case
   --  where the subprogram is an instantiation because the actual proper
-  --  body has not been built yet. This is also not done in GNATprove mode
-  --  as we need to check other conditions for creating a body to inline
-  --  in that case, which are controlled in Analyze_Subprogram_Body_Helper.
+  --  body has not been built yet.
 
   if Ekind (Old_S) in E_Function | E_Procedure
 and then Nkind (Decl) = N_Subprogram_Declaration
 and then not Is_Generic_Instance (Old_S)
-and then not GNATprove_Mode
   then
  Set_Body_To_Inline (Decl, Old_S);
   end if;
-- 
2.34.1



[COMMITTED] ada: Clean up interface handling in Expand_N_Object_Declaration

2023-01-05 Thread Marc Poulhiès via Gcc-patches
From: Eric Botcazou 

The code performing the expansion of objects with (class-wide) interface
type in Expand_N_Object_Declaration is fairly low-level, fiddling with the
homonym and entity chains, which is unnecessary.

gcc/ada/

* exp_ch3.adb (Expand_N_Object_Declaration): Rewrite the end of the
handling of objects with (class-wide) interface type by using the
same idiom as the other cases generating a renaming.
* exp_util.adb (Is_Displacement_Of_Object_Or_Function_Result): Tweak
pattern matching code and exclude special return objects.
(Requires_Cleanup_Actions): Adjust comment.
* exp_ch7.adb (Build_Finalizer): Likewise.

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

---
 gcc/ada/exp_ch3.adb  | 155 ---
 gcc/ada/exp_ch7.adb  |  13 ++--
 gcc/ada/exp_util.adb |  39 +++
 3 files changed, 93 insertions(+), 114 deletions(-)

diff --git a/gcc/ada/exp_ch3.adb b/gcc/ada/exp_ch3.adb
index 23a910ecdba..fc4089dc123 100644
--- a/gcc/ada/exp_ch3.adb
+++ b/gcc/ada/exp_ch3.adb
@@ -7501,12 +7501,14 @@ package body Exp_Ch3 is
 
 elsif Tagged_Type_Expansion then
declare
-  Iface: constant Entity_Id := Root_Type (Typ);
-  Expr_N   : Node_Id := Expr;
-  Expr_Typ : Entity_Id;
-  New_Expr : Node_Id;
-  Obj_Id   : Entity_Id;
-  Tag_Comp : Node_Id;
+  Iface : constant Entity_Id := Root_Type (Typ);
+
+  Expr_Typ : Entity_Id;
+  New_Expr : Node_Id;
+  Obj_Id   : Entity_Id;
+  Ptr_Obj_Decl : Node_Id;
+  Ptr_Obj_Id   : Entity_Id;
+  Tag_Comp : Node_Id;
 
begin
   --  If the original node of the expression was a conversion
@@ -7516,26 +7518,27 @@ package body Exp_Ch3 is
   --  component. This code must be kept synchronized with the
   --  expansion done by routine Expand_Interface_Conversion
 
-  if not Comes_From_Source (Expr_N)
-and then Nkind (Expr_N) = N_Explicit_Dereference
-and then Nkind (Original_Node (Expr_N)) = N_Type_Conversion
-and then Etype (Original_Node (Expr_N)) = Typ
+  if not Comes_From_Source (Expr)
+and then Nkind (Expr) = N_Explicit_Dereference
+and then Nkind (Original_Node (Expr)) = N_Type_Conversion
+and then Etype (Original_Node (Expr)) = Typ
   then
- Rewrite (Expr_N, Original_Node (Expression (N)));
+ Rewrite (Expr, Original_Node (Expression (N)));
   end if;
 
   --  Avoid expansion of redundant interface conversion
 
-  if Is_Interface (Etype (Expr_N))
-and then Nkind (Expr_N) = N_Type_Conversion
-and then Etype (Expr_N) = Typ
+  if Is_Interface (Etype (Expr))
+and then Nkind (Expr) = N_Type_Conversion
+and then Etype (Expr) = Typ
   then
- Expr_N := Expression (Expr_N);
- Set_Expression (N, Expr_N);
+ Expr_Q := Expression (Expr);
+  else
+ Expr_Q := Expr;
   end if;
 
-  Obj_Id   := Make_Temporary (Loc, 'D', Expr_N);
-  Expr_Typ := Base_Type (Etype (Expr_N));
+  Obj_Id   := Make_Temporary (Loc, 'D', Expr_Q);
+  Expr_Typ := Base_Type (Etype (Expr_Q));
 
   if Is_Class_Wide_Type (Expr_Typ) then
  Expr_Typ := Root_Type (Expr_Typ);
@@ -7544,12 +7547,13 @@ package body Exp_Ch3 is
   --  Replace
   -- CW : I'Class := Obj;
   --  by
-  -- Tmp : T := Obj;
+  -- Tmp : Typ := Obj;
   -- type Ityp is not null access I'Class;
-  -- CW  : I'Class renames Ityp (Tmp.I_Tag'Address).all;
+  -- Rnn : constant Ityp := Ityp (Tmp.I_Tag'Address);
+  -- CW  : I'Class renames Rnn.all;
 
-  if Comes_From_Source (Expr_N)
-and then Nkind (Expr_N) = N_Identifier
+  if Comes_From_Source (Expr_Q)
+and then Is_Entity_Name (Expr_Q)
 and then not Is_Interface (Expr_Typ)
 and then Interface_Present_In_Ancestor (Expr_Typ, Typ)
 and then (Expr_Typ = Etype (Expr_Typ)
@@ -7563,7 +7567,7 @@ package body Exp_Ch3 is
  Defining_Identifier => Obj_Id,
  Object_Definition   =>

[COMMITTED] ada: Fix nested generic instantiation

2023-01-05 Thread Marc Poulhiès via Gcc-patches
Previous fix for generic instantiation was not precise enough and could
wrongly assume the instantiation node to be an N_Expanded_Name.

gcc/ada/

* sem_ch12.adb (Instantiate_Package_Body): Better filtering when
installing parent on the scope stack.

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

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

diff --git a/gcc/ada/sem_ch12.adb b/gcc/ada/sem_ch12.adb
index 0f2dd39b53c..1755549bd8b 100644
--- a/gcc/ada/sem_ch12.adb
+++ b/gcc/ada/sem_ch12.adb
@@ -12182,6 +12182,9 @@ package body Sem_Ch12 is
  elsif Ekind (Scope (Gen_Unit)) = E_Generic_Package
and then Ekind (Scope (Act_Decl_Id)) = E_Package
and then Is_Generic_Instance (Scope (Act_Decl_Id))
+   and then Nkind
+ (Name (Get_Unit_Instantiation_Node
+  (Scope (Act_Decl_Id = N_Expanded_Name
  then
 Par_Ent := Entity
   (Prefix (Name (Get_Unit_Instantiation_Node
-- 
2.34.1



[COMMITTED] ada: INOX: prototype RFC on String Interpolation

2023-01-05 Thread Marc Poulhiès via Gcc-patches
From: Javier Miranda 

This patch incorporates a prototype for a new string literal syntax
which supports the use of "string interpolation," where the names
of variables or expressions can be used directly within the string
literal, such that the value of the variable or the expression is
"interpolated" directly into the value of the enclosing string
upon use at run-time.

gcc/ada/

* scans.ads (Tok_Left_Curly_Bracket, Tok_Right_Curly_Bracket)
(Tok_Left_Interpolated_String): Placed in no category since they
don't fit well in the existing categories. Fix typo in comment.
(Inside_Interpolated_String_Literal): New scan state variable.
* scng.adb (Slit): Scan interpolated string literals,
continuations of interpolated string literals and escaped
characters found in interpolated string literals.
(Scan): Handle consecutive interpolated expressions. Handle ending
delimiter placed immediately after an interpolated expression.
Handle string literal placed after interpolated expression. Handle
left and right curly brackets; when extensions are not allowed
they are treated as left and right paren; when extensions are
allowed they are handled as delimiters of interpolated string
literals.
* sinfo.ads (N_Interpolated_String_Literal): New node.
* gen_il-gen-gen_nodes.adb (N_Interpolated_String_Literal): Define
N_String_Literal node.
* gen_il-types.ads (Opt_Type_Enum): Define N_String_Literal as
concrete node type.
* par-ch2.adb (P_Interpolated_String_Literal): New subprogram.
* par-ch4.adb (P_Simple_Expression): Handle '}' as expression
terminator when scanning an interpolated expression; disable error
recovery machinery for binary operator when we are processing an
interpolated string literal and reach the expression terminator
'}'.
(P_Primary): Call P_Interpolated_String_Literal when the opening
interpolated-string-literal delimiter is found (that is, the left
curly bracket '{').
* par-tchk.adb (T_Right_Curly_Bracket): New subprogram.
* par.adb (P_Interpolated_String_Literal): New declaration.
(T_Right_Curly_Bracket): New declaration.
* sem.adb (Analyze): Call Analyze_Interpolated_String_Literal.
* sem_ch2.ads (Analyze_Interpolated_String_Literal): New
subprogram
* sem_ch2.adb (Analyze_Interpolated_String_Literal): Likewise.
* sem_util.adb (Is_User_Defined_Literal): Complete mapping of
literal aspects adding that interpolated string literals have no
correspondence with any aspect.
* sem_res.adb (Resolve_Interpolated_String_Literal): New
subprogram.
(Has_Applicable_User_Defined_Literal): Complete mapping of literal
aspects adding that interpolated string literals have no
correspondency with any aspect.
* expander.adb (Expand): Add call to
Expand_N_Interpolated_String_Literal.
* exp_util.adb (Insert_Actions): Handle
N_Interpolated_String_Literal nodes; that is, continue climbing.
* exp_ch2.ads (Expand_N_Interpolated_String_Literal): New
subprogram.
* exp_ch2.adb (Expand_N_Interpolated_String_Literal): Likewise.
* exp_put_image.adb (Build_Elementary_Put_Image_Call): Add missing
conversion to force dispatching call. Required to handle calls to
descendants.
(Build_String_Put_Image_Call): Do not output string delimiters
when the put_image call is part of an interpolated string literal.
* rtsfind.ads (RTU_Id): Add RE_Set_Trim_Leading_Spaces.
* sprint.adb (Sprint_Node): Output interpolated string contents.
* libgnat/a-stbubo.adb (Get_UTF_8): Add default value for
Trim_Leading_White_Spaces component in aggregate.
(Buffer_Type_Implementation): Update Trim_Leading_White_Spaces.
* libgnat/a-stbuun.adb (Get_UTF_8): Likewise.
(Buffer_Type_Implementation): Likewise.
* libgnat/a-sttebu.ads (Set_Trim_Leading_Spaces): New subprogram.
(Trim_Leading_Spaces): New subprogram.
(Root_Buffer_Type): Adding Trim_Leading_While_Spaces component.
* libgnat/a-sttebu.adb (procedure Set_Trim_Leading_Spaces): New
subprogram.
(Trim_Leading_Space): New subprogram.
(Put_UTF_8): Handle Trim_Leading_White_Spaces.
(New_Line): Likewise.
* libgnat/s-putima.ads (Put_Image_String): Adding formal
(with_delimiters).
(Put_Image_Wide_String): Likewise.
(Put_Image_Wide_Wide_String): Likewise.
* libgnat/s-putima.adb (Put_Image_String): Adding support for new
formal.
(Put_Image_Wide_String): Likewise.
(Put_Image_Wide_Wide_String): Likewise.

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

---
 gcc/ada/exp_ch2.adb  | 117 

[COMMITTED] ada: Optimize class-wide objects initialized with function calls

2023-01-05 Thread Marc Poulhiès via Gcc-patches
From: Eric Botcazou 

This optimizes the implementation of class-wide objects initialized with
function calls in the non-interface case, by avoiding an unnecessary copy
operation and/or a dispatching call to the _Size primitive when possible.

gcc/ada/

* exp_ch3.adb (Expand_N_Object_Declaration): New local variable
Func_Id holding the function for a special return object.
Use a direct renaming in the class-wide case when the initializing
expression is a captured function call, except for a special return
object when the two functions do not return on the same stack.
Apply the accessibility check for class-wide special return objects.
* exp_util.adb (Make_CW_Equivalent_Type) : New.
Do not force a dispatching call to the primitive operation _Size if
the expression is known to statically have the tag of its type.

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

---
 gcc/ada/exp_ch3.adb  | 54 +++
 gcc/ada/exp_util.adb | 89 ++--
 2 files changed, 108 insertions(+), 35 deletions(-)

diff --git a/gcc/ada/exp_ch3.adb b/gcc/ada/exp_ch3.adb
index a3b62249c7d..23a910ecdba 100644
--- a/gcc/ada/exp_ch3.adb
+++ b/gcc/ada/exp_ch3.adb
@@ -6235,6 +6235,10 @@ package body Exp_Ch3 is
   --  and ultimately rewritten as a renaming, so initialization activities
   --  need to be deferred until after that is done.
 
+  Func_Id : constant Entity_Id :=
+   (if Special_Ret_Obj then Return_Applies_To (Scope (Def_Id)) else Empty);
+  --  The function if this is a special return object, otherwise Empty
+
   function Build_Equivalent_Aggregate return Boolean;
   --  If the object has a constrained discriminated type and no initial
   --  value, it may be possible to build an equivalent aggregate instead,
@@ -6243,7 +6247,6 @@ package body Exp_Ch3 is
   function Build_Heap_Or_Pool_Allocator
 (Temp_Id: Entity_Id;
  Temp_Typ   : Entity_Id;
- Func_Id: Entity_Id;
  Ret_Typ: Entity_Id;
  Alloc_Expr : Node_Id) return Node_Id;
   --  Create the statements necessary to allocate a return object on the
@@ -6442,7 +6445,6 @@ package body Exp_Ch3 is
   function Build_Heap_Or_Pool_Allocator
 (Temp_Id: Entity_Id;
  Temp_Typ   : Entity_Id;
- Func_Id: Entity_Id;
  Ret_Typ: Entity_Id;
  Alloc_Expr : Node_Id) return Node_Id
   is
@@ -7103,8 +7105,6 @@ package body Exp_Ch3 is
   ---
 
   function Make_Allocator_For_Return (Expr : Node_Id) return Node_Id is
- Func_Id : constant Entity_Id := Return_Applies_To (Scope (Def_Id));
-
  Alloc : Node_Id;
 
   begin
@@ -7933,13 +7933,19 @@ package body Exp_Ch3 is
 --  finalize it prematurely (see Expand_Simple_Function_Return
 --  for the same test in the case of a simple return).
 
+--  Moreover, in the case of a special return object, we also
+--  need to make sure that the two functions return on the same
+--  stack, otherwise we would create a dangling reference.
+
 and then
   ((not Is_Library_Level_Entity (Def_Id)
  and then Is_Captured_Function_Call (Expr_Q)
- and then (not Special_Ret_Obj
-or else Is_Related_To_Func_Return
-  (Entity (Prefix (Expr_Q
- and then not Is_Class_Wide_Type (Typ))
+ and then
+   (not Special_Ret_Obj
+ or else
+  (Is_Related_To_Func_Return (Entity (Prefix (Expr_Q)))
+and then Needs_Secondary_Stack (Etype (Expr_Q)) =
+ Needs_Secondary_Stack (Etype (Func_Id)
 
--  If the initializing expression is a variable with the
--  flag OK_To_Rename set, then transform:
@@ -8148,8 +8154,6 @@ package body Exp_Ch3 is
 
   if Is_Build_In_Place_Return_Object (Def_Id) then
  declare
-Func_Id : constant Entity_Id := Return_Applies_To (Scope (Def_Id));
-
 Init_Stmt   : Node_Id;
 Obj_Acc_Formal  : Entity_Id;
 
@@ -8441,7 +8445,6 @@ package body Exp_Ch3 is
 Build_Heap_Or_Pool_Allocator
   (Temp_Id=> Alloc_Obj_Id,
Temp_Typ   => Acc_Typ,
-   Func_Id=> Func_Id,
Ret_Typ=> Desig_Typ,
Alloc_Expr => Heap_Allocator))),
 
@@ -8465,7 +8468,6 @@ package body Exp_Ch3 is
 Build_Heap_Or_Pool_Allocator
   (Temp_Id=> Alloc_Obj_Id,

[COMMITTED] ada: Flag renaming-as-spec as a body to inline

2023-01-05 Thread Marc Poulhiès via Gcc-patches
From: Piotr Trojanek 

For GNAT the frontend is only inlining subprograms with explicit specs,
including specs completed with renaming-as-body. For GNATprove the
frontend must also inline renamings acting as specs. Otherwise, we will
try to build a body-to-inline with code that is can't handle unusual
subprogram renamings, e.g. those of the form "object.call".

gcc/ada/

* freeze.adb (Build_Renamed_Body): Rewrite subprogram renaming to
subprogram declaration early and then set the Body_To_Inling flag.

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

---
 gcc/ada/freeze.adb | 13 ++---
 1 file changed, 6 insertions(+), 7 deletions(-)

diff --git a/gcc/ada/freeze.adb b/gcc/ada/freeze.adb
index a3ab685f5fc..0e55f146e28 100644
--- a/gcc/ada/freeze.adb
+++ b/gcc/ada/freeze.adb
@@ -473,6 +473,12 @@ package body Freeze is
  Set_Is_Overloaded (Call_Name, False);
   end if;
 
+  if Nkind (Decl) /= N_Subprogram_Declaration then
+ Rewrite (N,
+   Make_Subprogram_Declaration (Loc,
+ Specification => Specification (N)));
+  end if;
+
   --  For simple renamings, subsequent calls can be expanded directly as
   --  calls to the renamed entity. The body must be generated in any case
   --  for calls that may appear elsewhere. This is not done in the case
@@ -480,7 +486,6 @@ package body Freeze is
   --  body has not been built yet.
 
   if Ekind (Old_S) in E_Function | E_Procedure
-and then Nkind (Decl) = N_Subprogram_Declaration
 and then not Is_Generic_Instance (Old_S)
   then
  Set_Body_To_Inline (Decl, Old_S);
@@ -655,12 +660,6 @@ package body Freeze is
  Statements => New_List (Call_Node)));
   end if;
 
-  if Nkind (Decl) /= N_Subprogram_Declaration then
- Rewrite (N,
-   Make_Subprogram_Declaration (Loc,
- Specification => Specification (N)));
-  end if;
-
   --  Link the body to the entity whose declaration it completes. If
   --  the body is analyzed when the renamed entity is frozen, it may
   --  be necessary to restore the proper scope (see package Exp_Ch13).
-- 
2.34.1



[COMMITTED] ada: Update gnatpp documentation with --layout switch

2023-01-05 Thread Marc Poulhiès via Gcc-patches
From: Joao Azevedo 

Update legacy switches.

gcc/ada/

* doc/gnat_ugn/gnat_utility_programs.rst: add gnatpp --layout
switch and update legacy switches.

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

---
 .../doc/gnat_ugn/gnat_utility_programs.rst| 831 +++---
 1 file changed, 325 insertions(+), 506 deletions(-)

diff --git a/gcc/ada/doc/gnat_ugn/gnat_utility_programs.rst 
b/gcc/ada/doc/gnat_ugn/gnat_utility_programs.rst
index 7df45d518aa..639534d90e6 100644
--- a/gcc/ada/doc/gnat_ugn/gnat_utility_programs.rst
+++ b/gcc/ada/doc/gnat_ugn/gnat_utility_programs.rst
@@ -496,18 +496,18 @@ building specialized scripts.
 
where
 
-   * ``switches`` is an optional sequence of switches defining such properties 
as
- the formatting rules, the source search path, and the destination for the
- output source file
+   * ``switches`` is an optional sequence of switches defining such properties
+ as the formatting rules, the source search path, and the destination for
+ the output source file
 
* ``filename`` is the name of the source file to reformat; wildcards
  or several file names on the same gnatpp command are allowed. The
  file name may contain path information; it does not have to follow
  the GNAT file naming rules
 
- Note that it is no longer necessary to specify the Ada language version;
- ``gnatpp`` can process Ada source code written in any version from
- Ada 83 onward without specifying any language version switch.
+   Note that it is no longer necessary to specify the Ada language version;
+   ``gnatpp`` can process Ada source code written in any version from Ada 83
+   onward without specifying any language version switch.
 
 
.. _Switches_for_gnatpp:
@@ -519,8 +519,8 @@ building specialized scripts.
``gnatpp``, organized by category.
 
You specify a switch by supplying a name and generally also a value.
-   In many cases the values for a switch with a given name are incompatible 
with
-   each other
+   In many cases the values for a switch with a given name are incompatible
+   with each other
(for example the switch that controls the casing of a reserved word may have
exactly one value: upper case, lower case, or
mixed case) and thus exactly one such switch can be in effect for an
@@ -532,191 +532,267 @@ building specialized scripts.
Abbreviated forms (the name appearing once, followed by each value) are
not permitted.
 
-   .. _Alignment_Control:
 
-   Alignment Control
-   ^
+   .. _Layout_Control:
 
-   .. index:: Alignment control in gnatpp
-
-   Programs can be easier to read if certain constructs are vertically aligned.
-   By default, alignment of the following constructs is set ON:
-
- * ``:`` in declarations,
- * ``:=`` in initializations in declarations,
- * ``:=`` in assignment statements,
- * ``=>`` in associations, and
- * ``at`` keywords in the component clauses in record representation 
clauses.
-
-   In addition, ``in`` and ``out`` in parameter specifications are lined up.
+   Layout Control
+   ^^
 
-   .. index:: --no-alignment (gnatpp)
-   .. index:: --alignment (gnatpp)
-   .. index:: --no-align-modes (gnatpp)
+   .. index:: Layout control in gnatpp
 
+   ``gnatpp`` provides a layout switch which controls the general
+   formatting style:
 
-   :switch:`--no-alignment`
- Set alignment to OFF
+   .. index:: layout(gnatpp)
 
+   :switch:`--layout=default|minimal|compact|tall`
 
-   :switch:`--alignment`
- Set alignment to ON
+   :switch:`default`
+ The default layout will follow a compact style but add aligment and put
+ some keywords on a separate line.
+ 
+ Alignment is added in the the following constructs:
 
+ * ``:`` in declarations,
+ * ``:=`` in initializations in declarations,
+ * ``:=`` in assignment statements,
+ * ``=>`` in associations, and
+ * ``at`` keywords in the component clauses in record representation
+   clauses.
+
+ In addition, ``in`` and ``out`` keywords in parameter specifications are
+ also lined up.
+
+ The keyword ``is`` is placed on a separate line in a subprogram body in
+ case the spec occupies more than one line.
+
+ The keyword ``return`` is placed on a separate line if a subprogram spec
+ does not fit on one line.
+
+   :switch:`minimal`
+ The minimal layout will avoid changing the source layout by keeping all
+ line breaks from the original source (it will not insert or delete any).
+ It will add indentation where appropriate as long as it does not exceed
+ the line length limit.
+
+   :switch:`compact`
+ The compact layout will avoid adding line breaks and alignment by packing
+ as many subexpressions on the same line as possible.
+
+ Whole-line comments that form a paragraph will be filled in typical word
+ processor style (that is, moving words between lines to make them similar
+ 

[COMMITTED] ada: Fix spurious emissions of -gnatwj warning

2023-01-05 Thread Marc Poulhiès via Gcc-patches
From: Ronan Desplanques 

Before this patch, the compiler would erroneously emit a warning
about the use of parentheses for array aggregates being discouraged
in some situations. Those situations were the ones where array
aggregates were used as generic actuals when instantiating generic
packages defined in the runtime library.

This patch fixes this issue by looking at the Ada version explicitly
specified by the user instead of the Ada_Version flag which is
always set to the latest Ada version when compiling code from the
runtime library.

gcc/ada/

* sem_aggr.adb (Resolve_Array_Aggregate): Tweak conditions for
warning about use of parentheses for array aggregates.

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

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

diff --git a/gcc/ada/sem_aggr.adb b/gcc/ada/sem_aggr.adb
index 433f1ac84ca..958b2bbbd18 100644
--- a/gcc/ada/sem_aggr.adb
+++ b/gcc/ada/sem_aggr.adb
@@ -1922,7 +1922,7 @@ package body Sem_Aggr is
 
   --  Disable the warning for GNAT Mode to allow for easier transition.
 
-  if Ada_Version >= Ada_2022
+  if Ada_Version_Explicit >= Ada_2022
 and then Warn_On_Obsolescent_Feature
 and then not GNAT_Mode
 and then not Is_Homogeneous_Aggregate (N)
-- 
2.34.1



[COMMITTED] ada: Do not use decimal approximation in -gnatRj output

2023-01-05 Thread Marc Poulhiès via Gcc-patches
From: Eric Botcazou 

This avoids an unnecessary loss of precision for real values.

gcc/ada/

* repinfo.ads (The JSON output format): Document change.
* urealp.adb (UR_Write_To_JSON): Output a fraction instead of a
decimal approximation.

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

---
 gcc/ada/repinfo.ads |  4 ++--
 gcc/ada/urealp.adb  | 39 +--
 2 files changed, 15 insertions(+), 28 deletions(-)

diff --git a/gcc/ada/repinfo.ads b/gcc/ada/repinfo.ads
index 64624077cec..f9200ee04e4 100644
--- a/gcc/ada/repinfo.ads
+++ b/gcc/ada/repinfo.ads
@@ -196,8 +196,8 @@ package Repinfo is
--"Object_Size"  :  numerical expression
--"Value_Size"   :  numerical expression
--"Component_Size"   :  numerical expression
-   --"Range":  array of numbers
-   --"Small":  number
+   --"Range":  array of numerical expressions
+   --"Small":  numerical expression
--"Alignment":  number
--"Convention"   :  string
--"Linker_Section"   :  string
diff --git a/gcc/ada/urealp.adb b/gcc/ada/urealp.adb
index 830520788d9..37bf3a7cb79 100644
--- a/gcc/ada/urealp.adb
+++ b/gcc/ada/urealp.adb
@@ -1518,14 +1518,11 @@ package body Urealp is
-- UR_Write_To_JSON --
--
 
-   --  We defer to the implementation of UR_Write in all cases, either directly
-   --  for values that are naturally written in a JSON compatible format, or by
-   --  first computing a decimal approximation for other values.
+   --  We defer to the implementation of UR_Write for values that are naturally
+   --  written in a JSON compatible format and write a fraction for the others.
 
procedure UR_Write_To_JSON (Real : Ureal) is
-  Val  : constant Ureal_Entry  := Ureals.Table (Real);
-  Imrk : constant Uintp.Save_Mark  := Mark;
-  Rmrk : constant Urealp.Save_Mark := Mark;
+  Val : constant Ureal_Entry := Ureals.Table (Real);
 
   T : Ureal;
 
@@ -1561,31 +1558,21 @@ package body Urealp is
   elsif Val.Rbase = 0 and then Val.Num mod Val.Den = 0 then
  T := Real;
 
-  --  For other constants, compute an approximation in base 10
+  --  Other non-based (rational) constants are written in num/den style
 
   else
- declare
-A : constant Ureal := UR_Abs (Real);
---  The absolute value
-
-E : constant Uint  :=
-  (if A < Ureal_1
-   then UI_From_Int (3 - Decimal_Exponent_Lo (Real))
-   else Uint_3);
---  The exponent for at least 3 digits after the decimal point
-
-Num : constant Uint :=
-UR_To_Uint (UR_Mul (A, UR_Exponentiate (Ureal_10, E)));
---  The numerator appropriately rounded
-
- begin
-T := UR_From_Components (Num, E, 10, Val.Negative);
- end;
+ Write_Str ("{ ""code"": ""/"", ""operands"": [ ");
+ if Val.Negative then
+Write_Char ('-');
+ end if;
+ UI_Write (Val.Num, Decimal);
+ Write_Str (".0, ");
+ UI_Write (Val.Den, Decimal);
+ Write_Str (".0 ] }");
+ return;
   end if;
 
   UR_Write (T);
-  Release (Imrk);
-  Release (Rmrk);
end UR_Write_To_JSON;
 
-
-- 
2.34.1



[COMMITTED] ada: Further adjust freezing for expansion of contracts

2023-01-05 Thread Marc Poulhiès via Gcc-patches
From: Eric Botcazou 

This further adjusts a test deciding whether to freeze an entity coming from
an outer scope in an inner scope based on language rules, to the presence of
the new internal subprogram generated because of post-conditions.

gcc/ada/

* freeze.adb (Freeze_Entity): For the purpose of deciding whether to
freeze an entity coming from an outer scope in an inner scope, treat
the internal subprogram generated because of post-conditions as also
coming from source if the original subprogram itself does.

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

---
 gcc/ada/freeze.adb | 7 ++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/gcc/ada/freeze.adb b/gcc/ada/freeze.adb
index 7f78b4315a8..97a25d10835 100644
--- a/gcc/ada/freeze.adb
+++ b/gcc/ada/freeze.adb
@@ -6281,7 +6281,10 @@ package body Freeze is
  end if;
 
  --  Otherwise, loop through scopes checking if an enclosing scope
- --  comes from source or is a generic.
+ --  comes from source or is a generic. Note that, for the purpose
+ --  of this test, we need to consider that the internally generated
+ --  subprogram described above comes from source too if the original
+ --  subprogram itself does.
 
  declare
 S : Entity_Id;
@@ -6291,6 +6294,8 @@ package body Freeze is
 while Present (S) loop
if Is_Overloadable (S) then
   if Comes_From_Source (S)
+or else (Chars (S) = Name_uWrapped_Statements
+  and then Comes_From_Source (Scope (S)))
 or else Is_Generic_Instance (S)
 or else Is_Child_Unit (S)
   then
-- 
2.34.1



[COMMITTED] ada: Fix pasto in comment

2023-01-05 Thread Marc Poulhiès via Gcc-patches
From: Eric Botcazou 

gcc/ada/

* exp_ch3.adb (Expand_N_Object_Declaration): Fix pasto in comment.

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

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

diff --git a/gcc/ada/exp_ch3.adb b/gcc/ada/exp_ch3.adb
index a76acf34d66..a3b62249c7d 100644
--- a/gcc/ada/exp_ch3.adb
+++ b/gcc/ada/exp_ch3.adb
@@ -8715,8 +8715,8 @@ package body Exp_Ch3 is
   --type Txx is access all ...;
   --Rxx : constant Txx :=
   --  new ['()][storage_pool =
-  --system__secondary_stack__rs_pool][procedure_to_call =
-  --system__secondary_stack__rs_allocate];
+  --system__return_stack__rs_pool][procedure_to_call =
+  --system__return_stack__rs_allocate];
 
   --Result : T renames Rxx.all;
 
-- 
2.34.1



[COMMITTED] ada: Simplify new expansion of contracts

2023-01-05 Thread Marc Poulhiès via Gcc-patches
From: Eric Botcazou 

We can now use an extended return statement in all cases since it no longer
generates an extra copy for nonlimited by-reference types.

gcc/ada/

* contracts.adb (Build_Subprogram_Contract_Wrapper): Generate an
extended return statement in all cases.
(Expand_Subprogram_Contract): Adjust comment.

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

---
 gcc/ada/contracts.adb | 105 ++
 1 file changed, 5 insertions(+), 100 deletions(-)

diff --git a/gcc/ada/contracts.adb b/gcc/ada/contracts.adb
index 59121ca9ea2..77c231e1d4f 100644
--- a/gcc/ada/contracts.adb
+++ b/gcc/ada/contracts.adb
@@ -30,7 +30,6 @@ with Einfo.Entities; use Einfo.Entities;
 with Einfo.Utils;use Einfo.Utils;
 with Elists; use Elists;
 with Errout; use Errout;
-with Exp_Ch6;use Exp_Ch6;
 with Exp_Prag;   use Exp_Prag;
 with Exp_Tss;use Exp_Tss;
 with Exp_Util;   use Exp_Util;
@@ -1616,40 +1615,8 @@ package body Contracts is
   --  preserving the result for the purpose of evaluating postconditions,
   --  contracts, type invariants, etc.
 
-  --  In the case of a regular function, generate:
+  --  In the case of a function, generate:
   --
-  --  function Original_Func (X : in out Integer) return Typ is
-  -- 
-  -- 
-  --
-  -- function _Wrapped_Statements return Typ is
-  --
-  -- begin
-  --
-  -- end;
-  --
-  --  begin
-  -- declare
-  --type Axx is access all Typ;
-  --Rxx : constant Axx := _Wrapped_Statements'reference;
-  --Result_Obj : Typ renames Rxx.all;
-  --
-  -- begin
-  --
-  --return Rxx.all;
-  -- end;
-  --  end;
-  --
-  --  This sequence is recognized by Expand_Simple_Function_Return as a
-  --  tail call, in other words equivalent to "return _Wrapped_Statements;"
-  --  and thus the copy to the anonymous return object is elided, including
-  --  a pair of calls to Adjust/Finalize for types requiring finalization.
-
-  --  Note that an extended return statement does not yield the same result
-  --  because the copy of the return object is not elided by GNAT for now.
-
-  --  Or else, in the case of a BIP function, generate:
-
   --  function Original_Func (X : in out Integer) return Typ is
   -- 
   -- 
@@ -1733,9 +1700,9 @@ package body Contracts is
(Handled_Statement_Sequence (Body_Decl), Stmts);
 
   --  Generate the post-execution statements and the extended return
-  --  when the subprogram being wrapped is a BIP function.
+  --  when the subprogram being wrapped is a function.
 
-  elsif Is_Build_In_Place_Result_Type (Ret_Type) then
+  else
  Set_Statements (Handled_Statement_Sequence (Body_Decl), New_List (
Make_Extended_Return_Statement (Loc,
  Return_Object_Declarations => New_List (
@@ -1751,65 +1718,6 @@ package body Contracts is
  Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
  Statements => Stmts;
-
-  --  Declare a renaming of the result of the call to the wrapper and
-  --  append a return of the result of the call when the subprogram is
-  --  a function, after manually removing the side effects. Note that
-  --  we cannot call Remove_Side_Effects here because nothing has been
-  --  analyzed yet and we cannot return the renaming itself because
-  --  Expand_Simple_Function_Return expects an explicit dereference.
-
-  else
- declare
-A_Id : constant Node_Id := Make_Temporary (Loc, 'A');
-R_Id : constant Node_Id := Make_Temporary (Loc, 'R');
-
- begin
-Set_Statements (Handled_Statement_Sequence (Body_Decl), New_List (
-  Make_Block_Statement (Loc,
-
-Declarations => New_List (
-  Make_Full_Type_Declaration (Loc,
-Defining_Identifier => A_Id,
-Type_Definition =>
-  Make_Access_To_Object_Definition (Loc,
-All_Present=> True,
-Null_Exclusion_Present => True,
-Subtype_Indication =>
-  New_Occurrence_Of (Ret_Type, Loc))),
-
-  Make_Object_Declaration (Loc,
-Defining_Identifier => R_Id,
-Object_Definition   => New_Occurrence_Of (A_Id, Loc),
-Constant_Present=> True,
-Expression  =>
-  Make_Reference (Loc,
-Make_Function_Call (Loc,
-  Name => New_Occurrence_Of (Wrapper_Id, Loc,
-
-  Make_Object_Renaming_Declaration (Loc,
-

Re: [PATCH] gccrs: avoid printing to stderr in selftest::rust_flatten_list

2023-01-05 Thread Arthur Cohen

Hi David,

On 1/4/23 20:28, David Malcolm wrote:

On Mon, 2023-01-02 at 13:47 +0100, Arthur Cohen wrote:

Hi David,

Sorry for the delayed reply!

On 12/16/22 18:01, David Malcolm wrote:

Successfully bootstrapped & regrtested on x86_64-pc-linux-gnu.

OK for trunk?

gcc/rust/ChangeLog:
 * resolve/rust-ast-resolve-item.cc
(selftest::rust_flatten_list):
 Remove output to stderr.


For reference, the stderr spewage was:

foo::bar::baz
foo::bar::bul
>


Signed-off-by: David Malcolm 
---
   gcc/rust/resolve/rust-ast-resolve-item.cc | 3 ---
   1 file changed, 3 deletions(-)

diff --git a/gcc/rust/resolve/rust-ast-resolve-item.cc
b/gcc/rust/resolve/rust-ast-resolve-item.cc
index 0c38f28d530..1276e845acc 100644
--- a/gcc/rust/resolve/rust-ast-resolve-item.cc
+++ b/gcc/rust/resolve/rust-ast-resolve-item.cc
@@ -1202,9 +1202,6 @@ rust_flatten_list (void)
     auto paths = std::vector ();
     Rust::Resolver::flatten_list (list, paths);
   
-  for (auto  : paths)

-    fprintf (stderr, "%s\n", path.as_string ().c_str ());
-
     ASSERT_TRUE (!paths.empty ());
     ASSERT_EQ (paths.size (), 2);
     ASSERT_EQ (paths[0].get_segments ()[0].as_string (), "foo");


Looks good to me. OK for trunk :)

Thanks for taking the time!


I was about to push this and
   https://gcc.gnu.org/pipermail/gcc-patches/2022-December/608645.html
to trunk (after retesting against all the changes since before my
break), but you mentioned today on IRC something about merger issues:

 ibuclaw: I'm looking at the remaining issues for updating
GCC's master with our most recent gccrs commits. I've come to the
conclusion that it would be easier for me to upstream your target
changes while I'm upstreaming/submitting all of the missing commits
 would that suit you?
 it would just be me sending in your commits, but I
wouldn't be author on them or anything of course
 this would enable us to time them properly within the
rest of the commits, so there'd be no conflicts or anything of the sort
 dmalcolm: same question to you, actually :)


Sorry for the confusion, and for disappearing from IRC before you got a 
chance to answer! In those messages, I was talking about the 
`error_meta` PR you had submitted to us on Github. Since we are in the 
process of updating upstream with the current state of our dev branch, 
we have to figure out what to do with these commits that are already 
present in our dev branch but not upstreamed yet. Since you and Iain 
have pushed commits to our dev branch, we are wondering whether you'd 
like us to upstream them during this updating process or if you'd like 
to do so on your own.


Regarding the two new patches that you've submitted here and that aren't 
upstreamed or merged in our dev branch yet, it's a bit different. You 
can either go ahead and push them to trunk if that's what you'd like, 
and I'm assuming that when we merge upstream and our dev branch this 
won't cause any conflict. And if these two patches do, they are easy 
enough that we can fix them by hand.


If you'd like, you can also submit a PR instead, and we'll upstream them 
when updating the rest of the frontend upstream, similarly to your 
`error_meta` patches.


Last option, I can also take care of them and merge them directly in our 
dev branch, and we'll upstream them with the rest of the frontend. This 
way you don't have to deal with submitting a PR and so on.



Can I go ahead and push my two commits to trunk, or do you want to do
it?  (and if so, do you want them e.g. as PRs against your github
branch?)

Dave




All the best,


Sorry about all of this. We are working hard on updating upstream so 
that there's no such problems anymore. We'll get that done as soon as 
possible, but winter break put quite the wrench in our plans :)


Thank you for your understanding!

All the best,

Arthur



OpenPGP_0x1B3465B044AD9C65.asc
Description: OpenPGP public key


OpenPGP_signature
Description: OpenPGP digital signature


[COMMITTED] ada: Revert to constrained allocation for string concatenation

2023-01-05 Thread Marc Poulhiès via Gcc-patches
From: Eric Botcazou 

Using an unconstrained allocation is less efficient in the general case.

gcc/ada/

* exp_ch3.adb (Expand_N_Object_Declaration): New local variable used
throughout instead of testing Is_Special_Return_Object every time.
Do not rename an OK_To_Rename object for a special return object.
* exp_ch4.adb (Expand_Concatenate): Revert to constrained allocation
if the result is allocated on the secondary stack.

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

---
 gcc/ada/exp_ch3.adb | 29 +---
 gcc/ada/exp_ch4.adb | 82 +++--
 2 files changed, 50 insertions(+), 61 deletions(-)

diff --git a/gcc/ada/exp_ch3.adb b/gcc/ada/exp_ch3.adb
index 7dbf82671aa..a76acf34d66 100644
--- a/gcc/ada/exp_ch3.adb
+++ b/gcc/ada/exp_ch3.adb
@@ -6230,6 +6230,11 @@ package body Exp_Ch3 is
   Base_Typ : constant Entity_Id  := Base_Type (Typ);
   Next_N   : constant Node_Id:= Next (N);
 
+  Special_Ret_Obj : constant Boolean := Is_Special_Return_Object (Def_Id);
+  --  If this is a special return object, it will be allocated differently
+  --  and ultimately rewritten as a renaming, so initialization activities
+  --  need to be deferred until after that is done.
+
   function Build_Equivalent_Aggregate return Boolean;
   --  If the object has a constrained discriminated type and no initial
   --  value, it may be possible to build an equivalent aggregate instead,
@@ -7343,7 +7348,7 @@ package body Exp_Ch3 is
 end if;
  end if;
 
- if not Is_Special_Return_Object (Def_Id) then
+ if not Special_Ret_Obj then
 Default_Initialize_Object (Init_After);
  end if;
 
@@ -7403,7 +7408,7 @@ package body Exp_Ch3 is
Expander_Mode_Restore;
 end if;
 
-if not Is_Special_Return_Object (Def_Id) then
+if not Special_Ret_Obj then
Convert_Aggr_In_Object_Decl (N);
 end if;
 
@@ -7479,7 +7484,7 @@ package body Exp_Ch3 is
 --  case, the expansion of the return statement will take care of
 --  creating the object (via allocator) and initializing it.
 
-if Is_Special_Return_Object (Def_Id) then
+if Special_Ret_Obj then
 
--  If the type needs finalization and is not inherently
--  limited, then the target is adjusted after the copy
@@ -7791,7 +7796,7 @@ package body Exp_Ch3 is
 if Present (Tag_Assign) then
if Present (Following_Address_Clause (N)) then
   Ensure_Freeze_Node (Def_Id);
-   elsif not Is_Special_Return_Object (Def_Id) then
+   elsif not Special_Ret_Obj then
   Insert_Action_After (Init_After, Tag_Assign);
end if;
 
@@ -7931,7 +7936,7 @@ package body Exp_Ch3 is
 and then
   ((not Is_Library_Level_Entity (Def_Id)
  and then Is_Captured_Function_Call (Expr_Q)
- and then (not Is_Special_Return_Object (Def_Id)
+ and then (not Special_Ret_Obj
 or else Is_Related_To_Func_Return
   (Entity (Prefix (Expr_Q
  and then not Is_Class_Wide_Type (Typ))
@@ -7945,12 +7950,14 @@ package body Exp_Ch3 is
 
-- Obj : Typ renames Expr;
 
-   or else OK_To_Rename_Ref (Expr_Q)
+   or else (OK_To_Rename_Ref (Expr_Q)
+ and then not Special_Ret_Obj)
 
--  Likewise if it is a slice of such a variable
 
or else (Nkind (Expr_Q) = N_Slice
- and then OK_To_Rename_Ref (Prefix (Expr_Q;
+ and then OK_To_Rename_Ref (Prefix (Expr_Q))
+ and then not Special_Ret_Obj));
 
 --  If the type needs finalization and is not inherently limited,
 --  then the target is adjusted after the copy and attached to the
@@ -7971,9 +7978,7 @@ package body Exp_Ch3 is
Obj_Ref => New_Occurrence_Of (Def_Id, Loc),
Typ => Base_Typ);
 
-   if Present (Adj_Call)
- and then not Is_Special_Return_Object (Def_Id)
-   then
+   if Present (Adj_Call) and then not Special_Ret_Obj then
   Insert_Action_After (Init_After, Adj_Call);
end if;
 end if;
@@ -8601,9 +8606,7 @@ package body Exp_Ch3 is
 end;
  end if;
 
- if Is_Special_Return_Object (Def_Id)
-   and then Present (Tag_Assign)
- then
+ if Special_Ret_Obj and then Present (Tag_Assign) then
 Insert_Action_After (Init_After, Tag_Assign);
  end if;
 
diff --git a/gcc/ada/exp_ch4.adb 

[COMMITTED] ada: Fix generic instantiation of sibling package

2023-01-05 Thread Marc Poulhiès via Gcc-patches
The compiler would crash because it is failing at setting up the scope
stack correctly for a generic instantiation of a sibling package within
a child package instance. In this case, the parent instance isn't
explicitly referenced and it must be found differently.

gcc/ada/

* sem_ch12.adb (Instantiate_Package_Body): Correctly find the
parent instance to place on the scope stack.

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

---
 gcc/ada/sem_ch12.adb | 33 +++--
 1 file changed, 31 insertions(+), 2 deletions(-)

diff --git a/gcc/ada/sem_ch12.adb b/gcc/ada/sem_ch12.adb
index 1ea95845a16..0f2dd39b53c 100644
--- a/gcc/ada/sem_ch12.adb
+++ b/gcc/ada/sem_ch12.adb
@@ -12150,8 +12150,26 @@ package body Sem_Ch12 is
  end;
 
  --  If it is a child unit, make the parent instance (which is an
- --  instance of the parent of the generic) visible. The parent
- --  instance is the prefix of the name of the generic unit.
+ --  instance of the parent of the generic) visible.
+
+ --  1) The child unit's parent is an explicit parent instance (the
+ --  prefix of the name of the generic unit):
+
+ --package Child_Package is new Parent_Instance.Child_Unit;
+
+ --  2) The child unit's parent is an implicit parent instance (e.g.
+ --  when instantiating a sibling package):
+
+ --  generic
+ --  package Parent.Second_Child is
+ --...
+
+ --  generic
+ --  package Parent.First_Child is
+ --package Sibling_Package is new Second_Child;
+
+ --  3) The child unit's parent is not an instance, so the scope is
+ --  simply the one of the unit.
 
  if Ekind (Scope (Gen_Unit)) = E_Generic_Package
and then Nkind (Gen_Id) = N_Expanded_Name
@@ -12161,6 +12179,17 @@ package body Sem_Ch12 is
 Install_Parent (Par_Ent, In_Body => True);
 Par_Installed := True;
 
+ elsif Ekind (Scope (Gen_Unit)) = E_Generic_Package
+   and then Ekind (Scope (Act_Decl_Id)) = E_Package
+   and then Is_Generic_Instance (Scope (Act_Decl_Id))
+ then
+Par_Ent := Entity
+  (Prefix (Name (Get_Unit_Instantiation_Node
+   (Scope (Act_Decl_Id);
+Par_Vis := Is_Immediately_Visible (Par_Ent);
+Install_Parent (Par_Ent, In_Body => True);
+Par_Installed := True;
+
  elsif Is_Child_Unit (Gen_Unit) then
 Par_Ent := Scope (Gen_Unit);
 Par_Vis := Is_Immediately_Visible (Par_Ent);
-- 
2.34.1



[COMMITTED] ada: Better error message for bad Discard_Names configuration pragma

2023-01-05 Thread Marc Poulhiès via Gcc-patches
From: Steve Baird 

When a pragma Discard_Names is used as a configuration pragma, it does not
take an argument. If an argument is given, the resulting error message was
incorrect and confusing.

gcc/ada/

* sem_prag.adb (Analyze_Pragma): Fix Is_Configuration_Pragma
function to handle case where the pragma's parent is an
N_Aspect_Specification node. In analyzing a Discard_Names pragma,
do not assume that a nonzero number of arguments implies that the
pragma is not a configuration pragma; that assumption only holds
for legal programs.

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

---
 gcc/ada/sem_prag.adb | 20 +---
 1 file changed, 17 insertions(+), 3 deletions(-)

diff --git a/gcc/ada/sem_prag.adb b/gcc/ada/sem_prag.adb
index f3c23caeae4..555e09b74e9 100644
--- a/gcc/ada/sem_prag.adb
+++ b/gcc/ada/sem_prag.adb
@@ -7298,11 +7298,20 @@ package body Sem_Prag is
   --  the test below also permits use in a configuration pragma file.
 
   function Is_Configuration_Pragma return Boolean is
- Lis : constant List_Id := List_Containing (N);
+ Lis : List_Id;
  Par : constant Node_Id := Parent (N);
  Prg : Node_Id;
 
   begin
+ --  Don't evaluate List_Containing (N) if Parent (N) could be
+ --  an N_Aspect_Specification node.
+
+ if not Is_List_Member (N) then
+return False;
+ end if;
+
+ Lis := List_Containing (N);
+
  --  If no parent, then we are in the configuration pragma file,
  --  so the placement is definitely appropriate.
 
@@ -15729,8 +15738,13 @@ package body Sem_Prag is
 
 --  Deal with configuration pragma case
 
-if Arg_Count = 0 and then Is_Configuration_Pragma then
-   Global_Discard_Names := True;
+if Is_Configuration_Pragma then
+   if Arg_Count /= 0 then
+  Error_Pragma
+("nonzero number of arguments for configuration pragma%");
+   else
+  Global_Discard_Names := True;
+   end if;
return;
 
 --  Otherwise, check correct appropriate context
-- 
2.34.1



[COMMITTED] ada: Update doc for -gnatw_q

2023-01-05 Thread Marc Poulhiès via Gcc-patches
From: Bob Duff 

The -gnatw_q switch turns on warnings for noncomposing "="
operators. This patch updates the doc to refer to relevant
RM paragraphs.

gcc/ada/

* doc/gnat_ugn/building_executable_programs_with_gnat.rst:
Add RM references.
* gnat_ugn.texi: Regenerate.

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

---
 .../doc/gnat_ugn/building_executable_programs_with_gnat.rst   | 2 ++
 gcc/ada/gnat_ugn.texi | 4 +++-
 2 files changed, 5 insertions(+), 1 deletion(-)

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 fe0b567c2b9..634bbc94c31 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
@@ -3704,6 +3704,8 @@ of the pragma in the :title:`GNAT_Reference_manual`).
   containing a component whose type has the user-defined "=" as
   primitive). Note that the user-defined "=" must be a primitive operator
   in order to trigger the warning.
+  See RM-4.5.2(14/3-15/5, 21, 24/3, 32.1/1)
+  for the exact Ada rules on composability of "=".
 
   The default is that these warnings are not given.
 
diff --git a/gcc/ada/gnat_ugn.texi b/gcc/ada/gnat_ugn.texi
index 0470414e150..a1daff92fbe 100644
--- a/gcc/ada/gnat_ugn.texi
+++ b/gcc/ada/gnat_ugn.texi
@@ -19,7 +19,7 @@
 
 @copying
 @quotation
-GNAT User's Guide for Native Platforms , Jan 02, 2023
+GNAT User's Guide for Native Platforms , Jan 03, 2023
 
 AdaCore
 
@@ -11970,6 +11970,8 @@ not compose (i.e. is ignored for a predefined “=” for a 
composite type
 containing a component whose type has the user-defined “=” as
 primitive). Note that the user-defined “=” must be a primitive operator
 in order to trigger the warning.
+See RM-4.5.2(14/3-15/5, 21, 24/3, 32.1/1)
+for the exact Ada rules on composability of “=”.
 
 The default is that these warnings are not given.
 @end table
-- 
2.34.1



[COMMITTED] ada: Adjust handling of "%g" in GNAT.Formatted_String

2023-01-05 Thread Marc Poulhiès via Gcc-patches
From: Ronan Desplanques 

The way the "%g" specifier was handled by GNAT.Formatted_String
before this patch was very different from the behavior of C's printf.
This patch makes the handling of "%g" in GNAT.Formatted_String closer
to the behavior described in the specification of the C language.

gcc/ada/

* libgnat/g-forstr.adb (F_Kind): Rename enumeration literal.
(P_Flt_Format): Adjust handling of "%g".
(Determine_Notation_And_Aft): New procedure.
(Decimal_Exponent): New function.
(Increment_Integral_Part): New procedure.
(Remove_Extraneous_Decimal_Digit): New procedure.
(Trim_Fractional_Part): New procedure.
* libgnat/g-forstr.ads: Change description of "%g" specifier.

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

---
 gcc/ada/libgnat/g-forstr.adb | 341 +++
 gcc/ada/libgnat/g-forstr.ads |   6 +-
 2 files changed, 313 insertions(+), 34 deletions(-)

diff --git a/gcc/ada/libgnat/g-forstr.adb b/gcc/ada/libgnat/g-forstr.adb
index 2179818bba4..a58b1702eca 100644
--- a/gcc/ada/libgnat/g-forstr.adb
+++ b/gcc/ada/libgnat/g-forstr.adb
@@ -34,6 +34,7 @@ with Ada.Float_Text_IO;
 with Ada.Integer_Text_IO;
 with Ada.Long_Float_Text_IO;
 with Ada.Long_Integer_Text_IO;
+with Ada.Strings;
 with Ada.Strings.Fixed;
 with Ada.Unchecked_Deallocation;
 
@@ -49,8 +50,8 @@ package body GNAT.Formatted_String is
Decimal_Float,   -- %f %F
Decimal_Scientific_Float,-- %e
Decimal_Scientific_Float_Up, -- %E
-   Shortest_Decimal_Float,  -- %g
-   Shortest_Decimal_Float_Up,   -- %G
+   G_Specifier, -- %g
+   G_Specifier_Up,  -- %G
Char,-- %c
Str, -- %s
Pointer  -- %p
@@ -58,7 +59,7 @@ package body GNAT.Formatted_String is
 
type Sign_Kind is (Neg, Zero, Pos);
 
-   subtype Is_Number is F_Kind range Decimal_Int .. Shortest_Decimal_Float_Up;
+   subtype Is_Number is F_Kind range Decimal_Int .. G_Specifier_Up;
 
type F_Sign is (If_Neg, Forced, Space) with Default_Value => If_Neg;
 
@@ -77,6 +78,8 @@ package body GNAT.Formatted_String is
   Value_Needed : Natural range 0 .. 2 := 0;
end record;
 
+   type Notation is (Decimal, Scientific);
+
procedure Advance_And_Accumulate_Until_Next_Specifier
  (Format : Formatted_String);
--  Advance Format.D.Index until either the next format specifier is
@@ -90,12 +93,30 @@ package body GNAT.Formatted_String is
--  Parse the next format specifier, a format specifier has the following
--  syntax: %[flags][width][.precision][length]specifier
 
+   procedure Determine_Notation_And_Aft
+ (Exponent: Integer;
+  Precision   : Text_IO.Field;
+  Nota: out Notation;
+  Aft : out Text_IO.Field);
+   --  Determine whether to use scientific or decimal notation and the value of
+   --  Aft given the exponent and precision of a real number, as described in
+   --  the C language specification, section 7.21.6.1.
+
function Get_Formatted
  (F_Spec : F_Data;
   Value  : String;
   Len: Positive) return String;
--  Returns Value formatted given the information in F_Spec
 
+   procedure Increment_Integral_Part
+ (Buffer  : in out String;
+  First_Non_Blank : in out Positive;
+  Last_Digit_Position : Positive);
+   --  Buffer must contain the textual representation of a number.
+   --  Last_Digit_Position must be the position of the rightmost digit of the
+   --  integral part. Buffer must have at least one padding blank. Increment
+   --  the integral part.
+
procedure Raise_Wrong_Format (Format : Formatted_String) with No_Return;
--  Raise the Format_Error exception which information about the context
 
@@ -128,6 +149,18 @@ package body GNAT.Formatted_String is
   Var: Int) return Formatted_String;
--  Generic routine which handles all the integer numbers
 
+   procedure Remove_Extraneous_Decimal_Digit
+ (Textual_Rep : in out String;
+  First_Non_Blank : in out Positive);
+   --  Remove the unique digit to the right of the point in Textual_Rep
+
+   procedure Trim_Fractional_Part
+ (Textual_Rep : in out String;
+  First_Non_Blank : in out Positive);
+   --  Remove trailing zeros from Textual_Rep, which must be the textual
+   --  representation of a real number. If the fractional part only contains
+   --  zeros, also remove the point.
+
-
-- "+" --
-
@@ -335,6 +368,30 @@ package body GNAT.Formatted_String is
   end loop;
end Advance_And_Accumulate_Until_Next_Specifier;
 
+   
+   -- Determine_Notation_And_Aft --
+   

[COMMITTED] ada: Spurious error on Lock_Free protected type with discriminants

2023-01-05 Thread Marc Poulhiès via Gcc-patches
From: Justin Squirek 

This patch corrects an issue in the compiler whereby unprefixed discriminants
appearing in protected subprograms were unable to be properly resolved -
leading to spurious resolution errors.

gcc/ada/

* sem_ch8.adb (Set_Entity_Or_Discriminal): Verify we are actually
resetting the entity field of a non-prefixed discriminant
reference.

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

---
 gcc/ada/sem_ch8.adb | 12 +++-
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/gcc/ada/sem_ch8.adb b/gcc/ada/sem_ch8.adb
index 841076bbd01..fe89e1127ee 100644
--- a/gcc/ada/sem_ch8.adb
+++ b/gcc/ada/sem_ch8.adb
@@ -4891,14 +4891,16 @@ package body Sem_Ch8 is
  then
 null;
 
- --  Don't replace the discriminant in strict preanalysis mode since
- --  it can lead to errors during full analysis when the discriminant
- --  gets referenced later.
+ --  Don't replace a non-qualified discriminant in strict preanalysis
+ --  mode since it can lead to errors during full analysis when the
+ --  discriminant gets referenced later.
 
  --  This can occur in situations where a protected type contains
- --  an expression function which references a discriminant.
+ --  an expression function which references a non-prefixed
+ --  discriminant.
 
- elsif Preanalysis_Active
+ elsif No (P)
+   and then Preanalysis_Active
and then Inside_Preanalysis_Without_Freezing = 0
  then
 null;
-- 
2.34.1



[COMMITTED] ada: Fix finalization issues in extended return statements

2023-01-05 Thread Marc Poulhiès via Gcc-patches
From: Eric Botcazou 

The first issue pertains to return objects of (class-wide) interface types,
which need to be adjusted if the type is not inherently limited.  The second
issue is for return objects of non-class-wide types that are initialized by
a function call, which can use a direct renaming only if the object doing
the capture of the function call is flagged by Is_Related_To_Func_Return.
The third one is that, in the second case, we may need to reassign the tag.

gcc/ada/

* exp_ch3.adb (Expand_N_Object_Declaration): For a special return
object of an interface type that is not inherently limited, make
a call to the Adjust primitive after doing the copy.  For a special
return object of a non-class-wide type initialized by a function
call, use a direct renaming only if the object doing the capture
is flagged by Is_Related_To_Func_Return.  For a special return
object using a direct renaming, reassign the tag, if need be.
* exp_ch6.adb (Expand_Simple_Function_Return): Fix comment.
* exp_util.adb (Is_Related_To_Func_Return): Accept both regular and
renaming object declarations for return objects.

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

---
 gcc/ada/exp_ch3.adb  | 34 --
 gcc/ada/exp_ch6.adb  |  2 +-
 gcc/ada/exp_util.adb |  3 ++-
 3 files changed, 35 insertions(+), 4 deletions(-)

diff --git a/gcc/ada/exp_ch3.adb b/gcc/ada/exp_ch3.adb
index def63ed0513..7dbf82671aa 100644
--- a/gcc/ada/exp_ch3.adb
+++ b/gcc/ada/exp_ch3.adb
@@ -7480,7 +7480,19 @@ package body Exp_Ch3 is
 --  creating the object (via allocator) and initializing it.
 
 if Is_Special_Return_Object (Def_Id) then
-   null;
+
+   --  If the type needs finalization and is not inherently
+   --  limited, then the target is adjusted after the copy
+   --  and attached to the finalization list.
+
+   if Needs_Finalization (Typ)
+ and then not Is_Limited_View (Typ)
+   then
+  Adj_Call :=
+Make_Adjust_Call (
+  Obj_Ref => New_Occurrence_Of (Def_Id, Loc),
+  Typ => Base_Typ);
+   end if;
 
 elsif Tagged_Type_Expansion then
declare
@@ -7908,9 +7920,20 @@ package body Exp_Ch3 is
 --  This avoids an extra copy and, in the case where Typ needs
 --  finalization, a pair of Adjust/Finalize calls (see below).
 
+--  However, in the case of a special return object, we need to
+--  make sure that the object Rnn is properly recognized by the
+--  Is_Related_To_Func_Return predicate; otherwise, if it is of
+--  a type that needs finalization, Requires_Cleanup_Actions
+--  would return true because of this and Build_Finalizer would
+--  finalize it prematurely (see Expand_Simple_Function_Return
+--  for the same test in the case of a simple return).
+
 and then
   ((not Is_Library_Level_Entity (Def_Id)
  and then Is_Captured_Function_Call (Expr_Q)
+ and then (not Is_Special_Return_Object (Def_Id)
+or else Is_Related_To_Func_Return
+  (Entity (Prefix (Expr_Q
  and then not Is_Class_Wide_Type (Typ))
 
--  If the initializing expression is a variable with the
@@ -8554,7 +8577,8 @@ package body Exp_Ch3 is
 
   --  If we can rename the initialization expression, we need to make sure
   --  that we use the proper type in the case of a return object that lives
-  --  on the secondary stack. See other cases below for a similar handling.
+  --  on the secondary stack (see other cases below for a similar handling)
+  --  and that the tag is assigned in the case of any return object.
 
   elsif Rewrite_As_Renaming then
  if Is_Secondary_Stack_Return_Object (Def_Id) then
@@ -8577,6 +8601,12 @@ package body Exp_Ch3 is
 end;
  end if;
 
+ if Is_Special_Return_Object (Def_Id)
+   and then Present (Tag_Assign)
+ then
+Insert_Action_After (Init_After, Tag_Assign);
+ end if;
+
   --  If this is the return object of a function returning on the secondary
   --  stack, convert the declaration to a renaming of the dereference of ah
   --  allocator for the secondary stack.
diff --git a/gcc/ada/exp_ch6.adb b/gcc/ada/exp_ch6.adb
index db1fd1d172b..b97d69b81b6 100644
--- a/gcc/ada/exp_ch6.adb
+++ b/gcc/ada/exp_ch6.adb
@@ -6449,7 +6449,7 @@ package body Exp_Ch6 is
   --  sure that the object doing the capture is properly recognized by the
   --  Is_Related_To_Func_Return predicate; otherwise, if 

[COMMITTED] ada: Fix incorrect warning about unreferenced packed arrays

2023-01-05 Thread Marc Poulhiès via Gcc-patches
From: Bob Duff 

This patch fixes a bug in which a reference to a renaming of a
component of a packed array was not counted as a reference,
and thus caused incorrect warnings about unreferenced objects.

gcc/ada/

* sem_ch5.adb (Analyze_Assignment): Fix the bug by checking
Original_Node. The renaming might be elsewhere, but the (original)
reference is right here.
* errout.adb: Remove pragma Unreferenced which was added because
of the above bug.
* einfo.ads: Misc cleanup.
* lib.adb: Likewise.
* lib.ads: Likewise.

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

---
 gcc/ada/einfo.ads   |  6 +--
 gcc/ada/errout.adb  |  2 +-
 gcc/ada/lib.adb | 96 -
 gcc/ada/lib.ads |  9 ++---
 gcc/ada/sem_ch5.adb | 13 +++---
 5 files changed, 41 insertions(+), 85 deletions(-)

diff --git a/gcc/ada/einfo.ads b/gcc/ada/einfo.ads
index d71dcaf8969..94022e7c635 100644
--- a/gcc/ada/einfo.ads
+++ b/gcc/ada/einfo.ads
@@ -1865,7 +1865,7 @@ package Einfo is
 --Has_Per_Object_Constraint
 --   Defined in E_Component entities. Set if the subtype of the component
 --   has a per object constraint. Per object constraints result from the
---   following situations :
+--   following situations:
 --
 --   1. N_Attribute_Reference - when the prefix is the enclosing type and
 --  the attribute is Access.
@@ -4136,14 +4136,14 @@ package Einfo is
 --   set instead, or a similar appearance as an out parameter actual, in
 --   which case Referenced_As_Out_Parameter is set.
 
---Referenced_As_LHS :
+--Referenced_As_LHS
 --   Defined in all entities. This flag is set instead of Referenced if a
 --   simple variable that is not a renaming appears as the left side of an
 --   assignment. The reason we distinguish this kind of reference is that
 --   we have a separate warning for variables that are only assigned and
 --   never read.
 
---Referenced_As_Out_Parameter :
+--Referenced_As_Out_Parameter
 --   Defined in all entities. This flag is set instead of Referenced if a
 --   simple variable that is not a renaming appears as an actual for an out
 --   formal. The reason we distinguish this kind of reference is that
diff --git a/gcc/ada/errout.adb b/gcc/ada/errout.adb
index 261ba2e8033..151096607c6 100644
--- a/gcc/ada/errout.adb
+++ b/gcc/ada/errout.adb
@@ -53,7 +53,7 @@ with Stand;  use Stand;
 with Stylesw;use Stylesw;
 with System.OS_Lib;
 with Uname;  use Uname;
-with Warnsw; pragma Unreferenced (Warnsw); -- disable spurious warning
+with Warnsw;
 
 package body Errout is
 
diff --git a/gcc/ada/lib.adb b/gcc/ada/lib.adb
index 691d8e4acb9..68ae46a3584 100644
--- a/gcc/ada/lib.adb
+++ b/gcc/ada/lib.adb
@@ -320,15 +320,13 @@ package body Lib is
begin
   if S1 = No_Location or else S2 = No_Location then
  return No;
+  end if;
 
-  elsif S1 = Standard_Location then
- if S2 = Standard_Location then
-return Yes_Same;
- else
-return No;
- end if;
+  if S1 = S2 then
+ return Yes_Same;
+  end if;
 
-  elsif S2 = Standard_Location then
+  if S1 = Standard_Location or else S2 = Standard_Location then
  return No;
   end if;
 
@@ -841,53 +839,36 @@ package body Lib is
  (N : Node_Or_Entity_Id) return Boolean
is
begin
-  if Sloc (N) = Standard_Location then
- return False;
-
-  elsif Sloc (N) = No_Location then
- return False;
-
   --  Special case Itypes to test the Sloc of the associated node. The
   --  reason we do this is for possible calls from gigi after -gnatD
   --  processing is complete in sprint. This processing updates the
   --  sloc fields of all nodes in the tree, but itypes are not in the
   --  tree so their slocs do not get updated.
 
-  elsif Nkind (N) = N_Defining_Identifier
-and then Is_Itype (N)
-  then
+  if Nkind (N) = N_Defining_Identifier and then Is_Itype (N) then
  return In_Extended_Main_Code_Unit (Associated_Node_For_Itype (N));
-
-  --  Otherwise see if we are in the main unit
-
-  elsif Get_Code_Unit (Sloc (N)) = Get_Code_Unit (Cunit (Main_Unit)) then
- return True;
-
-  --  Node may be in spec (or subunit etc) of main unit
-
-  else
- return In_Same_Extended_Unit (N, Cunit (Main_Unit));
   end if;
+
+  return In_Extended_Main_Code_Unit (Sloc (N));
end In_Extended_Main_Code_Unit;
 
function In_Extended_Main_Code_Unit (Loc : Source_Ptr) return Boolean is
begin
-  if Loc = Standard_Location then
- return False;
+  --  Special value cases
 
-  elsif Loc = No_Location then
+  if Loc in No_Location | Standard_Location then
  return False;
+  end if;
 
   --  Otherwise see if we are in the main unit
 
-  elsif 

[x86_64 PATCH] Introduce insvti_highpart define_insn_and_split.

2023-01-05 Thread Roger Sayle

This patch adds a convenient post-reload splitter for setting/updating
the highpart of a TImode variable, using the recently added
split_double_concat infrastructure.

For the new test case below:

__int128 foo(__int128 x, unsigned long long y)
{
  __int128 t = (__int128)y << 64;
  __int128 r = (x & ~0ull) | t;
  return r;
}

mainline GCC with -O2 currently generates:

foo:movq%rdi, %rcx
xorl%eax, %eax
xorl%edi, %edi
orq %rcx, %rax
orq %rdi, %rdx
ret

with this patch, GCC instead now generates the much better:

foo:movq%rdi, %rcx
movq%rcx, %rax
ret

[which interestingly shows the deeper (ABI) issue that I'm trying
to fix, this new define_insn_and_split being the next piece].

It turns out that the -m32 equivalent of this testcase, already
avoids using explict orl/xor instructions, as it gets optimized
(in combine) by a completely different path.  Given that this idiom
isn't seen in 32-bit code (and therefore this pattern wouldn't match),
and also that the shorter 32-bit AND bitmask is represented as a
CONST_INT rather than a CONST_WIDE_INT, this new define_insn_and_split
is implemented for just TARGET_64BIT rather than contort a "generic"
implementation using DWI mode iterators.

This patch has been tested on x86_64-pc-linux-gnu with make bootstrap
and make -k check, both with and without --target_board=unix{-m32},
with no new failures.  Ok for mainline?  Please let me know if you'd
prefer a different pattern name [insv seemed better than mov].


2023-01-05  Roger Sayle  

gcc/ChangeLog
* config/i386/i386.md (any_or_plus): Move definition earlier.
(*insvti_highpart_1): New define_insn_and_split to overwrite
(insv) the highpart of a TImode register/memory.

gcc/testsuite/ChangeLog
* gcc.target/i386/insvti_highpart-1.c: New test case.


Thanks in advance,
Roger
--

diff --git a/gcc/config/i386/i386.md b/gcc/config/i386/i386.md
index 890c4c8..9f3c62b 100644
--- a/gcc/config/i386/i386.md
+++ b/gcc/config/i386/i386.md
@@ -3401,6 +3401,31 @@
   "mov{b}\t{%h1, %h0|%h0, %h1}"
   [(set_attr "type" "imov")
(set_attr "mode" "QI")])
+
+(define_code_iterator any_or_plus [plus ior xor])
+(define_insn_and_split "*insvti_highpart_1"
+  [(set (match_operand:TI 0 "nonimmediate_operand" "=ro,r,r,")
+   (any_or_plus:TI
+ (and:TI
+   (match_operand:TI 1 "nonimmediate_operand" "r,m,r,m")
+   (match_operand:TI 3 "const_scalar_int_operand" "n,n,n,n"))
+ (ashift:TI
+   (zero_extend:TI
+ (match_operand:DI 2 "nonimmediate_operand" "r,r,m,m"))
+   (const_int 64]
+  "TARGET_64BIT
+   && CONST_WIDE_INT_P (operands[3])
+   && CONST_WIDE_INT_NUNITS (operands[3]) == 2
+   && CONST_WIDE_INT_ELT (operands[3], 0) == -1
+   && CONST_WIDE_INT_ELT (operands[3], 1) == 0"
+  "#"
+  "&& reload_completed"
+  [(clobber (const_int 0))]
+{
+  operands[4] = gen_lowpart (DImode, operands[1]);
+  split_double_concat (TImode, operands[0], operands[4], operands[2]);
+  DONE;
+})
 
 ;; Floating point push instructions.
 
@@ -11418,7 +11443,6 @@
(set_attr "mode" "QI")])
 
 ;; Split DST = (HI<<32)|LO early to minimize register usage.
-(define_code_iterator any_or_plus [plus ior xor])
 (define_insn_and_split "*concat3_1"
   [(set (match_operand: 0 "nonimmediate_operand" "=ro,r")
(any_or_plus:
diff --git a/gcc/testsuite/gcc.target/i386/insvti_highpart-1.c 
b/gcc/testsuite/gcc.target/i386/insvti_highpart-1.c
new file mode 100644
index 000..4ae9ccf
--- /dev/null
+++ b/gcc/testsuite/gcc.target/i386/insvti_highpart-1.c
@@ -0,0 +1,12 @@
+/* { dg-do compile { target int128 } } */
+/* { dg-options "-O2" } */
+
+__int128 foo(__int128 x, unsigned long long y)
+{
+  __int128 t = (__int128)y << 64;
+  __int128 r = (x & ~0ull) | t;
+  return r;
+}
+
+/* { dg-final { scan-assembler-not "xorl" } } */
+/* { dg-final { scan-assembler-not "orq" } } */


Re: [PATCH] modula-2: Remove uses of scalb*() and significand*() [PR107631]

2023-01-05 Thread Gaius Mulley via Gcc-patches
Iain Sandoe  writes:

> Tested on x86_64-darwin21 and x86_64-linux-gnu without any m2 regressions.
> OK for trunk?
> thanks
> Iain

yes sure LGTM

thank you!
Gaius


[PATCH] modula-2: Remove uses of scalb*() and significand*() [PR107631]

2023-01-05 Thread Iain Sandoe via Gcc-patches
Tested on x86_64-darwin21 and x86_64-linux-gnu without any m2 regressions.
OK for trunk?
thanks
Iain

--- 8< ---

The scalb*() functions are obsolete in Posix from 2004 and removed in
2008.

The significand*() functions are glibc-only and considered there to be
obsolescent (not supported for types such as _Float128).

We can remove them from Modula-2 since they are not required for ISO
support, but we need to provide an implementation of significand* for
the "fraction()" functions.

PR modula2/107631

gcc/m2/ChangeLog:

* gm2-gcc/m2builtins.cc: Remove scalb, scalbf, scalbl,
significand, significandf, significandl.
* gm2-libs/Builtins.def (significand): Likewise.
* gm2-libs/Builtins.mod: Likewise.
* target-independent/Builtins.texi: Likewise.
* gm2-libs-iso/LowLong.mod: Implement fraction with scalbn*() and
ilogb*().
* gm2-libs-iso/LowReal.mod: Likewise.
* gm2-libs-iso/LowShort.mod: Likewise.
---
 gcc/m2/gm2-gcc/m2builtins.cc| 12 --
 gcc/m2/gm2-libs-iso/LowLong.mod |  5 ++---
 gcc/m2/gm2-libs-iso/LowReal.mod |  4 ++--
 gcc/m2/gm2-libs-iso/LowShort.mod|  4 ++--
 gcc/m2/gm2-libs/Builtins.def|  8 ---
 gcc/m2/gm2-libs/Builtins.mod| 30 -
 gcc/m2/target-independent/Builtins.texi | 14 
 7 files changed, 6 insertions(+), 71 deletions(-)

diff --git a/gcc/m2/gm2-gcc/m2builtins.cc b/gcc/m2/gm2-gcc/m2builtins.cc
index bbfc605a36d..35901a20003 100644
--- a/gcc/m2/gm2-gcc/m2builtins.cc
+++ b/gcc/m2/gm2-gcc/m2builtins.cc
@@ -192,12 +192,6 @@ static struct builtin_function_entry list_of_builtins[] = {
 "signbitf", NULL, NULL },
   { "__builtin_signbitl", BT_FN_INT_LONG_DOUBLE, BUILT_IN_SIGNBITL,
 BUILT_IN_NORMAL, "signbitl", NULL, NULL },
-  { "__builtin_significand", BT_FN_DOUBLE_DOUBLE, BUILT_IN_SIGNIFICAND,
-BUILT_IN_NORMAL, "significand", NULL, NULL },
-  { "__builtin_significandf", BT_FN_FLOAT_FLOAT, BUILT_IN_SIGNIFICANDF,
-BUILT_IN_NORMAL, "significandf", NULL, NULL },
-  { "__builtin_significandl", BT_FN_LONG_DOUBLE_LONG_DOUBLE,
-BUILT_IN_SIGNIFICANDL, BUILT_IN_NORMAL, "significandl", NULL, NULL },
   { "__builtin_modf", BT_FN_DOUBLE_DOUBLE_DOUBLEPTR, BUILT_IN_MODF,
 BUILT_IN_NORMAL, "modf", NULL, NULL },
   { "__builtin_modff", BT_FN_FLOAT_FLOAT_FLOATPTR, BUILT_IN_MODFF,
@@ -216,12 +210,6 @@ static struct builtin_function_entry list_of_builtins[] = {
 BUILT_IN_NEXTTOWARDF, BUILT_IN_NORMAL, "nexttowardf", NULL, NULL },
   { "__builtin_nexttowardl", BT_FN_LONG_DOUBLE_LONG_DOUBLE_LONG_DOUBLE,
 BUILT_IN_NEXTTOWARDL, BUILT_IN_NORMAL, "nexttowardl", NULL, NULL },
-  { "__builtin_scalb", BT_FN_DOUBLE_DOUBLE_DOUBLE, BUILT_IN_SCALB,
-BUILT_IN_NORMAL, "scalb", NULL, NULL },
-  { "__builtin_scalbf", BT_FN_FLOAT_FLOAT_FLOAT, BUILT_IN_SCALBF,
-BUILT_IN_NORMAL, "scalbf", NULL, NULL },
-  { "__builtin_scalbl", BT_FN_LONG_DOUBLE_LONG_DOUBLE_LONG_DOUBLE,
-BUILT_IN_SCALBL, BUILT_IN_NORMAL, "scalbl", NULL, NULL },
   { "__builtin_scalbln", BT_FN_DOUBLE_DOUBLE_LONG, BUILT_IN_SCALBLN,
 BUILT_IN_NORMAL, "scalbln", NULL, NULL },
   { "__builtin_scalblnf", BT_FN_FLOAT_FLOAT_LONG, BUILT_IN_SCALBLNF,
diff --git a/gcc/m2/gm2-libs-iso/LowLong.mod b/gcc/m2/gm2-libs-iso/LowLong.mod
index 74f7ca923f8..9842679d1ed 100644
--- a/gcc/m2/gm2-libs-iso/LowLong.mod
+++ b/gcc/m2/gm2-libs-iso/LowLong.mod
@@ -27,7 +27,7 @@ see the files COPYING3 and COPYING.RUNTIME respectively.  If 
not, see
 IMPLEMENTATION MODULE LowLong ;
 
 FROM SYSTEM IMPORT ADDRESS ;
-FROM Builtins IMPORT ilogbl, significandl, modfl, signbitl, scalbnl, 
huge_vall, nextafterl ;
+FROM Builtins IMPORT ilogbl, modfl, signbitl, scalbnl, huge_vall, nextafterl ;
 FROM dtoa IMPORT Mode, strtod, dtoa ;
 FROM libc IMPORT free ;
 FROM RealMath IMPORT power ;
@@ -64,10 +64,9 @@ END exponent ;
 
 PROCEDURE fraction (x: LONGREAL) : LONGREAL ;
 BEGIN
-   RETURN significandl(x)
+   RETURN scalbnl(x, -ilogbl (x))
 END fraction ;
 
-
 (*
sign - returns the signum of x.  sign(x) = 1.0  for all x>0.0
   sign(x) = -1.0  for all x<0.0.
diff --git a/gcc/m2/gm2-libs-iso/LowReal.mod b/gcc/m2/gm2-libs-iso/LowReal.mod
index cc74f6564dc..7db6ff0472a 100644
--- a/gcc/m2/gm2-libs-iso/LowReal.mod
+++ b/gcc/m2/gm2-libs-iso/LowReal.mod
@@ -27,7 +27,7 @@ see the files COPYING3 and COPYING.RUNTIME respectively.  If 
not, see
 IMPLEMENTATION MODULE LowReal ;
 
 FROM SYSTEM IMPORT ADDRESS ;
-FROM Builtins IMPORT ilogb, significand, modf, signbit, scalbn, huge_val, 
nextafter ;
+FROM Builtins IMPORT ilogb, modf, signbit, scalbn, huge_val, nextafter ;
 FROM dtoa IMPORT Mode, strtod, dtoa ;
 FROM libc IMPORT free ;
 FROM RealMath IMPORT power ;
@@ -64,7 +64,7 @@ END exponent ;
 
 PROCEDURE fraction (x: REAL) : REAL ;
 BEGIN
-   RETURN significand(x)
+   RETURN scalbn (x, -ilogb (x))
 END fraction ;
 
 
diff --git a/gcc/m2/gm2-libs-iso/LowShort.mod 

[PATCH] PR target/89828 Inernal compiler error on -fno-omit-frame-pointer

2023-01-05 Thread Yoshinori Sato
The problem was caused by an erroneous note about creating a stack frame,
which caused the cur_cfa reg to fail to assert with a value other than
the frame pointer.

This fix will generate notes that correctly update cur_cfa.

gcc/config/rx/
* rx.cc (add_pop_cfi_notes): Release the frame pointer if it is used.
(rx_expand_prologue): Redesigned stack pointer and frame pointer update 
process.

Signed-off-by: Yoshinori Sato 
---
 gcc/config/rx/rx.cc | 50 +++--
 1 file changed, 17 insertions(+), 33 deletions(-)

diff --git a/gcc/config/rx/rx.cc b/gcc/config/rx/rx.cc
index 412a3a354b0..8c246d42cd8 100644
--- a/gcc/config/rx/rx.cc
+++ b/gcc/config/rx/rx.cc
@@ -1647,16 +1647,20 @@ mark_frame_related (rtx insn)
 static void
 add_pop_cfi_notes (rtx_insn *insn, unsigned int high, unsigned int low)
 {
-  rtx t = plus_constant (Pmode, stack_pointer_rtx,
-(high - low + 1) * UNITS_PER_WORD);
+  rtx src = stack_pointer_rtx;
+  rtx t;
+  for (unsigned int i = low; i <= high; i++)
+{
+  add_reg_note (insn, REG_CFA_RESTORE, gen_rtx_REG (word_mode, i));
+  if (i == FRAME_POINTER_REGNUM)
+   src = frame_pointer_rtx;
+}
+  t = plus_constant (Pmode, src, (high - low + 1) * UNITS_PER_WORD);
   t = gen_rtx_SET (stack_pointer_rtx, t);
   add_reg_note (insn, REG_CFA_ADJUST_CFA, t);
   RTX_FRAME_RELATED_P (insn) = 1;
-  for (unsigned int i = low; i <= high; i++)
-add_reg_note (insn, REG_CFA_RESTORE, gen_rtx_REG (word_mode, i));
 }
 
-
 static bool
 ok_for_max_constant (HOST_WIDE_INT val)
 {
@@ -1815,37 +1819,17 @@ rx_expand_prologue (void)
}
 }
 
-  /* If needed, set up the frame pointer.  */
-  if (frame_pointer_needed)
-gen_safe_add (frame_pointer_rtx, stack_pointer_rtx,
- GEN_INT (- (HOST_WIDE_INT) frame_size), true);
-
-  /* Allocate space for the outgoing args.
- If the stack frame has not already been set up then handle this as well.  
*/
-  if (stack_size)
+  if (stack_size || frame_size)
 {
-  if (frame_size)
-   {
- if (frame_pointer_needed)
-   gen_safe_add (stack_pointer_rtx, frame_pointer_rtx,
- GEN_INT (- (HOST_WIDE_INT) stack_size), true);
- else
-   gen_safe_add (stack_pointer_rtx, stack_pointer_rtx,
- GEN_INT (- (HOST_WIDE_INT) (frame_size + stack_size)),
- true);
-   }
-  else
-   gen_safe_add (stack_pointer_rtx, stack_pointer_rtx,
- GEN_INT (- (HOST_WIDE_INT) stack_size), true);
+  gen_safe_add (stack_pointer_rtx, stack_pointer_rtx,
+   GEN_INT (- (HOST_WIDE_INT) (stack_size + frame_size)),
+   true);
 }
-  else if (frame_size)
+  if (frame_pointer_needed)
 {
-  if (! frame_pointer_needed)
-   gen_safe_add (stack_pointer_rtx, stack_pointer_rtx,
- GEN_INT (- (HOST_WIDE_INT) frame_size), true);
-  else
-   gen_safe_add (stack_pointer_rtx, frame_pointer_rtx, NULL_RTX,
- false /* False because the epilogue will use the FP not 
the SP.  */);
+  gen_safe_add (frame_pointer_rtx, stack_pointer_rtx,
+   GEN_INT ((HOST_WIDE_INT) stack_size),
+   true);
 }
 }
 
-- 
2.30.2



[PATCH] xtensa: Optimize stack frame adjustment more

2023-01-05 Thread Takayuki 'January June' Suwa via Gcc-patches
This patch introduces a convenient helper function for integer immediate
addition with scratch register as needed, that splits and emits either
up to two ADDI/ADDMI machine instructions or an addition by register
following an immediate integer load (which may later be transformed by
constantsynth).

By using the helper function, it makes stack frame adjustment logic
simplified and instruction count less in some cases.

gcc/ChangeLog:

* config/xtensa/xtensa.cc
(xtensa_split_imm_two_addends, xtensa_emit_add_imm):
New helper functions.
(xtensa_emit_adjust_stack_ptr, xtensa_set_return_address,
xtensa_output_mi_thunk): Change to use the helper function.
---
 gcc/config/xtensa/xtensa.cc | 139 +++-
 1 file changed, 88 insertions(+), 51 deletions(-)

diff --git a/gcc/config/xtensa/xtensa.cc b/gcc/config/xtensa/xtensa.cc
index ae44199bc98..3b8a7bcda37 100644
--- a/gcc/config/xtensa/xtensa.cc
+++ b/gcc/config/xtensa/xtensa.cc
@@ -2518,6 +2518,82 @@ xtensa_split_DI_reg_imm (rtx *operands)
 }
 
 
+/* Try to split an integer value into what are suitable for two consecutive
+   immediate addition instructions, ADDI or ADDMI.  */
+
+static bool
+xtensa_split_imm_two_addends (HOST_WIDE_INT imm, HOST_WIDE_INT v[2])
+{
+  HOST_WIDE_INT v0, v1;
+
+  if (imm < -32768)
+v0 = -32768, v1 = imm + 32768;
+  else if (imm > 32512)
+v0 = 32512, v1 = imm - 32512;
+  else if (TARGET_DENSITY && optimize_size && xtensa_simm12b (imm))
+/* A pair of MOVI(.N) and ADD.N is one or two bytes less than two
+   immediate additions if TARGET_DENSITY.  */
+return false;
+  else
+v0 = (imm + 128) & ~255L, v1 = imm - v0;
+
+  if (xtensa_simm8 (v1) || xtensa_simm8x256 (v1))
+{
+  v[0] = v0, v[1] = v1;
+  return true;
+}
+
+  return false;
+}
+
+
+/* Helper function for integer immediate addition with scratch register
+   as needed, that splits and emits either up to two ADDI/ADDMI machine
+   instructions or an addition by register following an immediate integer
+   load (which may later be transformed by constantsynth).
+
+   If 'scratch' is NULL_RTX but still needed, a new pseudo-register will
+   be allocated.  Thus, after the reload/LRA pass, the specified scratch
+   register must be a hard one.  */
+
+static void
+xtensa_emit_add_imm (rtx dst, rtx src, HOST_WIDE_INT imm, rtx scratch,
+bool need_note)
+{
+  HOST_WIDE_INT v[2];
+  rtx_insn *insn0, *insn1;
+
+  if (imm == 0)
+return;
+
+  if (xtensa_simm8 (imm) || xtensa_simm8x256 (imm))
+insn0 = emit_insn (gen_addsi3 (dst, src, GEN_INT (imm)));
+  else if (xtensa_split_imm_two_addends (imm, v))
+{
+  insn0 = emit_insn (gen_addsi3 (dst, src, GEN_INT (v[0])));
+  insn1 = emit_insn (gen_addsi3 (dst, dst, GEN_INT (v[1])));
+  if (need_note)
+   RTX_FRAME_RELATED_P (insn1) = 1;
+}
+  else
+{
+  if (scratch)
+   emit_move_insn (scratch, GEN_INT (imm));
+  else
+   scratch = force_reg (SImode, GEN_INT (imm));
+  insn0 = emit_insn (gen_addsi3 (dst, src, scratch));
+}
+
+  if (need_note)
+{
+  rtx note_rtx = gen_rtx_SET (dst, plus_constant (Pmode, src, imm));
+
+  RTX_FRAME_RELATED_P (insn0) = 1;
+  add_reg_note (insn0, REG_FRAME_RELATED_EXPR, note_rtx);
+}
+}
+
+
 /* Implement TARGET_CANNOT_FORCE_CONST_MEM.  */
 
 static bool
@@ -3245,41 +3321,14 @@ xtensa_initial_elimination_offset (int from, int to 
ATTRIBUTE_UNUSED)
 static void
 xtensa_emit_adjust_stack_ptr (HOST_WIDE_INT offset, int flags)
 {
-  rtx_insn *insn;
-  rtx ptr = (flags & ADJUST_SP_FRAME_PTR) ? hard_frame_pointer_rtx
- : stack_pointer_rtx;
-
   if (cfun->machine->inhibit_logues_a1_adjusts)
 return;
 
-  if (xtensa_simm8 (offset)
-  || xtensa_simm8x256 (offset))
-insn = emit_insn (gen_addsi3 (stack_pointer_rtx, ptr, GEN_INT (offset)));
-  else
-{
-  rtx tmp_reg = gen_rtx_REG (Pmode, A9_REG);
-
-  if (offset < 0)
-   {
- emit_move_insn (tmp_reg, GEN_INT (-offset));
- insn = emit_insn (gen_subsi3 (stack_pointer_rtx, ptr, tmp_reg));
-   }
-  else
-   {
- emit_move_insn (tmp_reg, GEN_INT (offset));
- insn = emit_insn (gen_addsi3 (stack_pointer_rtx, ptr, tmp_reg));
-   }
-}
-
-  if (flags & ADJUST_SP_NEED_NOTE)
-{
-  rtx note_rtx = gen_rtx_SET (stack_pointer_rtx,
- plus_constant (Pmode, stack_pointer_rtx,
-offset));
-
-  RTX_FRAME_RELATED_P (insn) = 1;
-  add_reg_note (insn, REG_FRAME_RELATED_EXPR, note_rtx);
-}
+  xtensa_emit_add_imm (stack_pointer_rtx,
+  (flags & ADJUST_SP_FRAME_PTR)
+   ? hard_frame_pointer_rtx : stack_pointer_rtx,
+  offset, gen_rtx_REG (Pmode, A9_REG),
+  (flags & ADJUST_SP_NEED_NOTE));
 }
 
 /* minimum frame = reg 

[committed] openmp: Fix up finish_omp_target_clauses [PR108286]

2023-01-05 Thread Jakub Jelinek via Gcc-patches
Hi!

The comment in the loop says that we shouldn't add a map clause if such
a clause exists already, but the loop was actually using OMP_CLAUSE_DECL
on any clause.  Target construct can have various clauses which don't
have OMP_CLAUSE_DECL at all (e.g. nowait, device or if) or clause
where it means something different (e.g. privatization clauses, allocate,
depend).

So, only check OMP_CLAUSE_DECL on OMP_CLAUSE_MAP clauses.

Bootstrapped/regtested on x86_64-linux and i686-linux, committed to trunk
so far.

2023-01-05  Jakub Jelinek  

PR c++/108286
* semantics.cc (finish_omp_target_clauses): Ignore clauses other than
OMP_CLAUSE_MAP.

* testsuite/libgomp.c++/pr108286.C: New test.

--- gcc/cp/semantics.cc.jj  2022-12-05 11:10:37.610673062 +0100
+++ gcc/cp/semantics.cc 2023-01-04 19:10:52.882277867 +0100
@@ -9825,7 +9825,9 @@ finish_omp_target_clauses (location_t lo
 
for (tree c = *clauses_ptr; c; c = OMP_CLAUSE_CHAIN (c))
  {
-   /* If map(this->ptr[:N] already exists, avoid creating another
+   if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_MAP)
+ continue;
+   /* If map(this->ptr[:N]) already exists, avoid creating another
   such map.  */
tree decl = OMP_CLAUSE_DECL (c);
if ((TREE_CODE (decl) == INDIRECT_REF
--- libgomp/testsuite/libgomp.c++/pr108286.C.jj 2023-01-04 19:21:07.401384587 
+0100
+++ libgomp/testsuite/libgomp.c++/pr108286.C2023-01-04 19:20:05.793276171 
+0100
@@ -0,0 +1,29 @@
+// PR c++/108286
+// { dg-do run }
+
+struct S {
+  int
+  foo ()
+  {
+int res = 0;
+#pragma omp target map(size, ptr[:size], res) nowait
+res = ptr[size - 1];
+#pragma omp taskwait
+return res;
+  }
+
+  unsigned size;
+  int *ptr;
+};
+
+int
+main ()
+{
+  S s;
+  int buf[5];
+  s.size = 5;
+  s.ptr = buf;
+  buf[4] = 42;
+  if (s.foo () != 42)
+__builtin_abort ();
+}

Jakub



RE: [PATCH v2] libgfortran: Replace mutex with rwlock

2023-01-05 Thread Zhu, Lipeng via Gcc-patches
> > Hi Lipeng,
> > 
> > > This patch try to introduce the rwlock and split the read/write to 
> > > unit_root tree and unit_cache with rwlock instead of the mutex to 
> > > increase CPU efficiency. In the get_gfc_unit function, the 
> > > percentage to step into the insert_unit function is around 30%, in 
> > > most instances, we can get the unit in the phase of reading the 
> > > unit_cache or unit_root tree. So split the read/write phase by 
> > > rwlock would be an approach to make it more parallel.
> >
> > No comment on the code itself, as yet... but I'd like to know how 
> > throroughly you tested it, using which tools, and on which programs.
> > Did you use valgrind --tool=helgrind or --tool=drd?  Since it is prone to 
> > race conditions, did you also test Fortran's asynchronous I/O?
> >
> > Best regards
> >
> > Thomas
> 
> Hi Thomas,
> 
> I didn’t use valgrind and make check-fortran succeed in local. 
> And the tools/programs I used is pts/neatbench 
> https://openbenchmarking.org/test/pts/neatbench
> 
> Best Regards,
> Lipeng Zhu

Hi Thomas,

Thanks for your comments, I just use valgrind --tool=helgrind or --tool=drd to 
test make check-fortran, no errors occurred.
==2609780== Helgrind, a thread error detector
==2609780== Copyright (C) 2007-2017, and GNU GPL'd, by OpenWorks LLP et al.
==2609780== Using Valgrind-3.19.0 and LibVEX; rerun with -h for copyright info
==2609780== Command: make check-fortran -j150
==2609780==
==2609780==
==2609780== Use --history-level=approx or =none to gain increased speed, at
==2609780== the cost of reduced accuracy of conflicting-access information
==2609780== For lists of detected and suppressed errors, rerun with: -s
==2609780== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

==2976599== drd, a thread error detector
==2976599== Copyright (C) 2006-2020, and GNU GPL'd, by Bart Van Assche.
==2976599== Using Valgrind-3.19.0 and LibVEX; rerun with -h for copyright info
==2976599== Command: make check-fortran -j150
==2976599==
==2976599==
==2976599== For lists of detected and suppressed errors, rerun with: -s
==2976599== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

BTW, can you give me some guidance of how to test Fortran's asynchronous I/O?

Best Regards,
Lipeng Zhu