[Ada] Excess finalization on assignment with target name symbol

Message ID 20220511085432.GA2166541@adacore.com
State Committed
Headers
Series [Ada] Excess finalization on assignment with target name symbol |

Commit Message

Pierre-Marie de Rodat May 11, 2022, 8:54 a.m. UTC
  In cases where the Ada 2022 feature of target name symbols (@) is used
and the evaluation of the name is side-effect free, the compiler creates
a temporary object to hold the value of the target object for use as
the value of "@" symbols in the right-hand side expression. In the case
where the target's type is controlled, or has controlled subcomponents,
this can result in extra finalization calls (for the temporary object).
The correction is to bypass the use of a temp and fall back on the more
general approach of creating and calling a procedure with an in-out
parameter for performing the assignment.

Tested on x86_64-pc-linux-gnu, committed on trunk

gcc/ada/

	* exp_ch5.adb (Expand_Assign_With_Target_Names): Bypass the temp
	object approach in the case where the type of the LHS is
	controlled or has controlled subcomponents (Needs_Finalization
	is True), and use the procedure approach instead.
  

Patch

diff --git a/gcc/ada/exp_ch5.adb b/gcc/ada/exp_ch5.adb
--- a/gcc/ada/exp_ch5.adb
+++ b/gcc/ada/exp_ch5.adb
@@ -2246,9 +2246,15 @@  package body Exp_Ch5 is
              Expression => New_RHS));
 
       --  The left-hand side is not a direct name, but is side-effect free.
-      --  Capture its value in a temporary to avoid multiple evaluations.
-
-      elsif Side_Effect_Free (LHS) then
+      --  Capture its value in a temporary to avoid generating a procedure.
+      --  We don't do this optimization if the target object's type may need
+      --  finalization actions, because we don't want extra finalizations to
+      --  be done for the temp object, and instead we use the more general
+      --  procedure-based approach below.
+
+      elsif Side_Effect_Free (LHS)
+        and then not Needs_Finalization (Etype (LHS))
+      then
          Ent := Make_Temporary (Loc, 'T');
          Replace_Target_Name (New_RHS);