1 ------------------------------------------------------------------------------
3 -- GNAT COMPILER COMPONENTS --
9 -- Copyright (C) 1992-2015, 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 Aspects; use Aspects;
27 with Atree; use Atree;
28 with Checks; use Checks;
29 with Debug; use Debug;
30 with Einfo; use Einfo;
31 with Elists; use Elists;
32 with Errout; use Errout;
33 with Exp_Aggr; use Exp_Aggr;
34 with Exp_Ch6; use Exp_Ch6;
35 with Exp_Ch7; use Exp_Ch7;
36 with Exp_Ch11; use Exp_Ch11;
37 with Exp_Dbug; use Exp_Dbug;
38 with Exp_Pakd; use Exp_Pakd;
39 with Exp_Tss; use Exp_Tss;
40 with Exp_Util; use Exp_Util;
41 with Ghost; use Ghost;
42 with Inline; use Inline;
43 with Namet; use Namet;
44 with Nlists; use Nlists;
45 with Nmake; use Nmake;
47 with Restrict; use Restrict;
48 with Rident; use Rident;
49 with Rtsfind; use Rtsfind;
50 with Sinfo; use Sinfo;
52 with Sem_Aux; use Sem_Aux;
53 with Sem_Ch3; use Sem_Ch3;
54 with Sem_Ch8; use Sem_Ch8;
55 with Sem_Ch13; use Sem_Ch13;
56 with Sem_Eval; use Sem_Eval;
57 with Sem_Res; use Sem_Res;
58 with Sem_Util; use Sem_Util;
59 with Snames; use Snames;
60 with Stand; use Stand;
61 with Stringt; use Stringt;
62 with Targparm; use Targparm;
63 with Tbuild; use Tbuild;
64 with Uintp; use Uintp;
65 with Validsw; use Validsw;
67 package body Exp_Ch5 is
69 procedure Build_Formal_Container_Iteration
71 Container : Entity_Id;
74 Advance : out Node_Id;
75 New_Loop : out Node_Id);
76 -- Utility to create declarations and loop statement for both forms
77 -- of formal container iterators.
79 function Change_Of_Representation (N : Node_Id) return Boolean;
80 -- Determine if the right hand side of assignment N is a type conversion
81 -- which requires a change of representation. Called only for the array
84 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id);
85 -- N is an assignment which assigns an array value. This routine process
86 -- the various special cases and checks required for such assignments,
87 -- including change of representation. Rhs is normally simply the right
88 -- hand side of the assignment, except that if the right hand side is a
89 -- type conversion or a qualified expression, then the RHS is the actual
90 -- expression inside any such type conversions or qualifications.
92 function Expand_Assign_Array_Loop
99 Rev : Boolean) return Node_Id;
100 -- N is an assignment statement which assigns an array value. This routine
101 -- expands the assignment into a loop (or nested loops for the case of a
102 -- multi-dimensional array) to do the assignment component by component.
103 -- Larray and Rarray are the entities of the actual arrays on the left
104 -- hand and right hand sides. L_Type and R_Type are the types of these
105 -- arrays (which may not be the same, due to either sliding, or to a
106 -- change of representation case). Ndim is the number of dimensions and
107 -- the parameter Rev indicates if the loops run normally (Rev = False),
108 -- or reversed (Rev = True). The value returned is the constructed
109 -- loop statement. Auxiliary declarations are inserted before node N
110 -- using the standard Insert_Actions mechanism.
112 procedure Expand_Assign_Record (N : Node_Id);
113 -- N is an assignment of an untagged record value. This routine handles
114 -- the case where the assignment must be made component by component,
115 -- either because the target is not byte aligned, or there is a change
116 -- of representation, or when we have a tagged type with a representation
117 -- clause (this last case is required because holes in the tagged type
118 -- might be filled with components from child types).
120 procedure Expand_Formal_Container_Loop (N : Node_Id);
121 -- Use the primitives specified in an Iterable aspect to expand a loop
122 -- over a so-called formal container, primarily for SPARK usage.
124 procedure Expand_Formal_Container_Element_Loop (N : Node_Id);
125 -- Same, for an iterator of the form " For E of C". In this case the
126 -- iterator provides the name of the element, and the cursor is generated
129 procedure Expand_Iterator_Loop (N : Node_Id);
130 -- Expand loop over arrays and containers that uses the form "for X of C"
131 -- with an optional subtype mark, or "for Y in C".
133 procedure Expand_Iterator_Loop_Over_Container
138 Container_Typ : Entity_Id);
139 -- Expand loop over containers that uses the form "for X of C" with an
140 -- optional subtype mark, or "for Y in C". Isc is the iteration scheme.
141 -- I_Spec is the iterator specification and Container is either the
142 -- Container (for OF) or the iterator (for IN).
144 procedure Expand_Predicated_Loop (N : Node_Id);
145 -- Expand for loop over predicated subtype
147 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id;
148 -- Generate the necessary code for controlled and tagged assignment, that
149 -- is to say, finalization of the target before, adjustment of the target
150 -- after and save and restore of the tag and finalization pointers which
151 -- are not 'part of the value' and must not be changed upon assignment. N
152 -- is the original Assignment node.
154 --------------------------------------
155 -- Build_Formal_Container_iteration --
156 --------------------------------------
158 procedure Build_Formal_Container_Iteration
160 Container : Entity_Id;
163 Advance : out Node_Id;
164 New_Loop : out Node_Id)
166 Loc : constant Source_Ptr := Sloc (N);
167 Stats : constant List_Id := Statements (N);
168 Typ : constant Entity_Id := Base_Type (Etype (Container));
169 First_Op : constant Entity_Id :=
170 Get_Iterable_Type_Primitive (Typ, Name_First);
171 Next_Op : constant Entity_Id :=
172 Get_Iterable_Type_Primitive (Typ, Name_Next);
174 Has_Element_Op : constant Entity_Id :=
175 Get_Iterable_Type_Primitive (Typ, Name_Has_Element);
177 -- Declaration for Cursor
180 Make_Object_Declaration (Loc,
181 Defining_Identifier => Cursor,
182 Object_Definition => New_Occurrence_Of (Etype (First_Op), Loc),
184 Make_Function_Call (Loc,
185 Name => New_Occurrence_Of (First_Op, Loc),
186 Parameter_Associations => New_List (
187 New_Occurrence_Of (Container, Loc))));
189 -- Statement that advances cursor in loop
192 Make_Assignment_Statement (Loc,
193 Name => New_Occurrence_Of (Cursor, Loc),
195 Make_Function_Call (Loc,
196 Name => New_Occurrence_Of (Next_Op, Loc),
197 Parameter_Associations => New_List (
198 New_Occurrence_Of (Container, Loc),
199 New_Occurrence_Of (Cursor, Loc))));
201 -- Iterator is rewritten as a while_loop
204 Make_Loop_Statement (Loc,
206 Make_Iteration_Scheme (Loc,
208 Make_Function_Call (Loc,
209 Name => New_Occurrence_Of (Has_Element_Op, Loc),
210 Parameter_Associations => New_List (
211 New_Occurrence_Of (Container, Loc),
212 New_Occurrence_Of (Cursor, Loc)))),
215 end Build_Formal_Container_Iteration;
217 ------------------------------
218 -- Change_Of_Representation --
219 ------------------------------
221 function Change_Of_Representation (N : Node_Id) return Boolean is
222 Rhs : constant Node_Id := Expression (N);
225 Nkind (Rhs) = N_Type_Conversion
227 not Same_Representation (Etype (Rhs), Etype (Expression (Rhs)));
228 end Change_Of_Representation;
230 -------------------------
231 -- Expand_Assign_Array --
232 -------------------------
234 -- There are two issues here. First, do we let Gigi do a block move, or
235 -- do we expand out into a loop? Second, we need to set the two flags
236 -- Forwards_OK and Backwards_OK which show whether the block move (or
237 -- corresponding loops) can be legitimately done in a forwards (low to
238 -- high) or backwards (high to low) manner.
240 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id) is
241 Loc : constant Source_Ptr := Sloc (N);
243 Lhs : constant Node_Id := Name (N);
245 Act_Lhs : constant Node_Id := Get_Referenced_Object (Lhs);
246 Act_Rhs : Node_Id := Get_Referenced_Object (Rhs);
248 L_Type : constant Entity_Id :=
249 Underlying_Type (Get_Actual_Subtype (Act_Lhs));
250 R_Type : Entity_Id :=
251 Underlying_Type (Get_Actual_Subtype (Act_Rhs));
253 L_Slice : constant Boolean := Nkind (Act_Lhs) = N_Slice;
254 R_Slice : constant Boolean := Nkind (Act_Rhs) = N_Slice;
256 Crep : constant Boolean := Change_Of_Representation (N);
261 Ndim : constant Pos := Number_Dimensions (L_Type);
263 Loop_Required : Boolean := False;
264 -- This switch is set to True if the array move must be done using
265 -- an explicit front end generated loop.
267 procedure Apply_Dereference (Arg : Node_Id);
268 -- If the argument is an access to an array, and the assignment is
269 -- converted into a procedure call, apply explicit dereference.
271 function Has_Address_Clause (Exp : Node_Id) return Boolean;
272 -- Test if Exp is a reference to an array whose declaration has
273 -- an address clause, or it is a slice of such an array.
275 function Is_Formal_Array (Exp : Node_Id) return Boolean;
276 -- Test if Exp is a reference to an array which is either a formal
277 -- parameter or a slice of a formal parameter. These are the cases
278 -- where hidden aliasing can occur.
280 function Is_Non_Local_Array (Exp : Node_Id) return Boolean;
281 -- Determine if Exp is a reference to an array variable which is other
282 -- than an object defined in the current scope, or a slice of such
283 -- an object. Such objects can be aliased to parameters (unlike local
284 -- array references).
286 -----------------------
287 -- Apply_Dereference --
288 -----------------------
290 procedure Apply_Dereference (Arg : Node_Id) is
291 Typ : constant Entity_Id := Etype (Arg);
293 if Is_Access_Type (Typ) then
294 Rewrite (Arg, Make_Explicit_Dereference (Loc,
295 Prefix => Relocate_Node (Arg)));
296 Analyze_And_Resolve (Arg, Designated_Type (Typ));
298 end Apply_Dereference;
300 ------------------------
301 -- Has_Address_Clause --
302 ------------------------
304 function Has_Address_Clause (Exp : Node_Id) return Boolean is
307 (Is_Entity_Name (Exp) and then
308 Present (Address_Clause (Entity (Exp))))
310 (Nkind (Exp) = N_Slice and then Has_Address_Clause (Prefix (Exp)));
311 end Has_Address_Clause;
313 ---------------------
314 -- Is_Formal_Array --
315 ---------------------
317 function Is_Formal_Array (Exp : Node_Id) return Boolean is
320 (Is_Entity_Name (Exp) and then Is_Formal (Entity (Exp)))
322 (Nkind (Exp) = N_Slice and then Is_Formal_Array (Prefix (Exp)));
325 ------------------------
326 -- Is_Non_Local_Array --
327 ------------------------
329 function Is_Non_Local_Array (Exp : Node_Id) return Boolean is
331 return (Is_Entity_Name (Exp)
332 and then Scope (Entity (Exp)) /= Current_Scope)
333 or else (Nkind (Exp) = N_Slice
334 and then Is_Non_Local_Array (Prefix (Exp)));
335 end Is_Non_Local_Array;
337 -- Determine if Lhs, Rhs are formal arrays or nonlocal arrays
339 Lhs_Formal : constant Boolean := Is_Formal_Array (Act_Lhs);
340 Rhs_Formal : constant Boolean := Is_Formal_Array (Act_Rhs);
342 Lhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Lhs);
343 Rhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Rhs);
345 -- Start of processing for Expand_Assign_Array
348 -- Deal with length check. Note that the length check is done with
349 -- respect to the right hand side as given, not a possible underlying
350 -- renamed object, since this would generate incorrect extra checks.
352 Apply_Length_Check (Rhs, L_Type);
354 -- We start by assuming that the move can be done in either direction,
355 -- i.e. that the two sides are completely disjoint.
357 Set_Forwards_OK (N, True);
358 Set_Backwards_OK (N, True);
360 -- Normally it is only the slice case that can lead to overlap, and
361 -- explicit checks for slices are made below. But there is one case
362 -- where the slice can be implicit and invisible to us: when we have a
363 -- one dimensional array, and either both operands are parameters, or
364 -- one is a parameter (which can be a slice passed by reference) and the
365 -- other is a non-local variable. In this case the parameter could be a
366 -- slice that overlaps with the other operand.
368 -- However, if the array subtype is a constrained first subtype in the
369 -- parameter case, then we don't have to worry about overlap, since
370 -- slice assignments aren't possible (other than for a slice denoting
373 -- Note: No overlap is possible if there is a change of representation,
374 -- so we can exclude this case.
379 ((Lhs_Formal and Rhs_Formal)
381 (Lhs_Formal and Rhs_Non_Local_Var)
383 (Rhs_Formal and Lhs_Non_Local_Var))
385 (not Is_Constrained (Etype (Lhs))
386 or else not Is_First_Subtype (Etype (Lhs)))
388 Set_Forwards_OK (N, False);
389 Set_Backwards_OK (N, False);
391 -- Note: the bit-packed case is not worrisome here, since if we have
392 -- a slice passed as a parameter, it is always aligned on a byte
393 -- boundary, and if there are no explicit slices, the assignment
394 -- can be performed directly.
397 -- If either operand has an address clause clear Backwards_OK and
398 -- Forwards_OK, since we cannot tell if the operands overlap. We
399 -- exclude this treatment when Rhs is an aggregate, since we know
400 -- that overlap can't occur.
402 if (Has_Address_Clause (Lhs) and then Nkind (Rhs) /= N_Aggregate)
403 or else Has_Address_Clause (Rhs)
405 Set_Forwards_OK (N, False);
406 Set_Backwards_OK (N, False);
409 -- We certainly must use a loop for change of representation and also
410 -- we use the operand of the conversion on the right hand side as the
411 -- effective right hand side (the component types must match in this
415 Act_Rhs := Get_Referenced_Object (Rhs);
416 R_Type := Get_Actual_Subtype (Act_Rhs);
417 Loop_Required := True;
419 -- We require a loop if the left side is possibly bit unaligned
421 elsif Possible_Bit_Aligned_Component (Lhs)
423 Possible_Bit_Aligned_Component (Rhs)
425 Loop_Required := True;
427 -- Arrays with controlled components are expanded into a loop to force
428 -- calls to Adjust at the component level.
430 elsif Has_Controlled_Component (L_Type) then
431 Loop_Required := True;
433 -- If object is atomic/VFA, we cannot tolerate a loop
435 elsif Is_Atomic_Or_VFA_Object (Act_Lhs)
437 Is_Atomic_Or_VFA_Object (Act_Rhs)
441 -- Loop is required if we have atomic components since we have to
442 -- be sure to do any accesses on an element by element basis.
444 elsif Has_Atomic_Components (L_Type)
445 or else Has_Atomic_Components (R_Type)
446 or else Is_Atomic_Or_VFA (Component_Type (L_Type))
447 or else Is_Atomic_Or_VFA (Component_Type (R_Type))
449 Loop_Required := True;
451 -- Case where no slice is involved
453 elsif not L_Slice and not R_Slice then
455 -- The following code deals with the case of unconstrained bit packed
456 -- arrays. The problem is that the template for such arrays contains
457 -- the bounds of the actual source level array, but the copy of an
458 -- entire array requires the bounds of the underlying array. It would
459 -- be nice if the back end could take care of this, but right now it
460 -- does not know how, so if we have such a type, then we expand out
461 -- into a loop, which is inefficient but works correctly. If we don't
462 -- do this, we get the wrong length computed for the array to be
463 -- moved. The two cases we need to worry about are:
465 -- Explicit dereference of an unconstrained packed array type as in
466 -- the following example:
469 -- type BITS is array(INTEGER range <>) of BOOLEAN;
470 -- pragma PACK(BITS);
471 -- type A is access BITS;
474 -- P1 := new BITS (1 .. 65_535);
475 -- P2 := new BITS (1 .. 65_535);
479 -- A formal parameter reference with an unconstrained bit array type
480 -- is the other case we need to worry about (here we assume the same
481 -- BITS type declared above):
483 -- procedure Write_All (File : out BITS; Contents : BITS);
485 -- File.Storage := Contents;
488 -- We expand to a loop in either of these two cases
490 -- Question for future thought. Another potentially more efficient
491 -- approach would be to create the actual subtype, and then do an
492 -- unchecked conversion to this actual subtype ???
494 Check_Unconstrained_Bit_Packed_Array : declare
496 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean;
497 -- Function to perform required test for the first case, above
498 -- (dereference of an unconstrained bit packed array).
500 -----------------------
501 -- Is_UBPA_Reference --
502 -----------------------
504 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean is
505 Typ : constant Entity_Id := Underlying_Type (Etype (Opnd));
507 Des_Type : Entity_Id;
510 if Present (Packed_Array_Impl_Type (Typ))
511 and then Is_Array_Type (Packed_Array_Impl_Type (Typ))
512 and then not Is_Constrained (Packed_Array_Impl_Type (Typ))
516 elsif Nkind (Opnd) = N_Explicit_Dereference then
517 P_Type := Underlying_Type (Etype (Prefix (Opnd)));
519 if not Is_Access_Type (P_Type) then
523 Des_Type := Designated_Type (P_Type);
525 Is_Bit_Packed_Array (Des_Type)
526 and then not Is_Constrained (Des_Type);
532 end Is_UBPA_Reference;
534 -- Start of processing for Check_Unconstrained_Bit_Packed_Array
537 if Is_UBPA_Reference (Lhs)
539 Is_UBPA_Reference (Rhs)
541 Loop_Required := True;
543 -- Here if we do not have the case of a reference to a bit packed
544 -- unconstrained array case. In this case gigi can most certainly
545 -- handle the assignment if a forwards move is allowed.
547 -- (could it handle the backwards case also???)
549 elsif Forwards_OK (N) then
552 end Check_Unconstrained_Bit_Packed_Array;
554 -- The back end can always handle the assignment if the right side is a
555 -- string literal (note that overlap is definitely impossible in this
556 -- case). If the type is packed, a string literal is always converted
557 -- into an aggregate, except in the case of a null slice, for which no
558 -- aggregate can be written. In that case, rewrite the assignment as a
559 -- null statement, a length check has already been emitted to verify
560 -- that the range of the left-hand side is empty.
562 -- Note that this code is not executed if we have an assignment of a
563 -- string literal to a non-bit aligned component of a record, a case
564 -- which cannot be handled by the backend.
566 elsif Nkind (Rhs) = N_String_Literal then
567 if String_Length (Strval (Rhs)) = 0
568 and then Is_Bit_Packed_Array (L_Type)
570 Rewrite (N, Make_Null_Statement (Loc));
576 -- If either operand is bit packed, then we need a loop, since we can't
577 -- be sure that the slice is byte aligned. Similarly, if either operand
578 -- is a possibly unaligned slice, then we need a loop (since the back
579 -- end cannot handle unaligned slices).
581 elsif Is_Bit_Packed_Array (L_Type)
582 or else Is_Bit_Packed_Array (R_Type)
583 or else Is_Possibly_Unaligned_Slice (Lhs)
584 or else Is_Possibly_Unaligned_Slice (Rhs)
586 Loop_Required := True;
588 -- If we are not bit-packed, and we have only one slice, then no overlap
589 -- is possible except in the parameter case, so we can let the back end
592 elsif not (L_Slice and R_Slice) then
593 if Forwards_OK (N) then
598 -- If the right-hand side is a string literal, introduce a temporary for
599 -- it, for use in the generated loop that will follow.
601 if Nkind (Rhs) = N_String_Literal then
603 Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Rhs);
608 Make_Object_Declaration (Loc,
609 Defining_Identifier => Temp,
610 Object_Definition => New_Occurrence_Of (L_Type, Loc),
611 Expression => Relocate_Node (Rhs));
613 Insert_Action (N, Decl);
614 Rewrite (Rhs, New_Occurrence_Of (Temp, Loc));
615 R_Type := Etype (Temp);
619 -- Come here to complete the analysis
621 -- Loop_Required: Set to True if we know that a loop is required
622 -- regardless of overlap considerations.
624 -- Forwards_OK: Set to False if we already know that a forwards
625 -- move is not safe, else set to True.
627 -- Backwards_OK: Set to False if we already know that a backwards
628 -- move is not safe, else set to True
630 -- Our task at this stage is to complete the overlap analysis, which can
631 -- result in possibly setting Forwards_OK or Backwards_OK to False, and
632 -- then generating the final code, either by deciding that it is OK
633 -- after all to let Gigi handle it, or by generating appropriate code
637 L_Index_Typ : constant Node_Id := Etype (First_Index (L_Type));
638 R_Index_Typ : constant Node_Id := Etype (First_Index (R_Type));
640 Left_Lo : constant Node_Id := Type_Low_Bound (L_Index_Typ);
641 Left_Hi : constant Node_Id := Type_High_Bound (L_Index_Typ);
642 Right_Lo : constant Node_Id := Type_Low_Bound (R_Index_Typ);
643 Right_Hi : constant Node_Id := Type_High_Bound (R_Index_Typ);
645 Act_L_Array : Node_Id;
646 Act_R_Array : Node_Id;
652 Cresult : Compare_Result;
655 -- Get the expressions for the arrays. If we are dealing with a
656 -- private type, then convert to the underlying type. We can do
657 -- direct assignments to an array that is a private type, but we
658 -- cannot assign to elements of the array without this extra
659 -- unchecked conversion.
661 -- Note: We propagate Parent to the conversion nodes to generate
662 -- a well-formed subtree.
664 if Nkind (Act_Lhs) = N_Slice then
665 Larray := Prefix (Act_Lhs);
669 if Is_Private_Type (Etype (Larray)) then
671 Par : constant Node_Id := Parent (Larray);
675 (Underlying_Type (Etype (Larray)), Larray);
676 Set_Parent (Larray, Par);
681 if Nkind (Act_Rhs) = N_Slice then
682 Rarray := Prefix (Act_Rhs);
686 if Is_Private_Type (Etype (Rarray)) then
688 Par : constant Node_Id := Parent (Rarray);
692 (Underlying_Type (Etype (Rarray)), Rarray);
693 Set_Parent (Rarray, Par);
698 -- If both sides are slices, we must figure out whether it is safe
699 -- to do the move in one direction or the other. It is always safe
700 -- if there is a change of representation since obviously two arrays
701 -- with different representations cannot possibly overlap.
703 if (not Crep) and L_Slice and R_Slice then
704 Act_L_Array := Get_Referenced_Object (Prefix (Act_Lhs));
705 Act_R_Array := Get_Referenced_Object (Prefix (Act_Rhs));
707 -- If both left and right hand arrays are entity names, and refer
708 -- to different entities, then we know that the move is safe (the
709 -- two storage areas are completely disjoint).
711 if Is_Entity_Name (Act_L_Array)
712 and then Is_Entity_Name (Act_R_Array)
713 and then Entity (Act_L_Array) /= Entity (Act_R_Array)
717 -- Otherwise, we assume the worst, which is that the two arrays
718 -- are the same array. There is no need to check if we know that
719 -- is the case, because if we don't know it, we still have to
722 -- Generally if the same array is involved, then we have an
723 -- overlapping case. We will have to really assume the worst (i.e.
724 -- set neither of the OK flags) unless we can determine the lower
725 -- or upper bounds at compile time and compare them.
730 (Left_Lo, Right_Lo, Assume_Valid => True);
732 if Cresult = Unknown then
735 (Left_Hi, Right_Hi, Assume_Valid => True);
739 when LT | LE | EQ => Set_Backwards_OK (N, False);
740 when GT | GE => Set_Forwards_OK (N, False);
741 when NE | Unknown => Set_Backwards_OK (N, False);
742 Set_Forwards_OK (N, False);
747 -- If after that analysis Loop_Required is False, meaning that we
748 -- have not discovered some non-overlap reason for requiring a loop,
749 -- then the outcome depends on the capabilities of the back end.
751 if not Loop_Required then
753 -- The GCC back end can deal with all cases of overlap by falling
754 -- back to memmove if it cannot use a more efficient approach.
756 if not AAMP_On_Target then
759 -- Assume other back ends can handle it if Forwards_OK is set
761 elsif Forwards_OK (N) then
764 -- If Forwards_OK is not set, the back end will need something
765 -- like memmove to handle the move. For now, this processing is
766 -- activated using the .s debug flag (-gnatd.s).
768 elsif Debug_Flag_Dot_S then
773 -- At this stage we have to generate an explicit loop, and we have
774 -- the following cases:
776 -- Forwards_OK = True
778 -- Rnn : right_index := right_index'First;
779 -- for Lnn in left-index loop
780 -- left (Lnn) := right (Rnn);
781 -- Rnn := right_index'Succ (Rnn);
784 -- Note: the above code MUST be analyzed with checks off, because
785 -- otherwise the Succ could overflow. But in any case this is more
788 -- Forwards_OK = False, Backwards_OK = True
790 -- Rnn : right_index := right_index'Last;
791 -- for Lnn in reverse left-index loop
792 -- left (Lnn) := right (Rnn);
793 -- Rnn := right_index'Pred (Rnn);
796 -- Note: the above code MUST be analyzed with checks off, because
797 -- otherwise the Pred could overflow. But in any case this is more
800 -- Forwards_OK = Backwards_OK = False
802 -- This only happens if we have the same array on each side. It is
803 -- possible to create situations using overlays that violate this,
804 -- but we simply do not promise to get this "right" in this case.
806 -- There are two possible subcases. If the No_Implicit_Conditionals
807 -- restriction is set, then we generate the following code:
810 -- T : constant <operand-type> := rhs;
815 -- If implicit conditionals are permitted, then we generate:
817 -- if Left_Lo <= Right_Lo then
818 -- <code for Forwards_OK = True above>
820 -- <code for Backwards_OK = True above>
823 -- In order to detect possible aliasing, we examine the renamed
824 -- expression when the source or target is a renaming. However,
825 -- the renaming may be intended to capture an address that may be
826 -- affected by subsequent code, and therefore we must recover
827 -- the actual entity for the expansion that follows, not the
828 -- object it renames. In particular, if source or target designate
829 -- a portion of a dynamically allocated object, the pointer to it
830 -- may be reassigned but the renaming preserves the proper location.
832 if Is_Entity_Name (Rhs)
834 Nkind (Parent (Entity (Rhs))) = N_Object_Renaming_Declaration
835 and then Nkind (Act_Rhs) = N_Slice
840 if Is_Entity_Name (Lhs)
842 Nkind (Parent (Entity (Lhs))) = N_Object_Renaming_Declaration
843 and then Nkind (Act_Lhs) = N_Slice
848 -- Cases where either Forwards_OK or Backwards_OK is true
850 if Forwards_OK (N) or else Backwards_OK (N) then
851 if Needs_Finalization (Component_Type (L_Type))
852 and then Base_Type (L_Type) = Base_Type (R_Type)
854 and then not No_Ctrl_Actions (N)
857 Proc : constant Entity_Id :=
858 TSS (Base_Type (L_Type), TSS_Slice_Assign);
862 Apply_Dereference (Larray);
863 Apply_Dereference (Rarray);
864 Actuals := New_List (
865 Duplicate_Subexpr (Larray, Name_Req => True),
866 Duplicate_Subexpr (Rarray, Name_Req => True),
867 Duplicate_Subexpr (Left_Lo, Name_Req => True),
868 Duplicate_Subexpr (Left_Hi, Name_Req => True),
869 Duplicate_Subexpr (Right_Lo, Name_Req => True),
870 Duplicate_Subexpr (Right_Hi, Name_Req => True));
874 Boolean_Literals (not Forwards_OK (N)), Loc));
877 Make_Procedure_Call_Statement (Loc,
878 Name => New_Occurrence_Of (Proc, Loc),
879 Parameter_Associations => Actuals));
884 Expand_Assign_Array_Loop
885 (N, Larray, Rarray, L_Type, R_Type, Ndim,
886 Rev => not Forwards_OK (N)));
889 -- Case of both are false with No_Implicit_Conditionals
891 elsif Restriction_Active (No_Implicit_Conditionals) then
893 T : constant Entity_Id :=
894 Make_Defining_Identifier (Loc, Chars => Name_T);
898 Make_Block_Statement (Loc,
899 Declarations => New_List (
900 Make_Object_Declaration (Loc,
901 Defining_Identifier => T,
902 Constant_Present => True,
904 New_Occurrence_Of (Etype (Rhs), Loc),
905 Expression => Relocate_Node (Rhs))),
907 Handled_Statement_Sequence =>
908 Make_Handled_Sequence_Of_Statements (Loc,
909 Statements => New_List (
910 Make_Assignment_Statement (Loc,
911 Name => Relocate_Node (Lhs),
912 Expression => New_Occurrence_Of (T, Loc))))));
915 -- Case of both are false with implicit conditionals allowed
918 -- Before we generate this code, we must ensure that the left and
919 -- right side array types are defined. They may be itypes, and we
920 -- cannot let them be defined inside the if, since the first use
921 -- in the then may not be executed.
923 Ensure_Defined (L_Type, N);
924 Ensure_Defined (R_Type, N);
926 -- We normally compare addresses to find out which way round to
927 -- do the loop, since this is reliable, and handles the cases of
928 -- parameters, conversions etc. But we can't do that in the bit
929 -- packed case, because addresses don't work there.
931 if not Is_Bit_Packed_Array (L_Type) then
935 Unchecked_Convert_To (RTE (RE_Integer_Address),
936 Make_Attribute_Reference (Loc,
938 Make_Indexed_Component (Loc,
940 Duplicate_Subexpr_Move_Checks (Larray, True),
941 Expressions => New_List (
942 Make_Attribute_Reference (Loc,
946 Attribute_Name => Name_First))),
947 Attribute_Name => Name_Address)),
950 Unchecked_Convert_To (RTE (RE_Integer_Address),
951 Make_Attribute_Reference (Loc,
953 Make_Indexed_Component (Loc,
955 Duplicate_Subexpr_Move_Checks (Rarray, True),
956 Expressions => New_List (
957 Make_Attribute_Reference (Loc,
961 Attribute_Name => Name_First))),
962 Attribute_Name => Name_Address)));
964 -- For the bit packed and VM cases we use the bounds. That's OK,
965 -- because we don't have to worry about parameters, since they
966 -- cannot cause overlap. Perhaps we should worry about weird slice
972 Cleft_Lo := New_Copy_Tree (Left_Lo);
973 Cright_Lo := New_Copy_Tree (Right_Lo);
975 -- If the types do not match we add an implicit conversion
976 -- here to ensure proper match
978 if Etype (Left_Lo) /= Etype (Right_Lo) then
980 Unchecked_Convert_To (Etype (Left_Lo), Cright_Lo);
983 -- Reset the Analyzed flag, because the bounds of the index
984 -- type itself may be universal, and must must be reanalyzed
985 -- to acquire the proper type for the back end.
987 Set_Analyzed (Cleft_Lo, False);
988 Set_Analyzed (Cright_Lo, False);
992 Left_Opnd => Cleft_Lo,
993 Right_Opnd => Cright_Lo);
996 if Needs_Finalization (Component_Type (L_Type))
997 and then Base_Type (L_Type) = Base_Type (R_Type)
999 and then not No_Ctrl_Actions (N)
1002 -- Call TSS procedure for array assignment, passing the
1003 -- explicit bounds of right and left hand sides.
1006 Proc : constant Entity_Id :=
1007 TSS (Base_Type (L_Type), TSS_Slice_Assign);
1011 Apply_Dereference (Larray);
1012 Apply_Dereference (Rarray);
1013 Actuals := New_List (
1014 Duplicate_Subexpr (Larray, Name_Req => True),
1015 Duplicate_Subexpr (Rarray, Name_Req => True),
1016 Duplicate_Subexpr (Left_Lo, Name_Req => True),
1017 Duplicate_Subexpr (Left_Hi, Name_Req => True),
1018 Duplicate_Subexpr (Right_Lo, Name_Req => True),
1019 Duplicate_Subexpr (Right_Hi, Name_Req => True));
1023 Right_Opnd => Condition));
1026 Make_Procedure_Call_Statement (Loc,
1027 Name => New_Occurrence_Of (Proc, Loc),
1028 Parameter_Associations => Actuals));
1033 Make_Implicit_If_Statement (N,
1034 Condition => Condition,
1036 Then_Statements => New_List (
1037 Expand_Assign_Array_Loop
1038 (N, Larray, Rarray, L_Type, R_Type, Ndim,
1041 Else_Statements => New_List (
1042 Expand_Assign_Array_Loop
1043 (N, Larray, Rarray, L_Type, R_Type, Ndim,
1048 Analyze (N, Suppress => All_Checks);
1052 when RE_Not_Available =>
1054 end Expand_Assign_Array;
1056 ------------------------------
1057 -- Expand_Assign_Array_Loop --
1058 ------------------------------
1060 -- The following is an example of the loop generated for the case of a
1061 -- two-dimensional array:
1064 -- R2b : Tm1X1 := 1;
1066 -- for L1b in 1 .. 100 loop
1068 -- R4b : Tm1X2 := 1;
1070 -- for L3b in 1 .. 100 loop
1071 -- vm1 (L1b, L3b) := vm2 (R2b, R4b);
1072 -- R4b := Tm1X2'succ(R4b);
1075 -- R2b := Tm1X1'succ(R2b);
1079 -- Here Rev is False, and Tm1Xn are the subscript types for the right hand
1080 -- side. The declarations of R2b and R4b are inserted before the original
1081 -- assignment statement.
1083 function Expand_Assign_Array_Loop
1090 Rev : Boolean) return Node_Id
1092 Loc : constant Source_Ptr := Sloc (N);
1094 Lnn : array (1 .. Ndim) of Entity_Id;
1095 Rnn : array (1 .. Ndim) of Entity_Id;
1096 -- Entities used as subscripts on left and right sides
1098 L_Index_Type : array (1 .. Ndim) of Entity_Id;
1099 R_Index_Type : array (1 .. Ndim) of Entity_Id;
1100 -- Left and right index types
1107 function Build_Step (J : Nat) return Node_Id;
1108 -- The increment step for the index of the right-hand side is written
1109 -- as an attribute reference (Succ or Pred). This function returns
1110 -- the corresponding node, which is placed at the end of the loop body.
1116 function Build_Step (J : Nat) return Node_Id is
1128 Make_Assignment_Statement (Loc,
1129 Name => New_Occurrence_Of (Rnn (J), Loc),
1131 Make_Attribute_Reference (Loc,
1133 New_Occurrence_Of (R_Index_Type (J), Loc),
1134 Attribute_Name => S_Or_P,
1135 Expressions => New_List (
1136 New_Occurrence_Of (Rnn (J), Loc))));
1138 -- Note that on the last iteration of the loop, the index is increased
1139 -- (or decreased) past the corresponding bound. This is consistent with
1140 -- the C semantics of the back-end, where such an off-by-one value on a
1141 -- dead index variable is OK. However, in CodePeer mode this leads to
1142 -- spurious warnings, and thus we place a guard around the attribute
1143 -- reference. For obvious reasons we only do this for CodePeer.
1145 if CodePeer_Mode then
1147 Make_If_Statement (Loc,
1150 Left_Opnd => New_Occurrence_Of (Lnn (J), Loc),
1152 Make_Attribute_Reference (Loc,
1153 Prefix => New_Occurrence_Of (L_Index_Type (J), Loc),
1154 Attribute_Name => Lim)),
1155 Then_Statements => New_List (Step));
1161 -- Start of processing for Expand_Assign_Array_Loop
1165 F_Or_L := Name_Last;
1166 S_Or_P := Name_Pred;
1168 F_Or_L := Name_First;
1169 S_Or_P := Name_Succ;
1172 -- Setup index types and subscript entities
1179 L_Index := First_Index (L_Type);
1180 R_Index := First_Index (R_Type);
1182 for J in 1 .. Ndim loop
1183 Lnn (J) := Make_Temporary (Loc, 'L');
1184 Rnn (J) := Make_Temporary (Loc, 'R');
1186 L_Index_Type (J) := Etype (L_Index);
1187 R_Index_Type (J) := Etype (R_Index);
1189 Next_Index (L_Index);
1190 Next_Index (R_Index);
1194 -- Now construct the assignment statement
1197 ExprL : constant List_Id := New_List;
1198 ExprR : constant List_Id := New_List;
1201 for J in 1 .. Ndim loop
1202 Append_To (ExprL, New_Occurrence_Of (Lnn (J), Loc));
1203 Append_To (ExprR, New_Occurrence_Of (Rnn (J), Loc));
1207 Make_Assignment_Statement (Loc,
1209 Make_Indexed_Component (Loc,
1210 Prefix => Duplicate_Subexpr (Larray, Name_Req => True),
1211 Expressions => ExprL),
1213 Make_Indexed_Component (Loc,
1214 Prefix => Duplicate_Subexpr (Rarray, Name_Req => True),
1215 Expressions => ExprR));
1217 -- We set assignment OK, since there are some cases, e.g. in object
1218 -- declarations, where we are actually assigning into a constant.
1219 -- If there really is an illegality, it was caught long before now,
1220 -- and was flagged when the original assignment was analyzed.
1222 Set_Assignment_OK (Name (Assign));
1224 -- Propagate the No_Ctrl_Actions flag to individual assignments
1226 Set_No_Ctrl_Actions (Assign, No_Ctrl_Actions (N));
1229 -- Now construct the loop from the inside out, with the last subscript
1230 -- varying most rapidly. Note that Assign is first the raw assignment
1231 -- statement, and then subsequently the loop that wraps it up.
1233 for J in reverse 1 .. Ndim loop
1235 Make_Block_Statement (Loc,
1236 Declarations => New_List (
1237 Make_Object_Declaration (Loc,
1238 Defining_Identifier => Rnn (J),
1239 Object_Definition =>
1240 New_Occurrence_Of (R_Index_Type (J), Loc),
1242 Make_Attribute_Reference (Loc,
1243 Prefix => New_Occurrence_Of (R_Index_Type (J), Loc),
1244 Attribute_Name => F_Or_L))),
1246 Handled_Statement_Sequence =>
1247 Make_Handled_Sequence_Of_Statements (Loc,
1248 Statements => New_List (
1249 Make_Implicit_Loop_Statement (N,
1251 Make_Iteration_Scheme (Loc,
1252 Loop_Parameter_Specification =>
1253 Make_Loop_Parameter_Specification (Loc,
1254 Defining_Identifier => Lnn (J),
1255 Reverse_Present => Rev,
1256 Discrete_Subtype_Definition =>
1257 New_Occurrence_Of (L_Index_Type (J), Loc))),
1259 Statements => New_List (Assign, Build_Step (J))))));
1263 end Expand_Assign_Array_Loop;
1265 --------------------------
1266 -- Expand_Assign_Record --
1267 --------------------------
1269 procedure Expand_Assign_Record (N : Node_Id) is
1270 Lhs : constant Node_Id := Name (N);
1271 Rhs : Node_Id := Expression (N);
1272 L_Typ : constant Entity_Id := Base_Type (Etype (Lhs));
1275 -- If change of representation, then extract the real right hand side
1276 -- from the type conversion, and proceed with component-wise assignment,
1277 -- since the two types are not the same as far as the back end is
1280 if Change_Of_Representation (N) then
1281 Rhs := Expression (Rhs);
1283 -- If this may be a case of a large bit aligned component, then proceed
1284 -- with component-wise assignment, to avoid possible clobbering of other
1285 -- components sharing bits in the first or last byte of the component to
1288 elsif Possible_Bit_Aligned_Component (Lhs)
1290 Possible_Bit_Aligned_Component (Rhs)
1294 -- If we have a tagged type that has a complete record representation
1295 -- clause, we must do we must do component-wise assignments, since child
1296 -- types may have used gaps for their components, and we might be
1297 -- dealing with a view conversion.
1299 elsif Is_Fully_Repped_Tagged_Type (L_Typ) then
1302 -- If neither condition met, then nothing special to do, the back end
1303 -- can handle assignment of the entire component as a single entity.
1309 -- At this stage we know that we must do a component wise assignment
1312 Loc : constant Source_Ptr := Sloc (N);
1313 R_Typ : constant Entity_Id := Base_Type (Etype (Rhs));
1314 Decl : constant Node_Id := Declaration_Node (R_Typ);
1318 function Find_Component
1320 Comp : Entity_Id) return Entity_Id;
1321 -- Find the component with the given name in the underlying record
1322 -- declaration for Typ. We need to use the actual entity because the
1323 -- type may be private and resolution by identifier alone would fail.
1325 function Make_Component_List_Assign
1327 U_U : Boolean := False) return List_Id;
1328 -- Returns a sequence of statements to assign the components that
1329 -- are referenced in the given component list. The flag U_U is
1330 -- used to force the usage of the inferred value of the variant
1331 -- part expression as the switch for the generated case statement.
1333 function Make_Field_Assign
1335 U_U : Boolean := False) return Node_Id;
1336 -- Given C, the entity for a discriminant or component, build an
1337 -- assignment for the corresponding field values. The flag U_U
1338 -- signals the presence of an Unchecked_Union and forces the usage
1339 -- of the inferred discriminant value of C as the right hand side
1340 -- of the assignment.
1342 function Make_Field_Assigns (CI : List_Id) return List_Id;
1343 -- Given CI, a component items list, construct series of statements
1344 -- for fieldwise assignment of the corresponding components.
1346 --------------------
1347 -- Find_Component --
1348 --------------------
1350 function Find_Component
1352 Comp : Entity_Id) return Entity_Id
1354 Utyp : constant Entity_Id := Underlying_Type (Typ);
1358 C := First_Entity (Utyp);
1359 while Present (C) loop
1360 if Chars (C) = Chars (Comp) then
1367 raise Program_Error;
1370 --------------------------------
1371 -- Make_Component_List_Assign --
1372 --------------------------------
1374 function Make_Component_List_Assign
1376 U_U : Boolean := False) return List_Id
1378 CI : constant List_Id := Component_Items (CL);
1379 VP : constant Node_Id := Variant_Part (CL);
1389 Result := Make_Field_Assigns (CI);
1391 if Present (VP) then
1392 V := First_Non_Pragma (Variants (VP));
1394 while Present (V) loop
1396 DC := First (Discrete_Choices (V));
1397 while Present (DC) loop
1398 Append_To (DCH, New_Copy_Tree (DC));
1403 Make_Case_Statement_Alternative (Loc,
1404 Discrete_Choices => DCH,
1406 Make_Component_List_Assign (Component_List (V))));
1407 Next_Non_Pragma (V);
1410 -- If we have an Unchecked_Union, use the value of the inferred
1411 -- discriminant of the variant part expression as the switch
1412 -- for the case statement. The case statement may later be
1417 New_Copy (Get_Discriminant_Value (
1420 Discriminant_Constraint (Etype (Rhs))));
1423 Make_Selected_Component (Loc,
1424 Prefix => Duplicate_Subexpr (Rhs),
1426 Make_Identifier (Loc, Chars (Name (VP))));
1430 Make_Case_Statement (Loc,
1432 Alternatives => Alts));
1436 end Make_Component_List_Assign;
1438 -----------------------
1439 -- Make_Field_Assign --
1440 -----------------------
1442 function Make_Field_Assign
1444 U_U : Boolean := False) return Node_Id
1450 -- In the case of an Unchecked_Union, use the discriminant
1451 -- constraint value as on the right hand side of the assignment.
1455 New_Copy (Get_Discriminant_Value (C,
1457 Discriminant_Constraint (Etype (Rhs))));
1460 Make_Selected_Component (Loc,
1461 Prefix => Duplicate_Subexpr (Rhs),
1462 Selector_Name => New_Occurrence_Of (C, Loc));
1466 Make_Assignment_Statement (Loc,
1468 Make_Selected_Component (Loc,
1469 Prefix => Duplicate_Subexpr (Lhs),
1471 New_Occurrence_Of (Find_Component (L_Typ, C), Loc)),
1472 Expression => Expr);
1474 -- Set Assignment_OK, so discriminants can be assigned
1476 Set_Assignment_OK (Name (A), True);
1478 if Componentwise_Assignment (N)
1479 and then Nkind (Name (A)) = N_Selected_Component
1480 and then Chars (Selector_Name (Name (A))) = Name_uParent
1482 Set_Componentwise_Assignment (A);
1486 end Make_Field_Assign;
1488 ------------------------
1489 -- Make_Field_Assigns --
1490 ------------------------
1492 function Make_Field_Assigns (CI : List_Id) return List_Id is
1500 while Present (Item) loop
1502 -- Look for components, but exclude _tag field assignment if
1503 -- the special Componentwise_Assignment flag is set.
1505 if Nkind (Item) = N_Component_Declaration
1506 and then not (Is_Tag (Defining_Identifier (Item))
1507 and then Componentwise_Assignment (N))
1510 (Result, Make_Field_Assign (Defining_Identifier (Item)));
1517 end Make_Field_Assigns;
1519 -- Start of processing for Expand_Assign_Record
1522 -- Note that we use the base types for this processing. This results
1523 -- in some extra work in the constrained case, but the change of
1524 -- representation case is so unusual that it is not worth the effort.
1526 -- First copy the discriminants. This is done unconditionally. It
1527 -- is required in the unconstrained left side case, and also in the
1528 -- case where this assignment was constructed during the expansion
1529 -- of a type conversion (since initialization of discriminants is
1530 -- suppressed in this case). It is unnecessary but harmless in
1533 if Has_Discriminants (L_Typ) then
1534 F := First_Discriminant (R_Typ);
1535 while Present (F) loop
1537 -- If we are expanding the initialization of a derived record
1538 -- that constrains or renames discriminants of the parent, we
1539 -- must use the corresponding discriminant in the parent.
1546 and then Present (Corresponding_Discriminant (F))
1548 CF := Corresponding_Discriminant (F);
1553 if Is_Unchecked_Union (Base_Type (R_Typ)) then
1555 -- Within an initialization procedure this is the
1556 -- assignment to an unchecked union component, in which
1557 -- case there is no discriminant to initialize.
1559 if Inside_Init_Proc then
1563 -- The assignment is part of a conversion from a
1564 -- derived unchecked union type with an inferable
1565 -- discriminant, to a parent type.
1567 Insert_Action (N, Make_Field_Assign (CF, True));
1571 Insert_Action (N, Make_Field_Assign (CF));
1574 Next_Discriminant (F);
1579 -- We know the underlying type is a record, but its current view
1580 -- may be private. We must retrieve the usable record declaration.
1582 if Nkind_In (Decl, N_Private_Type_Declaration,
1583 N_Private_Extension_Declaration)
1584 and then Present (Full_View (R_Typ))
1586 RDef := Type_Definition (Declaration_Node (Full_View (R_Typ)));
1588 RDef := Type_Definition (Decl);
1591 if Nkind (RDef) = N_Derived_Type_Definition then
1592 RDef := Record_Extension_Part (RDef);
1595 if Nkind (RDef) = N_Record_Definition
1596 and then Present (Component_List (RDef))
1598 if Is_Unchecked_Union (R_Typ) then
1600 Make_Component_List_Assign (Component_List (RDef), True));
1603 (N, Make_Component_List_Assign (Component_List (RDef)));
1606 Rewrite (N, Make_Null_Statement (Loc));
1609 end Expand_Assign_Record;
1611 -----------------------------------
1612 -- Expand_N_Assignment_Statement --
1613 -----------------------------------
1615 -- This procedure implements various cases where an assignment statement
1616 -- cannot just be passed on to the back end in untransformed state.
1618 procedure Expand_N_Assignment_Statement (N : Node_Id) is
1619 Crep : constant Boolean := Change_Of_Representation (N);
1620 Lhs : constant Node_Id := Name (N);
1621 Loc : constant Source_Ptr := Sloc (N);
1622 Rhs : constant Node_Id := Expression (N);
1623 Typ : constant Entity_Id := Underlying_Type (Etype (Lhs));
1626 Save_Ghost_Mode : constant Ghost_Mode_Type := Ghost_Mode;
1629 -- The assignment statement is Ghost when the left hand side is Ghost.
1630 -- Set the mode now to ensure that any nodes generated during expansion
1631 -- are properly marked as Ghost.
1635 -- Special case to check right away, if the Componentwise_Assignment
1636 -- flag is set, this is a reanalysis from the expansion of the primitive
1637 -- assignment procedure for a tagged type, and all we need to do is to
1638 -- expand to assignment of components, because otherwise, we would get
1639 -- infinite recursion (since this looks like a tagged assignment which
1640 -- would normally try to *call* the primitive assignment procedure).
1642 if Componentwise_Assignment (N) then
1643 Expand_Assign_Record (N);
1644 Ghost_Mode := Save_Ghost_Mode;
1648 -- Defend against invalid subscripts on left side if we are in standard
1649 -- validity checking mode. No need to do this if we are checking all
1652 -- Note that we do this right away, because there are some early return
1653 -- paths in this procedure, and this is required on all paths.
1655 if Validity_Checks_On
1656 and then Validity_Check_Default
1657 and then not Validity_Check_Subscripts
1659 Check_Valid_Lvalue_Subscripts (Lhs);
1662 -- Ada 2005 (AI-327): Handle assignment to priority of protected object
1664 -- Rewrite an assignment to X'Priority into a run-time call
1666 -- For example: X'Priority := New_Prio_Expr;
1667 -- ...is expanded into Set_Ceiling (X._Object, New_Prio_Expr);
1669 -- Note that although X'Priority is notionally an object, it is quite
1670 -- deliberately not defined as an aliased object in the RM. This means
1671 -- that it works fine to rewrite it as a call, without having to worry
1672 -- about complications that would other arise from X'Priority'Access,
1673 -- which is illegal, because of the lack of aliasing.
1675 if Ada_Version >= Ada_2005 then
1678 Conctyp : Entity_Id;
1681 RT_Subprg_Name : Node_Id;
1684 -- Handle chains of renamings
1687 while Nkind (Ent) in N_Has_Entity
1688 and then Present (Entity (Ent))
1689 and then Present (Renamed_Object (Entity (Ent)))
1691 Ent := Renamed_Object (Entity (Ent));
1694 -- The attribute Priority applied to protected objects has been
1695 -- previously expanded into a call to the Get_Ceiling run-time
1696 -- subprogram. In restricted profiles this is not available.
1698 if Nkind (Ent) = N_Function_Call
1699 and then not Configurable_Run_Time_Mode
1700 and then (Entity (Name (Ent)) = RTE (RE_Get_Ceiling)
1702 Entity (Name (Ent)) = RTE (RO_PE_Get_Ceiling))
1704 -- Look for the enclosing concurrent type
1706 Conctyp := Current_Scope;
1707 while not Is_Concurrent_Type (Conctyp) loop
1708 Conctyp := Scope (Conctyp);
1711 pragma Assert (Is_Protected_Type (Conctyp));
1713 -- Generate the first actual of the call
1715 Subprg := Current_Scope;
1716 while not Present (Protected_Body_Subprogram (Subprg)) loop
1717 Subprg := Scope (Subprg);
1720 -- Select the appropriate run-time call
1722 if Number_Entries (Conctyp) = 0 then
1724 New_Occurrence_Of (RTE (RE_Set_Ceiling), Loc);
1727 New_Occurrence_Of (RTE (RO_PE_Set_Ceiling), Loc);
1731 Make_Procedure_Call_Statement (Loc,
1732 Name => RT_Subprg_Name,
1733 Parameter_Associations => New_List (
1734 New_Copy_Tree (First (Parameter_Associations (Ent))),
1735 Relocate_Node (Expression (N))));
1740 Ghost_Mode := Save_Ghost_Mode;
1746 -- Deal with assignment checks unless suppressed
1748 if not Suppress_Assignment_Checks (N) then
1750 -- First deal with generation of range check if required
1752 if Do_Range_Check (Rhs) then
1753 Generate_Range_Check (Rhs, Typ, CE_Range_Check_Failed);
1756 -- Then generate predicate check if required
1758 Apply_Predicate_Check (Rhs, Typ);
1761 -- Check for a special case where a high level transformation is
1762 -- required. If we have either of:
1767 -- where P is a reference to a bit packed array, then we have to unwind
1768 -- the assignment. The exact meaning of being a reference to a bit
1769 -- packed array is as follows:
1771 -- An indexed component whose prefix is a bit packed array is a
1772 -- reference to a bit packed array.
1774 -- An indexed component or selected component whose prefix is a
1775 -- reference to a bit packed array is itself a reference ot a
1776 -- bit packed array.
1778 -- The required transformation is
1780 -- Tnn : prefix_type := P;
1781 -- Tnn.field := rhs;
1786 -- Tnn : prefix_type := P;
1787 -- Tnn (subscr) := rhs;
1790 -- Since P is going to be evaluated more than once, any subscripts
1791 -- in P must have their evaluation forced.
1793 if Nkind_In (Lhs, N_Indexed_Component, N_Selected_Component)
1794 and then Is_Ref_To_Bit_Packed_Array (Prefix (Lhs))
1797 BPAR_Expr : constant Node_Id := Relocate_Node (Prefix (Lhs));
1798 BPAR_Typ : constant Entity_Id := Etype (BPAR_Expr);
1799 Tnn : constant Entity_Id :=
1800 Make_Temporary (Loc, 'T', BPAR_Expr);
1803 -- Insert the post assignment first, because we want to copy the
1804 -- BPAR_Expr tree before it gets analyzed in the context of the
1805 -- pre assignment. Note that we do not analyze the post assignment
1806 -- yet (we cannot till we have completed the analysis of the pre
1807 -- assignment). As usual, the analysis of this post assignment
1808 -- will happen on its own when we "run into" it after finishing
1809 -- the current assignment.
1812 Make_Assignment_Statement (Loc,
1813 Name => New_Copy_Tree (BPAR_Expr),
1814 Expression => New_Occurrence_Of (Tnn, Loc)));
1816 -- At this stage BPAR_Expr is a reference to a bit packed array
1817 -- where the reference was not expanded in the original tree,
1818 -- since it was on the left side of an assignment. But in the
1819 -- pre-assignment statement (the object definition), BPAR_Expr
1820 -- will end up on the right hand side, and must be reexpanded. To
1821 -- achieve this, we reset the analyzed flag of all selected and
1822 -- indexed components down to the actual indexed component for
1823 -- the packed array.
1827 Set_Analyzed (Exp, False);
1830 (Exp, N_Selected_Component, N_Indexed_Component)
1832 Exp := Prefix (Exp);
1838 -- Now we can insert and analyze the pre-assignment
1840 -- If the right-hand side requires a transient scope, it has
1841 -- already been placed on the stack. However, the declaration is
1842 -- inserted in the tree outside of this scope, and must reflect
1843 -- the proper scope for its variable. This awkward bit is forced
1844 -- by the stricter scope discipline imposed by GCC 2.97.
1847 Uses_Transient_Scope : constant Boolean :=
1849 and then N = Node_To_Be_Wrapped;
1852 if Uses_Transient_Scope then
1853 Push_Scope (Scope (Current_Scope));
1856 Insert_Before_And_Analyze (N,
1857 Make_Object_Declaration (Loc,
1858 Defining_Identifier => Tnn,
1859 Object_Definition => New_Occurrence_Of (BPAR_Typ, Loc),
1860 Expression => BPAR_Expr));
1862 if Uses_Transient_Scope then
1867 -- Now fix up the original assignment and continue processing
1869 Rewrite (Prefix (Lhs),
1870 New_Occurrence_Of (Tnn, Loc));
1872 -- We do not need to reanalyze that assignment, and we do not need
1873 -- to worry about references to the temporary, but we do need to
1874 -- make sure that the temporary is not marked as a true constant
1875 -- since we now have a generated assignment to it.
1877 Set_Is_True_Constant (Tnn, False);
1881 -- When we have the appropriate type of aggregate in the expression (it
1882 -- has been determined during analysis of the aggregate by setting the
1883 -- delay flag), let's perform in place assignment and thus avoid
1884 -- creating a temporary.
1886 if Is_Delayed_Aggregate (Rhs) then
1887 Convert_Aggr_In_Assignment (N);
1888 Rewrite (N, Make_Null_Statement (Loc));
1891 Ghost_Mode := Save_Ghost_Mode;
1895 -- Apply discriminant check if required. If Lhs is an access type to a
1896 -- designated type with discriminants, we must always check. If the
1897 -- type has unknown discriminants, more elaborate processing below.
1899 if Has_Discriminants (Etype (Lhs))
1900 and then not Has_Unknown_Discriminants (Etype (Lhs))
1902 -- Skip discriminant check if change of representation. Will be
1903 -- done when the change of representation is expanded out.
1906 Apply_Discriminant_Check (Rhs, Etype (Lhs), Lhs);
1909 -- If the type is private without discriminants, and the full type
1910 -- has discriminants (necessarily with defaults) a check may still be
1911 -- necessary if the Lhs is aliased. The private discriminants must be
1912 -- visible to build the discriminant constraints.
1914 -- Only an explicit dereference that comes from source indicates
1915 -- aliasing. Access to formals of protected operations and entries
1916 -- create dereferences but are not semantic aliasings.
1918 elsif Is_Private_Type (Etype (Lhs))
1919 and then Has_Discriminants (Typ)
1920 and then Nkind (Lhs) = N_Explicit_Dereference
1921 and then Comes_From_Source (Lhs)
1924 Lt : constant Entity_Id := Etype (Lhs);
1925 Ubt : Entity_Id := Base_Type (Typ);
1928 -- In the case of an expander-generated record subtype whose base
1929 -- type still appears private, Typ will have been set to that
1930 -- private type rather than the underlying record type (because
1931 -- Underlying type will have returned the record subtype), so it's
1932 -- necessary to apply Underlying_Type again to the base type to
1933 -- get the record type we need for the discriminant check. Such
1934 -- subtypes can be created for assignments in certain cases, such
1935 -- as within an instantiation passed this kind of private type.
1936 -- It would be good to avoid this special test, but making changes
1937 -- to prevent this odd form of record subtype seems difficult. ???
1939 if Is_Private_Type (Ubt) then
1940 Ubt := Underlying_Type (Ubt);
1943 Set_Etype (Lhs, Ubt);
1944 Rewrite (Rhs, OK_Convert_To (Base_Type (Ubt), Rhs));
1945 Apply_Discriminant_Check (Rhs, Ubt, Lhs);
1946 Set_Etype (Lhs, Lt);
1949 -- If the Lhs has a private type with unknown discriminants, it may
1950 -- have a full view with discriminants, but those are nameable only
1951 -- in the underlying type, so convert the Rhs to it before potential
1952 -- checking. Convert Lhs as well, otherwise the actual subtype might
1953 -- not be constructible.
1955 elsif Has_Unknown_Discriminants (Base_Type (Etype (Lhs)))
1956 and then Has_Discriminants (Typ)
1958 Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
1959 Rewrite (Lhs, OK_Convert_To (Base_Type (Typ), Lhs));
1960 Apply_Discriminant_Check (Rhs, Typ, Lhs);
1962 -- In the access type case, we need the same discriminant check, and
1963 -- also range checks if we have an access to constrained array.
1965 elsif Is_Access_Type (Etype (Lhs))
1966 and then Is_Constrained (Designated_Type (Etype (Lhs)))
1968 if Has_Discriminants (Designated_Type (Etype (Lhs))) then
1970 -- Skip discriminant check if change of representation. Will be
1971 -- done when the change of representation is expanded out.
1974 Apply_Discriminant_Check (Rhs, Etype (Lhs));
1977 elsif Is_Array_Type (Designated_Type (Etype (Lhs))) then
1978 Apply_Range_Check (Rhs, Etype (Lhs));
1980 if Is_Constrained (Etype (Lhs)) then
1981 Apply_Length_Check (Rhs, Etype (Lhs));
1984 if Nkind (Rhs) = N_Allocator then
1986 Target_Typ : constant Entity_Id := Etype (Expression (Rhs));
1987 C_Es : Check_Result;
1994 Etype (Designated_Type (Etype (Lhs))));
2006 -- Apply range check for access type case
2008 elsif Is_Access_Type (Etype (Lhs))
2009 and then Nkind (Rhs) = N_Allocator
2010 and then Nkind (Expression (Rhs)) = N_Qualified_Expression
2012 Analyze_And_Resolve (Expression (Rhs));
2014 (Expression (Rhs), Designated_Type (Etype (Lhs)));
2017 -- Ada 2005 (AI-231): Generate the run-time check
2019 if Is_Access_Type (Typ)
2020 and then Can_Never_Be_Null (Etype (Lhs))
2021 and then not Can_Never_Be_Null (Etype (Rhs))
2023 -- If an actual is an out parameter of a null-excluding access
2024 -- type, there is access check on entry, so we set the flag
2025 -- Suppress_Assignment_Checks on the generated statement to
2026 -- assign the actual to the parameter block, and we do not want
2027 -- to generate an additional check at this point.
2029 and then not Suppress_Assignment_Checks (N)
2031 Apply_Constraint_Check (Rhs, Etype (Lhs));
2034 -- Ada 2012 (AI05-148): Update current accessibility level if Rhs is a
2035 -- stand-alone obj of an anonymous access type.
2037 if Is_Access_Type (Typ)
2038 and then Is_Entity_Name (Lhs)
2039 and then Present (Effective_Extra_Accessibility (Entity (Lhs)))
2042 function Lhs_Entity return Entity_Id;
2043 -- Look through renames to find the underlying entity.
2044 -- For assignment to a rename, we don't care about the
2045 -- Enclosing_Dynamic_Scope of the rename declaration.
2051 function Lhs_Entity return Entity_Id is
2052 Result : Entity_Id := Entity (Lhs);
2055 while Present (Renamed_Object (Result)) loop
2057 -- Renamed_Object must return an Entity_Name here
2058 -- because of preceding "Present (E_E_A (...))" test.
2060 Result := Entity (Renamed_Object (Result));
2066 -- Local Declarations
2068 Access_Check : constant Node_Id :=
2069 Make_Raise_Program_Error (Loc,
2073 Dynamic_Accessibility_Level (Rhs),
2075 Make_Integer_Literal (Loc,
2078 (Enclosing_Dynamic_Scope
2080 Reason => PE_Accessibility_Check_Failed);
2082 Access_Level_Update : constant Node_Id :=
2083 Make_Assignment_Statement (Loc,
2086 (Effective_Extra_Accessibility
2087 (Entity (Lhs)), Loc),
2089 Dynamic_Accessibility_Level (Rhs));
2092 if not Accessibility_Checks_Suppressed (Entity (Lhs)) then
2093 Insert_Action (N, Access_Check);
2096 Insert_Action (N, Access_Level_Update);
2100 -- Case of assignment to a bit packed array element. If there is a
2101 -- change of representation this must be expanded into components,
2102 -- otherwise this is a bit-field assignment.
2104 if Nkind (Lhs) = N_Indexed_Component
2105 and then Is_Bit_Packed_Array (Etype (Prefix (Lhs)))
2107 -- Normal case, no change of representation
2110 Expand_Bit_Packed_Element_Set (N);
2111 Ghost_Mode := Save_Ghost_Mode;
2114 -- Change of representation case
2117 -- Generate the following, to force component-by-component
2118 -- assignments in an efficient way. Otherwise each component
2119 -- will require a temporary and two bit-field manipulations.
2126 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T');
2132 Make_Object_Declaration (Loc,
2133 Defining_Identifier => Tnn,
2134 Object_Definition =>
2135 New_Occurrence_Of (Etype (Lhs), Loc)),
2136 Make_Assignment_Statement (Loc,
2137 Name => New_Occurrence_Of (Tnn, Loc),
2138 Expression => Relocate_Node (Rhs)),
2139 Make_Assignment_Statement (Loc,
2140 Name => Relocate_Node (Lhs),
2141 Expression => New_Occurrence_Of (Tnn, Loc)));
2143 Insert_Actions (N, Stats);
2144 Rewrite (N, Make_Null_Statement (Loc));
2149 -- Build-in-place function call case. Note that we're not yet doing
2150 -- build-in-place for user-written assignment statements (the assignment
2151 -- here came from an aggregate.)
2153 elsif Ada_Version >= Ada_2005
2154 and then Is_Build_In_Place_Function_Call (Rhs)
2156 Make_Build_In_Place_Call_In_Assignment (N, Rhs);
2158 elsif Is_Tagged_Type (Typ)
2159 or else (Needs_Finalization (Typ) and then not Is_Array_Type (Typ))
2161 Tagged_Case : declare
2162 L : List_Id := No_List;
2163 Expand_Ctrl_Actions : constant Boolean := not No_Ctrl_Actions (N);
2166 -- In the controlled case, we ensure that function calls are
2167 -- evaluated before finalizing the target. In all cases, it makes
2168 -- the expansion easier if the side-effects are removed first.
2170 Remove_Side_Effects (Lhs);
2171 Remove_Side_Effects (Rhs);
2173 -- Avoid recursion in the mechanism
2177 -- If dispatching assignment, we need to dispatch to _assign
2179 if Is_Class_Wide_Type (Typ)
2181 -- If the type is tagged, we may as well use the predefined
2182 -- primitive assignment. This avoids inlining a lot of code
2183 -- and in the class-wide case, the assignment is replaced
2184 -- by a dispatching call to _assign. It is suppressed in the
2185 -- case of assignments created by the expander that correspond
2186 -- to initializations, where we do want to copy the tag
2187 -- (Expand_Ctrl_Actions flag is set False in this case). It is
2188 -- also suppressed if restriction No_Dispatching_Calls is in
2189 -- force because in that case predefined primitives are not
2192 or else (Is_Tagged_Type (Typ)
2193 and then Chars (Current_Scope) /= Name_uAssign
2194 and then Expand_Ctrl_Actions
2196 not Restriction_Active (No_Dispatching_Calls))
2198 if Is_Limited_Type (Typ) then
2200 -- This can happen in an instance when the formal is an
2201 -- extension of a limited interface, and the actual is
2202 -- limited. This is an error according to AI05-0087, but
2203 -- is not caught at the point of instantiation in earlier
2206 -- This is wrong, error messages cannot be issued during
2207 -- expansion, since they would be missed in -gnatc mode ???
2209 Error_Msg_N ("assignment not available on limited type", N);
2210 Ghost_Mode := Save_Ghost_Mode;
2214 -- Fetch the primitive op _assign and proper type to call it.
2215 -- Because of possible conflicts between private and full view,
2216 -- fetch the proper type directly from the operation profile.
2219 Op : constant Entity_Id :=
2220 Find_Prim_Op (Typ, Name_uAssign);
2221 F_Typ : Entity_Id := Etype (First_Formal (Op));
2224 -- If the assignment is dispatching, make sure to use the
2227 if Is_Class_Wide_Type (Typ) then
2228 F_Typ := Class_Wide_Type (F_Typ);
2233 -- In case of assignment to a class-wide tagged type, before
2234 -- the assignment we generate run-time check to ensure that
2235 -- the tags of source and target match.
2237 if not Tag_Checks_Suppressed (Typ)
2238 and then Is_Class_Wide_Type (Typ)
2239 and then Is_Tagged_Type (Typ)
2240 and then Is_Tagged_Type (Underlying_Type (Etype (Rhs)))
2243 Make_Raise_Constraint_Error (Loc,
2247 Make_Selected_Component (Loc,
2248 Prefix => Duplicate_Subexpr (Lhs),
2250 Make_Identifier (Loc, Name_uTag)),
2252 Make_Selected_Component (Loc,
2253 Prefix => Duplicate_Subexpr (Rhs),
2255 Make_Identifier (Loc, Name_uTag))),
2256 Reason => CE_Tag_Check_Failed));
2260 Left_N : Node_Id := Duplicate_Subexpr (Lhs);
2261 Right_N : Node_Id := Duplicate_Subexpr (Rhs);
2264 -- In order to dispatch the call to _assign the type of
2265 -- the actuals must match. Add conversion (if required).
2267 if Etype (Lhs) /= F_Typ then
2268 Left_N := Unchecked_Convert_To (F_Typ, Left_N);
2271 if Etype (Rhs) /= F_Typ then
2272 Right_N := Unchecked_Convert_To (F_Typ, Right_N);
2276 Make_Procedure_Call_Statement (Loc,
2277 Name => New_Occurrence_Of (Op, Loc),
2278 Parameter_Associations => New_List (
2280 Node2 => Right_N)));
2285 L := Make_Tag_Ctrl_Assignment (N);
2287 -- We can't afford to have destructive Finalization Actions in
2288 -- the Self assignment case, so if the target and the source
2289 -- are not obviously different, code is generated to avoid the
2290 -- self assignment case:
2292 -- if lhs'address /= rhs'address then
2293 -- <code for controlled and/or tagged assignment>
2296 -- Skip this if Restriction (No_Finalization) is active
2298 if not Statically_Different (Lhs, Rhs)
2299 and then Expand_Ctrl_Actions
2300 and then not Restriction_Active (No_Finalization)
2303 Make_Implicit_If_Statement (N,
2307 Make_Attribute_Reference (Loc,
2308 Prefix => Duplicate_Subexpr (Lhs),
2309 Attribute_Name => Name_Address),
2312 Make_Attribute_Reference (Loc,
2313 Prefix => Duplicate_Subexpr (Rhs),
2314 Attribute_Name => Name_Address)),
2316 Then_Statements => L));
2319 -- We need to set up an exception handler for implementing
2320 -- 7.6.1(18). The remaining adjustments are tackled by the
2321 -- implementation of adjust for record_controllers (see
2324 -- This is skipped if we have no finalization
2326 if Expand_Ctrl_Actions
2327 and then not Restriction_Active (No_Finalization)
2330 Make_Block_Statement (Loc,
2331 Handled_Statement_Sequence =>
2332 Make_Handled_Sequence_Of_Statements (Loc,
2334 Exception_Handlers => New_List (
2335 Make_Handler_For_Ctrl_Operation (Loc)))));
2340 Make_Block_Statement (Loc,
2341 Handled_Statement_Sequence =>
2342 Make_Handled_Sequence_Of_Statements (Loc, Statements => L)));
2344 -- If no restrictions on aborts, protect the whole assignment
2345 -- for controlled objects as per 9.8(11).
2347 if Needs_Finalization (Typ)
2348 and then Expand_Ctrl_Actions
2349 and then Abort_Allowed
2352 Blk : constant Entity_Id :=
2354 (E_Block, Current_Scope, Sloc (N), 'B');
2355 AUD : constant Entity_Id := RTE (RE_Abort_Undefer_Direct);
2358 Set_Scope (Blk, Current_Scope);
2359 Set_Etype (Blk, Standard_Void_Type);
2360 Set_Identifier (N, New_Occurrence_Of (Blk, Sloc (N)));
2362 Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
2363 Set_At_End_Proc (Handled_Statement_Sequence (N),
2364 New_Occurrence_Of (AUD, Loc));
2366 -- Present the Abort_Undefer_Direct function to the backend
2367 -- so that it can inline the call to the function.
2369 Add_Inlined_Body (AUD, N);
2371 Expand_At_End_Handler
2372 (Handled_Statement_Sequence (N), Blk);
2376 -- N has been rewritten to a block statement for which it is
2377 -- known by construction that no checks are necessary: analyze
2378 -- it with all checks suppressed.
2380 Analyze (N, Suppress => All_Checks);
2381 Ghost_Mode := Save_Ghost_Mode;
2387 elsif Is_Array_Type (Typ) then
2389 Actual_Rhs : Node_Id := Rhs;
2392 while Nkind_In (Actual_Rhs, N_Type_Conversion,
2393 N_Qualified_Expression)
2395 Actual_Rhs := Expression (Actual_Rhs);
2398 Expand_Assign_Array (N, Actual_Rhs);
2399 Ghost_Mode := Save_Ghost_Mode;
2405 elsif Is_Record_Type (Typ) then
2406 Expand_Assign_Record (N);
2407 Ghost_Mode := Save_Ghost_Mode;
2410 -- Scalar types. This is where we perform the processing related to the
2411 -- requirements of (RM 13.9.1(9-11)) concerning the handling of invalid
2414 elsif Is_Scalar_Type (Typ) then
2416 -- Case where right side is known valid
2418 if Expr_Known_Valid (Rhs) then
2420 -- Here the right side is valid, so it is fine. The case to deal
2421 -- with is when the left side is a local variable reference whose
2422 -- value is not currently known to be valid. If this is the case,
2423 -- and the assignment appears in an unconditional context, then
2424 -- we can mark the left side as now being valid if one of these
2425 -- conditions holds:
2427 -- The expression of the right side has Do_Range_Check set so
2428 -- that we know a range check will be performed. Note that it
2429 -- can be the case that a range check is omitted because we
2430 -- make the assumption that we can assume validity for operands
2431 -- appearing in the right side in determining whether a range
2432 -- check is required
2434 -- The subtype of the right side matches the subtype of the
2435 -- left side. In this case, even though we have not checked
2436 -- the range of the right side, we know it is in range of its
2437 -- subtype if the expression is valid.
2439 if Is_Local_Variable_Reference (Lhs)
2440 and then not Is_Known_Valid (Entity (Lhs))
2441 and then In_Unconditional_Context (N)
2443 if Do_Range_Check (Rhs)
2444 or else Etype (Lhs) = Etype (Rhs)
2446 Set_Is_Known_Valid (Entity (Lhs), True);
2450 -- Case where right side may be invalid in the sense of the RM
2451 -- reference above. The RM does not require that we check for the
2452 -- validity on an assignment, but it does require that the assignment
2453 -- of an invalid value not cause erroneous behavior.
2455 -- The general approach in GNAT is to use the Is_Known_Valid flag
2456 -- to avoid the need for validity checking on assignments. However
2457 -- in some cases, we have to do validity checking in order to make
2458 -- sure that the setting of this flag is correct.
2461 -- Validate right side if we are validating copies
2463 if Validity_Checks_On
2464 and then Validity_Check_Copies
2466 -- Skip this if left hand side is an array or record component
2467 -- and elementary component validity checks are suppressed.
2469 if Nkind_In (Lhs, N_Selected_Component, N_Indexed_Component)
2470 and then not Validity_Check_Components
2477 -- We can propagate this to the left side where appropriate
2479 if Is_Local_Variable_Reference (Lhs)
2480 and then not Is_Known_Valid (Entity (Lhs))
2481 and then In_Unconditional_Context (N)
2483 Set_Is_Known_Valid (Entity (Lhs), True);
2486 -- Otherwise check to see what should be done
2488 -- If left side is a local variable, then we just set its flag to
2489 -- indicate that its value may no longer be valid, since we are
2490 -- copying a potentially invalid value.
2492 elsif Is_Local_Variable_Reference (Lhs) then
2493 Set_Is_Known_Valid (Entity (Lhs), False);
2495 -- Check for case of a nonlocal variable on the left side which
2496 -- is currently known to be valid. In this case, we simply ensure
2497 -- that the right side is valid. We only play the game of copying
2498 -- validity status for local variables, since we are doing this
2499 -- statically, not by tracing the full flow graph.
2501 elsif Is_Entity_Name (Lhs)
2502 and then Is_Known_Valid (Entity (Lhs))
2504 -- Note: If Validity_Checking mode is set to none, we ignore
2505 -- the Ensure_Valid call so don't worry about that case here.
2509 -- In all other cases, we can safely copy an invalid value without
2510 -- worrying about the status of the left side. Since it is not a
2511 -- variable reference it will not be considered
2512 -- as being known to be valid in any case.
2520 Ghost_Mode := Save_Ghost_Mode;
2523 when RE_Not_Available =>
2524 Ghost_Mode := Save_Ghost_Mode;
2526 end Expand_N_Assignment_Statement;
2528 ------------------------------
2529 -- Expand_N_Block_Statement --
2530 ------------------------------
2532 -- Encode entity names defined in block statement
2534 procedure Expand_N_Block_Statement (N : Node_Id) is
2536 Qualify_Entity_Names (N);
2537 end Expand_N_Block_Statement;
2539 -----------------------------
2540 -- Expand_N_Case_Statement --
2541 -----------------------------
2543 procedure Expand_N_Case_Statement (N : Node_Id) is
2544 Loc : constant Source_Ptr := Sloc (N);
2545 Expr : constant Node_Id := Expression (N);
2553 -- Check for the situation where we know at compile time which branch
2556 -- If the value is static but its subtype is predicated and the value
2557 -- does not obey the predicate, the value is marked non-static, and
2558 -- there can be no corresponding static alternative. In that case we
2559 -- replace the case statement with an exception, regardless of whether
2560 -- assertions are enabled or not.
2562 if Compile_Time_Known_Value (Expr)
2563 and then Has_Predicates (Etype (Expr))
2564 and then not Is_OK_Static_Expression (Expr)
2567 Make_Raise_Constraint_Error (Loc, Reason => CE_Invalid_Data));
2571 elsif Compile_Time_Known_Value (Expr)
2572 and then (not Has_Predicates (Etype (Expr))
2573 or else Is_Static_Expression (Expr))
2575 Alt := Find_Static_Alternative (N);
2577 -- Do not consider controlled objects found in a case statement which
2578 -- actually models a case expression because their early finalization
2579 -- will affect the result of the expression.
2581 if not From_Conditional_Expression (N) then
2582 Process_Statements_For_Controlled_Objects (Alt);
2585 -- Move statements from this alternative after the case statement.
2586 -- They are already analyzed, so will be skipped by the analyzer.
2588 Insert_List_After (N, Statements (Alt));
2590 -- That leaves the case statement as a shell. So now we can kill all
2591 -- other alternatives in the case statement.
2593 Kill_Dead_Code (Expression (N));
2599 -- Loop through case alternatives, skipping pragmas, and skipping
2600 -- the one alternative that we select (and therefore retain).
2602 Dead_Alt := First (Alternatives (N));
2603 while Present (Dead_Alt) loop
2605 and then Nkind (Dead_Alt) = N_Case_Statement_Alternative
2607 Kill_Dead_Code (Statements (Dead_Alt), Warn_On_Deleted_Code);
2614 Rewrite (N, Make_Null_Statement (Loc));
2618 -- Here if the choice is not determined at compile time
2621 Last_Alt : constant Node_Id := Last (Alternatives (N));
2623 Others_Present : Boolean;
2624 Others_Node : Node_Id;
2626 Then_Stms : List_Id;
2627 Else_Stms : List_Id;
2630 if Nkind (First (Discrete_Choices (Last_Alt))) = N_Others_Choice then
2631 Others_Present := True;
2632 Others_Node := Last_Alt;
2634 Others_Present := False;
2637 -- First step is to worry about possible invalid argument. The RM
2638 -- requires (RM 5.4(13)) that if the result is invalid (e.g. it is
2639 -- outside the base range), then Constraint_Error must be raised.
2641 -- Case of validity check required (validity checks are on, the
2642 -- expression is not known to be valid, and the case statement
2643 -- comes from source -- no need to validity check internally
2644 -- generated case statements).
2646 if Validity_Check_Default then
2647 Ensure_Valid (Expr);
2650 -- If there is only a single alternative, just replace it with the
2651 -- sequence of statements since obviously that is what is going to
2652 -- be executed in all cases.
2654 Len := List_Length (Alternatives (N));
2658 -- We still need to evaluate the expression if it has any side
2661 Remove_Side_Effects (Expression (N));
2662 Alt := First (Alternatives (N));
2664 -- Do not consider controlled objects found in a case statement
2665 -- which actually models a case expression because their early
2666 -- finalization will affect the result of the expression.
2668 if not From_Conditional_Expression (N) then
2669 Process_Statements_For_Controlled_Objects (Alt);
2672 Insert_List_After (N, Statements (Alt));
2674 -- That leaves the case statement as a shell. The alternative that
2675 -- will be executed is reset to a null list. So now we can kill
2676 -- the entire case statement.
2678 Kill_Dead_Code (Expression (N));
2679 Rewrite (N, Make_Null_Statement (Loc));
2682 -- An optimization. If there are only two alternatives, and only
2683 -- a single choice, then rewrite the whole case statement as an
2684 -- if statement, since this can result in subsequent optimizations.
2685 -- This helps not only with case statements in the source of a
2686 -- simple form, but also with generated code (discriminant check
2687 -- functions in particular).
2689 -- Note: it is OK to do this before expanding out choices for any
2690 -- static predicates, since the if statement processing will handle
2691 -- the static predicate case fine.
2694 Chlist := Discrete_Choices (First (Alternatives (N)));
2696 if List_Length (Chlist) = 1 then
2697 Choice := First (Chlist);
2699 Then_Stms := Statements (First (Alternatives (N)));
2700 Else_Stms := Statements (Last (Alternatives (N)));
2702 -- For TRUE, generate "expression", not expression = true
2704 if Nkind (Choice) = N_Identifier
2705 and then Entity (Choice) = Standard_True
2707 Cond := Expression (N);
2709 -- For FALSE, generate "expression" and switch then/else
2711 elsif Nkind (Choice) = N_Identifier
2712 and then Entity (Choice) = Standard_False
2714 Cond := Expression (N);
2715 Else_Stms := Statements (First (Alternatives (N)));
2716 Then_Stms := Statements (Last (Alternatives (N)));
2718 -- For a range, generate "expression in range"
2720 elsif Nkind (Choice) = N_Range
2721 or else (Nkind (Choice) = N_Attribute_Reference
2722 and then Attribute_Name (Choice) = Name_Range)
2723 or else (Is_Entity_Name (Choice)
2724 and then Is_Type (Entity (Choice)))
2728 Left_Opnd => Expression (N),
2729 Right_Opnd => Relocate_Node (Choice));
2731 -- A subtype indication is not a legal operator in a membership
2732 -- test, so retrieve its range.
2734 elsif Nkind (Choice) = N_Subtype_Indication then
2737 Left_Opnd => Expression (N),
2740 (Range_Expression (Constraint (Choice))));
2742 -- For any other subexpression "expression = value"
2747 Left_Opnd => Expression (N),
2748 Right_Opnd => Relocate_Node (Choice));
2751 -- Now rewrite the case as an IF
2754 Make_If_Statement (Loc,
2756 Then_Statements => Then_Stms,
2757 Else_Statements => Else_Stms));
2763 -- If the last alternative is not an Others choice, replace it with
2764 -- an N_Others_Choice. Note that we do not bother to call Analyze on
2765 -- the modified case statement, since it's only effect would be to
2766 -- compute the contents of the Others_Discrete_Choices which is not
2767 -- needed by the back end anyway.
2769 -- The reason for this is that the back end always needs some default
2770 -- for a switch, so if we have not supplied one in the processing
2771 -- above for validity checking, then we need to supply one here.
2773 if not Others_Present then
2774 Others_Node := Make_Others_Choice (Sloc (Last_Alt));
2775 Set_Others_Discrete_Choices
2776 (Others_Node, Discrete_Choices (Last_Alt));
2777 Set_Discrete_Choices (Last_Alt, New_List (Others_Node));
2780 -- Deal with possible declarations of controlled objects, and also
2781 -- with rewriting choice sequences for static predicate references.
2783 Alt := First_Non_Pragma (Alternatives (N));
2784 while Present (Alt) loop
2786 -- Do not consider controlled objects found in a case statement
2787 -- which actually models a case expression because their early
2788 -- finalization will affect the result of the expression.
2790 if not From_Conditional_Expression (N) then
2791 Process_Statements_For_Controlled_Objects (Alt);
2794 if Has_SP_Choice (Alt) then
2795 Expand_Static_Predicates_In_Choices (Alt);
2798 Next_Non_Pragma (Alt);
2801 end Expand_N_Case_Statement;
2803 -----------------------------
2804 -- Expand_N_Exit_Statement --
2805 -----------------------------
2807 -- The only processing required is to deal with a possible C/Fortran
2808 -- boolean value used as the condition for the exit statement.
2810 procedure Expand_N_Exit_Statement (N : Node_Id) is
2812 Adjust_Condition (Condition (N));
2813 end Expand_N_Exit_Statement;
2815 ----------------------------------
2816 -- Expand_Formal_Container_Loop --
2817 ----------------------------------
2819 procedure Expand_Formal_Container_Loop (N : Node_Id) is
2820 Loc : constant Source_Ptr := Sloc (N);
2821 Isc : constant Node_Id := Iteration_Scheme (N);
2822 I_Spec : constant Node_Id := Iterator_Specification (Isc);
2823 Cursor : constant Entity_Id := Defining_Identifier (I_Spec);
2824 Container : constant Node_Id := Entity (Name (I_Spec));
2825 Stats : constant List_Id := Statements (N);
2833 -- The expansion resembles the one for Ada containers, but the
2834 -- primitives mention the domain of iteration explicitly, and
2835 -- function First applied to the container yields a cursor directly.
2837 -- Cursor : Cursor_type := First (Container);
2838 -- while Has_Element (Cursor, Container) loop
2839 -- <original loop statements>
2840 -- Cursor := Next (Container, Cursor);
2843 Build_Formal_Container_Iteration
2844 (N, Container, Cursor, Init, Advance, New_Loop);
2846 Set_Ekind (Cursor, E_Variable);
2847 Append_To (Stats, Advance);
2849 -- Build block to capture declaration of cursor entity.
2852 Make_Block_Statement (Loc,
2853 Declarations => New_List (Init),
2854 Handled_Statement_Sequence =>
2855 Make_Handled_Sequence_Of_Statements (Loc,
2856 Statements => New_List (New_Loop)));
2858 Rewrite (N, Blk_Nod);
2860 end Expand_Formal_Container_Loop;
2862 ------------------------------------------
2863 -- Expand_Formal_Container_Element_Loop --
2864 ------------------------------------------
2866 procedure Expand_Formal_Container_Element_Loop (N : Node_Id) is
2867 Loc : constant Source_Ptr := Sloc (N);
2868 Isc : constant Node_Id := Iteration_Scheme (N);
2869 I_Spec : constant Node_Id := Iterator_Specification (Isc);
2870 Element : constant Entity_Id := Defining_Identifier (I_Spec);
2871 Container : constant Node_Id := Entity (Name (I_Spec));
2872 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
2873 Stats : constant List_Id := Statements (N);
2875 Cursor : constant Entity_Id :=
2876 Make_Defining_Identifier (Loc,
2877 Chars => New_External_Name (Chars (Element), 'C'));
2878 Elmt_Decl : Node_Id;
2881 Element_Op : constant Entity_Id :=
2882 Get_Iterable_Type_Primitive (Container_Typ, Name_Element);
2889 -- For an element iterator, the Element aspect must be present,
2890 -- (this is checked during analysis) and the expansion takes the form:
2892 -- Cursor : Cursor_type := First (Container);
2893 -- Elmt : Element_Type;
2894 -- while Has_Element (Cursor, Container) loop
2895 -- Elmt := Element (Container, Cursor);
2896 -- <original loop statements>
2897 -- Cursor := Next (Container, Cursor);
2900 -- However this expansion is not legal if the element is indefinite.
2901 -- In that case we create a block to hold a variable declaration
2902 -- initialized with a call to Element, and generate:
2904 -- Cursor : Cursor_type := First (Container);
2905 -- while Has_Element (Cursor, Container) loop
2907 -- Elmt : Element-Type := Element (Container, Cursor);
2909 -- <original loop statements>
2910 -- Cursor := Next (Container, Cursor);
2914 Build_Formal_Container_Iteration
2915 (N, Container, Cursor, Init, Advance, New_Loop);
2916 Append_To (Stats, Advance);
2918 Set_Ekind (Cursor, E_Variable);
2919 Insert_Action (N, Init);
2921 -- Declaration for Element.
2924 Make_Object_Declaration (Loc,
2925 Defining_Identifier => Element,
2926 Object_Definition => New_Occurrence_Of (Etype (Element_Op), Loc));
2928 if not Is_Constrained (Etype (Element_Op)) then
2929 Set_Expression (Elmt_Decl,
2930 Make_Function_Call (Loc,
2931 Name => New_Occurrence_Of (Element_Op, Loc),
2932 Parameter_Associations => New_List (
2933 New_Occurrence_Of (Container, Loc),
2934 New_Occurrence_Of (Cursor, Loc))));
2936 Set_Statements (New_Loop,
2938 (Make_Block_Statement (Loc,
2939 Declarations => New_List (Elmt_Decl),
2940 Handled_Statement_Sequence =>
2941 Make_Handled_Sequence_Of_Statements (Loc,
2942 Statements => Stats))));
2946 Make_Assignment_Statement (Loc,
2947 Name => New_Occurrence_Of (Element, Loc),
2949 Make_Function_Call (Loc,
2950 Name => New_Occurrence_Of (Element_Op, Loc),
2951 Parameter_Associations => New_List (
2952 New_Occurrence_Of (Container, Loc),
2953 New_Occurrence_Of (Cursor, Loc))));
2955 Prepend (Elmt_Ref, Stats);
2957 -- The element is assignable in the expanded code
2959 Set_Assignment_OK (Name (Elmt_Ref));
2961 -- The loop is rewritten as a block, to hold the element declaration
2964 Make_Block_Statement (Loc,
2965 Declarations => New_List (Elmt_Decl),
2966 Handled_Statement_Sequence =>
2967 Make_Handled_Sequence_Of_Statements (Loc,
2968 Statements => New_List (New_Loop)));
2971 -- The element is only modified in expanded code, so it appears as
2972 -- unassigned to the warning machinery. We must suppress this spurious
2973 -- warning explicitly.
2975 Set_Warnings_Off (Element);
2977 Rewrite (N, New_Loop);
2979 -- The loop parameter is declared by an object declaration, but within
2980 -- the loop we must prevent user assignments to it, so we analyze the
2981 -- declaration and reset the entity kind, before analyzing the rest of
2984 Analyze (Elmt_Decl);
2985 Set_Ekind (Defining_Identifier (Elmt_Decl), E_Loop_Parameter);
2988 end Expand_Formal_Container_Element_Loop;
2990 -----------------------------
2991 -- Expand_N_Goto_Statement --
2992 -----------------------------
2994 -- Add poll before goto if polling active
2996 procedure Expand_N_Goto_Statement (N : Node_Id) is
2998 Generate_Poll_Call (N);
2999 end Expand_N_Goto_Statement;
3001 ---------------------------
3002 -- Expand_N_If_Statement --
3003 ---------------------------
3005 -- First we deal with the case of C and Fortran convention boolean values,
3006 -- with zero/non-zero semantics.
3008 -- Second, we deal with the obvious rewriting for the cases where the
3009 -- condition of the IF is known at compile time to be True or False.
3011 -- Third, we remove elsif parts which have non-empty Condition_Actions and
3012 -- rewrite as independent if statements. For example:
3023 -- <<condition actions of y>>
3029 -- This rewriting is needed if at least one elsif part has a non-empty
3030 -- Condition_Actions list. We also do the same processing if there is a
3031 -- constant condition in an elsif part (in conjunction with the first
3032 -- processing step mentioned above, for the recursive call made to deal
3033 -- with the created inner if, this deals with properly optimizing the
3034 -- cases of constant elsif conditions).
3036 procedure Expand_N_If_Statement (N : Node_Id) is
3037 Loc : constant Source_Ptr := Sloc (N);
3042 Warn_If_Deleted : constant Boolean :=
3043 Warn_On_Deleted_Code and then Comes_From_Source (N);
3044 -- Indicates whether we want warnings when we delete branches of the
3045 -- if statement based on constant condition analysis. We never want
3046 -- these warnings for expander generated code.
3049 -- Do not consider controlled objects found in an if statement which
3050 -- actually models an if expression because their early finalization
3051 -- will affect the result of the expression.
3053 if not From_Conditional_Expression (N) then
3054 Process_Statements_For_Controlled_Objects (N);
3057 Adjust_Condition (Condition (N));
3059 -- The following loop deals with constant conditions for the IF. We
3060 -- need a loop because as we eliminate False conditions, we grab the
3061 -- first elsif condition and use it as the primary condition.
3063 while Compile_Time_Known_Value (Condition (N)) loop
3065 -- If condition is True, we can simply rewrite the if statement now
3066 -- by replacing it by the series of then statements.
3068 if Is_True (Expr_Value (Condition (N))) then
3070 -- All the else parts can be killed
3072 Kill_Dead_Code (Elsif_Parts (N), Warn_If_Deleted);
3073 Kill_Dead_Code (Else_Statements (N), Warn_If_Deleted);
3075 Hed := Remove_Head (Then_Statements (N));
3076 Insert_List_After (N, Then_Statements (N));
3080 -- If condition is False, then we can delete the condition and
3081 -- the Then statements
3084 -- We do not delete the condition if constant condition warnings
3085 -- are enabled, since otherwise we end up deleting the desired
3086 -- warning. Of course the backend will get rid of this True/False
3087 -- test anyway, so nothing is lost here.
3089 if not Constant_Condition_Warnings then
3090 Kill_Dead_Code (Condition (N));
3093 Kill_Dead_Code (Then_Statements (N), Warn_If_Deleted);
3095 -- If there are no elsif statements, then we simply replace the
3096 -- entire if statement by the sequence of else statements.
3098 if No (Elsif_Parts (N)) then
3099 if No (Else_Statements (N))
3100 or else Is_Empty_List (Else_Statements (N))
3103 Make_Null_Statement (Sloc (N)));
3105 Hed := Remove_Head (Else_Statements (N));
3106 Insert_List_After (N, Else_Statements (N));
3112 -- If there are elsif statements, the first of them becomes the
3113 -- if/then section of the rebuilt if statement This is the case
3114 -- where we loop to reprocess this copied condition.
3117 Hed := Remove_Head (Elsif_Parts (N));
3118 Insert_Actions (N, Condition_Actions (Hed));
3119 Set_Condition (N, Condition (Hed));
3120 Set_Then_Statements (N, Then_Statements (Hed));
3122 -- Hed might have been captured as the condition determining
3123 -- the current value for an entity. Now it is detached from
3124 -- the tree, so a Current_Value pointer in the condition might
3125 -- need to be updated.
3127 Set_Current_Value_Condition (N);
3129 if Is_Empty_List (Elsif_Parts (N)) then
3130 Set_Elsif_Parts (N, No_List);
3136 -- Loop through elsif parts, dealing with constant conditions and
3137 -- possible condition actions that are present.
3139 if Present (Elsif_Parts (N)) then
3140 E := First (Elsif_Parts (N));
3141 while Present (E) loop
3143 -- Do not consider controlled objects found in an if statement
3144 -- which actually models an if expression because their early
3145 -- finalization will affect the result of the expression.
3147 if not From_Conditional_Expression (N) then
3148 Process_Statements_For_Controlled_Objects (E);
3151 Adjust_Condition (Condition (E));
3153 -- If there are condition actions, then rewrite the if statement
3154 -- as indicated above. We also do the same rewrite for a True or
3155 -- False condition. The further processing of this constant
3156 -- condition is then done by the recursive call to expand the
3157 -- newly created if statement
3159 if Present (Condition_Actions (E))
3160 or else Compile_Time_Known_Value (Condition (E))
3162 -- Note this is not an implicit if statement, since it is part
3163 -- of an explicit if statement in the source (or of an implicit
3164 -- if statement that has already been tested).
3167 Make_If_Statement (Sloc (E),
3168 Condition => Condition (E),
3169 Then_Statements => Then_Statements (E),
3170 Elsif_Parts => No_List,
3171 Else_Statements => Else_Statements (N));
3173 -- Elsif parts for new if come from remaining elsif's of parent
3175 while Present (Next (E)) loop
3176 if No (Elsif_Parts (New_If)) then
3177 Set_Elsif_Parts (New_If, New_List);
3180 Append (Remove_Next (E), Elsif_Parts (New_If));
3183 Set_Else_Statements (N, New_List (New_If));
3185 if Present (Condition_Actions (E)) then
3186 Insert_List_Before (New_If, Condition_Actions (E));
3191 if Is_Empty_List (Elsif_Parts (N)) then
3192 Set_Elsif_Parts (N, No_List);
3198 -- No special processing for that elsif part, move to next
3206 -- Some more optimizations applicable if we still have an IF statement
3208 if Nkind (N) /= N_If_Statement then
3212 -- Another optimization, special cases that can be simplified
3214 -- if expression then
3220 -- can be changed to:
3222 -- return expression;
3226 -- if expression then
3232 -- can be changed to:
3234 -- return not (expression);
3236 -- Only do these optimizations if we are at least at -O1 level and
3237 -- do not do them if control flow optimizations are suppressed.
3239 if Optimization_Level > 0
3240 and then not Opt.Suppress_Control_Flow_Optimizations
3242 if Nkind (N) = N_If_Statement
3243 and then No (Elsif_Parts (N))
3244 and then Present (Else_Statements (N))
3245 and then List_Length (Then_Statements (N)) = 1
3246 and then List_Length (Else_Statements (N)) = 1
3249 Then_Stm : constant Node_Id := First (Then_Statements (N));
3250 Else_Stm : constant Node_Id := First (Else_Statements (N));
3253 if Nkind (Then_Stm) = N_Simple_Return_Statement
3255 Nkind (Else_Stm) = N_Simple_Return_Statement
3258 Then_Expr : constant Node_Id := Expression (Then_Stm);
3259 Else_Expr : constant Node_Id := Expression (Else_Stm);
3262 if Nkind (Then_Expr) = N_Identifier
3264 Nkind (Else_Expr) = N_Identifier
3266 if Entity (Then_Expr) = Standard_True
3267 and then Entity (Else_Expr) = Standard_False
3270 Make_Simple_Return_Statement (Loc,
3271 Expression => Relocate_Node (Condition (N))));
3275 elsif Entity (Then_Expr) = Standard_False
3276 and then Entity (Else_Expr) = Standard_True
3279 Make_Simple_Return_Statement (Loc,
3283 Relocate_Node (Condition (N)))));
3293 end Expand_N_If_Statement;
3295 --------------------------
3296 -- Expand_Iterator_Loop --
3297 --------------------------
3299 procedure Expand_Iterator_Loop (N : Node_Id) is
3300 Isc : constant Node_Id := Iteration_Scheme (N);
3301 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3303 Container : constant Node_Id := Name (I_Spec);
3304 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
3307 -- Processing for arrays
3309 if Is_Array_Type (Container_Typ) then
3310 pragma Assert (Of_Present (I_Spec));
3311 Expand_Iterator_Loop_Over_Array (N);
3313 elsif Has_Aspect (Container_Typ, Aspect_Iterable) then
3314 if Of_Present (I_Spec) then
3315 Expand_Formal_Container_Element_Loop (N);
3317 Expand_Formal_Container_Loop (N);
3320 -- Processing for containers
3323 Expand_Iterator_Loop_Over_Container
3324 (N, Isc, I_Spec, Container, Container_Typ);
3326 end Expand_Iterator_Loop;
3328 -------------------------------------
3329 -- Expand_Iterator_Loop_Over_Array --
3330 -------------------------------------
3332 procedure Expand_Iterator_Loop_Over_Array (N : Node_Id) is
3333 Isc : constant Node_Id := Iteration_Scheme (N);
3334 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3335 Array_Node : constant Node_Id := Name (I_Spec);
3336 Array_Typ : constant Entity_Id := Base_Type (Etype (Array_Node));
3337 Array_Dim : constant Pos := Number_Dimensions (Array_Typ);
3338 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3339 Loc : constant Source_Ptr := Sloc (N);
3340 Stats : constant List_Id := Statements (N);
3341 Core_Loop : Node_Id;
3344 Iterator : Entity_Id;
3346 -- Start of processing for Expand_Iterator_Loop_Over_Array
3349 -- for Element of Array loop
3351 -- It requires an internally generated cursor to iterate over the array
3353 pragma Assert (Of_Present (I_Spec));
3355 Iterator := Make_Temporary (Loc, 'C');
3358 -- Element : Component_Type renames Array (Iterator);
3359 -- Iterator is the index value, or a list of index values
3360 -- in the case of a multidimensional array.
3363 Make_Indexed_Component (Loc,
3364 Prefix => Relocate_Node (Array_Node),
3365 Expressions => New_List (New_Occurrence_Of (Iterator, Loc)));
3368 Make_Object_Renaming_Declaration (Loc,
3369 Defining_Identifier => Id,
3371 New_Occurrence_Of (Component_Type (Array_Typ), Loc),
3374 -- Mark the loop variable as needing debug info, so that expansion
3375 -- of the renaming will result in Materialize_Entity getting set via
3376 -- Debug_Renaming_Declaration. (This setting is needed here because
3377 -- the setting in Freeze_Entity comes after the expansion, which is
3380 Set_Debug_Info_Needed (Id);
3384 -- for Iterator in [reverse] Array'Range (Array_Dim) loop
3385 -- Element : Component_Type renames Array (Iterator);
3386 -- <original loop statements>
3389 -- If this is an iteration over a multidimensional array, the
3390 -- innermost loop is over the last dimension in Ada, and over
3391 -- the first dimension in Fortran.
3393 if Convention (Array_Typ) = Convention_Fortran then
3400 Make_Loop_Statement (Loc,
3402 Make_Iteration_Scheme (Loc,
3403 Loop_Parameter_Specification =>
3404 Make_Loop_Parameter_Specification (Loc,
3405 Defining_Identifier => Iterator,
3406 Discrete_Subtype_Definition =>
3407 Make_Attribute_Reference (Loc,
3408 Prefix => Relocate_Node (Array_Node),
3409 Attribute_Name => Name_Range,
3410 Expressions => New_List (
3411 Make_Integer_Literal (Loc, Dim1))),
3412 Reverse_Present => Reverse_Present (I_Spec))),
3413 Statements => Stats,
3414 End_Label => Empty);
3416 -- Processing for multidimensional array. The body of each loop is
3417 -- a loop over a previous dimension, going in decreasing order in Ada
3418 -- and in increasing order in Fortran.
3420 if Array_Dim > 1 then
3421 for Dim in 1 .. Array_Dim - 1 loop
3422 if Convention (Array_Typ) = Convention_Fortran then
3425 Dim1 := Array_Dim - Dim;
3428 Iterator := Make_Temporary (Loc, 'C');
3430 -- Generate the dimension loops starting from the innermost one
3432 -- for Iterator in [reverse] Array'Range (Array_Dim - Dim) loop
3437 Make_Loop_Statement (Loc,
3439 Make_Iteration_Scheme (Loc,
3440 Loop_Parameter_Specification =>
3441 Make_Loop_Parameter_Specification (Loc,
3442 Defining_Identifier => Iterator,
3443 Discrete_Subtype_Definition =>
3444 Make_Attribute_Reference (Loc,
3445 Prefix => Relocate_Node (Array_Node),
3446 Attribute_Name => Name_Range,
3447 Expressions => New_List (
3448 Make_Integer_Literal (Loc, Dim1))),
3449 Reverse_Present => Reverse_Present (I_Spec))),
3450 Statements => New_List (Core_Loop),
3451 End_Label => Empty);
3453 -- Update the previously created object renaming declaration with
3454 -- the new iterator, by adding the index of the next loop to the
3455 -- indexed component, in the order that corresponds to the
3458 if Convention (Array_Typ) = Convention_Fortran then
3459 Append_To (Expressions (Ind_Comp),
3460 New_Occurrence_Of (Iterator, Loc));
3462 Prepend_To (Expressions (Ind_Comp),
3463 New_Occurrence_Of (Iterator, Loc));
3468 -- Inherit the loop identifier from the original loop. This ensures that
3469 -- the scope stack is consistent after the rewriting.
3471 if Present (Identifier (N)) then
3472 Set_Identifier (Core_Loop, Relocate_Node (Identifier (N)));
3475 Rewrite (N, Core_Loop);
3477 end Expand_Iterator_Loop_Over_Array;
3479 -----------------------------------------
3480 -- Expand_Iterator_Loop_Over_Container --
3481 -----------------------------------------
3483 -- For a 'for ... in' loop, such as:
3485 -- for Cursor in Iterator_Function (...) loop
3491 -- Iter : Iterator_Type := Iterator_Function (...);
3492 -- Cursor : Cursor_type := First (Iter); -- or Last for "reverse"
3493 -- while Has_Element (Cursor) loop
3496 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
3499 -- For a 'for ... of' loop, such as:
3501 -- for X of Container loop
3505 -- the RM implies the generation of:
3507 -- Iter : Iterator_Type := Container.Iterate; -- the Default_Iterator
3508 -- Cursor : Cursor_Type := First (Iter); -- or Last for "reverse"
3509 -- while Has_Element (Cursor) loop
3511 -- X : Element_Type renames Element (Cursor).Element.all;
3512 -- -- or Constant_Element
3516 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
3519 -- In the general case, we do what the RM says. However, the operations
3520 -- Element and Iter.Next are slow, which is bad inside a loop, because they
3521 -- involve dispatching via interfaces, secondary stack manipulation,
3522 -- Busy/Lock incr/decr, and adjust/finalization/at-end handling. So for the
3523 -- predefined containers, we use an equivalent but optimized expansion.
3525 -- In the optimized case, we make use of these:
3527 -- procedure Next (Position : in out Cursor); -- instead of Iter.Next
3529 -- function Pseudo_Reference
3530 -- (Container : aliased Vector'Class) return Reference_Control_Type;
3532 -- type Element_Access is access all Element_Type;
3534 -- function Get_Element_Access
3535 -- (Position : Cursor) return not null Element_Access;
3537 -- Next is declared in the visible part of the container packages.
3538 -- The other three are added in the private part. (We're not supposed to
3539 -- pollute the namespace for clients. The compiler has no trouble breaking
3540 -- privacy to call things in the private part of an instance.)
3544 -- for X of My_Vector loop
3545 -- X.Count := X.Count + 1;
3549 -- The compiler will generate:
3551 -- Iter : Reversible_Iterator'Class := Iterate (My_Vector);
3552 -- -- Reversible_Iterator is an interface. Iterate is the
3553 -- -- Default_Iterator aspect of Vector. This increments Lock,
3554 -- -- disallowing tampering with cursors. Unfortunately, it does not
3555 -- -- increment Busy. The result of Iterate is Limited_Controlled;
3556 -- -- finalization will decrement Lock. This is a build-in-place
3557 -- -- dispatching call to Iterate.
3559 -- Cur : Cursor := First (Iter); -- or Last
3560 -- -- Dispatching call via interface.
3562 -- Control : Reference_Control_Type := Pseudo_Reference (My_Vector);
3563 -- -- Pseudo_Reference increments Busy, to detect tampering with
3564 -- -- elements, as required by RM. Also redundantly increment
3565 -- -- Lock. Finalization of Control will decrement both Busy and
3566 -- -- Lock. Pseudo_Reference returns a record containing a pointer to
3567 -- -- My_Vector, used by Finalize.
3569 -- -- Control is not used below, except to finalize it -- it's purely
3570 -- -- an RAII thing. This is needed because we are eliminating the
3571 -- -- call to Reference within the loop.
3573 -- while Has_Element (Cur) loop
3575 -- X : My_Element renames Get_Element_Access (Cur).all;
3576 -- -- Get_Element_Access returns a pointer to the element
3577 -- -- designated by Cur. No dispatching here, and no horsing
3578 -- -- around with access discriminants. This is instead of the
3581 -- -- X : My_Element renames Reference (Cur).Element.all;
3583 -- -- which creates a controlled object.
3585 -- -- Any attempt to tamper with My_Vector here in the loop
3586 -- -- will correctly raise Program_Error, because of the
3589 -- X.Count := X.Count + 1;
3592 -- Next (Cur); -- or Prev
3593 -- -- This is instead of "Cur := Next (Iter, Cur);"
3595 -- -- No finalization here
3597 -- Finalize Iter and Control here, decrementing Lock twice and Busy
3600 -- This optimization makes "for ... of" loops over 30 times faster in cases
3603 procedure Expand_Iterator_Loop_Over_Container
3607 Container : Node_Id;
3608 Container_Typ : Entity_Id)
3610 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3611 Loc : constant Source_Ptr := Sloc (N);
3613 I_Kind : constant Entity_Kind := Ekind (Id);
3615 Iterator : Entity_Id;
3617 Stats : constant List_Id := Statements (N);
3619 Element_Type : constant Entity_Id := Etype (Id);
3620 Iter_Type : Entity_Id;
3623 Name_Init : Name_Id;
3624 Name_Step : Name_Id;
3626 Fast_Element_Access_Op, Fast_Step_Op : Entity_Id := Empty;
3627 -- Only for optimized version of "for ... of"
3630 -- Determine the advancement and initialization steps for the cursor.
3631 -- Analysis of the expanded loop will verify that the container has a
3632 -- reverse iterator.
3634 if Reverse_Present (I_Spec) then
3635 Name_Init := Name_Last;
3636 Name_Step := Name_Previous;
3638 Name_Init := Name_First;
3639 Name_Step := Name_Next;
3642 -- The type of the iterator is the return type of the Iterate function
3643 -- used. For the "of" form this is the default iterator for the type,
3644 -- otherwise it is the type of the explicit function used in the
3645 -- iterator specification. The most common case will be an Iterate
3646 -- function in the container package.
3648 -- The Iterator type is declared in an instance within the container
3649 -- package itself, for example:
3651 -- package Vector_Iterator_Interfaces is new
3652 -- Ada.Iterator_Interfaces (Cursor, Has_Element);
3654 -- If the container type is a derived type, the cursor type is found in
3655 -- the package of the ultimate ancestor type.
3657 if Is_Derived_Type (Container_Typ) then
3658 Pack := Scope (Root_Type (Container_Typ));
3660 Pack := Scope (Container_Typ);
3663 Iter_Type := Etype (Name (I_Spec));
3665 if Of_Present (I_Spec) then
3667 Container_Arg : Node_Id;
3669 function Get_Default_Iterator
3670 (T : Entity_Id) return Entity_Id;
3671 -- If the container is a derived type, the aspect holds the parent
3672 -- operation. The required one is a primitive of the derived type
3673 -- and is either inherited or overridden. Also sets Container_Arg.
3675 --------------------------
3676 -- Get_Default_Iterator --
3677 --------------------------
3679 function Get_Default_Iterator
3680 (T : Entity_Id) return Entity_Id
3682 Iter : constant Entity_Id :=
3683 Entity (Find_Value_Of_Aspect (T, Aspect_Default_Iterator));
3688 Container_Arg := New_Copy_Tree (Container);
3690 -- A previous version of GNAT allowed indexing aspects to
3691 -- be redefined on derived container types, while the
3692 -- default iterator was inherited from the parent type.
3693 -- This non-standard extension is preserved temporarily for
3694 -- use by the modelling project under debug flag d.X.
3696 if Debug_Flag_Dot_XX then
3697 if Base_Type (Etype (Container)) /=
3698 Base_Type (Etype (First_Formal (Iter)))
3701 Make_Type_Conversion (Loc,
3704 (Etype (First_Formal (Iter)), Loc),
3705 Expression => Container_Arg);
3710 elsif Is_Derived_Type (T) then
3712 -- The default iterator must be a primitive operation of the
3713 -- type, at the same dispatch slot position.
3715 Prim := First_Elmt (Primitive_Operations (T));
3716 while Present (Prim) loop
3719 if Chars (Op) = Chars (Iter)
3720 and then DT_Position (Op) = DT_Position (Iter)
3728 -- Default iterator must exist
3730 pragma Assert (False);
3732 -- Otherwise not a derived type
3737 end Get_Default_Iterator;
3739 Default_Iter : Entity_Id;
3742 Reference_Control_Type : Entity_Id := Empty;
3743 Pseudo_Reference : Entity_Id := Empty;
3745 -- Start of processing for Handle_Of
3748 if Is_Class_Wide_Type (Container_Typ) then
3750 Get_Default_Iterator (Etype (Base_Type (Container_Typ)));
3752 Default_Iter := Get_Default_Iterator (Etype (Container));
3755 Cursor := Make_Temporary (Loc, 'C');
3757 -- For a container element iterator, the iterator type is obtained
3758 -- from the corresponding aspect, whose return type is descended
3759 -- from the corresponding interface type in some instance of
3760 -- Ada.Iterator_Interfaces. The actuals of that instantiation
3761 -- are Cursor and Has_Element.
3763 Iter_Type := Etype (Default_Iter);
3765 -- Find declarations needed for "for ... of" optimization
3767 Ent := First_Entity (Pack);
3768 while Present (Ent) loop
3769 if Chars (Ent) = Name_Get_Element_Access then
3770 Fast_Element_Access_Op := Ent;
3772 elsif Chars (Ent) = Name_Step
3773 and then Ekind (Ent) = E_Procedure
3775 Fast_Step_Op := Ent;
3777 elsif Chars (Ent) = Name_Reference_Control_Type then
3778 Reference_Control_Type := Ent;
3780 elsif Chars (Ent) = Name_Pseudo_Reference then
3781 Pseudo_Reference := Ent;
3787 if Present (Reference_Control_Type)
3788 and then Present (Pseudo_Reference)
3791 Make_Object_Declaration (Loc,
3792 Defining_Identifier => Make_Temporary (Loc, 'D'),
3793 Object_Definition =>
3794 New_Occurrence_Of (Reference_Control_Type, Loc),
3796 Make_Function_Call (Loc,
3798 New_Occurrence_Of (Pseudo_Reference, Loc),
3799 Parameter_Associations =>
3800 New_List (New_Copy_Tree (Container_Arg)))));
3803 -- The iterator type, which is a class-wide type, may itself be
3804 -- derived locally, so the desired instantiation is the scope of
3805 -- the root type of the iterator type. Currently, Pack is the
3806 -- container instance; this overwrites it with the iterator
3809 Pack := Scope (Root_Type (Etype (Iter_Type)));
3811 -- Rewrite domain of iteration as a call to the default iterator
3812 -- for the container type.
3814 Rewrite (Name (I_Spec),
3815 Make_Function_Call (Loc,
3817 New_Occurrence_Of (Default_Iter, Loc),
3818 Parameter_Associations => New_List (Container_Arg)));
3819 Analyze_And_Resolve (Name (I_Spec));
3821 -- Find cursor type in proper iterator package, which is an
3822 -- instantiation of Iterator_Interfaces.
3824 Ent := First_Entity (Pack);
3825 while Present (Ent) loop
3826 if Chars (Ent) = Name_Cursor then
3827 Set_Etype (Cursor, Etype (Ent));
3834 if Present (Fast_Element_Access_Op) then
3836 Make_Object_Renaming_Declaration (Loc,
3837 Defining_Identifier => Id,
3839 New_Occurrence_Of (Element_Type, Loc),
3841 Make_Explicit_Dereference (Loc,
3843 Make_Function_Call (Loc,
3845 New_Occurrence_Of (Fast_Element_Access_Op, Loc),
3846 Parameter_Associations =>
3847 New_List (New_Occurrence_Of (Cursor, Loc)))));
3851 Make_Object_Renaming_Declaration (Loc,
3852 Defining_Identifier => Id,
3854 New_Occurrence_Of (Element_Type, Loc),
3856 Make_Indexed_Component (Loc,
3857 Prefix => Relocate_Node (Container_Arg),
3859 New_List (New_Occurrence_Of (Cursor, Loc))));
3862 -- The defining identifier in the iterator is user-visible
3863 -- and must be visible in the debugger.
3865 Set_Debug_Info_Needed (Id);
3867 -- If the container does not have a variable indexing aspect,
3868 -- the element is a constant in the loop. The container itself
3869 -- may be constant, in which case the element is a constant as
3870 -- well. The container has been rewritten as a call to Iterate,
3871 -- so examine original node.
3873 if No (Find_Value_Of_Aspect
3874 (Container_Typ, Aspect_Variable_Indexing))
3875 or else not Is_Variable (Original_Node (Container))
3877 Set_Ekind (Id, E_Constant);
3880 Prepend_To (Stats, Decl);
3883 -- X in Iterate (S) : type of iterator is type of explicitly
3884 -- given Iterate function, and the loop variable is the cursor.
3885 -- It will be assigned in the loop and must be a variable.
3891 Iterator := Make_Temporary (Loc, 'I');
3893 -- For both iterator forms, add a call to the step operation to
3894 -- advance the cursor. Generate:
3896 -- Cursor := Iterator.Next (Cursor);
3900 -- Cursor := Next (Cursor);
3902 if Present (Fast_Element_Access_Op) and then Present (Fast_Step_Op) then
3904 Step_Call : Node_Id;
3905 Curs_Name : constant Node_Id := New_Occurrence_Of (Cursor, Loc);
3908 Make_Procedure_Call_Statement (Loc,
3910 New_Occurrence_Of (Fast_Step_Op, Loc),
3911 Parameter_Associations => New_List (Curs_Name));
3913 Append_To (Stats, Step_Call);
3914 Set_Assignment_OK (Curs_Name);
3923 Make_Function_Call (Loc,
3925 Make_Selected_Component (Loc,
3926 Prefix => New_Occurrence_Of (Iterator, Loc),
3927 Selector_Name => Make_Identifier (Loc, Name_Step)),
3928 Parameter_Associations => New_List (
3929 New_Occurrence_Of (Cursor, Loc)));
3932 Make_Assignment_Statement (Loc,
3933 Name => New_Occurrence_Of (Cursor, Loc),
3934 Expression => Rhs));
3935 Set_Assignment_OK (Name (Last (Stats)));
3940 -- while Has_Element (Cursor) loop
3944 -- Has_Element is the second actual in the iterator package
3947 Make_Loop_Statement (Loc,
3949 Make_Iteration_Scheme (Loc,
3951 Make_Function_Call (Loc,
3954 Next_Entity (First_Entity (Pack)), Loc),
3955 Parameter_Associations =>
3956 New_List (New_Occurrence_Of (Cursor, Loc)))),
3958 Statements => Stats,
3959 End_Label => Empty);
3961 -- If present, preserve identifier of loop, which can be used in
3962 -- an exit statement in the body.
3964 if Present (Identifier (N)) then
3965 Set_Identifier (New_Loop, Relocate_Node (Identifier (N)));
3968 -- Create the declarations for Iterator and cursor and insert them
3969 -- before the source loop. Given that the domain of iteration is already
3970 -- an entity, the iterator is just a renaming of that entity. Possible
3974 Make_Object_Renaming_Declaration (Loc,
3975 Defining_Identifier => Iterator,
3976 Subtype_Mark => New_Occurrence_Of (Iter_Type, Loc),
3977 Name => Relocate_Node (Name (I_Spec))));
3979 -- Create declaration for cursor
3982 Cursor_Decl : constant Node_Id :=
3983 Make_Object_Declaration (Loc,
3984 Defining_Identifier => Cursor,
3985 Object_Definition =>
3986 New_Occurrence_Of (Etype (Cursor), Loc),
3988 Make_Selected_Component (Loc,
3989 Prefix => New_Occurrence_Of (Iterator, Loc),
3991 Make_Identifier (Loc, Name_Init)));
3994 -- The cursor is only modified in expanded code, so it appears
3995 -- as unassigned to the warning machinery. We must suppress this
3996 -- spurious warning explicitly. The cursor's kind is that of the
3997 -- original loop parameter (it is a constant if the domain of
3998 -- iteration is constant).
4000 Set_Warnings_Off (Cursor);
4001 Set_Assignment_OK (Cursor_Decl);
4003 Insert_Action (N, Cursor_Decl);
4004 Set_Ekind (Cursor, I_Kind);
4007 -- If the range of iteration is given by a function call that returns
4008 -- a container, the finalization actions have been saved in the
4009 -- Condition_Actions of the iterator. Insert them now at the head of
4012 if Present (Condition_Actions (Isc)) then
4013 Insert_List_Before (N, Condition_Actions (Isc));
4016 Rewrite (N, New_Loop);
4018 end Expand_Iterator_Loop_Over_Container;
4020 -----------------------------
4021 -- Expand_N_Loop_Statement --
4022 -----------------------------
4024 -- 1. Remove null loop entirely
4025 -- 2. Deal with while condition for C/Fortran boolean
4026 -- 3. Deal with loops with a non-standard enumeration type range
4027 -- 4. Deal with while loops where Condition_Actions is set
4028 -- 5. Deal with loops over predicated subtypes
4029 -- 6. Deal with loops with iterators over arrays and containers
4030 -- 7. Insert polling call if required
4032 procedure Expand_N_Loop_Statement (N : Node_Id) is
4033 Loc : constant Source_Ptr := Sloc (N);
4034 Scheme : constant Node_Id := Iteration_Scheme (N);
4040 if Is_Null_Loop (N) then
4041 Rewrite (N, Make_Null_Statement (Loc));
4045 -- Deal with condition for C/Fortran Boolean
4047 if Present (Scheme) then
4048 Adjust_Condition (Condition (Scheme));
4051 -- Generate polling call
4053 if Is_Non_Empty_List (Statements (N)) then
4054 Generate_Poll_Call (First (Statements (N)));
4057 -- Nothing more to do for plain loop with no iteration scheme
4062 -- Case of for loop (Loop_Parameter_Specification present)
4064 -- Note: we do not have to worry about validity checking of the for loop
4065 -- range bounds here, since they were frozen with constant declarations
4066 -- and it is during that process that the validity checking is done.
4068 elsif Present (Loop_Parameter_Specification (Scheme)) then
4070 LPS : constant Node_Id :=
4071 Loop_Parameter_Specification (Scheme);
4072 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4073 Ltype : constant Entity_Id := Etype (Loop_Id);
4074 Btype : constant Entity_Id := Base_Type (Ltype);
4080 -- Deal with loop over predicates
4082 if Is_Discrete_Type (Ltype)
4083 and then Present (Predicate_Function (Ltype))
4085 Expand_Predicated_Loop (N);
4087 -- Handle the case where we have a for loop with the range type
4088 -- being an enumeration type with non-standard representation.
4089 -- In this case we expand:
4091 -- for x in [reverse] a .. b loop
4097 -- for xP in [reverse] integer
4098 -- range etype'Pos (a) .. etype'Pos (b)
4101 -- x : constant etype := Pos_To_Rep (xP);
4107 elsif Is_Enumeration_Type (Btype)
4108 and then Present (Enum_Pos_To_Rep (Btype))
4111 Make_Defining_Identifier (Loc,
4112 Chars => New_External_Name (Chars (Loop_Id), 'P'));
4114 -- If the type has a contiguous representation, successive
4115 -- values can be generated as offsets from the first literal.
4117 if Has_Contiguous_Rep (Btype) then
4119 Unchecked_Convert_To (Btype,
4122 Make_Integer_Literal (Loc,
4123 Enumeration_Rep (First_Literal (Btype))),
4124 Right_Opnd => New_Occurrence_Of (New_Id, Loc)));
4126 -- Use the constructed array Enum_Pos_To_Rep
4129 Make_Indexed_Component (Loc,
4131 New_Occurrence_Of (Enum_Pos_To_Rep (Btype), Loc),
4133 New_List (New_Occurrence_Of (New_Id, Loc)));
4136 -- Build declaration for loop identifier
4140 Make_Object_Declaration (Loc,
4141 Defining_Identifier => Loop_Id,
4142 Constant_Present => True,
4143 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4144 Expression => Expr));
4147 Make_Loop_Statement (Loc,
4148 Identifier => Identifier (N),
4151 Make_Iteration_Scheme (Loc,
4152 Loop_Parameter_Specification =>
4153 Make_Loop_Parameter_Specification (Loc,
4154 Defining_Identifier => New_Id,
4155 Reverse_Present => Reverse_Present (LPS),
4157 Discrete_Subtype_Definition =>
4158 Make_Subtype_Indication (Loc,
4161 New_Occurrence_Of (Standard_Natural, Loc),
4164 Make_Range_Constraint (Loc,
4169 Make_Attribute_Reference (Loc,
4171 New_Occurrence_Of (Btype, Loc),
4173 Attribute_Name => Name_Pos,
4175 Expressions => New_List (
4177 (Type_Low_Bound (Ltype)))),
4180 Make_Attribute_Reference (Loc,
4182 New_Occurrence_Of (Btype, Loc),
4184 Attribute_Name => Name_Pos,
4186 Expressions => New_List (
4191 Statements => New_List (
4192 Make_Block_Statement (Loc,
4193 Declarations => Decls,
4194 Handled_Statement_Sequence =>
4195 Make_Handled_Sequence_Of_Statements (Loc,
4196 Statements => Statements (N)))),
4198 End_Label => End_Label (N)));
4200 -- The loop parameter's entity must be removed from the loop
4201 -- scope's entity list and rendered invisible, since it will
4202 -- now be located in the new block scope. Any other entities
4203 -- already associated with the loop scope, such as the loop
4204 -- parameter's subtype, will remain there.
4206 -- In an element loop, the loop will contain a declaration for
4207 -- a cursor variable; otherwise the loop id is the first entity
4208 -- in the scope constructed for the loop.
4210 if Comes_From_Source (Loop_Id) then
4211 pragma Assert (First_Entity (Scope (Loop_Id)) = Loop_Id);
4215 Set_First_Entity (Scope (Loop_Id), Next_Entity (Loop_Id));
4216 Remove_Homonym (Loop_Id);
4218 if Last_Entity (Scope (Loop_Id)) = Loop_Id then
4219 Set_Last_Entity (Scope (Loop_Id), Empty);
4224 -- Nothing to do with other cases of for loops
4231 -- Second case, if we have a while loop with Condition_Actions set, then
4232 -- we change it into a plain loop:
4241 -- <<condition actions>>
4246 elsif Present (Scheme)
4247 and then Present (Condition_Actions (Scheme))
4248 and then Present (Condition (Scheme))
4255 Make_Exit_Statement (Sloc (Condition (Scheme)),
4257 Make_Op_Not (Sloc (Condition (Scheme)),
4258 Right_Opnd => Condition (Scheme)));
4260 Prepend (ES, Statements (N));
4261 Insert_List_Before (ES, Condition_Actions (Scheme));
4263 -- This is not an implicit loop, since it is generated in response
4264 -- to the loop statement being processed. If this is itself
4265 -- implicit, the restriction has already been checked. If not,
4266 -- it is an explicit loop.
4269 Make_Loop_Statement (Sloc (N),
4270 Identifier => Identifier (N),
4271 Statements => Statements (N),
4272 End_Label => End_Label (N)));
4277 -- Here to deal with iterator case
4279 elsif Present (Scheme)
4280 and then Present (Iterator_Specification (Scheme))
4282 Expand_Iterator_Loop (N);
4284 -- An iterator loop may generate renaming declarations for elements
4285 -- that require debug information. This is the case in particular
4286 -- with element iterators, where debug information must be generated
4287 -- for the temporary that holds the element value. These temporaries
4288 -- are created within a transient block whose local declarations are
4289 -- transferred to the loop, which now has nontrivial local objects.
4291 if Nkind (N) = N_Loop_Statement
4292 and then Present (Identifier (N))
4294 Qualify_Entity_Names (N);
4298 -- When the iteration scheme mentiones attribute 'Loop_Entry, the loop
4299 -- is transformed into a conditional block where the original loop is
4300 -- the sole statement. Inspect the statements of the nested loop for
4301 -- controlled objects.
4305 if Subject_To_Loop_Entry_Attributes (Stmt) then
4306 Stmt := Find_Loop_In_Conditional_Block (Stmt);
4309 Process_Statements_For_Controlled_Objects (Stmt);
4310 end Expand_N_Loop_Statement;
4312 ----------------------------
4313 -- Expand_Predicated_Loop --
4314 ----------------------------
4316 -- Note: the expander can handle generation of loops over predicated
4317 -- subtypes for both the dynamic and static cases. Depending on what
4318 -- we decide is allowed in Ada 2012 mode and/or extensions allowed
4319 -- mode, the semantic analyzer may disallow one or both forms.
4321 procedure Expand_Predicated_Loop (N : Node_Id) is
4322 Loc : constant Source_Ptr := Sloc (N);
4323 Isc : constant Node_Id := Iteration_Scheme (N);
4324 LPS : constant Node_Id := Loop_Parameter_Specification (Isc);
4325 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4326 Ltype : constant Entity_Id := Etype (Loop_Id);
4327 Stat : constant List_Id := Static_Discrete_Predicate (Ltype);
4328 Stmts : constant List_Id := Statements (N);
4331 -- Case of iteration over non-static predicate, should not be possible
4332 -- since this is not allowed by the semantics and should have been
4333 -- caught during analysis of the loop statement.
4336 raise Program_Error;
4338 -- If the predicate list is empty, that corresponds to a predicate of
4339 -- False, in which case the loop won't run at all, and we rewrite the
4340 -- entire loop as a null statement.
4342 elsif Is_Empty_List (Stat) then
4343 Rewrite (N, Make_Null_Statement (Loc));
4346 -- For expansion over a static predicate we generate the following
4349 -- J : Ltype := min-val;
4354 -- when endpoint => J := startpoint;
4355 -- when endpoint => J := startpoint;
4357 -- when max-val => exit;
4358 -- when others => J := Lval'Succ (J);
4363 -- with min-val replaced by max-val and Succ replaced by Pred if the
4364 -- loop parameter specification carries a Reverse indicator.
4366 -- To make this a little clearer, let's take a specific example:
4368 -- type Int is range 1 .. 10;
4369 -- subtype StaticP is Int with
4370 -- predicate => StaticP in 3 | 10 | 5 .. 7;
4372 -- for L in StaticP loop
4373 -- Put_Line ("static:" & J'Img);
4376 -- In this case, the loop is transformed into
4383 -- when 3 => J := 5;
4384 -- when 7 => J := 10;
4386 -- when others => J := L'Succ (J);
4392 Static_Predicate : declare
4399 function Lo_Val (N : Node_Id) return Node_Id;
4400 -- Given static expression or static range, returns an identifier
4401 -- whose value is the low bound of the expression value or range.
4403 function Hi_Val (N : Node_Id) return Node_Id;
4404 -- Given static expression or static range, returns an identifier
4405 -- whose value is the high bound of the expression value or range.
4411 function Hi_Val (N : Node_Id) return Node_Id is
4413 if Is_OK_Static_Expression (N) then
4414 return New_Copy (N);
4416 pragma Assert (Nkind (N) = N_Range);
4417 return New_Copy (High_Bound (N));
4425 function Lo_Val (N : Node_Id) return Node_Id is
4427 if Is_OK_Static_Expression (N) then
4428 return New_Copy (N);
4430 pragma Assert (Nkind (N) = N_Range);
4431 return New_Copy (Low_Bound (N));
4435 -- Start of processing for Static_Predicate
4438 -- Convert loop identifier to normal variable and reanalyze it so
4439 -- that this conversion works. We have to use the same defining
4440 -- identifier, since there may be references in the loop body.
4442 Set_Analyzed (Loop_Id, False);
4443 Set_Ekind (Loop_Id, E_Variable);
4445 -- In most loops the loop variable is assigned in various
4446 -- alternatives in the body. However, in the rare case when
4447 -- the range specifies a single element, the loop variable
4448 -- may trigger a spurious warning that is could be constant.
4449 -- This warning might as well be suppressed.
4451 Set_Warnings_Off (Loop_Id);
4453 -- Loop to create branches of case statement
4457 if Reverse_Present (LPS) then
4459 -- Initial value is largest value in predicate.
4462 Make_Object_Declaration (Loc,
4463 Defining_Identifier => Loop_Id,
4464 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4465 Expression => Hi_Val (Last (Stat)));
4468 while Present (P) loop
4469 if No (Prev (P)) then
4470 S := Make_Exit_Statement (Loc);
4473 Make_Assignment_Statement (Loc,
4474 Name => New_Occurrence_Of (Loop_Id, Loc),
4475 Expression => Hi_Val (Prev (P)));
4476 Set_Suppress_Assignment_Checks (S);
4480 Make_Case_Statement_Alternative (Loc,
4481 Statements => New_List (S),
4482 Discrete_Choices => New_List (Lo_Val (P))));
4489 -- Initial value is smallest value in predicate.
4492 Make_Object_Declaration (Loc,
4493 Defining_Identifier => Loop_Id,
4494 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4495 Expression => Lo_Val (First (Stat)));
4498 while Present (P) loop
4499 if No (Next (P)) then
4500 S := Make_Exit_Statement (Loc);
4503 Make_Assignment_Statement (Loc,
4504 Name => New_Occurrence_Of (Loop_Id, Loc),
4505 Expression => Lo_Val (Next (P)));
4506 Set_Suppress_Assignment_Checks (S);
4510 Make_Case_Statement_Alternative (Loc,
4511 Statements => New_List (S),
4512 Discrete_Choices => New_List (Hi_Val (P))));
4518 -- Add others choice
4521 Name_Next : Name_Id;
4524 if Reverse_Present (LPS) then
4525 Name_Next := Name_Pred;
4527 Name_Next := Name_Succ;
4531 Make_Assignment_Statement (Loc,
4532 Name => New_Occurrence_Of (Loop_Id, Loc),
4534 Make_Attribute_Reference (Loc,
4535 Prefix => New_Occurrence_Of (Ltype, Loc),
4536 Attribute_Name => Name_Next,
4537 Expressions => New_List (
4538 New_Occurrence_Of (Loop_Id, Loc))));
4539 Set_Suppress_Assignment_Checks (S);
4543 Make_Case_Statement_Alternative (Loc,
4544 Discrete_Choices => New_List (Make_Others_Choice (Loc)),
4545 Statements => New_List (S)));
4547 -- Construct case statement and append to body statements
4550 Make_Case_Statement (Loc,
4551 Expression => New_Occurrence_Of (Loop_Id, Loc),
4552 Alternatives => Alts);
4553 Append_To (Stmts, Cstm);
4557 Set_Suppress_Assignment_Checks (D);
4560 Make_Block_Statement (Loc,
4561 Declarations => New_List (D),
4562 Handled_Statement_Sequence =>
4563 Make_Handled_Sequence_Of_Statements (Loc,
4564 Statements => New_List (
4565 Make_Loop_Statement (Loc,
4566 Statements => Stmts,
4567 End_Label => Empty)))));
4570 end Static_Predicate;
4572 end Expand_Predicated_Loop;
4574 ------------------------------
4575 -- Make_Tag_Ctrl_Assignment --
4576 ------------------------------
4578 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
4579 Asn : constant Node_Id := Relocate_Node (N);
4580 L : constant Node_Id := Name (N);
4581 Loc : constant Source_Ptr := Sloc (N);
4582 Res : constant List_Id := New_List;
4583 T : constant Entity_Id := Underlying_Type (Etype (L));
4585 Comp_Asn : constant Boolean := Is_Fully_Repped_Tagged_Type (T);
4586 Ctrl_Act : constant Boolean := Needs_Finalization (T)
4587 and then not No_Ctrl_Actions (N);
4588 Save_Tag : constant Boolean := Is_Tagged_Type (T)
4589 and then not Comp_Asn
4590 and then not No_Ctrl_Actions (N)
4591 and then Tagged_Type_Expansion;
4595 -- Finalize the target of the assignment when controlled
4597 -- We have two exceptions here:
4599 -- 1. If we are in an init proc since it is an initialization more
4600 -- than an assignment.
4602 -- 2. If the left-hand side is a temporary that was not initialized
4603 -- (or the parent part of a temporary since it is the case in
4604 -- extension aggregates). Such a temporary does not come from
4605 -- source. We must examine the original node for the prefix, because
4606 -- it may be a component of an entry formal, in which case it has
4607 -- been rewritten and does not appear to come from source either.
4609 -- Case of init proc
4611 if not Ctrl_Act then
4614 -- The left hand side is an uninitialized temporary object
4616 elsif Nkind (L) = N_Type_Conversion
4617 and then Is_Entity_Name (Expression (L))
4618 and then Nkind (Parent (Entity (Expression (L)))) =
4619 N_Object_Declaration
4620 and then No_Initialization (Parent (Entity (Expression (L))))
4627 (Obj_Ref => Duplicate_Subexpr_No_Checks (L),
4631 -- Save the Tag in a local variable Tag_Id
4634 Tag_Id := Make_Temporary (Loc, 'A');
4637 Make_Object_Declaration (Loc,
4638 Defining_Identifier => Tag_Id,
4639 Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc),
4641 Make_Selected_Component (Loc,
4642 Prefix => Duplicate_Subexpr_No_Checks (L),
4644 New_Occurrence_Of (First_Tag_Component (T), Loc))));
4646 -- Otherwise Tag_Id is not used
4652 -- If the tagged type has a full rep clause, expand the assignment into
4653 -- component-wise assignments. Mark the node as unanalyzed in order to
4654 -- generate the proper code and propagate this scenario by setting a
4655 -- flag to avoid infinite recursion.
4658 Set_Analyzed (Asn, False);
4659 Set_Componentwise_Assignment (Asn, True);
4662 Append_To (Res, Asn);
4668 Make_Assignment_Statement (Loc,
4670 Make_Selected_Component (Loc,
4671 Prefix => Duplicate_Subexpr_No_Checks (L),
4673 New_Occurrence_Of (First_Tag_Component (T), Loc)),
4674 Expression => New_Occurrence_Of (Tag_Id, Loc)));
4677 -- Adjust the target after the assignment when controlled (not in the
4678 -- init proc since it is an initialization more than an assignment).
4683 (Obj_Ref => Duplicate_Subexpr_Move_Checks (L),
4691 -- Could use comment here ???
4693 when RE_Not_Available =>
4695 end Make_Tag_Ctrl_Assignment;