1 ------------------------------------------------------------------------------
3 -- GNAT COMPILER COMPONENTS --
9 -- Copyright (C) 1992-2008, Free Software Foundation, Inc. --
11 -- GNAT is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 3, or (at your option) any later ver- --
14 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
17 -- for more details. You should have received a copy of the GNU General --
18 -- Public License distributed with GNAT; see file COPYING3. If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license. --
21 -- GNAT was originally developed by the GNAT team at New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc. --
24 ------------------------------------------------------------------------------
26 with Atree; use Atree;
27 with Checks; use Checks;
28 with Debug; use Debug;
29 with Einfo; use Einfo;
30 with Elists; use Elists;
31 with Exp_Atag; use Exp_Atag;
32 with Exp_Aggr; use Exp_Aggr;
33 with Exp_Ch6; use Exp_Ch6;
34 with Exp_Ch7; use Exp_Ch7;
35 with Exp_Ch11; use Exp_Ch11;
36 with Exp_Dbug; use Exp_Dbug;
37 with Exp_Pakd; use Exp_Pakd;
38 with Exp_Tss; use Exp_Tss;
39 with Exp_Util; use Exp_Util;
40 with Namet; use Namet;
41 with Nlists; use Nlists;
42 with Nmake; use Nmake;
44 with Restrict; use Restrict;
45 with Rident; use Rident;
46 with Rtsfind; use Rtsfind;
47 with Sinfo; use Sinfo;
49 with Sem_Aux; use Sem_Aux;
50 with Sem_Ch3; use Sem_Ch3;
51 with Sem_Ch8; use Sem_Ch8;
52 with Sem_Ch13; use Sem_Ch13;
53 with Sem_Eval; use Sem_Eval;
54 with Sem_Res; use Sem_Res;
55 with Sem_Util; use Sem_Util;
56 with Snames; use Snames;
57 with Stand; use Stand;
58 with Stringt; use Stringt;
59 with Targparm; use Targparm;
60 with Tbuild; use Tbuild;
61 with Ttypes; use Ttypes;
62 with Uintp; use Uintp;
63 with Validsw; use Validsw;
65 package body Exp_Ch5 is
67 function Change_Of_Representation (N : Node_Id) return Boolean;
68 -- Determine if the right hand side of the assignment N is a type
69 -- conversion which requires a change of representation. Called
70 -- only for the array and record cases.
72 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id);
73 -- N is an assignment which assigns an array value. This routine process
74 -- the various special cases and checks required for such assignments,
75 -- including change of representation. Rhs is normally simply the right
76 -- hand side of the assignment, except that if the right hand side is
77 -- a type conversion or a qualified expression, then the Rhs is the
78 -- actual expression inside any such type conversions or qualifications.
80 function Expand_Assign_Array_Loop
87 Rev : Boolean) return Node_Id;
88 -- N is an assignment statement which assigns an array value. This routine
89 -- expands the assignment into a loop (or nested loops for the case of a
90 -- multi-dimensional array) to do the assignment component by component.
91 -- Larray and Rarray are the entities of the actual arrays on the left
92 -- hand and right hand sides. L_Type and R_Type are the types of these
93 -- arrays (which may not be the same, due to either sliding, or to a
94 -- change of representation case). Ndim is the number of dimensions and
95 -- the parameter Rev indicates if the loops run normally (Rev = False),
96 -- or reversed (Rev = True). The value returned is the constructed
97 -- loop statement. Auxiliary declarations are inserted before node N
98 -- using the standard Insert_Actions mechanism.
100 procedure Expand_Assign_Record (N : Node_Id);
101 -- N is an assignment of a non-tagged record value. This routine handles
102 -- the case where the assignment must be made component by component,
103 -- either because the target is not byte aligned, or there is a change
104 -- of representation.
106 procedure Expand_Non_Function_Return (N : Node_Id);
107 -- Called by Expand_N_Simple_Return_Statement in case we're returning from
108 -- a procedure body, entry body, accept statement, or extended return
109 -- statement. Note that all non-function returns are simple return
112 procedure Expand_Simple_Function_Return (N : Node_Id);
113 -- Expand simple return from function. In the case where we are returning
114 -- from a function body this is called by Expand_N_Simple_Return_Statement.
116 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id;
117 -- Generate the necessary code for controlled and tagged assignment,
118 -- that is to say, finalization of the target before, adjustment of
119 -- the target after and save and restore of the tag and finalization
120 -- pointers which are not 'part of the value' and must not be changed
121 -- upon assignment. N is the original Assignment node.
123 ------------------------------
124 -- Change_Of_Representation --
125 ------------------------------
127 function Change_Of_Representation (N : Node_Id) return Boolean is
128 Rhs : constant Node_Id := Expression (N);
131 Nkind (Rhs) = N_Type_Conversion
133 not Same_Representation (Etype (Rhs), Etype (Expression (Rhs)));
134 end Change_Of_Representation;
136 -------------------------
137 -- Expand_Assign_Array --
138 -------------------------
140 -- There are two issues here. First, do we let Gigi do a block move, or
141 -- do we expand out into a loop? Second, we need to set the two flags
142 -- Forwards_OK and Backwards_OK which show whether the block move (or
143 -- corresponding loops) can be legitimately done in a forwards (low to
144 -- high) or backwards (high to low) manner.
146 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id) is
147 Loc : constant Source_Ptr := Sloc (N);
149 Lhs : constant Node_Id := Name (N);
151 Act_Lhs : constant Node_Id := Get_Referenced_Object (Lhs);
152 Act_Rhs : Node_Id := Get_Referenced_Object (Rhs);
154 L_Type : constant Entity_Id :=
155 Underlying_Type (Get_Actual_Subtype (Act_Lhs));
156 R_Type : Entity_Id :=
157 Underlying_Type (Get_Actual_Subtype (Act_Rhs));
159 L_Slice : constant Boolean := Nkind (Act_Lhs) = N_Slice;
160 R_Slice : constant Boolean := Nkind (Act_Rhs) = N_Slice;
162 Crep : constant Boolean := Change_Of_Representation (N);
167 Ndim : constant Pos := Number_Dimensions (L_Type);
169 Loop_Required : Boolean := False;
170 -- This switch is set to True if the array move must be done using
171 -- an explicit front end generated loop.
173 procedure Apply_Dereference (Arg : Node_Id);
174 -- If the argument is an access to an array, and the assignment is
175 -- converted into a procedure call, apply explicit dereference.
177 function Has_Address_Clause (Exp : Node_Id) return Boolean;
178 -- Test if Exp is a reference to an array whose declaration has
179 -- an address clause, or it is a slice of such an array.
181 function Is_Formal_Array (Exp : Node_Id) return Boolean;
182 -- Test if Exp is a reference to an array which is either a formal
183 -- parameter or a slice of a formal parameter. These are the cases
184 -- where hidden aliasing can occur.
186 function Is_Non_Local_Array (Exp : Node_Id) return Boolean;
187 -- Determine if Exp is a reference to an array variable which is other
188 -- than an object defined in the current scope, or a slice of such
189 -- an object. Such objects can be aliased to parameters (unlike local
190 -- array references).
192 -----------------------
193 -- Apply_Dereference --
194 -----------------------
196 procedure Apply_Dereference (Arg : Node_Id) is
197 Typ : constant Entity_Id := Etype (Arg);
199 if Is_Access_Type (Typ) then
200 Rewrite (Arg, Make_Explicit_Dereference (Loc,
201 Prefix => Relocate_Node (Arg)));
202 Analyze_And_Resolve (Arg, Designated_Type (Typ));
204 end Apply_Dereference;
206 ------------------------
207 -- Has_Address_Clause --
208 ------------------------
210 function Has_Address_Clause (Exp : Node_Id) return Boolean is
213 (Is_Entity_Name (Exp) and then
214 Present (Address_Clause (Entity (Exp))))
216 (Nkind (Exp) = N_Slice and then Has_Address_Clause (Prefix (Exp)));
217 end Has_Address_Clause;
219 ---------------------
220 -- Is_Formal_Array --
221 ---------------------
223 function Is_Formal_Array (Exp : Node_Id) return Boolean is
226 (Is_Entity_Name (Exp) and then Is_Formal (Entity (Exp)))
228 (Nkind (Exp) = N_Slice and then Is_Formal_Array (Prefix (Exp)));
231 ------------------------
232 -- Is_Non_Local_Array --
233 ------------------------
235 function Is_Non_Local_Array (Exp : Node_Id) return Boolean is
237 return (Is_Entity_Name (Exp)
238 and then Scope (Entity (Exp)) /= Current_Scope)
239 or else (Nkind (Exp) = N_Slice
240 and then Is_Non_Local_Array (Prefix (Exp)));
241 end Is_Non_Local_Array;
243 -- Determine if Lhs, Rhs are formal arrays or nonlocal arrays
245 Lhs_Formal : constant Boolean := Is_Formal_Array (Act_Lhs);
246 Rhs_Formal : constant Boolean := Is_Formal_Array (Act_Rhs);
248 Lhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Lhs);
249 Rhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Rhs);
251 -- Start of processing for Expand_Assign_Array
254 -- Deal with length check. Note that the length check is done with
255 -- respect to the right hand side as given, not a possible underlying
256 -- renamed object, since this would generate incorrect extra checks.
258 Apply_Length_Check (Rhs, L_Type);
260 -- We start by assuming that the move can be done in either direction,
261 -- i.e. that the two sides are completely disjoint.
263 Set_Forwards_OK (N, True);
264 Set_Backwards_OK (N, True);
266 -- Normally it is only the slice case that can lead to overlap, and
267 -- explicit checks for slices are made below. But there is one case
268 -- where the slice can be implicit and invisible to us: when we have a
269 -- one dimensional array, and either both operands are parameters, or
270 -- one is a parameter (which can be a slice passed by reference) and the
271 -- other is a non-local variable. In this case the parameter could be a
272 -- slice that overlaps with the other operand.
274 -- However, if the array subtype is a constrained first subtype in the
275 -- parameter case, then we don't have to worry about overlap, since
276 -- slice assignments aren't possible (other than for a slice denoting
279 -- Note: No overlap is possible if there is a change of representation,
280 -- so we can exclude this case.
285 ((Lhs_Formal and Rhs_Formal)
287 (Lhs_Formal and Rhs_Non_Local_Var)
289 (Rhs_Formal and Lhs_Non_Local_Var))
291 (not Is_Constrained (Etype (Lhs))
292 or else not Is_First_Subtype (Etype (Lhs)))
294 -- In the case of compiling for the Java or .NET Virtual Machine,
295 -- slices are always passed by making a copy, so we don't have to
296 -- worry about overlap. We also want to prevent generation of "<"
297 -- comparisons for array addresses, since that's a meaningless
298 -- operation on the VM.
300 and then VM_Target = No_VM
302 Set_Forwards_OK (N, False);
303 Set_Backwards_OK (N, False);
305 -- Note: the bit-packed case is not worrisome here, since if we have
306 -- a slice passed as a parameter, it is always aligned on a byte
307 -- boundary, and if there are no explicit slices, the assignment
308 -- can be performed directly.
311 -- If either operand has an address clause clear Backwards_OK and
312 -- Forwards_OK, since we cannot tell if the operands overlap.
314 if Has_Address_Clause (Lhs) or else Has_Address_Clause (Rhs) then
315 Set_Forwards_OK (N, False);
316 Set_Backwards_OK (N, False);
319 -- We certainly must use a loop for change of representation and also
320 -- we use the operand of the conversion on the right hand side as the
321 -- effective right hand side (the component types must match in this
325 Act_Rhs := Get_Referenced_Object (Rhs);
326 R_Type := Get_Actual_Subtype (Act_Rhs);
327 Loop_Required := True;
329 -- We require a loop if the left side is possibly bit unaligned
331 elsif Possible_Bit_Aligned_Component (Lhs)
333 Possible_Bit_Aligned_Component (Rhs)
335 Loop_Required := True;
337 -- Arrays with controlled components are expanded into a loop to force
338 -- calls to Adjust at the component level.
340 elsif Has_Controlled_Component (L_Type) then
341 Loop_Required := True;
343 -- If object is atomic, we cannot tolerate a loop
345 elsif Is_Atomic_Object (Act_Lhs)
347 Is_Atomic_Object (Act_Rhs)
351 -- Loop is required if we have atomic components since we have to
352 -- be sure to do any accesses on an element by element basis.
354 elsif Has_Atomic_Components (L_Type)
355 or else Has_Atomic_Components (R_Type)
356 or else Is_Atomic (Component_Type (L_Type))
357 or else Is_Atomic (Component_Type (R_Type))
359 Loop_Required := True;
361 -- Case where no slice is involved
363 elsif not L_Slice and not R_Slice then
365 -- The following code deals with the case of unconstrained bit packed
366 -- arrays. The problem is that the template for such arrays contains
367 -- the bounds of the actual source level array, but the copy of an
368 -- entire array requires the bounds of the underlying array. It would
369 -- be nice if the back end could take care of this, but right now it
370 -- does not know how, so if we have such a type, then we expand out
371 -- into a loop, which is inefficient but works correctly. If we don't
372 -- do this, we get the wrong length computed for the array to be
373 -- moved. The two cases we need to worry about are:
375 -- Explicit deference of an unconstrained packed array type as in the
376 -- following example:
379 -- type BITS is array(INTEGER range <>) of BOOLEAN;
380 -- pragma PACK(BITS);
381 -- type A is access BITS;
384 -- P1 := new BITS (1 .. 65_535);
385 -- P2 := new BITS (1 .. 65_535);
389 -- A formal parameter reference with an unconstrained bit array type
390 -- is the other case we need to worry about (here we assume the same
391 -- BITS type declared above):
393 -- procedure Write_All (File : out BITS; Contents : BITS);
395 -- File.Storage := Contents;
398 -- We expand to a loop in either of these two cases
400 -- Question for future thought. Another potentially more efficient
401 -- approach would be to create the actual subtype, and then do an
402 -- unchecked conversion to this actual subtype ???
404 Check_Unconstrained_Bit_Packed_Array : declare
406 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean;
407 -- Function to perform required test for the first case, above
408 -- (dereference of an unconstrained bit packed array).
410 -----------------------
411 -- Is_UBPA_Reference --
412 -----------------------
414 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean is
415 Typ : constant Entity_Id := Underlying_Type (Etype (Opnd));
417 Des_Type : Entity_Id;
420 if Present (Packed_Array_Type (Typ))
421 and then Is_Array_Type (Packed_Array_Type (Typ))
422 and then not Is_Constrained (Packed_Array_Type (Typ))
426 elsif Nkind (Opnd) = N_Explicit_Dereference then
427 P_Type := Underlying_Type (Etype (Prefix (Opnd)));
429 if not Is_Access_Type (P_Type) then
433 Des_Type := Designated_Type (P_Type);
435 Is_Bit_Packed_Array (Des_Type)
436 and then not Is_Constrained (Des_Type);
442 end Is_UBPA_Reference;
444 -- Start of processing for Check_Unconstrained_Bit_Packed_Array
447 if Is_UBPA_Reference (Lhs)
449 Is_UBPA_Reference (Rhs)
451 Loop_Required := True;
453 -- Here if we do not have the case of a reference to a bit packed
454 -- unconstrained array case. In this case gigi can most certainly
455 -- handle the assignment if a forwards move is allowed.
457 -- (could it handle the backwards case also???)
459 elsif Forwards_OK (N) then
462 end Check_Unconstrained_Bit_Packed_Array;
464 -- The back end can always handle the assignment if the right side is a
465 -- string literal (note that overlap is definitely impossible in this
466 -- case). If the type is packed, a string literal is always converted
467 -- into an aggregate, except in the case of a null slice, for which no
468 -- aggregate can be written. In that case, rewrite the assignment as a
469 -- null statement, a length check has already been emitted to verify
470 -- that the range of the left-hand side is empty.
472 -- Note that this code is not executed if we have an assignment of a
473 -- string literal to a non-bit aligned component of a record, a case
474 -- which cannot be handled by the backend.
476 elsif Nkind (Rhs) = N_String_Literal then
477 if String_Length (Strval (Rhs)) = 0
478 and then Is_Bit_Packed_Array (L_Type)
480 Rewrite (N, Make_Null_Statement (Loc));
486 -- If either operand is bit packed, then we need a loop, since we can't
487 -- be sure that the slice is byte aligned. Similarly, if either operand
488 -- is a possibly unaligned slice, then we need a loop (since the back
489 -- end cannot handle unaligned slices).
491 elsif Is_Bit_Packed_Array (L_Type)
492 or else Is_Bit_Packed_Array (R_Type)
493 or else Is_Possibly_Unaligned_Slice (Lhs)
494 or else Is_Possibly_Unaligned_Slice (Rhs)
496 Loop_Required := True;
498 -- If we are not bit-packed, and we have only one slice, then no overlap
499 -- is possible except in the parameter case, so we can let the back end
502 elsif not (L_Slice and R_Slice) then
503 if Forwards_OK (N) then
508 -- If the right-hand side is a string literal, introduce a temporary for
509 -- it, for use in the generated loop that will follow.
511 if Nkind (Rhs) = N_String_Literal then
513 Temp : constant Entity_Id :=
514 Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
519 Make_Object_Declaration (Loc,
520 Defining_Identifier => Temp,
521 Object_Definition => New_Occurrence_Of (L_Type, Loc),
522 Expression => Relocate_Node (Rhs));
524 Insert_Action (N, Decl);
525 Rewrite (Rhs, New_Occurrence_Of (Temp, Loc));
526 R_Type := Etype (Temp);
530 -- Come here to complete the analysis
532 -- Loop_Required: Set to True if we know that a loop is required
533 -- regardless of overlap considerations.
535 -- Forwards_OK: Set to False if we already know that a forwards
536 -- move is not safe, else set to True.
538 -- Backwards_OK: Set to False if we already know that a backwards
539 -- move is not safe, else set to True
541 -- Our task at this stage is to complete the overlap analysis, which can
542 -- result in possibly setting Forwards_OK or Backwards_OK to False, and
543 -- then generating the final code, either by deciding that it is OK
544 -- after all to let Gigi handle it, or by generating appropriate code
548 L_Index_Typ : constant Node_Id := Etype (First_Index (L_Type));
549 R_Index_Typ : constant Node_Id := Etype (First_Index (R_Type));
551 Left_Lo : constant Node_Id := Type_Low_Bound (L_Index_Typ);
552 Left_Hi : constant Node_Id := Type_High_Bound (L_Index_Typ);
553 Right_Lo : constant Node_Id := Type_Low_Bound (R_Index_Typ);
554 Right_Hi : constant Node_Id := Type_High_Bound (R_Index_Typ);
556 Act_L_Array : Node_Id;
557 Act_R_Array : Node_Id;
563 Cresult : Compare_Result;
566 -- Get the expressions for the arrays. If we are dealing with a
567 -- private type, then convert to the underlying type. We can do
568 -- direct assignments to an array that is a private type, but we
569 -- cannot assign to elements of the array without this extra
570 -- unchecked conversion.
572 if Nkind (Act_Lhs) = N_Slice then
573 Larray := Prefix (Act_Lhs);
577 if Is_Private_Type (Etype (Larray)) then
580 (Underlying_Type (Etype (Larray)), Larray);
584 if Nkind (Act_Rhs) = N_Slice then
585 Rarray := Prefix (Act_Rhs);
589 if Is_Private_Type (Etype (Rarray)) then
592 (Underlying_Type (Etype (Rarray)), Rarray);
596 -- If both sides are slices, we must figure out whether it is safe
597 -- to do the move in one direction or the other. It is always safe
598 -- if there is a change of representation since obviously two arrays
599 -- with different representations cannot possibly overlap.
601 if (not Crep) and L_Slice and R_Slice then
602 Act_L_Array := Get_Referenced_Object (Prefix (Act_Lhs));
603 Act_R_Array := Get_Referenced_Object (Prefix (Act_Rhs));
605 -- If both left and right hand arrays are entity names, and refer
606 -- to different entities, then we know that the move is safe (the
607 -- two storage areas are completely disjoint).
609 if Is_Entity_Name (Act_L_Array)
610 and then Is_Entity_Name (Act_R_Array)
611 and then Entity (Act_L_Array) /= Entity (Act_R_Array)
615 -- Otherwise, we assume the worst, which is that the two arrays
616 -- are the same array. There is no need to check if we know that
617 -- is the case, because if we don't know it, we still have to
620 -- Generally if the same array is involved, then we have an
621 -- overlapping case. We will have to really assume the worst (i.e.
622 -- set neither of the OK flags) unless we can determine the lower
623 -- or upper bounds at compile time and compare them.
628 (Left_Lo, Right_Lo, Assume_Valid => True);
630 if Cresult = Unknown then
633 (Left_Hi, Right_Hi, Assume_Valid => True);
637 when LT | LE | EQ => Set_Backwards_OK (N, False);
638 when GT | GE => Set_Forwards_OK (N, False);
639 when NE | Unknown => Set_Backwards_OK (N, False);
640 Set_Forwards_OK (N, False);
645 -- If after that analysis Loop_Required is False, meaning that we
646 -- have not discovered some non-overlap reason for requiring a loop,
647 -- then the outcome depends on the capabilities of the back end.
649 if not Loop_Required then
651 -- The GCC back end can deal with all cases of overlap by falling
652 -- back to memmove if it cannot use a more efficient approach.
654 if VM_Target = No_VM and not AAMP_On_Target then
657 -- Assume other back ends can handle it if Forwards_OK is set
659 elsif Forwards_OK (N) then
662 -- If Forwards_OK is not set, the back end will need something
663 -- like memmove to handle the move. For now, this processing is
664 -- activated using the .s debug flag (-gnatd.s).
666 elsif Debug_Flag_Dot_S then
671 -- At this stage we have to generate an explicit loop, and we have
672 -- the following cases:
674 -- Forwards_OK = True
676 -- Rnn : right_index := right_index'First;
677 -- for Lnn in left-index loop
678 -- left (Lnn) := right (Rnn);
679 -- Rnn := right_index'Succ (Rnn);
682 -- Note: the above code MUST be analyzed with checks off, because
683 -- otherwise the Succ could overflow. But in any case this is more
686 -- Forwards_OK = False, Backwards_OK = True
688 -- Rnn : right_index := right_index'Last;
689 -- for Lnn in reverse left-index loop
690 -- left (Lnn) := right (Rnn);
691 -- Rnn := right_index'Pred (Rnn);
694 -- Note: the above code MUST be analyzed with checks off, because
695 -- otherwise the Pred could overflow. But in any case this is more
698 -- Forwards_OK = Backwards_OK = False
700 -- This only happens if we have the same array on each side. It is
701 -- possible to create situations using overlays that violate this,
702 -- but we simply do not promise to get this "right" in this case.
704 -- There are two possible subcases. If the No_Implicit_Conditionals
705 -- restriction is set, then we generate the following code:
708 -- T : constant <operand-type> := rhs;
713 -- If implicit conditionals are permitted, then we generate:
715 -- if Left_Lo <= Right_Lo then
716 -- <code for Forwards_OK = True above>
718 -- <code for Backwards_OK = True above>
721 -- In order to detect possible aliasing, we examine the renamed
722 -- expression when the source or target is a renaming. However,
723 -- the renaming may be intended to capture an address that may be
724 -- affected by subsequent code, and therefore we must recover
725 -- the actual entity for the expansion that follows, not the
726 -- object it renames. In particular, if source or target designate
727 -- a portion of a dynamically allocated object, the pointer to it
728 -- may be reassigned but the renaming preserves the proper location.
730 if Is_Entity_Name (Rhs)
732 Nkind (Parent (Entity (Rhs))) = N_Object_Renaming_Declaration
733 and then Nkind (Act_Rhs) = N_Slice
738 if Is_Entity_Name (Lhs)
740 Nkind (Parent (Entity (Lhs))) = N_Object_Renaming_Declaration
741 and then Nkind (Act_Lhs) = N_Slice
746 -- Cases where either Forwards_OK or Backwards_OK is true
748 if Forwards_OK (N) or else Backwards_OK (N) then
749 if Needs_Finalization (Component_Type (L_Type))
750 and then Base_Type (L_Type) = Base_Type (R_Type)
752 and then not No_Ctrl_Actions (N)
755 Proc : constant Entity_Id :=
756 TSS (Base_Type (L_Type), TSS_Slice_Assign);
760 Apply_Dereference (Larray);
761 Apply_Dereference (Rarray);
762 Actuals := New_List (
763 Duplicate_Subexpr (Larray, Name_Req => True),
764 Duplicate_Subexpr (Rarray, Name_Req => True),
765 Duplicate_Subexpr (Left_Lo, Name_Req => True),
766 Duplicate_Subexpr (Left_Hi, Name_Req => True),
767 Duplicate_Subexpr (Right_Lo, Name_Req => True),
768 Duplicate_Subexpr (Right_Hi, Name_Req => True));
772 Boolean_Literals (not Forwards_OK (N)), Loc));
775 Make_Procedure_Call_Statement (Loc,
776 Name => New_Reference_To (Proc, Loc),
777 Parameter_Associations => Actuals));
782 Expand_Assign_Array_Loop
783 (N, Larray, Rarray, L_Type, R_Type, Ndim,
784 Rev => not Forwards_OK (N)));
787 -- Case of both are false with No_Implicit_Conditionals
789 elsif Restriction_Active (No_Implicit_Conditionals) then
791 T : constant Entity_Id :=
792 Make_Defining_Identifier (Loc, Chars => Name_T);
796 Make_Block_Statement (Loc,
797 Declarations => New_List (
798 Make_Object_Declaration (Loc,
799 Defining_Identifier => T,
800 Constant_Present => True,
802 New_Occurrence_Of (Etype (Rhs), Loc),
803 Expression => Relocate_Node (Rhs))),
805 Handled_Statement_Sequence =>
806 Make_Handled_Sequence_Of_Statements (Loc,
807 Statements => New_List (
808 Make_Assignment_Statement (Loc,
809 Name => Relocate_Node (Lhs),
810 Expression => New_Occurrence_Of (T, Loc))))));
813 -- Case of both are false with implicit conditionals allowed
816 -- Before we generate this code, we must ensure that the left and
817 -- right side array types are defined. They may be itypes, and we
818 -- cannot let them be defined inside the if, since the first use
819 -- in the then may not be executed.
821 Ensure_Defined (L_Type, N);
822 Ensure_Defined (R_Type, N);
824 -- We normally compare addresses to find out which way round to
825 -- do the loop, since this is reliable, and handles the cases of
826 -- parameters, conversions etc. But we can't do that in the bit
827 -- packed case or the VM case, because addresses don't work there.
829 if not Is_Bit_Packed_Array (L_Type) and then VM_Target = No_VM then
833 Unchecked_Convert_To (RTE (RE_Integer_Address),
834 Make_Attribute_Reference (Loc,
836 Make_Indexed_Component (Loc,
838 Duplicate_Subexpr_Move_Checks (Larray, True),
839 Expressions => New_List (
840 Make_Attribute_Reference (Loc,
844 Attribute_Name => Name_First))),
845 Attribute_Name => Name_Address)),
848 Unchecked_Convert_To (RTE (RE_Integer_Address),
849 Make_Attribute_Reference (Loc,
851 Make_Indexed_Component (Loc,
853 Duplicate_Subexpr_Move_Checks (Rarray, True),
854 Expressions => New_List (
855 Make_Attribute_Reference (Loc,
859 Attribute_Name => Name_First))),
860 Attribute_Name => Name_Address)));
862 -- For the bit packed and VM cases we use the bounds. That's OK,
863 -- because we don't have to worry about parameters, since they
864 -- cannot cause overlap. Perhaps we should worry about weird slice
870 Cleft_Lo := New_Copy_Tree (Left_Lo);
871 Cright_Lo := New_Copy_Tree (Right_Lo);
873 -- If the types do not match we add an implicit conversion
874 -- here to ensure proper match
876 if Etype (Left_Lo) /= Etype (Right_Lo) then
878 Unchecked_Convert_To (Etype (Left_Lo), Cright_Lo);
881 -- Reset the Analyzed flag, because the bounds of the index
882 -- type itself may be universal, and must must be reaanalyzed
883 -- to acquire the proper type for the back end.
885 Set_Analyzed (Cleft_Lo, False);
886 Set_Analyzed (Cright_Lo, False);
890 Left_Opnd => Cleft_Lo,
891 Right_Opnd => Cright_Lo);
894 if Needs_Finalization (Component_Type (L_Type))
895 and then Base_Type (L_Type) = Base_Type (R_Type)
897 and then not No_Ctrl_Actions (N)
900 -- Call TSS procedure for array assignment, passing the
901 -- explicit bounds of right and left hand sides.
904 Proc : constant Entity_Id :=
905 TSS (Base_Type (L_Type), TSS_Slice_Assign);
909 Apply_Dereference (Larray);
910 Apply_Dereference (Rarray);
911 Actuals := New_List (
912 Duplicate_Subexpr (Larray, Name_Req => True),
913 Duplicate_Subexpr (Rarray, Name_Req => True),
914 Duplicate_Subexpr (Left_Lo, Name_Req => True),
915 Duplicate_Subexpr (Left_Hi, Name_Req => True),
916 Duplicate_Subexpr (Right_Lo, Name_Req => True),
917 Duplicate_Subexpr (Right_Hi, Name_Req => True));
921 Right_Opnd => Condition));
924 Make_Procedure_Call_Statement (Loc,
925 Name => New_Reference_To (Proc, Loc),
926 Parameter_Associations => Actuals));
931 Make_Implicit_If_Statement (N,
932 Condition => Condition,
934 Then_Statements => New_List (
935 Expand_Assign_Array_Loop
936 (N, Larray, Rarray, L_Type, R_Type, Ndim,
939 Else_Statements => New_List (
940 Expand_Assign_Array_Loop
941 (N, Larray, Rarray, L_Type, R_Type, Ndim,
946 Analyze (N, Suppress => All_Checks);
950 when RE_Not_Available =>
952 end Expand_Assign_Array;
954 ------------------------------
955 -- Expand_Assign_Array_Loop --
956 ------------------------------
958 -- The following is an example of the loop generated for the case of a
959 -- two-dimensional array:
964 -- for L1b in 1 .. 100 loop
968 -- for L3b in 1 .. 100 loop
969 -- vm1 (L1b, L3b) := vm2 (R2b, R4b);
970 -- R4b := Tm1X2'succ(R4b);
973 -- R2b := Tm1X1'succ(R2b);
977 -- Here Rev is False, and Tm1Xn are the subscript types for the right hand
978 -- side. The declarations of R2b and R4b are inserted before the original
979 -- assignment statement.
981 function Expand_Assign_Array_Loop
988 Rev : Boolean) return Node_Id
990 Loc : constant Source_Ptr := Sloc (N);
992 Lnn : array (1 .. Ndim) of Entity_Id;
993 Rnn : array (1 .. Ndim) of Entity_Id;
994 -- Entities used as subscripts on left and right sides
996 L_Index_Type : array (1 .. Ndim) of Entity_Id;
997 R_Index_Type : array (1 .. Ndim) of Entity_Id;
998 -- Left and right index types
1007 F_Or_L := Name_Last;
1008 S_Or_P := Name_Pred;
1010 F_Or_L := Name_First;
1011 S_Or_P := Name_Succ;
1014 -- Setup index types and subscript entities
1021 L_Index := First_Index (L_Type);
1022 R_Index := First_Index (R_Type);
1024 for J in 1 .. Ndim loop
1026 Make_Defining_Identifier (Loc,
1027 Chars => New_Internal_Name ('L'));
1030 Make_Defining_Identifier (Loc,
1031 Chars => New_Internal_Name ('R'));
1033 L_Index_Type (J) := Etype (L_Index);
1034 R_Index_Type (J) := Etype (R_Index);
1036 Next_Index (L_Index);
1037 Next_Index (R_Index);
1041 -- Now construct the assignment statement
1044 ExprL : constant List_Id := New_List;
1045 ExprR : constant List_Id := New_List;
1048 for J in 1 .. Ndim loop
1049 Append_To (ExprL, New_Occurrence_Of (Lnn (J), Loc));
1050 Append_To (ExprR, New_Occurrence_Of (Rnn (J), Loc));
1054 Make_Assignment_Statement (Loc,
1056 Make_Indexed_Component (Loc,
1057 Prefix => Duplicate_Subexpr (Larray, Name_Req => True),
1058 Expressions => ExprL),
1060 Make_Indexed_Component (Loc,
1061 Prefix => Duplicate_Subexpr (Rarray, Name_Req => True),
1062 Expressions => ExprR));
1064 -- We set assignment OK, since there are some cases, e.g. in object
1065 -- declarations, where we are actually assigning into a constant.
1066 -- If there really is an illegality, it was caught long before now,
1067 -- and was flagged when the original assignment was analyzed.
1069 Set_Assignment_OK (Name (Assign));
1071 -- Propagate the No_Ctrl_Actions flag to individual assignments
1073 Set_No_Ctrl_Actions (Assign, No_Ctrl_Actions (N));
1076 -- Now construct the loop from the inside out, with the last subscript
1077 -- varying most rapidly. Note that Assign is first the raw assignment
1078 -- statement, and then subsequently the loop that wraps it up.
1080 for J in reverse 1 .. Ndim loop
1082 Make_Block_Statement (Loc,
1083 Declarations => New_List (
1084 Make_Object_Declaration (Loc,
1085 Defining_Identifier => Rnn (J),
1086 Object_Definition =>
1087 New_Occurrence_Of (R_Index_Type (J), Loc),
1089 Make_Attribute_Reference (Loc,
1090 Prefix => New_Occurrence_Of (R_Index_Type (J), Loc),
1091 Attribute_Name => F_Or_L))),
1093 Handled_Statement_Sequence =>
1094 Make_Handled_Sequence_Of_Statements (Loc,
1095 Statements => New_List (
1096 Make_Implicit_Loop_Statement (N,
1098 Make_Iteration_Scheme (Loc,
1099 Loop_Parameter_Specification =>
1100 Make_Loop_Parameter_Specification (Loc,
1101 Defining_Identifier => Lnn (J),
1102 Reverse_Present => Rev,
1103 Discrete_Subtype_Definition =>
1104 New_Reference_To (L_Index_Type (J), Loc))),
1106 Statements => New_List (
1109 Make_Assignment_Statement (Loc,
1110 Name => New_Occurrence_Of (Rnn (J), Loc),
1112 Make_Attribute_Reference (Loc,
1114 New_Occurrence_Of (R_Index_Type (J), Loc),
1115 Attribute_Name => S_Or_P,
1116 Expressions => New_List (
1117 New_Occurrence_Of (Rnn (J), Loc)))))))));
1121 end Expand_Assign_Array_Loop;
1123 --------------------------
1124 -- Expand_Assign_Record --
1125 --------------------------
1127 -- The only processing required is in the change of representation case,
1128 -- where we must expand the assignment to a series of field by field
1131 procedure Expand_Assign_Record (N : Node_Id) is
1132 Lhs : constant Node_Id := Name (N);
1133 Rhs : Node_Id := Expression (N);
1136 -- If change of representation, then extract the real right hand side
1137 -- from the type conversion, and proceed with component-wise assignment,
1138 -- since the two types are not the same as far as the back end is
1141 if Change_Of_Representation (N) then
1142 Rhs := Expression (Rhs);
1144 -- If this may be a case of a large bit aligned component, then proceed
1145 -- with component-wise assignment, to avoid possible clobbering of other
1146 -- components sharing bits in the first or last byte of the component to
1149 elsif Possible_Bit_Aligned_Component (Lhs)
1151 Possible_Bit_Aligned_Component (Rhs)
1155 -- If neither condition met, then nothing special to do, the back end
1156 -- can handle assignment of the entire component as a single entity.
1162 -- At this stage we know that we must do a component wise assignment
1165 Loc : constant Source_Ptr := Sloc (N);
1166 R_Typ : constant Entity_Id := Base_Type (Etype (Rhs));
1167 L_Typ : constant Entity_Id := Base_Type (Etype (Lhs));
1168 Decl : constant Node_Id := Declaration_Node (R_Typ);
1172 function Find_Component
1174 Comp : Entity_Id) return Entity_Id;
1175 -- Find the component with the given name in the underlying record
1176 -- declaration for Typ. We need to use the actual entity because the
1177 -- type may be private and resolution by identifier alone would fail.
1179 function Make_Component_List_Assign
1181 U_U : Boolean := False) return List_Id;
1182 -- Returns a sequence of statements to assign the components that
1183 -- are referenced in the given component list. The flag U_U is
1184 -- used to force the usage of the inferred value of the variant
1185 -- part expression as the switch for the generated case statement.
1187 function Make_Field_Assign
1189 U_U : Boolean := False) return Node_Id;
1190 -- Given C, the entity for a discriminant or component, build an
1191 -- assignment for the corresponding field values. The flag U_U
1192 -- signals the presence of an Unchecked_Union and forces the usage
1193 -- of the inferred discriminant value of C as the right hand side
1194 -- of the assignment.
1196 function Make_Field_Assigns (CI : List_Id) return List_Id;
1197 -- Given CI, a component items list, construct series of statements
1198 -- for fieldwise assignment of the corresponding components.
1200 --------------------
1201 -- Find_Component --
1202 --------------------
1204 function Find_Component
1206 Comp : Entity_Id) return Entity_Id
1208 Utyp : constant Entity_Id := Underlying_Type (Typ);
1212 C := First_Entity (Utyp);
1214 while Present (C) loop
1215 if Chars (C) = Chars (Comp) then
1221 raise Program_Error;
1224 --------------------------------
1225 -- Make_Component_List_Assign --
1226 --------------------------------
1228 function Make_Component_List_Assign
1230 U_U : Boolean := False) return List_Id
1232 CI : constant List_Id := Component_Items (CL);
1233 VP : constant Node_Id := Variant_Part (CL);
1243 Result := Make_Field_Assigns (CI);
1245 if Present (VP) then
1247 V := First_Non_Pragma (Variants (VP));
1249 while Present (V) loop
1252 DC := First (Discrete_Choices (V));
1253 while Present (DC) loop
1254 Append_To (DCH, New_Copy_Tree (DC));
1259 Make_Case_Statement_Alternative (Loc,
1260 Discrete_Choices => DCH,
1262 Make_Component_List_Assign (Component_List (V))));
1263 Next_Non_Pragma (V);
1266 -- If we have an Unchecked_Union, use the value of the inferred
1267 -- discriminant of the variant part expression as the switch
1268 -- for the case statement. The case statement may later be
1273 New_Copy (Get_Discriminant_Value (
1276 Discriminant_Constraint (Etype (Rhs))));
1279 Make_Selected_Component (Loc,
1280 Prefix => Duplicate_Subexpr (Rhs),
1282 Make_Identifier (Loc, Chars (Name (VP))));
1286 Make_Case_Statement (Loc,
1288 Alternatives => Alts));
1292 end Make_Component_List_Assign;
1294 -----------------------
1295 -- Make_Field_Assign --
1296 -----------------------
1298 function Make_Field_Assign
1300 U_U : Boolean := False) return Node_Id
1306 -- In the case of an Unchecked_Union, use the discriminant
1307 -- constraint value as on the right hand side of the assignment.
1311 New_Copy (Get_Discriminant_Value (C,
1313 Discriminant_Constraint (Etype (Rhs))));
1316 Make_Selected_Component (Loc,
1317 Prefix => Duplicate_Subexpr (Rhs),
1318 Selector_Name => New_Occurrence_Of (C, Loc));
1322 Make_Assignment_Statement (Loc,
1324 Make_Selected_Component (Loc,
1325 Prefix => Duplicate_Subexpr (Lhs),
1327 New_Occurrence_Of (Find_Component (L_Typ, C), Loc)),
1328 Expression => Expr);
1330 -- Set Assignment_OK, so discriminants can be assigned
1332 Set_Assignment_OK (Name (A), True);
1334 end Make_Field_Assign;
1336 ------------------------
1337 -- Make_Field_Assigns --
1338 ------------------------
1340 function Make_Field_Assigns (CI : List_Id) return List_Id is
1347 while Present (Item) loop
1348 if Nkind (Item) = N_Component_Declaration then
1350 (Result, Make_Field_Assign (Defining_Identifier (Item)));
1357 end Make_Field_Assigns;
1359 -- Start of processing for Expand_Assign_Record
1362 -- Note that we use the base types for this processing. This results
1363 -- in some extra work in the constrained case, but the change of
1364 -- representation case is so unusual that it is not worth the effort.
1366 -- First copy the discriminants. This is done unconditionally. It
1367 -- is required in the unconstrained left side case, and also in the
1368 -- case where this assignment was constructed during the expansion
1369 -- of a type conversion (since initialization of discriminants is
1370 -- suppressed in this case). It is unnecessary but harmless in
1373 if Has_Discriminants (L_Typ) then
1374 F := First_Discriminant (R_Typ);
1375 while Present (F) loop
1377 -- If we are expanding the initialization of a derived record
1378 -- that constrains or renames discriminants of the parent, we
1379 -- must use the corresponding discriminant in the parent.
1386 and then Present (Corresponding_Discriminant (F))
1388 CF := Corresponding_Discriminant (F);
1393 if Is_Unchecked_Union (Base_Type (R_Typ)) then
1394 Insert_Action (N, Make_Field_Assign (CF, True));
1396 Insert_Action (N, Make_Field_Assign (CF));
1399 Next_Discriminant (F);
1404 -- We know the underlying type is a record, but its current view
1405 -- may be private. We must retrieve the usable record declaration.
1407 if Nkind (Decl) = N_Private_Type_Declaration
1408 and then Present (Full_View (R_Typ))
1410 RDef := Type_Definition (Declaration_Node (Full_View (R_Typ)));
1412 RDef := Type_Definition (Decl);
1415 if Nkind (RDef) = N_Record_Definition
1416 and then Present (Component_List (RDef))
1419 if Is_Unchecked_Union (R_Typ) then
1421 Make_Component_List_Assign (Component_List (RDef), True));
1424 (N, Make_Component_List_Assign (Component_List (RDef)));
1427 Rewrite (N, Make_Null_Statement (Loc));
1431 end Expand_Assign_Record;
1433 -----------------------------------
1434 -- Expand_N_Assignment_Statement --
1435 -----------------------------------
1437 -- This procedure implements various cases where an assignment statement
1438 -- cannot just be passed on to the back end in untransformed state.
1440 procedure Expand_N_Assignment_Statement (N : Node_Id) is
1441 Loc : constant Source_Ptr := Sloc (N);
1442 Lhs : constant Node_Id := Name (N);
1443 Rhs : constant Node_Id := Expression (N);
1444 Typ : constant Entity_Id := Underlying_Type (Etype (Lhs));
1448 -- Ada 2005 (AI-327): Handle assignment to priority of protected object
1450 -- Rewrite an assignment to X'Priority into a run-time call
1452 -- For example: X'Priority := New_Prio_Expr;
1453 -- ...is expanded into Set_Ceiling (X._Object, New_Prio_Expr);
1455 -- Note that although X'Priority is notionally an object, it is quite
1456 -- deliberately not defined as an aliased object in the RM. This means
1457 -- that it works fine to rewrite it as a call, without having to worry
1458 -- about complications that would other arise from X'Priority'Access,
1459 -- which is illegal, because of the lack of aliasing.
1461 if Ada_Version >= Ada_05 then
1464 Conctyp : Entity_Id;
1467 RT_Subprg_Name : Node_Id;
1470 -- Handle chains of renamings
1473 while Nkind (Ent) in N_Has_Entity
1474 and then Present (Entity (Ent))
1475 and then Present (Renamed_Object (Entity (Ent)))
1477 Ent := Renamed_Object (Entity (Ent));
1480 -- The attribute Priority applied to protected objects has been
1481 -- previously expanded into a call to the Get_Ceiling run-time
1484 if Nkind (Ent) = N_Function_Call
1485 and then (Entity (Name (Ent)) = RTE (RE_Get_Ceiling)
1487 Entity (Name (Ent)) = RTE (RO_PE_Get_Ceiling))
1489 -- Look for the enclosing concurrent type
1491 Conctyp := Current_Scope;
1492 while not Is_Concurrent_Type (Conctyp) loop
1493 Conctyp := Scope (Conctyp);
1496 pragma Assert (Is_Protected_Type (Conctyp));
1498 -- Generate the first actual of the call
1500 Subprg := Current_Scope;
1501 while not Present (Protected_Body_Subprogram (Subprg)) loop
1502 Subprg := Scope (Subprg);
1505 -- Select the appropriate run-time call
1507 if Number_Entries (Conctyp) = 0 then
1509 New_Reference_To (RTE (RE_Set_Ceiling), Loc);
1512 New_Reference_To (RTE (RO_PE_Set_Ceiling), Loc);
1516 Make_Procedure_Call_Statement (Loc,
1517 Name => RT_Subprg_Name,
1518 Parameter_Associations => New_List (
1519 New_Copy_Tree (First (Parameter_Associations (Ent))),
1520 Relocate_Node (Expression (N))));
1529 -- First deal with generation of range check if required. For now we do
1530 -- this only for discrete types.
1532 if Do_Range_Check (Rhs)
1533 and then Is_Discrete_Type (Typ)
1535 Set_Do_Range_Check (Rhs, False);
1536 Generate_Range_Check (Rhs, Typ, CE_Range_Check_Failed);
1539 -- Check for a special case where a high level transformation is
1540 -- required. If we have either of:
1545 -- where P is a reference to a bit packed array, then we have to unwind
1546 -- the assignment. The exact meaning of being a reference to a bit
1547 -- packed array is as follows:
1549 -- An indexed component whose prefix is a bit packed array is a
1550 -- reference to a bit packed array.
1552 -- An indexed component or selected component whose prefix is a
1553 -- reference to a bit packed array is itself a reference ot a
1554 -- bit packed array.
1556 -- The required transformation is
1558 -- Tnn : prefix_type := P;
1559 -- Tnn.field := rhs;
1564 -- Tnn : prefix_type := P;
1565 -- Tnn (subscr) := rhs;
1568 -- Since P is going to be evaluated more than once, any subscripts
1569 -- in P must have their evaluation forced.
1571 if Nkind_In (Lhs, N_Indexed_Component, N_Selected_Component)
1572 and then Is_Ref_To_Bit_Packed_Array (Prefix (Lhs))
1575 BPAR_Expr : constant Node_Id := Relocate_Node (Prefix (Lhs));
1576 BPAR_Typ : constant Entity_Id := Etype (BPAR_Expr);
1577 Tnn : constant Entity_Id :=
1578 Make_Defining_Identifier (Loc,
1579 Chars => New_Internal_Name ('T'));
1582 -- Insert the post assignment first, because we want to copy the
1583 -- BPAR_Expr tree before it gets analyzed in the context of the
1584 -- pre assignment. Note that we do not analyze the post assignment
1585 -- yet (we cannot till we have completed the analysis of the pre
1586 -- assignment). As usual, the analysis of this post assignment
1587 -- will happen on its own when we "run into" it after finishing
1588 -- the current assignment.
1591 Make_Assignment_Statement (Loc,
1592 Name => New_Copy_Tree (BPAR_Expr),
1593 Expression => New_Occurrence_Of (Tnn, Loc)));
1595 -- At this stage BPAR_Expr is a reference to a bit packed array
1596 -- where the reference was not expanded in the original tree,
1597 -- since it was on the left side of an assignment. But in the
1598 -- pre-assignment statement (the object definition), BPAR_Expr
1599 -- will end up on the right hand side, and must be reexpanded. To
1600 -- achieve this, we reset the analyzed flag of all selected and
1601 -- indexed components down to the actual indexed component for
1602 -- the packed array.
1606 Set_Analyzed (Exp, False);
1609 (Exp, N_Selected_Component, N_Indexed_Component)
1611 Exp := Prefix (Exp);
1617 -- Now we can insert and analyze the pre-assignment
1619 -- If the right-hand side requires a transient scope, it has
1620 -- already been placed on the stack. However, the declaration is
1621 -- inserted in the tree outside of this scope, and must reflect
1622 -- the proper scope for its variable. This awkward bit is forced
1623 -- by the stricter scope discipline imposed by GCC 2.97.
1626 Uses_Transient_Scope : constant Boolean :=
1628 and then N = Node_To_Be_Wrapped;
1631 if Uses_Transient_Scope then
1632 Push_Scope (Scope (Current_Scope));
1635 Insert_Before_And_Analyze (N,
1636 Make_Object_Declaration (Loc,
1637 Defining_Identifier => Tnn,
1638 Object_Definition => New_Occurrence_Of (BPAR_Typ, Loc),
1639 Expression => BPAR_Expr));
1641 if Uses_Transient_Scope then
1646 -- Now fix up the original assignment and continue processing
1648 Rewrite (Prefix (Lhs),
1649 New_Occurrence_Of (Tnn, Loc));
1651 -- We do not need to reanalyze that assignment, and we do not need
1652 -- to worry about references to the temporary, but we do need to
1653 -- make sure that the temporary is not marked as a true constant
1654 -- since we now have a generated assignment to it!
1656 Set_Is_True_Constant (Tnn, False);
1660 -- When we have the appropriate type of aggregate in the expression (it
1661 -- has been determined during analysis of the aggregate by setting the
1662 -- delay flag), let's perform in place assignment and thus avoid
1663 -- creating a temporary.
1665 if Is_Delayed_Aggregate (Rhs) then
1666 Convert_Aggr_In_Assignment (N);
1667 Rewrite (N, Make_Null_Statement (Loc));
1672 -- Apply discriminant check if required. If Lhs is an access type to a
1673 -- designated type with discriminants, we must always check.
1675 if Has_Discriminants (Etype (Lhs)) then
1677 -- Skip discriminant check if change of representation. Will be
1678 -- done when the change of representation is expanded out.
1680 if not Change_Of_Representation (N) then
1681 Apply_Discriminant_Check (Rhs, Etype (Lhs), Lhs);
1684 -- If the type is private without discriminants, and the full type
1685 -- has discriminants (necessarily with defaults) a check may still be
1686 -- necessary if the Lhs is aliased. The private determinants must be
1687 -- visible to build the discriminant constraints.
1689 -- Only an explicit dereference that comes from source indicates
1690 -- aliasing. Access to formals of protected operations and entries
1691 -- create dereferences but are not semantic aliasings.
1693 elsif Is_Private_Type (Etype (Lhs))
1694 and then Has_Discriminants (Typ)
1695 and then Nkind (Lhs) = N_Explicit_Dereference
1696 and then Comes_From_Source (Lhs)
1699 Lt : constant Entity_Id := Etype (Lhs);
1701 Set_Etype (Lhs, Typ);
1702 Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
1703 Apply_Discriminant_Check (Rhs, Typ, Lhs);
1704 Set_Etype (Lhs, Lt);
1707 -- If the Lhs has a private type with unknown discriminants, it
1708 -- may have a full view with discriminants, but those are nameable
1709 -- only in the underlying type, so convert the Rhs to it before
1710 -- potential checking.
1712 elsif Has_Unknown_Discriminants (Base_Type (Etype (Lhs)))
1713 and then Has_Discriminants (Typ)
1715 Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
1716 Apply_Discriminant_Check (Rhs, Typ, Lhs);
1718 -- In the access type case, we need the same discriminant check, and
1719 -- also range checks if we have an access to constrained array.
1721 elsif Is_Access_Type (Etype (Lhs))
1722 and then Is_Constrained (Designated_Type (Etype (Lhs)))
1724 if Has_Discriminants (Designated_Type (Etype (Lhs))) then
1726 -- Skip discriminant check if change of representation. Will be
1727 -- done when the change of representation is expanded out.
1729 if not Change_Of_Representation (N) then
1730 Apply_Discriminant_Check (Rhs, Etype (Lhs));
1733 elsif Is_Array_Type (Designated_Type (Etype (Lhs))) then
1734 Apply_Range_Check (Rhs, Etype (Lhs));
1736 if Is_Constrained (Etype (Lhs)) then
1737 Apply_Length_Check (Rhs, Etype (Lhs));
1740 if Nkind (Rhs) = N_Allocator then
1742 Target_Typ : constant Entity_Id := Etype (Expression (Rhs));
1743 C_Es : Check_Result;
1750 Etype (Designated_Type (Etype (Lhs))));
1762 -- Apply range check for access type case
1764 elsif Is_Access_Type (Etype (Lhs))
1765 and then Nkind (Rhs) = N_Allocator
1766 and then Nkind (Expression (Rhs)) = N_Qualified_Expression
1768 Analyze_And_Resolve (Expression (Rhs));
1770 (Expression (Rhs), Designated_Type (Etype (Lhs)));
1773 -- Ada 2005 (AI-231): Generate the run-time check
1775 if Is_Access_Type (Typ)
1776 and then Can_Never_Be_Null (Etype (Lhs))
1777 and then not Can_Never_Be_Null (Etype (Rhs))
1779 Apply_Constraint_Check (Rhs, Etype (Lhs));
1782 -- Case of assignment to a bit packed array element
1784 if Nkind (Lhs) = N_Indexed_Component
1785 and then Is_Bit_Packed_Array (Etype (Prefix (Lhs)))
1787 Expand_Bit_Packed_Element_Set (N);
1790 -- Build-in-place function call case. Note that we're not yet doing
1791 -- build-in-place for user-written assignment statements (the assignment
1792 -- here came from an aggregate.)
1794 elsif Ada_Version >= Ada_05
1795 and then Is_Build_In_Place_Function_Call (Rhs)
1797 Make_Build_In_Place_Call_In_Assignment (N, Rhs);
1799 elsif Is_Tagged_Type (Typ) and then Is_Value_Type (Etype (Lhs)) then
1801 -- Nothing to do for valuetypes
1802 -- ??? Set_Scope_Is_Transient (False);
1806 elsif Is_Tagged_Type (Typ)
1807 or else (Needs_Finalization (Typ) and then not Is_Array_Type (Typ))
1809 Tagged_Case : declare
1810 L : List_Id := No_List;
1811 Expand_Ctrl_Actions : constant Boolean := not No_Ctrl_Actions (N);
1814 -- In the controlled case, we need to make sure that function
1815 -- calls are evaluated before finalizing the target. In all cases,
1816 -- it makes the expansion easier if the side-effects are removed
1819 Remove_Side_Effects (Lhs);
1820 Remove_Side_Effects (Rhs);
1822 -- Avoid recursion in the mechanism
1826 -- If dispatching assignment, we need to dispatch to _assign
1828 if Is_Class_Wide_Type (Typ)
1830 -- If the type is tagged, we may as well use the predefined
1831 -- primitive assignment. This avoids inlining a lot of code
1832 -- and in the class-wide case, the assignment is replaced by
1833 -- dispatch call to _assign. Note that this cannot be done when
1834 -- discriminant checks are locally suppressed (as in extension
1835 -- aggregate expansions) because otherwise the discriminant
1836 -- check will be performed within the _assign call. It is also
1837 -- suppressed for assignments created by the expander that
1838 -- correspond to initializations, where we do want to copy the
1839 -- tag (No_Ctrl_Actions flag set True) by the expander and we
1840 -- do not need to mess with tags ever (Expand_Ctrl_Actions flag
1841 -- is set True in this case).
1843 or else (Is_Tagged_Type (Typ)
1844 and then not Is_Value_Type (Etype (Lhs))
1845 and then Chars (Current_Scope) /= Name_uAssign
1846 and then Expand_Ctrl_Actions
1847 and then not Discriminant_Checks_Suppressed (Empty))
1849 -- Fetch the primitive op _assign and proper type to call it.
1850 -- Because of possible conflicts between private and full view
1851 -- the proper type is fetched directly from the operation
1855 Op : constant Entity_Id :=
1856 Find_Prim_Op (Typ, Name_uAssign);
1857 F_Typ : Entity_Id := Etype (First_Formal (Op));
1860 -- If the assignment is dispatching, make sure to use the
1863 if Is_Class_Wide_Type (Typ) then
1864 F_Typ := Class_Wide_Type (F_Typ);
1869 -- In case of assignment to a class-wide tagged type, before
1870 -- the assignment we generate run-time check to ensure that
1871 -- the tags of source and target match.
1873 if Is_Class_Wide_Type (Typ)
1874 and then Is_Tagged_Type (Typ)
1875 and then Is_Tagged_Type (Underlying_Type (Etype (Rhs)))
1878 Make_Raise_Constraint_Error (Loc,
1882 Make_Selected_Component (Loc,
1883 Prefix => Duplicate_Subexpr (Lhs),
1885 Make_Identifier (Loc,
1886 Chars => Name_uTag)),
1888 Make_Selected_Component (Loc,
1889 Prefix => Duplicate_Subexpr (Rhs),
1891 Make_Identifier (Loc,
1892 Chars => Name_uTag))),
1893 Reason => CE_Tag_Check_Failed));
1897 Make_Procedure_Call_Statement (Loc,
1898 Name => New_Reference_To (Op, Loc),
1899 Parameter_Associations => New_List (
1900 Unchecked_Convert_To (F_Typ,
1901 Duplicate_Subexpr (Lhs)),
1902 Unchecked_Convert_To (F_Typ,
1903 Duplicate_Subexpr (Rhs)))));
1907 L := Make_Tag_Ctrl_Assignment (N);
1909 -- We can't afford to have destructive Finalization Actions in
1910 -- the Self assignment case, so if the target and the source
1911 -- are not obviously different, code is generated to avoid the
1912 -- self assignment case:
1914 -- if lhs'address /= rhs'address then
1915 -- <code for controlled and/or tagged assignment>
1918 -- Skip this if Restriction (No_Finalization) is active
1920 if not Statically_Different (Lhs, Rhs)
1921 and then Expand_Ctrl_Actions
1922 and then not Restriction_Active (No_Finalization)
1925 Make_Implicit_If_Statement (N,
1929 Make_Attribute_Reference (Loc,
1930 Prefix => Duplicate_Subexpr (Lhs),
1931 Attribute_Name => Name_Address),
1934 Make_Attribute_Reference (Loc,
1935 Prefix => Duplicate_Subexpr (Rhs),
1936 Attribute_Name => Name_Address)),
1938 Then_Statements => L));
1941 -- We need to set up an exception handler for implementing
1942 -- 7.6.1(18). The remaining adjustments are tackled by the
1943 -- implementation of adjust for record_controllers (see
1946 -- This is skipped if we have no finalization
1948 if Expand_Ctrl_Actions
1949 and then not Restriction_Active (No_Finalization)
1952 Make_Block_Statement (Loc,
1953 Handled_Statement_Sequence =>
1954 Make_Handled_Sequence_Of_Statements (Loc,
1956 Exception_Handlers => New_List (
1957 Make_Handler_For_Ctrl_Operation (Loc)))));
1962 Make_Block_Statement (Loc,
1963 Handled_Statement_Sequence =>
1964 Make_Handled_Sequence_Of_Statements (Loc, Statements => L)));
1966 -- If no restrictions on aborts, protect the whole assignment
1967 -- for controlled objects as per 9.8(11).
1969 if Needs_Finalization (Typ)
1970 and then Expand_Ctrl_Actions
1971 and then Abort_Allowed
1974 Blk : constant Entity_Id :=
1976 (E_Block, Current_Scope, Sloc (N), 'B');
1979 Set_Scope (Blk, Current_Scope);
1980 Set_Etype (Blk, Standard_Void_Type);
1981 Set_Identifier (N, New_Occurrence_Of (Blk, Sloc (N)));
1983 Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
1984 Set_At_End_Proc (Handled_Statement_Sequence (N),
1985 New_Occurrence_Of (RTE (RE_Abort_Undefer_Direct), Loc));
1986 Expand_At_End_Handler
1987 (Handled_Statement_Sequence (N), Blk);
1991 -- N has been rewritten to a block statement for which it is
1992 -- known by construction that no checks are necessary: analyze
1993 -- it with all checks suppressed.
1995 Analyze (N, Suppress => All_Checks);
2001 elsif Is_Array_Type (Typ) then
2003 Actual_Rhs : Node_Id := Rhs;
2006 while Nkind_In (Actual_Rhs, N_Type_Conversion,
2007 N_Qualified_Expression)
2009 Actual_Rhs := Expression (Actual_Rhs);
2012 Expand_Assign_Array (N, Actual_Rhs);
2018 elsif Is_Record_Type (Typ) then
2019 Expand_Assign_Record (N);
2022 -- Scalar types. This is where we perform the processing related to the
2023 -- requirements of (RM 13.9.1(9-11)) concerning the handling of invalid
2026 elsif Is_Scalar_Type (Typ) then
2028 -- Case where right side is known valid
2030 if Expr_Known_Valid (Rhs) then
2032 -- Here the right side is valid, so it is fine. The case to deal
2033 -- with is when the left side is a local variable reference whose
2034 -- value is not currently known to be valid. If this is the case,
2035 -- and the assignment appears in an unconditional context, then we
2036 -- can mark the left side as now being valid.
2038 if Is_Local_Variable_Reference (Lhs)
2039 and then not Is_Known_Valid (Entity (Lhs))
2040 and then In_Unconditional_Context (N)
2042 Set_Is_Known_Valid (Entity (Lhs), True);
2045 -- Case where right side may be invalid in the sense of the RM
2046 -- reference above. The RM does not require that we check for the
2047 -- validity on an assignment, but it does require that the assignment
2048 -- of an invalid value not cause erroneous behavior.
2050 -- The general approach in GNAT is to use the Is_Known_Valid flag
2051 -- to avoid the need for validity checking on assignments. However
2052 -- in some cases, we have to do validity checking in order to make
2053 -- sure that the setting of this flag is correct.
2056 -- Validate right side if we are validating copies
2058 if Validity_Checks_On
2059 and then Validity_Check_Copies
2061 -- Skip this if left hand side is an array or record component
2062 -- and elementary component validity checks are suppressed.
2064 if Nkind_In (Lhs, N_Selected_Component, N_Indexed_Component)
2065 and then not Validity_Check_Components
2072 -- We can propagate this to the left side where appropriate
2074 if Is_Local_Variable_Reference (Lhs)
2075 and then not Is_Known_Valid (Entity (Lhs))
2076 and then In_Unconditional_Context (N)
2078 Set_Is_Known_Valid (Entity (Lhs), True);
2081 -- Otherwise check to see what should be done
2083 -- If left side is a local variable, then we just set its flag to
2084 -- indicate that its value may no longer be valid, since we are
2085 -- copying a potentially invalid value.
2087 elsif Is_Local_Variable_Reference (Lhs) then
2088 Set_Is_Known_Valid (Entity (Lhs), False);
2090 -- Check for case of a nonlocal variable on the left side which
2091 -- is currently known to be valid. In this case, we simply ensure
2092 -- that the right side is valid. We only play the game of copying
2093 -- validity status for local variables, since we are doing this
2094 -- statically, not by tracing the full flow graph.
2096 elsif Is_Entity_Name (Lhs)
2097 and then Is_Known_Valid (Entity (Lhs))
2099 -- Note: If Validity_Checking mode is set to none, we ignore
2100 -- the Ensure_Valid call so don't worry about that case here.
2104 -- In all other cases, we can safely copy an invalid value without
2105 -- worrying about the status of the left side. Since it is not a
2106 -- variable reference it will not be considered
2107 -- as being known to be valid in any case.
2115 -- Defend against invalid subscripts on left side if we are in standard
2116 -- validity checking mode. No need to do this if we are checking all
2119 if Validity_Checks_On
2120 and then Validity_Check_Default
2121 and then not Validity_Check_Subscripts
2123 Check_Valid_Lvalue_Subscripts (Lhs);
2127 when RE_Not_Available =>
2129 end Expand_N_Assignment_Statement;
2131 ------------------------------
2132 -- Expand_N_Block_Statement --
2133 ------------------------------
2135 -- Encode entity names defined in block statement
2137 procedure Expand_N_Block_Statement (N : Node_Id) is
2139 Qualify_Entity_Names (N);
2140 end Expand_N_Block_Statement;
2142 -----------------------------
2143 -- Expand_N_Case_Statement --
2144 -----------------------------
2146 procedure Expand_N_Case_Statement (N : Node_Id) is
2147 Loc : constant Source_Ptr := Sloc (N);
2148 Expr : constant Node_Id := Expression (N);
2156 -- Check for the situation where we know at compile time which branch
2159 if Compile_Time_Known_Value (Expr) then
2160 Alt := Find_Static_Alternative (N);
2162 -- Move statements from this alternative after the case statement.
2163 -- They are already analyzed, so will be skipped by the analyzer.
2165 Insert_List_After (N, Statements (Alt));
2167 -- That leaves the case statement as a shell. So now we can kill all
2168 -- other alternatives in the case statement.
2170 Kill_Dead_Code (Expression (N));
2176 -- Loop through case alternatives, skipping pragmas, and skipping
2177 -- the one alternative that we select (and therefore retain).
2179 A := First (Alternatives (N));
2180 while Present (A) loop
2182 and then Nkind (A) = N_Case_Statement_Alternative
2184 Kill_Dead_Code (Statements (A), Warn_On_Deleted_Code);
2191 Rewrite (N, Make_Null_Statement (Loc));
2195 -- Here if the choice is not determined at compile time
2198 Last_Alt : constant Node_Id := Last (Alternatives (N));
2200 Others_Present : Boolean;
2201 Others_Node : Node_Id;
2203 Then_Stms : List_Id;
2204 Else_Stms : List_Id;
2207 if Nkind (First (Discrete_Choices (Last_Alt))) = N_Others_Choice then
2208 Others_Present := True;
2209 Others_Node := Last_Alt;
2211 Others_Present := False;
2214 -- First step is to worry about possible invalid argument. The RM
2215 -- requires (RM 5.4(13)) that if the result is invalid (e.g. it is
2216 -- outside the base range), then Constraint_Error must be raised.
2218 -- Case of validity check required (validity checks are on, the
2219 -- expression is not known to be valid, and the case statement
2220 -- comes from source -- no need to validity check internally
2221 -- generated case statements).
2223 if Validity_Check_Default then
2224 Ensure_Valid (Expr);
2227 -- If there is only a single alternative, just replace it with the
2228 -- sequence of statements since obviously that is what is going to
2229 -- be executed in all cases.
2231 Len := List_Length (Alternatives (N));
2234 -- We still need to evaluate the expression if it has any
2237 Remove_Side_Effects (Expression (N));
2239 Insert_List_After (N, Statements (First (Alternatives (N))));
2241 -- That leaves the case statement as a shell. The alternative that
2242 -- will be executed is reset to a null list. So now we can kill
2243 -- the entire case statement.
2245 Kill_Dead_Code (Expression (N));
2246 Rewrite (N, Make_Null_Statement (Loc));
2250 -- An optimization. If there are only two alternatives, and only
2251 -- a single choice, then rewrite the whole case statement as an
2252 -- if statement, since this can result in subsequent optimizations.
2253 -- This helps not only with case statements in the source of a
2254 -- simple form, but also with generated code (discriminant check
2255 -- functions in particular)
2258 Chlist := Discrete_Choices (First (Alternatives (N)));
2260 if List_Length (Chlist) = 1 then
2261 Choice := First (Chlist);
2263 Then_Stms := Statements (First (Alternatives (N)));
2264 Else_Stms := Statements (Last (Alternatives (N)));
2266 -- For TRUE, generate "expression", not expression = true
2268 if Nkind (Choice) = N_Identifier
2269 and then Entity (Choice) = Standard_True
2271 Cond := Expression (N);
2273 -- For FALSE, generate "expression" and switch then/else
2275 elsif Nkind (Choice) = N_Identifier
2276 and then Entity (Choice) = Standard_False
2278 Cond := Expression (N);
2279 Else_Stms := Statements (First (Alternatives (N)));
2280 Then_Stms := Statements (Last (Alternatives (N)));
2282 -- For a range, generate "expression in range"
2284 elsif Nkind (Choice) = N_Range
2285 or else (Nkind (Choice) = N_Attribute_Reference
2286 and then Attribute_Name (Choice) = Name_Range)
2287 or else (Is_Entity_Name (Choice)
2288 and then Is_Type (Entity (Choice)))
2289 or else Nkind (Choice) = N_Subtype_Indication
2293 Left_Opnd => Expression (N),
2294 Right_Opnd => Relocate_Node (Choice));
2296 -- For any other subexpression "expression = value"
2301 Left_Opnd => Expression (N),
2302 Right_Opnd => Relocate_Node (Choice));
2305 -- Now rewrite the case as an IF
2308 Make_If_Statement (Loc,
2310 Then_Statements => Then_Stms,
2311 Else_Statements => Else_Stms));
2317 -- If the last alternative is not an Others choice, replace it with
2318 -- an N_Others_Choice. Note that we do not bother to call Analyze on
2319 -- the modified case statement, since it's only effect would be to
2320 -- compute the contents of the Others_Discrete_Choices which is not
2321 -- needed by the back end anyway.
2323 -- The reason we do this is that the back end always needs some
2324 -- default for a switch, so if we have not supplied one in the
2325 -- processing above for validity checking, then we need to supply
2328 if not Others_Present then
2329 Others_Node := Make_Others_Choice (Sloc (Last_Alt));
2330 Set_Others_Discrete_Choices
2331 (Others_Node, Discrete_Choices (Last_Alt));
2332 Set_Discrete_Choices (Last_Alt, New_List (Others_Node));
2335 end Expand_N_Case_Statement;
2337 -----------------------------
2338 -- Expand_N_Exit_Statement --
2339 -----------------------------
2341 -- The only processing required is to deal with a possible C/Fortran
2342 -- boolean value used as the condition for the exit statement.
2344 procedure Expand_N_Exit_Statement (N : Node_Id) is
2346 Adjust_Condition (Condition (N));
2347 end Expand_N_Exit_Statement;
2349 ----------------------------------------
2350 -- Expand_N_Extended_Return_Statement --
2351 ----------------------------------------
2353 -- If there is a Handled_Statement_Sequence, we rewrite this:
2355 -- return Result : T := <expression> do
2356 -- <handled_seq_of_stms>
2362 -- Result : T := <expression>;
2364 -- <handled_seq_of_stms>
2368 -- Otherwise (no Handled_Statement_Sequence), we rewrite this:
2370 -- return Result : T := <expression>;
2374 -- return <expression>;
2376 -- unless it's build-in-place or there's no <expression>, in which case
2380 -- Result : T := <expression>;
2385 -- Note that this case could have been written by the user as an extended
2386 -- return statement, or could have been transformed to this from a simple
2387 -- return statement.
2389 -- That is, we need to have a reified return object if there are statements
2390 -- (which might refer to it) or if we're doing build-in-place (so we can
2391 -- set its address to the final resting place or if there is no expression
2392 -- (in which case default initial values might need to be set).
2394 procedure Expand_N_Extended_Return_Statement (N : Node_Id) is
2395 Loc : constant Source_Ptr := Sloc (N);
2397 Return_Object_Entity : constant Entity_Id :=
2398 First_Entity (Return_Statement_Entity (N));
2399 Return_Object_Decl : constant Node_Id :=
2400 Parent (Return_Object_Entity);
2401 Parent_Function : constant Entity_Id :=
2402 Return_Applies_To (Return_Statement_Entity (N));
2403 Parent_Function_Typ : constant Entity_Id := Etype (Parent_Function);
2404 Is_Build_In_Place : constant Boolean :=
2405 Is_Build_In_Place_Function (Parent_Function);
2407 Return_Stm : Node_Id;
2408 Statements : List_Id;
2409 Handled_Stm_Seq : Node_Id;
2413 function Has_Controlled_Parts (Typ : Entity_Id) return Boolean;
2414 -- Determine whether type Typ is controlled or contains a controlled
2417 function Move_Activation_Chain return Node_Id;
2418 -- Construct a call to System.Tasking.Stages.Move_Activation_Chain
2420 -- From current activation chain
2421 -- To activation chain passed in by the caller
2422 -- New_Master master passed in by the caller
2424 function Move_Final_List return Node_Id;
2425 -- Construct call to System.Finalization_Implementation.Move_Final_List
2428 -- From finalization list of the return statement
2429 -- To finalization list passed in by the caller
2431 --------------------------
2432 -- Has_Controlled_Parts --
2433 --------------------------
2435 function Has_Controlled_Parts (Typ : Entity_Id) return Boolean is
2439 or else Has_Controlled_Component (Typ);
2440 end Has_Controlled_Parts;
2442 ---------------------------
2443 -- Move_Activation_Chain --
2444 ---------------------------
2446 function Move_Activation_Chain return Node_Id is
2447 Activation_Chain_Formal : constant Entity_Id :=
2448 Build_In_Place_Formal
2449 (Parent_Function, BIP_Activation_Chain);
2450 To : constant Node_Id :=
2452 (Activation_Chain_Formal, Loc);
2453 Master_Formal : constant Entity_Id :=
2454 Build_In_Place_Formal
2455 (Parent_Function, BIP_Master);
2456 New_Master : constant Node_Id :=
2457 New_Reference_To (Master_Formal, Loc);
2459 Chain_Entity : Entity_Id;
2463 Chain_Entity := First_Entity (Return_Statement_Entity (N));
2464 while Chars (Chain_Entity) /= Name_uChain loop
2465 Chain_Entity := Next_Entity (Chain_Entity);
2469 Make_Attribute_Reference (Loc,
2470 Prefix => New_Reference_To (Chain_Entity, Loc),
2471 Attribute_Name => Name_Unrestricted_Access);
2472 -- ??? Not clear why "Make_Identifier (Loc, Name_uChain)" doesn't
2473 -- work, instead of "New_Reference_To (Chain_Entity, Loc)" above.
2476 Make_Procedure_Call_Statement (Loc,
2477 Name => New_Reference_To (RTE (RE_Move_Activation_Chain), Loc),
2478 Parameter_Associations => New_List (From, To, New_Master));
2479 end Move_Activation_Chain;
2481 ---------------------
2482 -- Move_Final_List --
2483 ---------------------
2485 function Move_Final_List return Node_Id is
2486 Flist : constant Entity_Id :=
2487 Finalization_Chain_Entity (Return_Statement_Entity (N));
2489 From : constant Node_Id := New_Reference_To (Flist, Loc);
2491 Caller_Final_List : constant Entity_Id :=
2492 Build_In_Place_Formal
2493 (Parent_Function, BIP_Final_List);
2495 To : constant Node_Id := New_Reference_To (Caller_Final_List, Loc);
2498 -- Catch cases where a finalization chain entity has not been
2499 -- associated with the return statement entity.
2501 pragma Assert (Present (Flist));
2503 -- Build required call
2506 Make_If_Statement (Loc,
2509 Left_Opnd => New_Copy (From),
2510 Right_Opnd => New_Node (N_Null, Loc)),
2513 Make_Procedure_Call_Statement (Loc,
2514 Name => New_Reference_To (RTE (RE_Move_Final_List), Loc),
2515 Parameter_Associations => New_List (From, To))));
2516 end Move_Final_List;
2518 -- Start of processing for Expand_N_Extended_Return_Statement
2521 if Nkind (Return_Object_Decl) = N_Object_Declaration then
2522 Exp := Expression (Return_Object_Decl);
2527 Handled_Stm_Seq := Handled_Statement_Sequence (N);
2529 -- Build a simple_return_statement that returns the return object when
2530 -- there is a statement sequence, or no expression, or the result will
2531 -- be built in place. Note however that we currently do this for all
2532 -- composite cases, even though nonlimited composite results are not yet
2533 -- built in place (though we plan to do so eventually).
2535 if Present (Handled_Stm_Seq)
2536 or else Is_Composite_Type (Etype (Parent_Function))
2539 if No (Handled_Stm_Seq) then
2540 Statements := New_List;
2542 -- If the extended return has a handled statement sequence, then wrap
2543 -- it in a block and use the block as the first statement.
2547 New_List (Make_Block_Statement (Loc,
2548 Declarations => New_List,
2549 Handled_Statement_Sequence => Handled_Stm_Seq));
2552 -- If control gets past the above Statements, we have successfully
2553 -- completed the return statement. If the result type has controlled
2554 -- parts and the return is for a build-in-place function, then we
2555 -- call Move_Final_List to transfer responsibility for finalization
2556 -- of the return object to the caller. An alternative would be to
2557 -- declare a Success flag in the function, initialize it to False,
2558 -- and set it to True here. Then move the Move_Final_List call into
2559 -- the cleanup code, and check Success. If Success then make a call
2560 -- to Move_Final_List else do finalization. Then we can remove the
2561 -- abort-deferral and the nulling-out of the From parameter from
2562 -- Move_Final_List. Note that the current method is not quite correct
2563 -- in the rather obscure case of a select-then-abort statement whose
2564 -- abortable part contains the return statement.
2566 -- Check the type of the function to determine whether to move the
2567 -- finalization list. A special case arises when processing a simple
2568 -- return statement which has been rewritten as an extended return.
2569 -- In that case check the type of the returned object or the original
2572 if Is_Build_In_Place
2574 (Has_Controlled_Parts (Parent_Function_Typ)
2575 or else (Is_Class_Wide_Type (Parent_Function_Typ)
2577 Has_Controlled_Parts (Root_Type (Parent_Function_Typ)))
2578 or else Has_Controlled_Parts (Etype (Return_Object_Entity))
2579 or else (Present (Exp)
2580 and then Has_Controlled_Parts (Etype (Exp))))
2582 Append_To (Statements, Move_Final_List);
2585 -- Similarly to the above Move_Final_List, if the result type
2586 -- contains tasks, we call Move_Activation_Chain. Later, the cleanup
2587 -- code will call Complete_Master, which will terminate any
2588 -- unactivated tasks belonging to the return statement master. But
2589 -- Move_Activation_Chain updates their master to be that of the
2590 -- caller, so they will not be terminated unless the return statement
2591 -- completes unsuccessfully due to exception, abort, goto, or exit.
2592 -- As a formality, we test whether the function requires the result
2593 -- to be built in place, though that's necessarily true for the case
2594 -- of result types with task parts.
2596 if Is_Build_In_Place and Has_Task (Etype (Parent_Function)) then
2597 Append_To (Statements, Move_Activation_Chain);
2600 -- Build a simple_return_statement that returns the return object
2603 Make_Simple_Return_Statement (Loc,
2604 Expression => New_Occurrence_Of (Return_Object_Entity, Loc));
2605 Append_To (Statements, Return_Stm);
2608 Make_Handled_Sequence_Of_Statements (Loc, Statements);
2611 -- Case where we build a block
2613 if Present (Handled_Stm_Seq) then
2615 Make_Block_Statement (Loc,
2616 Declarations => Return_Object_Declarations (N),
2617 Handled_Statement_Sequence => Handled_Stm_Seq);
2619 -- We set the entity of the new block statement to be that of the
2620 -- return statement. This is necessary so that various fields, such
2621 -- as Finalization_Chain_Entity carry over from the return statement
2622 -- to the block. Note that this block is unusual, in that its entity
2623 -- is an E_Return_Statement rather than an E_Block.
2626 (Result, New_Occurrence_Of (Return_Statement_Entity (N), Loc));
2628 -- If the object decl was already rewritten as a renaming, then
2629 -- we don't want to do the object allocation and transformation of
2630 -- of the return object declaration to a renaming. This case occurs
2631 -- when the return object is initialized by a call to another
2632 -- build-in-place function, and that function is responsible for the
2633 -- allocation of the return object.
2635 if Is_Build_In_Place
2637 Nkind (Return_Object_Decl) = N_Object_Renaming_Declaration
2639 Set_By_Ref (Return_Stm); -- Return build-in-place results by ref
2641 elsif Is_Build_In_Place then
2643 -- Locate the implicit access parameter associated with the
2644 -- caller-supplied return object and convert the return
2645 -- statement's return object declaration to a renaming of a
2646 -- dereference of the access parameter. If the return object's
2647 -- declaration includes an expression that has not already been
2648 -- expanded as separate assignments, then add an assignment
2649 -- statement to ensure the return object gets initialized.
2652 -- Result : T [:= <expression>];
2659 -- Result : T renames FuncRA.all;
2660 -- [Result := <expression;]
2665 Return_Obj_Id : constant Entity_Id :=
2666 Defining_Identifier (Return_Object_Decl);
2667 Return_Obj_Typ : constant Entity_Id := Etype (Return_Obj_Id);
2668 Return_Obj_Expr : constant Node_Id :=
2669 Expression (Return_Object_Decl);
2670 Result_Subt : constant Entity_Id :=
2671 Etype (Parent_Function);
2672 Constr_Result : constant Boolean :=
2673 Is_Constrained (Result_Subt);
2674 Obj_Alloc_Formal : Entity_Id;
2675 Object_Access : Entity_Id;
2676 Obj_Acc_Deref : Node_Id;
2677 Init_Assignment : Node_Id := Empty;
2680 -- Build-in-place results must be returned by reference
2682 Set_By_Ref (Return_Stm);
2684 -- Retrieve the implicit access parameter passed by the caller
2687 Build_In_Place_Formal (Parent_Function, BIP_Object_Access);
2689 -- If the return object's declaration includes an expression
2690 -- and the declaration isn't marked as No_Initialization, then
2691 -- we need to generate an assignment to the object and insert
2692 -- it after the declaration before rewriting it as a renaming
2693 -- (otherwise we'll lose the initialization).
2695 if Present (Return_Obj_Expr)
2696 and then not No_Initialization (Return_Object_Decl)
2699 Make_Assignment_Statement (Loc,
2700 Name => New_Reference_To (Return_Obj_Id, Loc),
2701 Expression => Relocate_Node (Return_Obj_Expr));
2702 Set_Etype (Name (Init_Assignment), Etype (Return_Obj_Id));
2703 Set_Assignment_OK (Name (Init_Assignment));
2704 Set_No_Ctrl_Actions (Init_Assignment);
2706 Set_Parent (Name (Init_Assignment), Init_Assignment);
2707 Set_Parent (Expression (Init_Assignment), Init_Assignment);
2709 Set_Expression (Return_Object_Decl, Empty);
2711 if Is_Class_Wide_Type (Etype (Return_Obj_Id))
2712 and then not Is_Class_Wide_Type
2713 (Etype (Expression (Init_Assignment)))
2715 Rewrite (Expression (Init_Assignment),
2716 Make_Type_Conversion (Loc,
2719 (Etype (Return_Obj_Id), Loc),
2721 Relocate_Node (Expression (Init_Assignment))));
2724 -- In the case of functions where the calling context can
2725 -- determine the form of allocation needed, initialization
2726 -- is done with each part of the if statement that handles
2727 -- the different forms of allocation (this is true for
2728 -- unconstrained and tagged result subtypes).
2731 and then not Is_Tagged_Type (Underlying_Type (Result_Subt))
2733 Insert_After (Return_Object_Decl, Init_Assignment);
2737 -- When the function's subtype is unconstrained, a run-time
2738 -- test is needed to determine the form of allocation to use
2739 -- for the return object. The function has an implicit formal
2740 -- parameter indicating this. If the BIP_Alloc_Form formal has
2741 -- the value one, then the caller has passed access to an
2742 -- existing object for use as the return object. If the value
2743 -- is two, then the return object must be allocated on the
2744 -- secondary stack. Otherwise, the object must be allocated in
2745 -- a storage pool (currently only supported for the global
2746 -- heap, user-defined storage pools TBD ???). We generate an
2747 -- if statement to test the implicit allocation formal and
2748 -- initialize a local access value appropriately, creating
2749 -- allocators in the secondary stack and global heap cases.
2750 -- The special formal also exists and must be tested when the
2751 -- function has a tagged result, even when the result subtype
2752 -- is constrained, because in general such functions can be
2753 -- called in dispatching contexts and must be handled similarly
2754 -- to functions with a class-wide result.
2756 if not Constr_Result
2757 or else Is_Tagged_Type (Underlying_Type (Result_Subt))
2760 Build_In_Place_Formal (Parent_Function, BIP_Alloc_Form);
2763 Ref_Type : Entity_Id;
2764 Ptr_Type_Decl : Node_Id;
2765 Alloc_Obj_Id : Entity_Id;
2766 Alloc_Obj_Decl : Node_Id;
2767 Alloc_If_Stmt : Node_Id;
2768 SS_Allocator : Node_Id;
2769 Heap_Allocator : Node_Id;
2772 -- Reuse the itype created for the function's implicit
2773 -- access formal. This avoids the need to create a new
2774 -- access type here, plus it allows assigning the access
2775 -- formal directly without applying a conversion.
2777 -- Ref_Type := Etype (Object_Access);
2779 -- Create an access type designating the function's
2783 Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
2786 Make_Full_Type_Declaration (Loc,
2787 Defining_Identifier => Ref_Type,
2789 Make_Access_To_Object_Definition (Loc,
2790 All_Present => True,
2791 Subtype_Indication =>
2792 New_Reference_To (Return_Obj_Typ, Loc)));
2794 Insert_Before (Return_Object_Decl, Ptr_Type_Decl);
2796 -- Create an access object that will be initialized to an
2797 -- access value denoting the return object, either coming
2798 -- from an implicit access value passed in by the caller
2799 -- or from the result of an allocator.
2802 Make_Defining_Identifier (Loc,
2803 Chars => New_Internal_Name ('R'));
2804 Set_Etype (Alloc_Obj_Id, Ref_Type);
2807 Make_Object_Declaration (Loc,
2808 Defining_Identifier => Alloc_Obj_Id,
2809 Object_Definition => New_Reference_To
2812 Insert_Before (Return_Object_Decl, Alloc_Obj_Decl);
2814 -- Create allocators for both the secondary stack and
2815 -- global heap. If there's an initialization expression,
2816 -- then create these as initialized allocators.
2818 if Present (Return_Obj_Expr)
2819 and then not No_Initialization (Return_Object_Decl)
2822 Make_Allocator (Loc,
2824 Make_Qualified_Expression (Loc,
2826 New_Reference_To (Return_Obj_Typ, Loc),
2828 New_Copy_Tree (Return_Obj_Expr)));
2831 -- If the function returns a class-wide type we cannot
2832 -- use the return type for the allocator. Instead we
2833 -- use the type of the expression, which must be an
2834 -- aggregate of a definite type.
2836 if Is_Class_Wide_Type (Return_Obj_Typ) then
2838 Make_Allocator (Loc,
2841 (Etype (Return_Obj_Expr), Loc));
2844 Make_Allocator (Loc,
2846 New_Reference_To (Return_Obj_Typ, Loc));
2849 -- If the object requires default initialization then
2850 -- that will happen later following the elaboration of
2851 -- the object renaming. If we don't turn it off here
2852 -- then the object will be default initialized twice.
2854 Set_No_Initialization (Heap_Allocator);
2857 -- If the No_Allocators restriction is active, then only
2858 -- an allocator for secondary stack allocation is needed.
2859 -- It's OK for such allocators to have Comes_From_Source
2860 -- set to False, because gigi knows not to flag them as
2861 -- being a violation of No_Implicit_Heap_Allocations.
2863 if Restriction_Active (No_Allocators) then
2864 SS_Allocator := Heap_Allocator;
2865 Heap_Allocator := Make_Null (Loc);
2867 -- Otherwise the heap allocator may be needed, so we make
2868 -- another allocator for secondary stack allocation.
2871 SS_Allocator := New_Copy_Tree (Heap_Allocator);
2873 -- The heap allocator is marked Comes_From_Source
2874 -- since it corresponds to an explicit user-written
2875 -- allocator (that is, it will only be executed on
2876 -- behalf of callers that call the function as
2877 -- initialization for such an allocator). This
2878 -- prevents errors when No_Implicit_Heap_Allocations
2881 Set_Comes_From_Source (Heap_Allocator, True);
2884 -- The allocator is returned on the secondary stack. We
2885 -- don't do this on VM targets, since the SS is not used.
2887 if VM_Target = No_VM then
2888 Set_Storage_Pool (SS_Allocator, RTE (RE_SS_Pool));
2889 Set_Procedure_To_Call
2890 (SS_Allocator, RTE (RE_SS_Allocate));
2892 -- The allocator is returned on the secondary stack,
2893 -- so indicate that the function return, as well as
2894 -- the block that encloses the allocator, must not
2895 -- release it. The flags must be set now because the
2896 -- decision to use the secondary stack is done very
2897 -- late in the course of expanding the return
2898 -- statement, past the point where these flags are
2901 Set_Sec_Stack_Needed_For_Return (Parent_Function);
2902 Set_Sec_Stack_Needed_For_Return
2903 (Return_Statement_Entity (N));
2904 Set_Uses_Sec_Stack (Parent_Function);
2905 Set_Uses_Sec_Stack (Return_Statement_Entity (N));
2908 -- Create an if statement to test the BIP_Alloc_Form
2909 -- formal and initialize the access object to either the
2910 -- BIP_Object_Access formal (BIP_Alloc_Form = 0), the
2911 -- result of allocating the object in the secondary stack
2912 -- (BIP_Alloc_Form = 1), or else an allocator to create
2913 -- the return object in the heap (BIP_Alloc_Form = 2).
2915 -- ??? An unchecked type conversion must be made in the
2916 -- case of assigning the access object formal to the
2917 -- local access object, because a normal conversion would
2918 -- be illegal in some cases (such as converting access-
2919 -- to-unconstrained to access-to-constrained), but the
2920 -- the unchecked conversion will presumably fail to work
2921 -- right in just such cases. It's not clear at all how to
2925 Make_If_Statement (Loc,
2929 New_Reference_To (Obj_Alloc_Formal, Loc),
2931 Make_Integer_Literal (Loc,
2932 UI_From_Int (BIP_Allocation_Form'Pos
2933 (Caller_Allocation)))),
2935 New_List (Make_Assignment_Statement (Loc,
2938 (Alloc_Obj_Id, Loc),
2940 Make_Unchecked_Type_Conversion (Loc,
2942 New_Reference_To (Ref_Type, Loc),
2945 (Object_Access, Loc)))),
2947 New_List (Make_Elsif_Part (Loc,
2952 (Obj_Alloc_Formal, Loc),
2954 Make_Integer_Literal (Loc,
2956 BIP_Allocation_Form'Pos
2957 (Secondary_Stack)))),
2960 (Make_Assignment_Statement (Loc,
2963 (Alloc_Obj_Id, Loc),
2967 New_List (Make_Assignment_Statement (Loc,
2970 (Alloc_Obj_Id, Loc),
2974 -- If a separate initialization assignment was created
2975 -- earlier, append that following the assignment of the
2976 -- implicit access formal to the access object, to ensure
2977 -- that the return object is initialized in that case.
2978 -- In this situation, the target of the assignment must
2979 -- be rewritten to denote a dereference of the access to
2980 -- the return object passed in by the caller.
2982 if Present (Init_Assignment) then
2983 Rewrite (Name (Init_Assignment),
2984 Make_Explicit_Dereference (Loc,
2985 Prefix => New_Reference_To (Alloc_Obj_Id, Loc)));
2987 (Name (Init_Assignment), Etype (Return_Obj_Id));
2990 (Then_Statements (Alloc_If_Stmt),
2994 Insert_Before (Return_Object_Decl, Alloc_If_Stmt);
2996 -- Remember the local access object for use in the
2997 -- dereference of the renaming created below.
2999 Object_Access := Alloc_Obj_Id;
3003 -- Replace the return object declaration with a renaming of a
3004 -- dereference of the access value designating the return
3008 Make_Explicit_Dereference (Loc,
3009 Prefix => New_Reference_To (Object_Access, Loc));
3011 Rewrite (Return_Object_Decl,
3012 Make_Object_Renaming_Declaration (Loc,
3013 Defining_Identifier => Return_Obj_Id,
3014 Access_Definition => Empty,
3015 Subtype_Mark => New_Occurrence_Of
3016 (Return_Obj_Typ, Loc),
3017 Name => Obj_Acc_Deref));
3019 Set_Renamed_Object (Return_Obj_Id, Obj_Acc_Deref);
3023 -- Case where we do not build a block
3026 -- We're about to drop Return_Object_Declarations on the floor, so
3027 -- we need to insert it, in case it got expanded into useful code.
3029 Insert_List_Before (N, Return_Object_Declarations (N));
3031 -- Build simple_return_statement that returns the expression directly
3033 Return_Stm := Make_Simple_Return_Statement (Loc, Expression => Exp);
3035 Result := Return_Stm;
3038 -- Set the flag to prevent infinite recursion
3040 Set_Comes_From_Extended_Return_Statement (Return_Stm);
3042 Rewrite (N, Result);
3044 end Expand_N_Extended_Return_Statement;
3046 -----------------------------
3047 -- Expand_N_Goto_Statement --
3048 -----------------------------
3050 -- Add poll before goto if polling active
3052 procedure Expand_N_Goto_Statement (N : Node_Id) is
3054 Generate_Poll_Call (N);
3055 end Expand_N_Goto_Statement;
3057 ---------------------------
3058 -- Expand_N_If_Statement --
3059 ---------------------------
3061 -- First we deal with the case of C and Fortran convention boolean values,
3062 -- with zero/non-zero semantics.
3064 -- Second, we deal with the obvious rewriting for the cases where the
3065 -- condition of the IF is known at compile time to be True or False.
3067 -- Third, we remove elsif parts which have non-empty Condition_Actions
3068 -- and rewrite as independent if statements. For example:
3079 -- <<condition actions of y>>
3085 -- This rewriting is needed if at least one elsif part has a non-empty
3086 -- Condition_Actions list. We also do the same processing if there is a
3087 -- constant condition in an elsif part (in conjunction with the first
3088 -- processing step mentioned above, for the recursive call made to deal
3089 -- with the created inner if, this deals with properly optimizing the
3090 -- cases of constant elsif conditions).
3092 procedure Expand_N_If_Statement (N : Node_Id) is
3093 Loc : constant Source_Ptr := Sloc (N);
3098 Warn_If_Deleted : constant Boolean :=
3099 Warn_On_Deleted_Code and then Comes_From_Source (N);
3100 -- Indicates whether we want warnings when we delete branches of the
3101 -- if statement based on constant condition analysis. We never want
3102 -- these warnings for expander generated code.
3105 Adjust_Condition (Condition (N));
3107 -- The following loop deals with constant conditions for the IF. We
3108 -- need a loop because as we eliminate False conditions, we grab the
3109 -- first elsif condition and use it as the primary condition.
3111 while Compile_Time_Known_Value (Condition (N)) loop
3113 -- If condition is True, we can simply rewrite the if statement now
3114 -- by replacing it by the series of then statements.
3116 if Is_True (Expr_Value (Condition (N))) then
3118 -- All the else parts can be killed
3120 Kill_Dead_Code (Elsif_Parts (N), Warn_If_Deleted);
3121 Kill_Dead_Code (Else_Statements (N), Warn_If_Deleted);
3123 Hed := Remove_Head (Then_Statements (N));
3124 Insert_List_After (N, Then_Statements (N));
3128 -- If condition is False, then we can delete the condition and
3129 -- the Then statements
3132 -- We do not delete the condition if constant condition warnings
3133 -- are enabled, since otherwise we end up deleting the desired
3134 -- warning. Of course the backend will get rid of this True/False
3135 -- test anyway, so nothing is lost here.
3137 if not Constant_Condition_Warnings then
3138 Kill_Dead_Code (Condition (N));
3141 Kill_Dead_Code (Then_Statements (N), Warn_If_Deleted);
3143 -- If there are no elsif statements, then we simply replace the
3144 -- entire if statement by the sequence of else statements.
3146 if No (Elsif_Parts (N)) then
3147 if No (Else_Statements (N))
3148 or else Is_Empty_List (Else_Statements (N))
3151 Make_Null_Statement (Sloc (N)));
3153 Hed := Remove_Head (Else_Statements (N));
3154 Insert_List_After (N, Else_Statements (N));
3160 -- If there are elsif statements, the first of them becomes the
3161 -- if/then section of the rebuilt if statement This is the case
3162 -- where we loop to reprocess this copied condition.
3165 Hed := Remove_Head (Elsif_Parts (N));
3166 Insert_Actions (N, Condition_Actions (Hed));
3167 Set_Condition (N, Condition (Hed));
3168 Set_Then_Statements (N, Then_Statements (Hed));
3170 -- Hed might have been captured as the condition determining
3171 -- the current value for an entity. Now it is detached from
3172 -- the tree, so a Current_Value pointer in the condition might
3173 -- need to be updated.
3175 Set_Current_Value_Condition (N);
3177 if Is_Empty_List (Elsif_Parts (N)) then
3178 Set_Elsif_Parts (N, No_List);
3184 -- Loop through elsif parts, dealing with constant conditions and
3185 -- possible expression actions that are present.
3187 if Present (Elsif_Parts (N)) then
3188 E := First (Elsif_Parts (N));
3189 while Present (E) loop
3190 Adjust_Condition (Condition (E));
3192 -- If there are condition actions, then rewrite the if statement
3193 -- as indicated above. We also do the same rewrite for a True or
3194 -- False condition. The further processing of this constant
3195 -- condition is then done by the recursive call to expand the
3196 -- newly created if statement
3198 if Present (Condition_Actions (E))
3199 or else Compile_Time_Known_Value (Condition (E))
3201 -- Note this is not an implicit if statement, since it is part
3202 -- of an explicit if statement in the source (or of an implicit
3203 -- if statement that has already been tested).
3206 Make_If_Statement (Sloc (E),
3207 Condition => Condition (E),
3208 Then_Statements => Then_Statements (E),
3209 Elsif_Parts => No_List,
3210 Else_Statements => Else_Statements (N));
3212 -- Elsif parts for new if come from remaining elsif's of parent
3214 while Present (Next (E)) loop
3215 if No (Elsif_Parts (New_If)) then
3216 Set_Elsif_Parts (New_If, New_List);
3219 Append (Remove_Next (E), Elsif_Parts (New_If));
3222 Set_Else_Statements (N, New_List (New_If));
3224 if Present (Condition_Actions (E)) then
3225 Insert_List_Before (New_If, Condition_Actions (E));
3230 if Is_Empty_List (Elsif_Parts (N)) then
3231 Set_Elsif_Parts (N, No_List);
3237 -- No special processing for that elsif part, move to next
3245 -- Some more optimizations applicable if we still have an IF statement
3247 if Nkind (N) /= N_If_Statement then
3251 -- Another optimization, special cases that can be simplified
3253 -- if expression then
3259 -- can be changed to:
3261 -- return expression;
3265 -- if expression then
3271 -- can be changed to:
3273 -- return not (expression);
3275 -- Only do these optimizations if we are at least at -O1 level and
3276 -- do not do them if control flow optimizations are suppressed.
3278 if Optimization_Level > 0
3279 and then not Opt.Suppress_Control_Flow_Optimizations
3281 if Nkind (N) = N_If_Statement
3282 and then No (Elsif_Parts (N))
3283 and then Present (Else_Statements (N))
3284 and then List_Length (Then_Statements (N)) = 1
3285 and then List_Length (Else_Statements (N)) = 1
3288 Then_Stm : constant Node_Id := First (Then_Statements (N));
3289 Else_Stm : constant Node_Id := First (Else_Statements (N));
3292 if Nkind (Then_Stm) = N_Simple_Return_Statement
3294 Nkind (Else_Stm) = N_Simple_Return_Statement
3297 Then_Expr : constant Node_Id := Expression (Then_Stm);
3298 Else_Expr : constant Node_Id := Expression (Else_Stm);
3301 if Nkind (Then_Expr) = N_Identifier
3303 Nkind (Else_Expr) = N_Identifier
3305 if Entity (Then_Expr) = Standard_True
3306 and then Entity (Else_Expr) = Standard_False
3309 Make_Simple_Return_Statement (Loc,
3310 Expression => Relocate_Node (Condition (N))));
3314 elsif Entity (Then_Expr) = Standard_False
3315 and then Entity (Else_Expr) = Standard_True
3318 Make_Simple_Return_Statement (Loc,
3322 Relocate_Node (Condition (N)))));
3332 end Expand_N_If_Statement;
3334 -----------------------------
3335 -- Expand_N_Loop_Statement --
3336 -----------------------------
3338 -- 1. Remove null loop entirely
3339 -- 2. Deal with while condition for C/Fortran boolean
3340 -- 3. Deal with loops with a non-standard enumeration type range
3341 -- 4. Deal with while loops where Condition_Actions is set
3342 -- 5. Insert polling call if required
3344 procedure Expand_N_Loop_Statement (N : Node_Id) is
3345 Loc : constant Source_Ptr := Sloc (N);
3346 Isc : constant Node_Id := Iteration_Scheme (N);
3351 if Is_Null_Loop (N) then
3352 Rewrite (N, Make_Null_Statement (Loc));
3356 -- Deal with condition for C/Fortran Boolean
3358 if Present (Isc) then
3359 Adjust_Condition (Condition (Isc));
3362 -- Generate polling call
3364 if Is_Non_Empty_List (Statements (N)) then
3365 Generate_Poll_Call (First (Statements (N)));
3368 -- Nothing more to do for plain loop with no iteration scheme
3374 -- Note: we do not have to worry about validity checking of the for loop
3375 -- range bounds here, since they were frozen with constant declarations
3376 -- and it is during that process that the validity checking is done.
3378 -- Handle the case where we have a for loop with the range type being an
3379 -- enumeration type with non-standard representation. In this case we
3382 -- for x in [reverse] a .. b loop
3388 -- for xP in [reverse] integer
3389 -- range etype'Pos (a) .. etype'Pos (b) loop
3391 -- x : constant etype := Pos_To_Rep (xP);
3397 if Present (Loop_Parameter_Specification (Isc)) then
3399 LPS : constant Node_Id := Loop_Parameter_Specification (Isc);
3400 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
3401 Ltype : constant Entity_Id := Etype (Loop_Id);
3402 Btype : constant Entity_Id := Base_Type (Ltype);
3407 if not Is_Enumeration_Type (Btype)
3408 or else No (Enum_Pos_To_Rep (Btype))
3414 Make_Defining_Identifier (Loc,
3415 Chars => New_External_Name (Chars (Loop_Id), 'P'));
3417 -- If the type has a contiguous representation, successive values
3418 -- can be generated as offsets from the first literal.
3420 if Has_Contiguous_Rep (Btype) then
3422 Unchecked_Convert_To (Btype,
3425 Make_Integer_Literal (Loc,
3426 Enumeration_Rep (First_Literal (Btype))),
3427 Right_Opnd => New_Reference_To (New_Id, Loc)));
3429 -- Use the constructed array Enum_Pos_To_Rep
3432 Make_Indexed_Component (Loc,
3433 Prefix => New_Reference_To (Enum_Pos_To_Rep (Btype), Loc),
3434 Expressions => New_List (New_Reference_To (New_Id, Loc)));
3438 Make_Loop_Statement (Loc,
3439 Identifier => Identifier (N),
3442 Make_Iteration_Scheme (Loc,
3443 Loop_Parameter_Specification =>
3444 Make_Loop_Parameter_Specification (Loc,
3445 Defining_Identifier => New_Id,
3446 Reverse_Present => Reverse_Present (LPS),
3448 Discrete_Subtype_Definition =>
3449 Make_Subtype_Indication (Loc,
3452 New_Reference_To (Standard_Natural, Loc),
3455 Make_Range_Constraint (Loc,
3460 Make_Attribute_Reference (Loc,
3462 New_Reference_To (Btype, Loc),
3464 Attribute_Name => Name_Pos,
3466 Expressions => New_List (
3468 (Type_Low_Bound (Ltype)))),
3471 Make_Attribute_Reference (Loc,
3473 New_Reference_To (Btype, Loc),
3475 Attribute_Name => Name_Pos,
3477 Expressions => New_List (
3479 (Type_High_Bound (Ltype))))))))),
3481 Statements => New_List (
3482 Make_Block_Statement (Loc,
3483 Declarations => New_List (
3484 Make_Object_Declaration (Loc,
3485 Defining_Identifier => Loop_Id,
3486 Constant_Present => True,
3487 Object_Definition => New_Reference_To (Ltype, Loc),
3488 Expression => Expr)),
3490 Handled_Statement_Sequence =>
3491 Make_Handled_Sequence_Of_Statements (Loc,
3492 Statements => Statements (N)))),
3494 End_Label => End_Label (N)));
3498 -- Second case, if we have a while loop with Condition_Actions set, then
3499 -- we change it into a plain loop:
3508 -- <<condition actions>>
3514 and then Present (Condition_Actions (Isc))
3521 Make_Exit_Statement (Sloc (Condition (Isc)),
3523 Make_Op_Not (Sloc (Condition (Isc)),
3524 Right_Opnd => Condition (Isc)));
3526 Prepend (ES, Statements (N));
3527 Insert_List_Before (ES, Condition_Actions (Isc));
3529 -- This is not an implicit loop, since it is generated in response
3530 -- to the loop statement being processed. If this is itself
3531 -- implicit, the restriction has already been checked. If not,
3532 -- it is an explicit loop.
3535 Make_Loop_Statement (Sloc (N),
3536 Identifier => Identifier (N),
3537 Statements => Statements (N),
3538 End_Label => End_Label (N)));
3543 end Expand_N_Loop_Statement;
3545 --------------------------------------
3546 -- Expand_N_Simple_Return_Statement --
3547 --------------------------------------
3549 procedure Expand_N_Simple_Return_Statement (N : Node_Id) is
3551 -- Defend against previous errors (i.e. the return statement calls a
3552 -- function that is not available in configurable runtime).
3554 if Present (Expression (N))
3555 and then Nkind (Expression (N)) = N_Empty
3560 -- Distinguish the function and non-function cases:
3562 case Ekind (Return_Applies_To (Return_Statement_Entity (N))) is
3565 E_Generic_Function =>
3566 Expand_Simple_Function_Return (N);
3569 E_Generic_Procedure |
3572 E_Return_Statement =>
3573 Expand_Non_Function_Return (N);
3576 raise Program_Error;
3580 when RE_Not_Available =>
3582 end Expand_N_Simple_Return_Statement;
3584 --------------------------------
3585 -- Expand_Non_Function_Return --
3586 --------------------------------
3588 procedure Expand_Non_Function_Return (N : Node_Id) is
3589 pragma Assert (No (Expression (N)));
3591 Loc : constant Source_Ptr := Sloc (N);
3592 Scope_Id : Entity_Id :=
3593 Return_Applies_To (Return_Statement_Entity (N));
3594 Kind : constant Entity_Kind := Ekind (Scope_Id);
3597 Goto_Stat : Node_Id;
3601 -- Call _Postconditions procedure if procedure with active
3602 -- postconditions. Here, we use the Postcondition_Proc attribute, which
3603 -- is needed for implicitly-generated returns. Functions never
3604 -- have implicitly-generated returns, and there's no room for
3605 -- Postcondition_Proc in E_Function, so we look up the identifier
3606 -- Name_uPostconditions for function returns (see
3607 -- Expand_Simple_Function_Return).
3609 if Ekind (Scope_Id) = E_Procedure
3610 and then Has_Postconditions (Scope_Id)
3612 pragma Assert (Present (Postcondition_Proc (Scope_Id)));
3614 Make_Procedure_Call_Statement (Loc,
3615 Name => New_Reference_To (Postcondition_Proc (Scope_Id), Loc)));
3618 -- If it is a return from a procedure do no extra steps
3620 if Kind = E_Procedure or else Kind = E_Generic_Procedure then
3623 -- If it is a nested return within an extended one, replace it with a
3624 -- return of the previously declared return object.
3626 elsif Kind = E_Return_Statement then
3628 Make_Simple_Return_Statement (Loc,
3630 New_Occurrence_Of (First_Entity (Scope_Id), Loc)));
3631 Set_Comes_From_Extended_Return_Statement (N);
3632 Set_Return_Statement_Entity (N, Scope_Id);
3633 Expand_Simple_Function_Return (N);
3637 pragma Assert (Is_Entry (Scope_Id));
3639 -- Look at the enclosing block to see whether the return is from an
3640 -- accept statement or an entry body.
3642 for J in reverse 0 .. Scope_Stack.Last loop
3643 Scope_Id := Scope_Stack.Table (J).Entity;
3644 exit when Is_Concurrent_Type (Scope_Id);
3647 -- If it is a return from accept statement it is expanded as call to
3648 -- RTS Complete_Rendezvous and a goto to the end of the accept body.
3650 -- (cf : Expand_N_Accept_Statement, Expand_N_Selective_Accept,
3651 -- Expand_N_Accept_Alternative in exp_ch9.adb)
3653 if Is_Task_Type (Scope_Id) then
3656 Make_Procedure_Call_Statement (Loc,
3657 Name => New_Reference_To (RTE (RE_Complete_Rendezvous), Loc));
3658 Insert_Before (N, Call);
3659 -- why not insert actions here???
3662 Acc_Stat := Parent (N);
3663 while Nkind (Acc_Stat) /= N_Accept_Statement loop
3664 Acc_Stat := Parent (Acc_Stat);
3667 Lab_Node := Last (Statements
3668 (Handled_Statement_Sequence (Acc_Stat)));
3670 Goto_Stat := Make_Goto_Statement (Loc,
3671 Name => New_Occurrence_Of
3672 (Entity (Identifier (Lab_Node)), Loc));
3674 Set_Analyzed (Goto_Stat);
3676 Rewrite (N, Goto_Stat);
3679 -- If it is a return from an entry body, put a Complete_Entry_Body call
3680 -- in front of the return.
3682 elsif Is_Protected_Type (Scope_Id) then
3684 Make_Procedure_Call_Statement (Loc,
3686 New_Reference_To (RTE (RE_Complete_Entry_Body), Loc),
3687 Parameter_Associations => New_List (
3688 Make_Attribute_Reference (Loc,
3691 (Find_Protection_Object (Current_Scope), Loc),
3693 Name_Unchecked_Access)));
3695 Insert_Before (N, Call);
3698 end Expand_Non_Function_Return;
3700 -----------------------------------
3701 -- Expand_Simple_Function_Return --
3702 -----------------------------------
3704 -- The "simple" comes from the syntax rule simple_return_statement.
3705 -- The semantics are not at all simple!
3707 procedure Expand_Simple_Function_Return (N : Node_Id) is
3708 Loc : constant Source_Ptr := Sloc (N);
3710 Scope_Id : constant Entity_Id :=
3711 Return_Applies_To (Return_Statement_Entity (N));
3712 -- The function we are returning from
3714 R_Type : constant Entity_Id := Etype (Scope_Id);
3715 -- The result type of the function
3717 Utyp : constant Entity_Id := Underlying_Type (R_Type);
3719 Exp : constant Node_Id := Expression (N);
3720 pragma Assert (Present (Exp));
3722 Exptyp : constant Entity_Id := Etype (Exp);
3723 -- The type of the expression (not necessarily the same as R_Type)
3725 Subtype_Ind : Node_Id;
3726 -- If the result type of the function is class-wide and the
3727 -- expression has a specific type, then we use the expression's
3728 -- type as the type of the return object. In cases where the
3729 -- expression is an aggregate that is built in place, this avoids
3730 -- the need for an expensive conversion of the return object to
3731 -- the specific type on assignments to the individual components.
3734 if Is_Class_Wide_Type (R_Type)
3735 and then not Is_Class_Wide_Type (Etype (Exp))
3737 Subtype_Ind := New_Occurrence_Of (Etype (Exp), Loc);
3739 Subtype_Ind := New_Occurrence_Of (R_Type, Loc);
3742 -- For the case of a simple return that does not come from an extended
3743 -- return, in the case of Ada 2005 where we are returning a limited
3744 -- type, we rewrite "return <expression>;" to be:
3746 -- return _anon_ : <return_subtype> := <expression>
3748 -- The expansion produced by Expand_N_Extended_Return_Statement will
3749 -- contain simple return statements (for example, a block containing
3750 -- simple return of the return object), which brings us back here with
3751 -- Comes_From_Extended_Return_Statement set. The reason for the barrier
3752 -- checking for a simple return that does not come from an extended
3753 -- return is to avoid this infinite recursion.
3755 -- The reason for this design is that for Ada 2005 limited returns, we
3756 -- need to reify the return object, so we can build it "in place", and
3757 -- we need a block statement to hang finalization and tasking stuff.
3759 -- ??? In order to avoid disruption, we avoid translating to extended
3760 -- return except in the cases where we really need to (Ada 2005 for
3761 -- inherently limited). We might prefer to do this translation in all
3762 -- cases (except perhaps for the case of Ada 95 inherently limited),
3763 -- in order to fully exercise the Expand_N_Extended_Return_Statement
3764 -- code. This would also allow us to do the build-in-place optimization
3765 -- for efficiency even in cases where it is semantically not required.
3767 -- As before, we check the type of the return expression rather than the
3768 -- return type of the function, because the latter may be a limited
3769 -- class-wide interface type, which is not a limited type, even though
3770 -- the type of the expression may be.
3772 if not Comes_From_Extended_Return_Statement (N)
3773 and then Is_Inherently_Limited_Type (Etype (Expression (N)))
3774 and then Ada_Version >= Ada_05
3775 and then not Debug_Flag_Dot_L
3778 Return_Object_Entity : constant Entity_Id :=
3779 Make_Defining_Identifier (Loc,
3780 New_Internal_Name ('R'));
3781 Obj_Decl : constant Node_Id :=
3782 Make_Object_Declaration (Loc,
3783 Defining_Identifier => Return_Object_Entity,
3784 Object_Definition => Subtype_Ind,
3787 Ext : constant Node_Id := Make_Extended_Return_Statement (Loc,
3788 Return_Object_Declarations => New_List (Obj_Decl));
3789 -- Do not perform this high-level optimization if the result type
3790 -- is an interface because the "this" pointer must be displaced.
3799 -- Here we have a simple return statement that is part of the expansion
3800 -- of an extended return statement (either written by the user, or
3801 -- generated by the above code).
3803 -- Always normalize C/Fortran boolean result. This is not always needed,
3804 -- but it seems a good idea to minimize the passing around of non-
3805 -- normalized values, and in any case this handles the processing of
3806 -- barrier functions for protected types, which turn the condition into
3807 -- a return statement.
3809 if Is_Boolean_Type (Exptyp)
3810 and then Nonzero_Is_True (Exptyp)
3812 Adjust_Condition (Exp);
3813 Adjust_Result_Type (Exp, Exptyp);
3816 -- Do validity check if enabled for returns
3818 if Validity_Checks_On
3819 and then Validity_Check_Returns
3824 -- Check the result expression of a scalar function against the subtype
3825 -- of the function by inserting a conversion. This conversion must
3826 -- eventually be performed for other classes of types, but for now it's
3827 -- only done for scalars.
3830 if Is_Scalar_Type (Exptyp) then
3831 Rewrite (Exp, Convert_To (R_Type, Exp));
3835 -- Deal with returning variable length objects and controlled types
3837 -- Nothing to do if we are returning by reference, or this is not a
3838 -- type that requires special processing (indicated by the fact that
3839 -- it requires a cleanup scope for the secondary stack case).
3841 if Is_Inherently_Limited_Type (Exptyp)
3842 or else Is_Limited_Interface (Exptyp)
3846 elsif not Requires_Transient_Scope (R_Type) then
3848 -- Mutable records with no variable length components are not
3849 -- returned on the sec-stack, so we need to make sure that the
3850 -- backend will only copy back the size of the actual value, and not
3851 -- the maximum size. We create an actual subtype for this purpose.
3854 Ubt : constant Entity_Id := Underlying_Type (Base_Type (Exptyp));
3858 if Has_Discriminants (Ubt)
3859 and then not Is_Constrained (Ubt)
3860 and then not Has_Unchecked_Union (Ubt)
3862 Decl := Build_Actual_Subtype (Ubt, Exp);
3863 Ent := Defining_Identifier (Decl);
3864 Insert_Action (Exp, Decl);
3865 Rewrite (Exp, Unchecked_Convert_To (Ent, Exp));
3866 Analyze_And_Resolve (Exp);
3870 -- Here if secondary stack is used
3873 -- Make sure that no surrounding block will reclaim the secondary
3874 -- stack on which we are going to put the result. Not only may this
3875 -- introduce secondary stack leaks but worse, if the reclamation is
3876 -- done too early, then the result we are returning may get
3883 while Ekind (S) = E_Block or else Ekind (S) = E_Loop loop
3884 Set_Sec_Stack_Needed_For_Return (S, True);
3885 S := Enclosing_Dynamic_Scope (S);
3889 -- Optimize the case where the result is a function call. In this
3890 -- case either the result is already on the secondary stack, or is
3891 -- already being returned with the stack pointer depressed and no
3892 -- further processing is required except to set the By_Ref flag to
3893 -- ensure that gigi does not attempt an extra unnecessary copy.
3894 -- (actually not just unnecessary but harmfully wrong in the case
3895 -- of a controlled type, where gigi does not know how to do a copy).
3896 -- To make up for a gcc 2.8.1 deficiency (???), we perform
3897 -- the copy for array types if the constrained status of the
3898 -- target type is different from that of the expression.
3900 if Requires_Transient_Scope (Exptyp)
3902 (not Is_Array_Type (Exptyp)
3903 or else Is_Constrained (Exptyp) = Is_Constrained (R_Type)
3904 or else CW_Or_Has_Controlled_Part (Utyp))
3905 and then Nkind (Exp) = N_Function_Call
3909 -- Remove side effects from the expression now so that other parts
3910 -- of the expander do not have to reanalyze this node without this
3913 Rewrite (Exp, Duplicate_Subexpr_No_Checks (Exp));
3915 -- For controlled types, do the allocation on the secondary stack
3916 -- manually in order to call adjust at the right time:
3918 -- type Anon1 is access R_Type;
3919 -- for Anon1'Storage_pool use ss_pool;
3920 -- Anon2 : anon1 := new R_Type'(expr);
3921 -- return Anon2.all;
3923 -- We do the same for classwide types that are not potentially
3924 -- controlled (by the virtue of restriction No_Finalization) because
3925 -- gigi is not able to properly allocate class-wide types.
3927 elsif CW_Or_Has_Controlled_Part (Utyp) then
3929 Loc : constant Source_Ptr := Sloc (N);
3930 Temp : constant Entity_Id :=
3931 Make_Defining_Identifier (Loc,
3932 Chars => New_Internal_Name ('R'));
3933 Acc_Typ : constant Entity_Id :=
3934 Make_Defining_Identifier (Loc,
3935 Chars => New_Internal_Name ('A'));
3936 Alloc_Node : Node_Id;
3939 Set_Ekind (Acc_Typ, E_Access_Type);
3941 Set_Associated_Storage_Pool (Acc_Typ, RTE (RE_SS_Pool));
3943 -- This is an allocator for the secondary stack, and it's fine
3944 -- to have Comes_From_Source set False on it, as gigi knows not
3945 -- to flag it as a violation of No_Implicit_Heap_Allocations.
3948 Make_Allocator (Loc,
3950 Make_Qualified_Expression (Loc,
3951 Subtype_Mark => New_Reference_To (Etype (Exp), Loc),
3952 Expression => Relocate_Node (Exp)));
3954 -- We do not want discriminant checks on the declaration,
3955 -- given that it gets its value from the allocator.
3957 Set_No_Initialization (Alloc_Node);
3959 Insert_List_Before_And_Analyze (N, New_List (
3960 Make_Full_Type_Declaration (Loc,
3961 Defining_Identifier => Acc_Typ,
3963 Make_Access_To_Object_Definition (Loc,
3964 Subtype_Indication => Subtype_Ind)),
3966 Make_Object_Declaration (Loc,
3967 Defining_Identifier => Temp,
3968 Object_Definition => New_Reference_To (Acc_Typ, Loc),
3969 Expression => Alloc_Node)));
3972 Make_Explicit_Dereference (Loc,
3973 Prefix => New_Reference_To (Temp, Loc)));
3975 Analyze_And_Resolve (Exp, R_Type);
3978 -- Otherwise use the gigi mechanism to allocate result on the
3982 Check_Restriction (No_Secondary_Stack, N);
3983 Set_Storage_Pool (N, RTE (RE_SS_Pool));
3985 -- If we are generating code for the VM do not use
3986 -- SS_Allocate since everything is heap-allocated anyway.
3988 if VM_Target = No_VM then
3989 Set_Procedure_To_Call (N, RTE (RE_SS_Allocate));
3994 -- Implement the rules of 6.5(8-10), which require a tag check in the
3995 -- case of a limited tagged return type, and tag reassignment for
3996 -- nonlimited tagged results. These actions are needed when the return
3997 -- type is a specific tagged type and the result expression is a
3998 -- conversion or a formal parameter, because in that case the tag of the
3999 -- expression might differ from the tag of the specific result type.
4001 if Is_Tagged_Type (Utyp)
4002 and then not Is_Class_Wide_Type (Utyp)
4003 and then (Nkind_In (Exp, N_Type_Conversion,
4004 N_Unchecked_Type_Conversion)
4005 or else (Is_Entity_Name (Exp)
4006 and then Ekind (Entity (Exp)) in Formal_Kind))
4008 -- When the return type is limited, perform a check that the
4009 -- tag of the result is the same as the tag of the return type.
4011 if Is_Limited_Type (R_Type) then
4013 Make_Raise_Constraint_Error (Loc,
4017 Make_Selected_Component (Loc,
4018 Prefix => Duplicate_Subexpr (Exp),
4020 New_Reference_To (First_Tag_Component (Utyp), Loc)),
4022 Unchecked_Convert_To (RTE (RE_Tag),
4025 (Access_Disp_Table (Base_Type (Utyp)))),
4027 Reason => CE_Tag_Check_Failed));
4029 -- If the result type is a specific nonlimited tagged type, then we
4030 -- have to ensure that the tag of the result is that of the result
4031 -- type. This is handled by making a copy of the expression in the
4032 -- case where it might have a different tag, namely when the
4033 -- expression is a conversion or a formal parameter. We create a new
4034 -- object of the result type and initialize it from the expression,
4035 -- which will implicitly force the tag to be set appropriately.
4039 Result_Id : constant Entity_Id :=
4040 Make_Defining_Identifier (Loc,
4041 Chars => New_Internal_Name ('R'));
4042 Result_Exp : constant Node_Id :=
4043 New_Reference_To (Result_Id, Loc);
4044 Result_Obj : constant Node_Id :=
4045 Make_Object_Declaration (Loc,
4046 Defining_Identifier => Result_Id,
4047 Object_Definition =>
4048 New_Reference_To (R_Type, Loc),
4049 Constant_Present => True,
4050 Expression => Relocate_Node (Exp));
4053 Set_Assignment_OK (Result_Obj);
4054 Insert_Action (Exp, Result_Obj);
4056 Rewrite (Exp, Result_Exp);
4057 Analyze_And_Resolve (Exp, R_Type);
4061 -- Ada 2005 (AI-344): If the result type is class-wide, then insert
4062 -- a check that the level of the return expression's underlying type
4063 -- is not deeper than the level of the master enclosing the function.
4064 -- Always generate the check when the type of the return expression
4065 -- is class-wide, when it's a type conversion, or when it's a formal
4066 -- parameter. Otherwise, suppress the check in the case where the
4067 -- return expression has a specific type whose level is known not to
4068 -- be statically deeper than the function's result type.
4070 -- Note: accessibility check is skipped in the VM case, since there
4071 -- does not seem to be any practical way to implement this check.
4073 elsif Ada_Version >= Ada_05
4074 and then VM_Target = No_VM
4075 and then Is_Class_Wide_Type (R_Type)
4076 and then not Scope_Suppress (Accessibility_Check)
4078 (Is_Class_Wide_Type (Etype (Exp))
4079 or else Nkind_In (Exp, N_Type_Conversion,
4080 N_Unchecked_Type_Conversion)
4081 or else (Is_Entity_Name (Exp)
4082 and then Ekind (Entity (Exp)) in Formal_Kind)
4083 or else Scope_Depth (Enclosing_Dynamic_Scope (Etype (Exp))) >
4084 Scope_Depth (Enclosing_Dynamic_Scope (Scope_Id)))
4090 -- Ada 2005 (AI-251): In class-wide interface objects we displace
4091 -- "this" to reference the base of the object --- required to get
4092 -- access to the TSD of the object.
4094 if Is_Class_Wide_Type (Etype (Exp))
4095 and then Is_Interface (Etype (Exp))
4096 and then Nkind (Exp) = N_Explicit_Dereference
4099 Make_Explicit_Dereference (Loc,
4100 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
4101 Make_Function_Call (Loc,
4102 Name => New_Reference_To (RTE (RE_Base_Address), Loc),
4103 Parameter_Associations => New_List (
4104 Unchecked_Convert_To (RTE (RE_Address),
4105 Duplicate_Subexpr (Prefix (Exp)))))));
4108 Make_Attribute_Reference (Loc,
4109 Prefix => Duplicate_Subexpr (Exp),
4110 Attribute_Name => Name_Tag);
4114 Make_Raise_Program_Error (Loc,
4118 Build_Get_Access_Level (Loc, Tag_Node),
4120 Make_Integer_Literal (Loc,
4121 Scope_Depth (Enclosing_Dynamic_Scope (Scope_Id)))),
4122 Reason => PE_Accessibility_Check_Failed));
4126 -- If we are returning an object that may not be bit-aligned, then
4127 -- copy the value into a temporary first. This copy may need to expand
4128 -- to a loop of component operations..
4130 if Is_Possibly_Unaligned_Slice (Exp)
4131 or else Is_Possibly_Unaligned_Object (Exp)
4134 Tnn : constant Entity_Id :=
4135 Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
4138 Make_Object_Declaration (Loc,
4139 Defining_Identifier => Tnn,
4140 Constant_Present => True,
4141 Object_Definition => New_Occurrence_Of (R_Type, Loc),
4142 Expression => Relocate_Node (Exp)),
4143 Suppress => All_Checks);
4144 Rewrite (Exp, New_Occurrence_Of (Tnn, Loc));
4148 -- Generate call to postcondition checks if they are present
4150 if Ekind (Scope_Id) = E_Function
4151 and then Has_Postconditions (Scope_Id)
4153 -- We are going to reference the returned value twice in this case,
4154 -- once in the call to _Postconditions, and once in the actual return
4155 -- statement, but we can't have side effects happening twice, and in
4156 -- any case for efficiency we don't want to do the computation twice.
4158 -- If the returned expression is an entity name, we don't need to
4159 -- worry since it is efficient and safe to reference it twice, that's
4160 -- also true for literals other than string literals, and for the
4161 -- case of X.all where X is an entity name.
4163 if Is_Entity_Name (Exp)
4164 or else Nkind_In (Exp, N_Character_Literal,
4167 or else (Nkind (Exp) = N_Explicit_Dereference
4168 and then Is_Entity_Name (Prefix (Exp)))
4172 -- Otherwise we are going to need a temporary to capture the value
4176 Tnn : constant Entity_Id :=
4177 Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
4180 -- For a complex expression of an elementary type, capture
4181 -- value in the temporary and use it as the reference.
4183 if Is_Elementary_Type (R_Type) then
4185 Make_Object_Declaration (Loc,
4186 Defining_Identifier => Tnn,
4187 Constant_Present => True,
4188 Object_Definition => New_Occurrence_Of (R_Type, Loc),
4189 Expression => Relocate_Node (Exp)),
4190 Suppress => All_Checks);
4192 Rewrite (Exp, New_Occurrence_Of (Tnn, Loc));
4194 -- If we have something we can rename, generate a renaming of
4195 -- the object and replace the expression with a reference
4197 elsif Is_Object_Reference (Exp) then
4199 Make_Object_Renaming_Declaration (Loc,
4200 Defining_Identifier => Tnn,
4201 Subtype_Mark => New_Occurrence_Of (R_Type, Loc),
4202 Name => Relocate_Node (Exp)),
4203 Suppress => All_Checks);
4205 Rewrite (Exp, New_Occurrence_Of (Tnn, Loc));
4207 -- Otherwise we have something like a string literal or an
4208 -- aggregate. We could copy the value, but that would be
4209 -- inefficient. Instead we make a reference to the value and
4210 -- capture this reference with a renaming, the expression is
4211 -- then replaced by a dereference of this renaming.
4214 -- For now, copy the value, since the code below does not
4215 -- seem to work correctly ???
4218 Make_Object_Declaration (Loc,
4219 Defining_Identifier => Tnn,
4220 Constant_Present => True,
4221 Object_Definition => New_Occurrence_Of (R_Type, Loc),
4222 Expression => Relocate_Node (Exp)),
4223 Suppress => All_Checks);
4225 Rewrite (Exp, New_Occurrence_Of (Tnn, Loc));
4227 -- Insert_Action (Exp,
4228 -- Make_Object_Renaming_Declaration (Loc,
4229 -- Defining_Identifier => Tnn,
4230 -- Access_Definition =>
4231 -- Make_Access_Definition (Loc,
4232 -- All_Present => True,
4233 -- Subtype_Mark => New_Occurrence_Of (R_Type, Loc)),
4235 -- Make_Reference (Loc,
4236 -- Prefix => Relocate_Node (Exp))),
4237 -- Suppress => All_Checks);
4240 -- Make_Explicit_Dereference (Loc,
4241 -- Prefix => New_Occurrence_Of (Tnn, Loc)));
4246 -- Generate call to _postconditions
4249 Make_Procedure_Call_Statement (Loc,
4250 Name => Make_Identifier (Loc, Name_uPostconditions),
4251 Parameter_Associations => New_List (Duplicate_Subexpr (Exp))));
4254 -- Ada 2005 (AI-251): If this return statement corresponds with an
4255 -- simple return statement associated with an extended return statement
4256 -- and the type of the returned object is an interface then generate an
4257 -- implicit conversion to force displacement of the "this" pointer.
4259 if Ada_Version >= Ada_05
4260 and then Comes_From_Extended_Return_Statement (N)
4261 and then Nkind (Expression (N)) = N_Identifier
4262 and then Is_Interface (Utyp)
4263 and then Utyp /= Underlying_Type (Exptyp)
4265 Rewrite (Exp, Convert_To (Utyp, Relocate_Node (Exp)));
4266 Analyze_And_Resolve (Exp);
4268 end Expand_Simple_Function_Return;
4270 ------------------------------
4271 -- Make_Tag_Ctrl_Assignment --
4272 ------------------------------
4274 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
4275 Loc : constant Source_Ptr := Sloc (N);
4276 L : constant Node_Id := Name (N);
4277 T : constant Entity_Id := Underlying_Type (Etype (L));
4279 Ctrl_Act : constant Boolean := Needs_Finalization (T)
4280 and then not No_Ctrl_Actions (N);
4282 Save_Tag : constant Boolean := Is_Tagged_Type (T)
4283 and then not No_Ctrl_Actions (N)
4284 and then VM_Target = No_VM;
4285 -- Tags are not saved and restored when VM_Target because VM tags are
4286 -- represented implicitly in objects.
4289 Tag_Tmp : Entity_Id;
4291 Prev_Tmp : Entity_Id;
4292 Next_Tmp : Entity_Id;
4298 -- Finalize the target of the assignment when controlled.
4299 -- We have two exceptions here:
4301 -- 1. If we are in an init proc since it is an initialization
4302 -- more than an assignment
4304 -- 2. If the left-hand side is a temporary that was not initialized
4305 -- (or the parent part of a temporary since it is the case in
4306 -- extension aggregates). Such a temporary does not come from
4307 -- source. We must examine the original node for the prefix, because
4308 -- it may be a component of an entry formal, in which case it has
4309 -- been rewritten and does not appear to come from source either.
4311 -- Case of init proc
4313 if not Ctrl_Act then
4316 -- The left hand side is an uninitialized temporary object
4318 elsif Nkind (L) = N_Type_Conversion
4319 and then Is_Entity_Name (Expression (L))
4320 and then Nkind (Parent (Entity (Expression (L))))
4321 = N_Object_Declaration
4322 and then No_Initialization (Parent (Entity (Expression (L))))
4327 Append_List_To (Res,
4329 Ref => Duplicate_Subexpr_No_Checks (L),
4331 With_Detach => New_Reference_To (Standard_False, Loc)));
4334 -- Save the Tag in a local variable Tag_Tmp
4338 Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
4341 Make_Object_Declaration (Loc,
4342 Defining_Identifier => Tag_Tmp,
4343 Object_Definition => New_Reference_To (RTE (RE_Tag), Loc),
4345 Make_Selected_Component (Loc,
4346 Prefix => Duplicate_Subexpr_No_Checks (L),
4347 Selector_Name => New_Reference_To (First_Tag_Component (T),
4350 -- Otherwise Tag_Tmp not used
4357 if VM_Target /= No_VM then
4359 -- Cannot assign part of the object in a VM context, so instead
4360 -- fallback to the previous mechanism, even though it is not
4361 -- completely correct ???
4363 -- Save the Finalization Pointers in local variables Prev_Tmp and
4364 -- Next_Tmp. For objects with Has_Controlled_Component set, these
4365 -- pointers are in the Record_Controller
4367 Ctrl_Ref := Duplicate_Subexpr (L);
4369 if Has_Controlled_Component (T) then
4371 Make_Selected_Component (Loc,
4374 New_Reference_To (Controller_Component (T), Loc));
4378 Make_Defining_Identifier (Loc, New_Internal_Name ('B'));
4381 Make_Object_Declaration (Loc,
4382 Defining_Identifier => Prev_Tmp,
4384 Object_Definition =>
4385 New_Reference_To (RTE (RE_Finalizable_Ptr), Loc),
4388 Make_Selected_Component (Loc,
4390 Unchecked_Convert_To (RTE (RE_Finalizable), Ctrl_Ref),
4391 Selector_Name => Make_Identifier (Loc, Name_Prev))));
4394 Make_Defining_Identifier (Loc,
4395 Chars => New_Internal_Name ('C'));
4398 Make_Object_Declaration (Loc,
4399 Defining_Identifier => Next_Tmp,
4401 Object_Definition =>
4402 New_Reference_To (RTE (RE_Finalizable_Ptr), Loc),
4405 Make_Selected_Component (Loc,
4407 Unchecked_Convert_To (RTE (RE_Finalizable),
4408 New_Copy_Tree (Ctrl_Ref)),
4409 Selector_Name => Make_Identifier (Loc, Name_Next))));
4411 -- Do the Assignment
4413 Append_To (Res, Relocate_Node (N));
4416 -- Regular (non VM) processing for controlled types and types with
4417 -- controlled components
4419 -- Variables of such types contain pointers used to chain them in
4420 -- finalization lists, in addition to user data. These pointers
4421 -- are specific to each object of the type, not to the value being
4424 -- Thus they need to be left intact during the assignment. We
4425 -- achieve this by constructing a Storage_Array subtype, and by
4426 -- overlaying objects of this type on the source and target of the
4427 -- assignment. The assignment is then rewritten to assignments of
4428 -- slices of these arrays, copying the user data, and leaving the
4429 -- pointers untouched.
4431 Controlled_Actions : declare
4433 -- A reference to the Prev component of the record controller
4435 First_After_Root : Node_Id := Empty;
4436 -- Index of first byte to be copied (used to skip
4437 -- Root_Controlled in controlled objects).
4439 Last_Before_Hole : Node_Id := Empty;
4440 -- Index of last byte to be copied before outermost record
4443 Hole_Length : Node_Id := Empty;
4444 -- Length of record controller data (Prev and Next pointers)
4446 First_After_Hole : Node_Id := Empty;
4447 -- Index of first byte to be copied after outermost record
4450 Expr, Source_Size : Node_Id;
4451 Source_Actual_Subtype : Entity_Id;
4452 -- Used for computation of the size of the data to be copied
4454 Range_Type : Entity_Id;
4455 Opaque_Type : Entity_Id;
4457 function Build_Slice
4460 Hi : Node_Id) return Node_Id;
4461 -- Build and return a slice of an array of type S overlaid on
4462 -- object Rec, with bounds specified by Lo and Hi. If either
4463 -- bound is empty, a default of S'First (respectively S'Last)
4470 function Build_Slice
4473 Hi : Node_Id) return Node_Id
4478 Opaque : constant Node_Id :=
4479 Unchecked_Convert_To (Opaque_Type,
4480 Make_Attribute_Reference (Loc,
4482 Attribute_Name => Name_Address));
4483 -- Access value designating an opaque storage array of type
4484 -- S overlaid on record Rec.
4487 -- Compute slice bounds using S'First (1) and S'Last as
4488 -- default values when not specified by the caller.
4491 Lo_Bound := Make_Integer_Literal (Loc, 1);
4497 Hi_Bound := Make_Attribute_Reference (Loc,
4498 Prefix => New_Occurrence_Of (Range_Type, Loc),
4499 Attribute_Name => Name_Last);
4504 return Make_Slice (Loc,
4507 Discrete_Range => Make_Range (Loc,
4508 Lo_Bound, Hi_Bound));
4511 -- Start of processing for Controlled_Actions
4514 -- Create a constrained subtype of Storage_Array whose size
4515 -- corresponds to the value being assigned.
4517 -- subtype G is Storage_Offset range
4518 -- 1 .. (Expr'Size + Storage_Unit - 1) / Storage_Unit
4520 Expr := Duplicate_Subexpr_No_Checks (Expression (N));
4522 if Nkind (Expr) = N_Qualified_Expression then
4523 Expr := Expression (Expr);
4526 Source_Actual_Subtype := Etype (Expr);
4528 if Has_Discriminants (Source_Actual_Subtype)
4529 and then not Is_Constrained (Source_Actual_Subtype)
4532 Build_Actual_Subtype (Source_Actual_Subtype, Expr));
4533 Source_Actual_Subtype := Defining_Identifier (Last (Res));
4539 Make_Attribute_Reference (Loc,
4541 New_Occurrence_Of (Source_Actual_Subtype, Loc),
4542 Attribute_Name => Name_Size),
4544 Make_Integer_Literal (Loc,
4545 Intval => System_Storage_Unit - 1));
4548 Make_Op_Divide (Loc,
4549 Left_Opnd => Source_Size,
4551 Make_Integer_Literal (Loc,
4552 Intval => System_Storage_Unit));
4555 Make_Defining_Identifier (Loc,
4556 New_Internal_Name ('G'));
4559 Make_Subtype_Declaration (Loc,
4560 Defining_Identifier => Range_Type,
4561 Subtype_Indication =>
4562 Make_Subtype_Indication (Loc,
4564 New_Reference_To (RTE (RE_Storage_Offset), Loc),
4565 Constraint => Make_Range_Constraint (Loc,
4568 Low_Bound => Make_Integer_Literal (Loc, 1),
4569 High_Bound => Source_Size)))));
4571 -- subtype S is Storage_Array (G)
4574 Make_Subtype_Declaration (Loc,
4575 Defining_Identifier =>
4576 Make_Defining_Identifier (Loc,
4577 New_Internal_Name ('S')),
4578 Subtype_Indication =>
4579 Make_Subtype_Indication (Loc,
4581 New_Reference_To (RTE (RE_Storage_Array), Loc),
4583 Make_Index_Or_Discriminant_Constraint (Loc,
4585 New_List (New_Reference_To (Range_Type, Loc))))));
4587 -- type A is access S
4590 Make_Defining_Identifier (Loc,
4591 Chars => New_Internal_Name ('A'));
4594 Make_Full_Type_Declaration (Loc,
4595 Defining_Identifier => Opaque_Type,
4597 Make_Access_To_Object_Definition (Loc,
4598 Subtype_Indication =>
4600 Defining_Identifier (Last (Res)), Loc))));
4602 -- Generate appropriate slice assignments
4604 First_After_Root := Make_Integer_Literal (Loc, 1);
4606 -- For the case of a controlled object, skip the
4607 -- Root_Controlled part.
4609 if Is_Controlled (T) then
4613 Make_Op_Divide (Loc,
4614 Make_Attribute_Reference (Loc,
4616 New_Occurrence_Of (RTE (RE_Root_Controlled), Loc),
4617 Attribute_Name => Name_Size),
4618 Make_Integer_Literal (Loc, System_Storage_Unit)));
4621 -- For the case of a record with controlled components, skip
4622 -- the Prev and Next components of the record controller.
4623 -- These components constitute a 'hole' in the middle of the
4624 -- data to be copied.
4626 if Has_Controlled_Component (T) then
4628 Make_Selected_Component (Loc,
4630 Make_Selected_Component (Loc,
4631 Prefix => Duplicate_Subexpr_No_Checks (L),
4633 New_Reference_To (Controller_Component (T), Loc)),
4634 Selector_Name => Make_Identifier (Loc, Name_Prev));
4636 -- Last index before hole: determined by position of
4637 -- the _Controller.Prev component.
4640 Make_Defining_Identifier (Loc,
4641 New_Internal_Name ('L'));
4644 Make_Object_Declaration (Loc,
4645 Defining_Identifier => Last_Before_Hole,
4646 Object_Definition => New_Occurrence_Of (
4647 RTE (RE_Storage_Offset), Loc),
4648 Constant_Present => True,
4649 Expression => Make_Op_Add (Loc,
4650 Make_Attribute_Reference (Loc,
4652 Attribute_Name => Name_Position),
4653 Make_Attribute_Reference (Loc,
4654 Prefix => New_Copy_Tree (Prefix (Prev_Ref)),
4655 Attribute_Name => Name_Position))));
4657 -- Hole length: size of the Prev and Next components
4660 Make_Op_Multiply (Loc,
4661 Left_Opnd => Make_Integer_Literal (Loc, Uint_2),
4663 Make_Op_Divide (Loc,
4665 Make_Attribute_Reference (Loc,
4666 Prefix => New_Copy_Tree (Prev_Ref),
4667 Attribute_Name => Name_Size),
4669 Make_Integer_Literal (Loc,
4670 Intval => System_Storage_Unit)));
4672 -- First index after hole
4675 Make_Defining_Identifier (Loc,
4676 New_Internal_Name ('F'));
4679 Make_Object_Declaration (Loc,
4680 Defining_Identifier => First_After_Hole,
4681 Object_Definition => New_Occurrence_Of (
4682 RTE (RE_Storage_Offset), Loc),
4683 Constant_Present => True,
4689 New_Occurrence_Of (Last_Before_Hole, Loc),
4690 Right_Opnd => Hole_Length),
4691 Right_Opnd => Make_Integer_Literal (Loc, 1))));
4694 New_Occurrence_Of (Last_Before_Hole, Loc);
4696 New_Occurrence_Of (First_After_Hole, Loc);
4699 -- Assign the first slice (possibly skipping Root_Controlled,
4700 -- up to the beginning of the record controller if present,
4701 -- up to the end of the object if not).
4703 Append_To (Res, Make_Assignment_Statement (Loc,
4704 Name => Build_Slice (
4705 Rec => Duplicate_Subexpr_No_Checks (L),
4706 Lo => First_After_Root,
4707 Hi => Last_Before_Hole),
4709 Expression => Build_Slice (
4710 Rec => Expression (N),
4711 Lo => First_After_Root,
4712 Hi => New_Copy_Tree (Last_Before_Hole))));
4714 if Present (First_After_Hole) then
4716 -- If a record controller is present, copy the second slice,
4717 -- from right after the _Controller.Next component up to the
4718 -- end of the object.
4720 Append_To (Res, Make_Assignment_Statement (Loc,
4721 Name => Build_Slice (
4722 Rec => Duplicate_Subexpr_No_Checks (L),
4723 Lo => First_After_Hole,
4725 Expression => Build_Slice (
4726 Rec => Duplicate_Subexpr_No_Checks (Expression (N)),
4727 Lo => New_Copy_Tree (First_After_Hole),
4730 end Controlled_Actions;
4734 Append_To (Res, Relocate_Node (N));
4741 Make_Assignment_Statement (Loc,
4743 Make_Selected_Component (Loc,
4744 Prefix => Duplicate_Subexpr_No_Checks (L),
4745 Selector_Name => New_Reference_To (First_Tag_Component (T),
4747 Expression => New_Reference_To (Tag_Tmp, Loc)));
4751 if VM_Target /= No_VM then
4752 -- Restore the finalization pointers
4755 Make_Assignment_Statement (Loc,
4757 Make_Selected_Component (Loc,
4759 Unchecked_Convert_To (RTE (RE_Finalizable),
4760 New_Copy_Tree (Ctrl_Ref)),
4761 Selector_Name => Make_Identifier (Loc, Name_Prev)),
4762 Expression => New_Reference_To (Prev_Tmp, Loc)));
4765 Make_Assignment_Statement (Loc,
4767 Make_Selected_Component (Loc,
4769 Unchecked_Convert_To (RTE (RE_Finalizable),
4770 New_Copy_Tree (Ctrl_Ref)),
4771 Selector_Name => Make_Identifier (Loc, Name_Next)),
4772 Expression => New_Reference_To (Next_Tmp, Loc)));
4775 -- Adjust the target after the assignment when controlled (not in the
4776 -- init proc since it is an initialization more than an assignment).
4778 Append_List_To (Res,
4780 Ref => Duplicate_Subexpr_Move_Checks (L),
4782 Flist_Ref => New_Reference_To (RTE (RE_Global_Final_List), Loc),
4783 With_Attach => Make_Integer_Literal (Loc, 0)));
4789 -- Could use comment here ???
4791 when RE_Not_Available =>
4793 end Make_Tag_Ctrl_Assignment;