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_Array (N : Node_Id);
134 -- Expand loop over arrays that uses the form "for X of C"
136 procedure Expand_Iterator_Loop_Over_Container
141 Container_Typ : Entity_Id);
142 -- Expand loop over containers that uses the form "for X of C" with an
143 -- optional subtype mark, or "for Y in C". Isc is the iteration scheme.
144 -- I_Spec is the iterator specification and Container is either the
145 -- Container (for OF) or the iterator (for IN).
147 procedure Expand_Predicated_Loop (N : Node_Id);
148 -- Expand for loop over predicated subtype
150 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id;
151 -- Generate the necessary code for controlled and tagged assignment, that
152 -- is to say, finalization of the target before, adjustment of the target
153 -- after and save and restore of the tag and finalization pointers which
154 -- are not 'part of the value' and must not be changed upon assignment. N
155 -- is the original Assignment node.
157 --------------------------------------
158 -- Build_Formal_Container_iteration --
159 --------------------------------------
161 procedure Build_Formal_Container_Iteration
163 Container : Entity_Id;
166 Advance : out Node_Id;
167 New_Loop : out Node_Id)
169 Loc : constant Source_Ptr := Sloc (N);
170 Stats : constant List_Id := Statements (N);
171 Typ : constant Entity_Id := Base_Type (Etype (Container));
172 First_Op : constant Entity_Id :=
173 Get_Iterable_Type_Primitive (Typ, Name_First);
174 Next_Op : constant Entity_Id :=
175 Get_Iterable_Type_Primitive (Typ, Name_Next);
177 Has_Element_Op : constant Entity_Id :=
178 Get_Iterable_Type_Primitive (Typ, Name_Has_Element);
180 -- Declaration for Cursor
183 Make_Object_Declaration (Loc,
184 Defining_Identifier => Cursor,
185 Object_Definition => New_Occurrence_Of (Etype (First_Op), Loc),
187 Make_Function_Call (Loc,
188 Name => New_Occurrence_Of (First_Op, Loc),
189 Parameter_Associations => New_List (
190 New_Occurrence_Of (Container, Loc))));
192 -- Statement that advances cursor in loop
195 Make_Assignment_Statement (Loc,
196 Name => New_Occurrence_Of (Cursor, Loc),
198 Make_Function_Call (Loc,
199 Name => New_Occurrence_Of (Next_Op, Loc),
200 Parameter_Associations => New_List (
201 New_Occurrence_Of (Container, Loc),
202 New_Occurrence_Of (Cursor, Loc))));
204 -- Iterator is rewritten as a while_loop
207 Make_Loop_Statement (Loc,
209 Make_Iteration_Scheme (Loc,
211 Make_Function_Call (Loc,
212 Name => New_Occurrence_Of (Has_Element_Op, Loc),
213 Parameter_Associations => New_List (
214 New_Occurrence_Of (Container, Loc),
215 New_Occurrence_Of (Cursor, Loc)))),
218 end Build_Formal_Container_Iteration;
220 ------------------------------
221 -- Change_Of_Representation --
222 ------------------------------
224 function Change_Of_Representation (N : Node_Id) return Boolean is
225 Rhs : constant Node_Id := Expression (N);
228 Nkind (Rhs) = N_Type_Conversion
230 not Same_Representation (Etype (Rhs), Etype (Expression (Rhs)));
231 end Change_Of_Representation;
233 -------------------------
234 -- Expand_Assign_Array --
235 -------------------------
237 -- There are two issues here. First, do we let Gigi do a block move, or
238 -- do we expand out into a loop? Second, we need to set the two flags
239 -- Forwards_OK and Backwards_OK which show whether the block move (or
240 -- corresponding loops) can be legitimately done in a forwards (low to
241 -- high) or backwards (high to low) manner.
243 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id) is
244 Loc : constant Source_Ptr := Sloc (N);
246 Lhs : constant Node_Id := Name (N);
248 Act_Lhs : constant Node_Id := Get_Referenced_Object (Lhs);
249 Act_Rhs : Node_Id := Get_Referenced_Object (Rhs);
251 L_Type : constant Entity_Id :=
252 Underlying_Type (Get_Actual_Subtype (Act_Lhs));
253 R_Type : Entity_Id :=
254 Underlying_Type (Get_Actual_Subtype (Act_Rhs));
256 L_Slice : constant Boolean := Nkind (Act_Lhs) = N_Slice;
257 R_Slice : constant Boolean := Nkind (Act_Rhs) = N_Slice;
259 Crep : constant Boolean := Change_Of_Representation (N);
264 Ndim : constant Pos := Number_Dimensions (L_Type);
266 Loop_Required : Boolean := False;
267 -- This switch is set to True if the array move must be done using
268 -- an explicit front end generated loop.
270 procedure Apply_Dereference (Arg : Node_Id);
271 -- If the argument is an access to an array, and the assignment is
272 -- converted into a procedure call, apply explicit dereference.
274 function Has_Address_Clause (Exp : Node_Id) return Boolean;
275 -- Test if Exp is a reference to an array whose declaration has
276 -- an address clause, or it is a slice of such an array.
278 function Is_Formal_Array (Exp : Node_Id) return Boolean;
279 -- Test if Exp is a reference to an array which is either a formal
280 -- parameter or a slice of a formal parameter. These are the cases
281 -- where hidden aliasing can occur.
283 function Is_Non_Local_Array (Exp : Node_Id) return Boolean;
284 -- Determine if Exp is a reference to an array variable which is other
285 -- than an object defined in the current scope, or a slice of such
286 -- an object. Such objects can be aliased to parameters (unlike local
287 -- array references).
289 -----------------------
290 -- Apply_Dereference --
291 -----------------------
293 procedure Apply_Dereference (Arg : Node_Id) is
294 Typ : constant Entity_Id := Etype (Arg);
296 if Is_Access_Type (Typ) then
297 Rewrite (Arg, Make_Explicit_Dereference (Loc,
298 Prefix => Relocate_Node (Arg)));
299 Analyze_And_Resolve (Arg, Designated_Type (Typ));
301 end Apply_Dereference;
303 ------------------------
304 -- Has_Address_Clause --
305 ------------------------
307 function Has_Address_Clause (Exp : Node_Id) return Boolean is
310 (Is_Entity_Name (Exp) and then
311 Present (Address_Clause (Entity (Exp))))
313 (Nkind (Exp) = N_Slice and then Has_Address_Clause (Prefix (Exp)));
314 end Has_Address_Clause;
316 ---------------------
317 -- Is_Formal_Array --
318 ---------------------
320 function Is_Formal_Array (Exp : Node_Id) return Boolean is
323 (Is_Entity_Name (Exp) and then Is_Formal (Entity (Exp)))
325 (Nkind (Exp) = N_Slice and then Is_Formal_Array (Prefix (Exp)));
328 ------------------------
329 -- Is_Non_Local_Array --
330 ------------------------
332 function Is_Non_Local_Array (Exp : Node_Id) return Boolean is
334 return (Is_Entity_Name (Exp)
335 and then Scope (Entity (Exp)) /= Current_Scope)
336 or else (Nkind (Exp) = N_Slice
337 and then Is_Non_Local_Array (Prefix (Exp)));
338 end Is_Non_Local_Array;
340 -- Determine if Lhs, Rhs are formal arrays or nonlocal arrays
342 Lhs_Formal : constant Boolean := Is_Formal_Array (Act_Lhs);
343 Rhs_Formal : constant Boolean := Is_Formal_Array (Act_Rhs);
345 Lhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Lhs);
346 Rhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Rhs);
348 -- Start of processing for Expand_Assign_Array
351 -- Deal with length check. Note that the length check is done with
352 -- respect to the right hand side as given, not a possible underlying
353 -- renamed object, since this would generate incorrect extra checks.
355 Apply_Length_Check (Rhs, L_Type);
357 -- We start by assuming that the move can be done in either direction,
358 -- i.e. that the two sides are completely disjoint.
360 Set_Forwards_OK (N, True);
361 Set_Backwards_OK (N, True);
363 -- Normally it is only the slice case that can lead to overlap, and
364 -- explicit checks for slices are made below. But there is one case
365 -- where the slice can be implicit and invisible to us: when we have a
366 -- one dimensional array, and either both operands are parameters, or
367 -- one is a parameter (which can be a slice passed by reference) and the
368 -- other is a non-local variable. In this case the parameter could be a
369 -- slice that overlaps with the other operand.
371 -- However, if the array subtype is a constrained first subtype in the
372 -- parameter case, then we don't have to worry about overlap, since
373 -- slice assignments aren't possible (other than for a slice denoting
376 -- Note: No overlap is possible if there is a change of representation,
377 -- so we can exclude this case.
382 ((Lhs_Formal and Rhs_Formal)
384 (Lhs_Formal and Rhs_Non_Local_Var)
386 (Rhs_Formal and Lhs_Non_Local_Var))
388 (not Is_Constrained (Etype (Lhs))
389 or else not Is_First_Subtype (Etype (Lhs)))
391 Set_Forwards_OK (N, False);
392 Set_Backwards_OK (N, False);
394 -- Note: the bit-packed case is not worrisome here, since if we have
395 -- a slice passed as a parameter, it is always aligned on a byte
396 -- boundary, and if there are no explicit slices, the assignment
397 -- can be performed directly.
400 -- If either operand has an address clause clear Backwards_OK and
401 -- Forwards_OK, since we cannot tell if the operands overlap. We
402 -- exclude this treatment when Rhs is an aggregate, since we know
403 -- that overlap can't occur.
405 if (Has_Address_Clause (Lhs) and then Nkind (Rhs) /= N_Aggregate)
406 or else Has_Address_Clause (Rhs)
408 Set_Forwards_OK (N, False);
409 Set_Backwards_OK (N, False);
412 -- We certainly must use a loop for change of representation and also
413 -- we use the operand of the conversion on the right hand side as the
414 -- effective right hand side (the component types must match in this
418 Act_Rhs := Get_Referenced_Object (Rhs);
419 R_Type := Get_Actual_Subtype (Act_Rhs);
420 Loop_Required := True;
422 -- We require a loop if the left side is possibly bit unaligned
424 elsif Possible_Bit_Aligned_Component (Lhs)
426 Possible_Bit_Aligned_Component (Rhs)
428 Loop_Required := True;
430 -- Arrays with controlled components are expanded into a loop to force
431 -- calls to Adjust at the component level.
433 elsif Has_Controlled_Component (L_Type) then
434 Loop_Required := True;
436 -- If object is atomic/VFA, we cannot tolerate a loop
438 elsif Is_Atomic_Or_VFA_Object (Act_Lhs)
440 Is_Atomic_Or_VFA_Object (Act_Rhs)
444 -- Loop is required if we have atomic components since we have to
445 -- be sure to do any accesses on an element by element basis.
447 elsif Has_Atomic_Components (L_Type)
448 or else Has_Atomic_Components (R_Type)
449 or else Is_Atomic_Or_VFA (Component_Type (L_Type))
450 or else Is_Atomic_Or_VFA (Component_Type (R_Type))
452 Loop_Required := True;
454 -- Case where no slice is involved
456 elsif not L_Slice and not R_Slice then
458 -- The following code deals with the case of unconstrained bit packed
459 -- arrays. The problem is that the template for such arrays contains
460 -- the bounds of the actual source level array, but the copy of an
461 -- entire array requires the bounds of the underlying array. It would
462 -- be nice if the back end could take care of this, but right now it
463 -- does not know how, so if we have such a type, then we expand out
464 -- into a loop, which is inefficient but works correctly. If we don't
465 -- do this, we get the wrong length computed for the array to be
466 -- moved. The two cases we need to worry about are:
468 -- Explicit dereference of an unconstrained packed array type as in
469 -- the following example:
472 -- type BITS is array(INTEGER range <>) of BOOLEAN;
473 -- pragma PACK(BITS);
474 -- type A is access BITS;
477 -- P1 := new BITS (1 .. 65_535);
478 -- P2 := new BITS (1 .. 65_535);
482 -- A formal parameter reference with an unconstrained bit array type
483 -- is the other case we need to worry about (here we assume the same
484 -- BITS type declared above):
486 -- procedure Write_All (File : out BITS; Contents : BITS);
488 -- File.Storage := Contents;
491 -- We expand to a loop in either of these two cases
493 -- Question for future thought. Another potentially more efficient
494 -- approach would be to create the actual subtype, and then do an
495 -- unchecked conversion to this actual subtype ???
497 Check_Unconstrained_Bit_Packed_Array : declare
499 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean;
500 -- Function to perform required test for the first case, above
501 -- (dereference of an unconstrained bit packed array).
503 -----------------------
504 -- Is_UBPA_Reference --
505 -----------------------
507 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean is
508 Typ : constant Entity_Id := Underlying_Type (Etype (Opnd));
510 Des_Type : Entity_Id;
513 if Present (Packed_Array_Impl_Type (Typ))
514 and then Is_Array_Type (Packed_Array_Impl_Type (Typ))
515 and then not Is_Constrained (Packed_Array_Impl_Type (Typ))
519 elsif Nkind (Opnd) = N_Explicit_Dereference then
520 P_Type := Underlying_Type (Etype (Prefix (Opnd)));
522 if not Is_Access_Type (P_Type) then
526 Des_Type := Designated_Type (P_Type);
528 Is_Bit_Packed_Array (Des_Type)
529 and then not Is_Constrained (Des_Type);
535 end Is_UBPA_Reference;
537 -- Start of processing for Check_Unconstrained_Bit_Packed_Array
540 if Is_UBPA_Reference (Lhs)
542 Is_UBPA_Reference (Rhs)
544 Loop_Required := True;
546 -- Here if we do not have the case of a reference to a bit packed
547 -- unconstrained array case. In this case gigi can most certainly
548 -- handle the assignment if a forwards move is allowed.
550 -- (could it handle the backwards case also???)
552 elsif Forwards_OK (N) then
555 end Check_Unconstrained_Bit_Packed_Array;
557 -- The back end can always handle the assignment if the right side is a
558 -- string literal (note that overlap is definitely impossible in this
559 -- case). If the type is packed, a string literal is always converted
560 -- into an aggregate, except in the case of a null slice, for which no
561 -- aggregate can be written. In that case, rewrite the assignment as a
562 -- null statement, a length check has already been emitted to verify
563 -- that the range of the left-hand side is empty.
565 -- Note that this code is not executed if we have an assignment of a
566 -- string literal to a non-bit aligned component of a record, a case
567 -- which cannot be handled by the backend.
569 elsif Nkind (Rhs) = N_String_Literal then
570 if String_Length (Strval (Rhs)) = 0
571 and then Is_Bit_Packed_Array (L_Type)
573 Rewrite (N, Make_Null_Statement (Loc));
579 -- If either operand is bit packed, then we need a loop, since we can't
580 -- be sure that the slice is byte aligned. Similarly, if either operand
581 -- is a possibly unaligned slice, then we need a loop (since the back
582 -- end cannot handle unaligned slices).
584 elsif Is_Bit_Packed_Array (L_Type)
585 or else Is_Bit_Packed_Array (R_Type)
586 or else Is_Possibly_Unaligned_Slice (Lhs)
587 or else Is_Possibly_Unaligned_Slice (Rhs)
589 Loop_Required := True;
591 -- If we are not bit-packed, and we have only one slice, then no overlap
592 -- is possible except in the parameter case, so we can let the back end
595 elsif not (L_Slice and R_Slice) then
596 if Forwards_OK (N) then
601 -- If the right-hand side is a string literal, introduce a temporary for
602 -- it, for use in the generated loop that will follow.
604 if Nkind (Rhs) = N_String_Literal then
606 Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Rhs);
611 Make_Object_Declaration (Loc,
612 Defining_Identifier => Temp,
613 Object_Definition => New_Occurrence_Of (L_Type, Loc),
614 Expression => Relocate_Node (Rhs));
616 Insert_Action (N, Decl);
617 Rewrite (Rhs, New_Occurrence_Of (Temp, Loc));
618 R_Type := Etype (Temp);
622 -- Come here to complete the analysis
624 -- Loop_Required: Set to True if we know that a loop is required
625 -- regardless of overlap considerations.
627 -- Forwards_OK: Set to False if we already know that a forwards
628 -- move is not safe, else set to True.
630 -- Backwards_OK: Set to False if we already know that a backwards
631 -- move is not safe, else set to True
633 -- Our task at this stage is to complete the overlap analysis, which can
634 -- result in possibly setting Forwards_OK or Backwards_OK to False, and
635 -- then generating the final code, either by deciding that it is OK
636 -- after all to let Gigi handle it, or by generating appropriate code
640 L_Index_Typ : constant Node_Id := Etype (First_Index (L_Type));
641 R_Index_Typ : constant Node_Id := Etype (First_Index (R_Type));
643 Left_Lo : constant Node_Id := Type_Low_Bound (L_Index_Typ);
644 Left_Hi : constant Node_Id := Type_High_Bound (L_Index_Typ);
645 Right_Lo : constant Node_Id := Type_Low_Bound (R_Index_Typ);
646 Right_Hi : constant Node_Id := Type_High_Bound (R_Index_Typ);
648 Act_L_Array : Node_Id;
649 Act_R_Array : Node_Id;
655 Cresult : Compare_Result;
658 -- Get the expressions for the arrays. If we are dealing with a
659 -- private type, then convert to the underlying type. We can do
660 -- direct assignments to an array that is a private type, but we
661 -- cannot assign to elements of the array without this extra
662 -- unchecked conversion.
664 -- Note: We propagate Parent to the conversion nodes to generate
665 -- a well-formed subtree.
667 if Nkind (Act_Lhs) = N_Slice then
668 Larray := Prefix (Act_Lhs);
672 if Is_Private_Type (Etype (Larray)) then
674 Par : constant Node_Id := Parent (Larray);
678 (Underlying_Type (Etype (Larray)), Larray);
679 Set_Parent (Larray, Par);
684 if Nkind (Act_Rhs) = N_Slice then
685 Rarray := Prefix (Act_Rhs);
689 if Is_Private_Type (Etype (Rarray)) then
691 Par : constant Node_Id := Parent (Rarray);
695 (Underlying_Type (Etype (Rarray)), Rarray);
696 Set_Parent (Rarray, Par);
701 -- If both sides are slices, we must figure out whether it is safe
702 -- to do the move in one direction or the other. It is always safe
703 -- if there is a change of representation since obviously two arrays
704 -- with different representations cannot possibly overlap.
706 if (not Crep) and L_Slice and R_Slice then
707 Act_L_Array := Get_Referenced_Object (Prefix (Act_Lhs));
708 Act_R_Array := Get_Referenced_Object (Prefix (Act_Rhs));
710 -- If both left and right hand arrays are entity names, and refer
711 -- to different entities, then we know that the move is safe (the
712 -- two storage areas are completely disjoint).
714 if Is_Entity_Name (Act_L_Array)
715 and then Is_Entity_Name (Act_R_Array)
716 and then Entity (Act_L_Array) /= Entity (Act_R_Array)
720 -- Otherwise, we assume the worst, which is that the two arrays
721 -- are the same array. There is no need to check if we know that
722 -- is the case, because if we don't know it, we still have to
725 -- Generally if the same array is involved, then we have an
726 -- overlapping case. We will have to really assume the worst (i.e.
727 -- set neither of the OK flags) unless we can determine the lower
728 -- or upper bounds at compile time and compare them.
733 (Left_Lo, Right_Lo, Assume_Valid => True);
735 if Cresult = Unknown then
738 (Left_Hi, Right_Hi, Assume_Valid => True);
742 when LT | LE | EQ => Set_Backwards_OK (N, False);
743 when GT | GE => Set_Forwards_OK (N, False);
744 when NE | Unknown => Set_Backwards_OK (N, False);
745 Set_Forwards_OK (N, False);
750 -- If after that analysis Loop_Required is False, meaning that we
751 -- have not discovered some non-overlap reason for requiring a loop,
752 -- then the outcome depends on the capabilities of the back end.
754 if not Loop_Required then
756 -- The GCC back end can deal with all cases of overlap by falling
757 -- back to memmove if it cannot use a more efficient approach.
759 if not AAMP_On_Target then
762 -- Assume other back ends can handle it if Forwards_OK is set
764 elsif Forwards_OK (N) then
767 -- If Forwards_OK is not set, the back end will need something
768 -- like memmove to handle the move. For now, this processing is
769 -- activated using the .s debug flag (-gnatd.s).
771 elsif Debug_Flag_Dot_S then
776 -- At this stage we have to generate an explicit loop, and we have
777 -- the following cases:
779 -- Forwards_OK = True
781 -- Rnn : right_index := right_index'First;
782 -- for Lnn in left-index loop
783 -- left (Lnn) := right (Rnn);
784 -- Rnn := right_index'Succ (Rnn);
787 -- Note: the above code MUST be analyzed with checks off, because
788 -- otherwise the Succ could overflow. But in any case this is more
791 -- Forwards_OK = False, Backwards_OK = True
793 -- Rnn : right_index := right_index'Last;
794 -- for Lnn in reverse left-index loop
795 -- left (Lnn) := right (Rnn);
796 -- Rnn := right_index'Pred (Rnn);
799 -- Note: the above code MUST be analyzed with checks off, because
800 -- otherwise the Pred could overflow. But in any case this is more
803 -- Forwards_OK = Backwards_OK = False
805 -- This only happens if we have the same array on each side. It is
806 -- possible to create situations using overlays that violate this,
807 -- but we simply do not promise to get this "right" in this case.
809 -- There are two possible subcases. If the No_Implicit_Conditionals
810 -- restriction is set, then we generate the following code:
813 -- T : constant <operand-type> := rhs;
818 -- If implicit conditionals are permitted, then we generate:
820 -- if Left_Lo <= Right_Lo then
821 -- <code for Forwards_OK = True above>
823 -- <code for Backwards_OK = True above>
826 -- In order to detect possible aliasing, we examine the renamed
827 -- expression when the source or target is a renaming. However,
828 -- the renaming may be intended to capture an address that may be
829 -- affected by subsequent code, and therefore we must recover
830 -- the actual entity for the expansion that follows, not the
831 -- object it renames. In particular, if source or target designate
832 -- a portion of a dynamically allocated object, the pointer to it
833 -- may be reassigned but the renaming preserves the proper location.
835 if Is_Entity_Name (Rhs)
837 Nkind (Parent (Entity (Rhs))) = N_Object_Renaming_Declaration
838 and then Nkind (Act_Rhs) = N_Slice
843 if Is_Entity_Name (Lhs)
845 Nkind (Parent (Entity (Lhs))) = N_Object_Renaming_Declaration
846 and then Nkind (Act_Lhs) = N_Slice
851 -- Cases where either Forwards_OK or Backwards_OK is true
853 if Forwards_OK (N) or else Backwards_OK (N) then
854 if Needs_Finalization (Component_Type (L_Type))
855 and then Base_Type (L_Type) = Base_Type (R_Type)
857 and then not No_Ctrl_Actions (N)
860 Proc : constant Entity_Id :=
861 TSS (Base_Type (L_Type), TSS_Slice_Assign);
865 Apply_Dereference (Larray);
866 Apply_Dereference (Rarray);
867 Actuals := New_List (
868 Duplicate_Subexpr (Larray, Name_Req => True),
869 Duplicate_Subexpr (Rarray, Name_Req => True),
870 Duplicate_Subexpr (Left_Lo, Name_Req => True),
871 Duplicate_Subexpr (Left_Hi, Name_Req => True),
872 Duplicate_Subexpr (Right_Lo, Name_Req => True),
873 Duplicate_Subexpr (Right_Hi, Name_Req => True));
877 Boolean_Literals (not Forwards_OK (N)), Loc));
880 Make_Procedure_Call_Statement (Loc,
881 Name => New_Occurrence_Of (Proc, Loc),
882 Parameter_Associations => Actuals));
887 Expand_Assign_Array_Loop
888 (N, Larray, Rarray, L_Type, R_Type, Ndim,
889 Rev => not Forwards_OK (N)));
892 -- Case of both are false with No_Implicit_Conditionals
894 elsif Restriction_Active (No_Implicit_Conditionals) then
896 T : constant Entity_Id :=
897 Make_Defining_Identifier (Loc, Chars => Name_T);
901 Make_Block_Statement (Loc,
902 Declarations => New_List (
903 Make_Object_Declaration (Loc,
904 Defining_Identifier => T,
905 Constant_Present => True,
907 New_Occurrence_Of (Etype (Rhs), Loc),
908 Expression => Relocate_Node (Rhs))),
910 Handled_Statement_Sequence =>
911 Make_Handled_Sequence_Of_Statements (Loc,
912 Statements => New_List (
913 Make_Assignment_Statement (Loc,
914 Name => Relocate_Node (Lhs),
915 Expression => New_Occurrence_Of (T, Loc))))));
918 -- Case of both are false with implicit conditionals allowed
921 -- Before we generate this code, we must ensure that the left and
922 -- right side array types are defined. They may be itypes, and we
923 -- cannot let them be defined inside the if, since the first use
924 -- in the then may not be executed.
926 Ensure_Defined (L_Type, N);
927 Ensure_Defined (R_Type, N);
929 -- We normally compare addresses to find out which way round to
930 -- do the loop, since this is reliable, and handles the cases of
931 -- parameters, conversions etc. But we can't do that in the bit
932 -- packed case, because addresses don't work there.
934 if not Is_Bit_Packed_Array (L_Type) then
938 Unchecked_Convert_To (RTE (RE_Integer_Address),
939 Make_Attribute_Reference (Loc,
941 Make_Indexed_Component (Loc,
943 Duplicate_Subexpr_Move_Checks (Larray, True),
944 Expressions => New_List (
945 Make_Attribute_Reference (Loc,
949 Attribute_Name => Name_First))),
950 Attribute_Name => Name_Address)),
953 Unchecked_Convert_To (RTE (RE_Integer_Address),
954 Make_Attribute_Reference (Loc,
956 Make_Indexed_Component (Loc,
958 Duplicate_Subexpr_Move_Checks (Rarray, True),
959 Expressions => New_List (
960 Make_Attribute_Reference (Loc,
964 Attribute_Name => Name_First))),
965 Attribute_Name => Name_Address)));
967 -- For the bit packed and VM cases we use the bounds. That's OK,
968 -- because we don't have to worry about parameters, since they
969 -- cannot cause overlap. Perhaps we should worry about weird slice
975 Cleft_Lo := New_Copy_Tree (Left_Lo);
976 Cright_Lo := New_Copy_Tree (Right_Lo);
978 -- If the types do not match we add an implicit conversion
979 -- here to ensure proper match
981 if Etype (Left_Lo) /= Etype (Right_Lo) then
983 Unchecked_Convert_To (Etype (Left_Lo), Cright_Lo);
986 -- Reset the Analyzed flag, because the bounds of the index
987 -- type itself may be universal, and must must be reanalyzed
988 -- to acquire the proper type for the back end.
990 Set_Analyzed (Cleft_Lo, False);
991 Set_Analyzed (Cright_Lo, False);
995 Left_Opnd => Cleft_Lo,
996 Right_Opnd => Cright_Lo);
999 if Needs_Finalization (Component_Type (L_Type))
1000 and then Base_Type (L_Type) = Base_Type (R_Type)
1002 and then not No_Ctrl_Actions (N)
1005 -- Call TSS procedure for array assignment, passing the
1006 -- explicit bounds of right and left hand sides.
1009 Proc : constant Entity_Id :=
1010 TSS (Base_Type (L_Type), TSS_Slice_Assign);
1014 Apply_Dereference (Larray);
1015 Apply_Dereference (Rarray);
1016 Actuals := New_List (
1017 Duplicate_Subexpr (Larray, Name_Req => True),
1018 Duplicate_Subexpr (Rarray, Name_Req => True),
1019 Duplicate_Subexpr (Left_Lo, Name_Req => True),
1020 Duplicate_Subexpr (Left_Hi, Name_Req => True),
1021 Duplicate_Subexpr (Right_Lo, Name_Req => True),
1022 Duplicate_Subexpr (Right_Hi, Name_Req => True));
1026 Right_Opnd => Condition));
1029 Make_Procedure_Call_Statement (Loc,
1030 Name => New_Occurrence_Of (Proc, Loc),
1031 Parameter_Associations => Actuals));
1036 Make_Implicit_If_Statement (N,
1037 Condition => Condition,
1039 Then_Statements => New_List (
1040 Expand_Assign_Array_Loop
1041 (N, Larray, Rarray, L_Type, R_Type, Ndim,
1044 Else_Statements => New_List (
1045 Expand_Assign_Array_Loop
1046 (N, Larray, Rarray, L_Type, R_Type, Ndim,
1051 Analyze (N, Suppress => All_Checks);
1055 when RE_Not_Available =>
1057 end Expand_Assign_Array;
1059 ------------------------------
1060 -- Expand_Assign_Array_Loop --
1061 ------------------------------
1063 -- The following is an example of the loop generated for the case of a
1064 -- two-dimensional array:
1067 -- R2b : Tm1X1 := 1;
1069 -- for L1b in 1 .. 100 loop
1071 -- R4b : Tm1X2 := 1;
1073 -- for L3b in 1 .. 100 loop
1074 -- vm1 (L1b, L3b) := vm2 (R2b, R4b);
1075 -- R4b := Tm1X2'succ(R4b);
1078 -- R2b := Tm1X1'succ(R2b);
1082 -- Here Rev is False, and Tm1Xn are the subscript types for the right hand
1083 -- side. The declarations of R2b and R4b are inserted before the original
1084 -- assignment statement.
1086 function Expand_Assign_Array_Loop
1093 Rev : Boolean) return Node_Id
1095 Loc : constant Source_Ptr := Sloc (N);
1097 Lnn : array (1 .. Ndim) of Entity_Id;
1098 Rnn : array (1 .. Ndim) of Entity_Id;
1099 -- Entities used as subscripts on left and right sides
1101 L_Index_Type : array (1 .. Ndim) of Entity_Id;
1102 R_Index_Type : array (1 .. Ndim) of Entity_Id;
1103 -- Left and right index types
1110 function Build_Step (J : Nat) return Node_Id;
1111 -- The increment step for the index of the right-hand side is written
1112 -- as an attribute reference (Succ or Pred). This function returns
1113 -- the corresponding node, which is placed at the end of the loop body.
1119 function Build_Step (J : Nat) return Node_Id is
1131 Make_Assignment_Statement (Loc,
1132 Name => New_Occurrence_Of (Rnn (J), Loc),
1134 Make_Attribute_Reference (Loc,
1136 New_Occurrence_Of (R_Index_Type (J), Loc),
1137 Attribute_Name => S_Or_P,
1138 Expressions => New_List (
1139 New_Occurrence_Of (Rnn (J), Loc))));
1141 -- Note that on the last iteration of the loop, the index is increased
1142 -- (or decreased) past the corresponding bound. This is consistent with
1143 -- the C semantics of the back-end, where such an off-by-one value on a
1144 -- dead index variable is OK. However, in CodePeer mode this leads to
1145 -- spurious warnings, and thus we place a guard around the attribute
1146 -- reference. For obvious reasons we only do this for CodePeer.
1148 if CodePeer_Mode then
1150 Make_If_Statement (Loc,
1153 Left_Opnd => New_Occurrence_Of (Lnn (J), Loc),
1155 Make_Attribute_Reference (Loc,
1156 Prefix => New_Occurrence_Of (L_Index_Type (J), Loc),
1157 Attribute_Name => Lim)),
1158 Then_Statements => New_List (Step));
1164 -- Start of processing for Expand_Assign_Array_Loop
1168 F_Or_L := Name_Last;
1169 S_Or_P := Name_Pred;
1171 F_Or_L := Name_First;
1172 S_Or_P := Name_Succ;
1175 -- Setup index types and subscript entities
1182 L_Index := First_Index (L_Type);
1183 R_Index := First_Index (R_Type);
1185 for J in 1 .. Ndim loop
1186 Lnn (J) := Make_Temporary (Loc, 'L');
1187 Rnn (J) := Make_Temporary (Loc, 'R');
1189 L_Index_Type (J) := Etype (L_Index);
1190 R_Index_Type (J) := Etype (R_Index);
1192 Next_Index (L_Index);
1193 Next_Index (R_Index);
1197 -- Now construct the assignment statement
1200 ExprL : constant List_Id := New_List;
1201 ExprR : constant List_Id := New_List;
1204 for J in 1 .. Ndim loop
1205 Append_To (ExprL, New_Occurrence_Of (Lnn (J), Loc));
1206 Append_To (ExprR, New_Occurrence_Of (Rnn (J), Loc));
1210 Make_Assignment_Statement (Loc,
1212 Make_Indexed_Component (Loc,
1213 Prefix => Duplicate_Subexpr (Larray, Name_Req => True),
1214 Expressions => ExprL),
1216 Make_Indexed_Component (Loc,
1217 Prefix => Duplicate_Subexpr (Rarray, Name_Req => True),
1218 Expressions => ExprR));
1220 -- We set assignment OK, since there are some cases, e.g. in object
1221 -- declarations, where we are actually assigning into a constant.
1222 -- If there really is an illegality, it was caught long before now,
1223 -- and was flagged when the original assignment was analyzed.
1225 Set_Assignment_OK (Name (Assign));
1227 -- Propagate the No_Ctrl_Actions flag to individual assignments
1229 Set_No_Ctrl_Actions (Assign, No_Ctrl_Actions (N));
1232 -- Now construct the loop from the inside out, with the last subscript
1233 -- varying most rapidly. Note that Assign is first the raw assignment
1234 -- statement, and then subsequently the loop that wraps it up.
1236 for J in reverse 1 .. Ndim loop
1238 Make_Block_Statement (Loc,
1239 Declarations => New_List (
1240 Make_Object_Declaration (Loc,
1241 Defining_Identifier => Rnn (J),
1242 Object_Definition =>
1243 New_Occurrence_Of (R_Index_Type (J), Loc),
1245 Make_Attribute_Reference (Loc,
1246 Prefix => New_Occurrence_Of (R_Index_Type (J), Loc),
1247 Attribute_Name => F_Or_L))),
1249 Handled_Statement_Sequence =>
1250 Make_Handled_Sequence_Of_Statements (Loc,
1251 Statements => New_List (
1252 Make_Implicit_Loop_Statement (N,
1254 Make_Iteration_Scheme (Loc,
1255 Loop_Parameter_Specification =>
1256 Make_Loop_Parameter_Specification (Loc,
1257 Defining_Identifier => Lnn (J),
1258 Reverse_Present => Rev,
1259 Discrete_Subtype_Definition =>
1260 New_Occurrence_Of (L_Index_Type (J), Loc))),
1262 Statements => New_List (Assign, Build_Step (J))))));
1266 end Expand_Assign_Array_Loop;
1268 --------------------------
1269 -- Expand_Assign_Record --
1270 --------------------------
1272 procedure Expand_Assign_Record (N : Node_Id) is
1273 Lhs : constant Node_Id := Name (N);
1274 Rhs : Node_Id := Expression (N);
1275 L_Typ : constant Entity_Id := Base_Type (Etype (Lhs));
1278 -- If change of representation, then extract the real right hand side
1279 -- from the type conversion, and proceed with component-wise assignment,
1280 -- since the two types are not the same as far as the back end is
1283 if Change_Of_Representation (N) then
1284 Rhs := Expression (Rhs);
1286 -- If this may be a case of a large bit aligned component, then proceed
1287 -- with component-wise assignment, to avoid possible clobbering of other
1288 -- components sharing bits in the first or last byte of the component to
1291 elsif Possible_Bit_Aligned_Component (Lhs)
1293 Possible_Bit_Aligned_Component (Rhs)
1297 -- If we have a tagged type that has a complete record representation
1298 -- clause, we must do we must do component-wise assignments, since child
1299 -- types may have used gaps for their components, and we might be
1300 -- dealing with a view conversion.
1302 elsif Is_Fully_Repped_Tagged_Type (L_Typ) then
1305 -- If neither condition met, then nothing special to do, the back end
1306 -- can handle assignment of the entire component as a single entity.
1312 -- At this stage we know that we must do a component wise assignment
1315 Loc : constant Source_Ptr := Sloc (N);
1316 R_Typ : constant Entity_Id := Base_Type (Etype (Rhs));
1317 Decl : constant Node_Id := Declaration_Node (R_Typ);
1321 function Find_Component
1323 Comp : Entity_Id) return Entity_Id;
1324 -- Find the component with the given name in the underlying record
1325 -- declaration for Typ. We need to use the actual entity because the
1326 -- type may be private and resolution by identifier alone would fail.
1328 function Make_Component_List_Assign
1330 U_U : Boolean := False) return List_Id;
1331 -- Returns a sequence of statements to assign the components that
1332 -- are referenced in the given component list. The flag U_U is
1333 -- used to force the usage of the inferred value of the variant
1334 -- part expression as the switch for the generated case statement.
1336 function Make_Field_Assign
1338 U_U : Boolean := False) return Node_Id;
1339 -- Given C, the entity for a discriminant or component, build an
1340 -- assignment for the corresponding field values. The flag U_U
1341 -- signals the presence of an Unchecked_Union and forces the usage
1342 -- of the inferred discriminant value of C as the right hand side
1343 -- of the assignment.
1345 function Make_Field_Assigns (CI : List_Id) return List_Id;
1346 -- Given CI, a component items list, construct series of statements
1347 -- for fieldwise assignment of the corresponding components.
1349 --------------------
1350 -- Find_Component --
1351 --------------------
1353 function Find_Component
1355 Comp : Entity_Id) return Entity_Id
1357 Utyp : constant Entity_Id := Underlying_Type (Typ);
1361 C := First_Entity (Utyp);
1362 while Present (C) loop
1363 if Chars (C) = Chars (Comp) then
1370 raise Program_Error;
1373 --------------------------------
1374 -- Make_Component_List_Assign --
1375 --------------------------------
1377 function Make_Component_List_Assign
1379 U_U : Boolean := False) return List_Id
1381 CI : constant List_Id := Component_Items (CL);
1382 VP : constant Node_Id := Variant_Part (CL);
1392 Result := Make_Field_Assigns (CI);
1394 if Present (VP) then
1395 V := First_Non_Pragma (Variants (VP));
1397 while Present (V) loop
1399 DC := First (Discrete_Choices (V));
1400 while Present (DC) loop
1401 Append_To (DCH, New_Copy_Tree (DC));
1406 Make_Case_Statement_Alternative (Loc,
1407 Discrete_Choices => DCH,
1409 Make_Component_List_Assign (Component_List (V))));
1410 Next_Non_Pragma (V);
1413 -- If we have an Unchecked_Union, use the value of the inferred
1414 -- discriminant of the variant part expression as the switch
1415 -- for the case statement. The case statement may later be
1420 New_Copy (Get_Discriminant_Value (
1423 Discriminant_Constraint (Etype (Rhs))));
1426 Make_Selected_Component (Loc,
1427 Prefix => Duplicate_Subexpr (Rhs),
1429 Make_Identifier (Loc, Chars (Name (VP))));
1433 Make_Case_Statement (Loc,
1435 Alternatives => Alts));
1439 end Make_Component_List_Assign;
1441 -----------------------
1442 -- Make_Field_Assign --
1443 -----------------------
1445 function Make_Field_Assign
1447 U_U : Boolean := False) return Node_Id
1453 -- In the case of an Unchecked_Union, use the discriminant
1454 -- constraint value as on the right hand side of the assignment.
1458 New_Copy (Get_Discriminant_Value (C,
1460 Discriminant_Constraint (Etype (Rhs))));
1463 Make_Selected_Component (Loc,
1464 Prefix => Duplicate_Subexpr (Rhs),
1465 Selector_Name => New_Occurrence_Of (C, Loc));
1469 Make_Assignment_Statement (Loc,
1471 Make_Selected_Component (Loc,
1472 Prefix => Duplicate_Subexpr (Lhs),
1474 New_Occurrence_Of (Find_Component (L_Typ, C), Loc)),
1475 Expression => Expr);
1477 -- Set Assignment_OK, so discriminants can be assigned
1479 Set_Assignment_OK (Name (A), True);
1481 if Componentwise_Assignment (N)
1482 and then Nkind (Name (A)) = N_Selected_Component
1483 and then Chars (Selector_Name (Name (A))) = Name_uParent
1485 Set_Componentwise_Assignment (A);
1489 end Make_Field_Assign;
1491 ------------------------
1492 -- Make_Field_Assigns --
1493 ------------------------
1495 function Make_Field_Assigns (CI : List_Id) return List_Id is
1503 while Present (Item) loop
1505 -- Look for components, but exclude _tag field assignment if
1506 -- the special Componentwise_Assignment flag is set.
1508 if Nkind (Item) = N_Component_Declaration
1509 and then not (Is_Tag (Defining_Identifier (Item))
1510 and then Componentwise_Assignment (N))
1513 (Result, Make_Field_Assign (Defining_Identifier (Item)));
1520 end Make_Field_Assigns;
1522 -- Start of processing for Expand_Assign_Record
1525 -- Note that we use the base types for this processing. This results
1526 -- in some extra work in the constrained case, but the change of
1527 -- representation case is so unusual that it is not worth the effort.
1529 -- First copy the discriminants. This is done unconditionally. It
1530 -- is required in the unconstrained left side case, and also in the
1531 -- case where this assignment was constructed during the expansion
1532 -- of a type conversion (since initialization of discriminants is
1533 -- suppressed in this case). It is unnecessary but harmless in
1536 if Has_Discriminants (L_Typ) then
1537 F := First_Discriminant (R_Typ);
1538 while Present (F) loop
1540 -- If we are expanding the initialization of a derived record
1541 -- that constrains or renames discriminants of the parent, we
1542 -- must use the corresponding discriminant in the parent.
1549 and then Present (Corresponding_Discriminant (F))
1551 CF := Corresponding_Discriminant (F);
1556 if Is_Unchecked_Union (Base_Type (R_Typ)) then
1558 -- Within an initialization procedure this is the
1559 -- assignment to an unchecked union component, in which
1560 -- case there is no discriminant to initialize.
1562 if Inside_Init_Proc then
1566 -- The assignment is part of a conversion from a
1567 -- derived unchecked union type with an inferable
1568 -- discriminant, to a parent type.
1570 Insert_Action (N, Make_Field_Assign (CF, True));
1574 Insert_Action (N, Make_Field_Assign (CF));
1577 Next_Discriminant (F);
1582 -- We know the underlying type is a record, but its current view
1583 -- may be private. We must retrieve the usable record declaration.
1585 if Nkind_In (Decl, N_Private_Type_Declaration,
1586 N_Private_Extension_Declaration)
1587 and then Present (Full_View (R_Typ))
1589 RDef := Type_Definition (Declaration_Node (Full_View (R_Typ)));
1591 RDef := Type_Definition (Decl);
1594 if Nkind (RDef) = N_Derived_Type_Definition then
1595 RDef := Record_Extension_Part (RDef);
1598 if Nkind (RDef) = N_Record_Definition
1599 and then Present (Component_List (RDef))
1601 if Is_Unchecked_Union (R_Typ) then
1603 Make_Component_List_Assign (Component_List (RDef), True));
1606 (N, Make_Component_List_Assign (Component_List (RDef)));
1609 Rewrite (N, Make_Null_Statement (Loc));
1612 end Expand_Assign_Record;
1614 -----------------------------------
1615 -- Expand_N_Assignment_Statement --
1616 -----------------------------------
1618 -- This procedure implements various cases where an assignment statement
1619 -- cannot just be passed on to the back end in untransformed state.
1621 procedure Expand_N_Assignment_Statement (N : Node_Id) is
1622 Crep : constant Boolean := Change_Of_Representation (N);
1623 Lhs : constant Node_Id := Name (N);
1624 Loc : constant Source_Ptr := Sloc (N);
1625 Rhs : constant Node_Id := Expression (N);
1626 Typ : constant Entity_Id := Underlying_Type (Etype (Lhs));
1629 Save_Ghost_Mode : constant Ghost_Mode_Type := Ghost_Mode;
1632 -- The assignment statement is Ghost when the left hand side is Ghost.
1633 -- Set the mode now to ensure that any nodes generated during expansion
1634 -- are properly marked as Ghost.
1638 -- Special case to check right away, if the Componentwise_Assignment
1639 -- flag is set, this is a reanalysis from the expansion of the primitive
1640 -- assignment procedure for a tagged type, and all we need to do is to
1641 -- expand to assignment of components, because otherwise, we would get
1642 -- infinite recursion (since this looks like a tagged assignment which
1643 -- would normally try to *call* the primitive assignment procedure).
1645 if Componentwise_Assignment (N) then
1646 Expand_Assign_Record (N);
1647 Ghost_Mode := Save_Ghost_Mode;
1651 -- Defend against invalid subscripts on left side if we are in standard
1652 -- validity checking mode. No need to do this if we are checking all
1655 -- Note that we do this right away, because there are some early return
1656 -- paths in this procedure, and this is required on all paths.
1658 if Validity_Checks_On
1659 and then Validity_Check_Default
1660 and then not Validity_Check_Subscripts
1662 Check_Valid_Lvalue_Subscripts (Lhs);
1665 -- Ada 2005 (AI-327): Handle assignment to priority of protected object
1667 -- Rewrite an assignment to X'Priority into a run-time call
1669 -- For example: X'Priority := New_Prio_Expr;
1670 -- ...is expanded into Set_Ceiling (X._Object, New_Prio_Expr);
1672 -- Note that although X'Priority is notionally an object, it is quite
1673 -- deliberately not defined as an aliased object in the RM. This means
1674 -- that it works fine to rewrite it as a call, without having to worry
1675 -- about complications that would other arise from X'Priority'Access,
1676 -- which is illegal, because of the lack of aliasing.
1678 if Ada_Version >= Ada_2005 then
1681 Conctyp : Entity_Id;
1684 RT_Subprg_Name : Node_Id;
1687 -- Handle chains of renamings
1690 while Nkind (Ent) in N_Has_Entity
1691 and then Present (Entity (Ent))
1692 and then Present (Renamed_Object (Entity (Ent)))
1694 Ent := Renamed_Object (Entity (Ent));
1697 -- The attribute Priority applied to protected objects has been
1698 -- previously expanded into a call to the Get_Ceiling run-time
1701 if Nkind (Ent) = N_Function_Call
1702 and then (Entity (Name (Ent)) = RTE (RE_Get_Ceiling)
1704 Entity (Name (Ent)) = RTE (RO_PE_Get_Ceiling))
1706 -- Look for the enclosing concurrent type
1708 Conctyp := Current_Scope;
1709 while not Is_Concurrent_Type (Conctyp) loop
1710 Conctyp := Scope (Conctyp);
1713 pragma Assert (Is_Protected_Type (Conctyp));
1715 -- Generate the first actual of the call
1717 Subprg := Current_Scope;
1718 while not Present (Protected_Body_Subprogram (Subprg)) loop
1719 Subprg := Scope (Subprg);
1722 -- Select the appropriate run-time call
1724 if Number_Entries (Conctyp) = 0 then
1726 New_Occurrence_Of (RTE (RE_Set_Ceiling), Loc);
1729 New_Occurrence_Of (RTE (RO_PE_Set_Ceiling), Loc);
1733 Make_Procedure_Call_Statement (Loc,
1734 Name => RT_Subprg_Name,
1735 Parameter_Associations => New_List (
1736 New_Copy_Tree (First (Parameter_Associations (Ent))),
1737 Relocate_Node (Expression (N))));
1742 Ghost_Mode := Save_Ghost_Mode;
1748 -- Deal with assignment checks unless suppressed
1750 if not Suppress_Assignment_Checks (N) then
1752 -- First deal with generation of range check if required
1754 if Do_Range_Check (Rhs) then
1755 Generate_Range_Check (Rhs, Typ, CE_Range_Check_Failed);
1758 -- Then generate predicate check if required
1760 Apply_Predicate_Check (Rhs, Typ);
1763 -- Check for a special case where a high level transformation is
1764 -- required. If we have either of:
1769 -- where P is a reference to a bit packed array, then we have to unwind
1770 -- the assignment. The exact meaning of being a reference to a bit
1771 -- packed array is as follows:
1773 -- An indexed component whose prefix is a bit packed array is a
1774 -- reference to a bit packed array.
1776 -- An indexed component or selected component whose prefix is a
1777 -- reference to a bit packed array is itself a reference ot a
1778 -- bit packed array.
1780 -- The required transformation is
1782 -- Tnn : prefix_type := P;
1783 -- Tnn.field := rhs;
1788 -- Tnn : prefix_type := P;
1789 -- Tnn (subscr) := rhs;
1792 -- Since P is going to be evaluated more than once, any subscripts
1793 -- in P must have their evaluation forced.
1795 if Nkind_In (Lhs, N_Indexed_Component, N_Selected_Component)
1796 and then Is_Ref_To_Bit_Packed_Array (Prefix (Lhs))
1799 BPAR_Expr : constant Node_Id := Relocate_Node (Prefix (Lhs));
1800 BPAR_Typ : constant Entity_Id := Etype (BPAR_Expr);
1801 Tnn : constant Entity_Id :=
1802 Make_Temporary (Loc, 'T', BPAR_Expr);
1805 -- Insert the post assignment first, because we want to copy the
1806 -- BPAR_Expr tree before it gets analyzed in the context of the
1807 -- pre assignment. Note that we do not analyze the post assignment
1808 -- yet (we cannot till we have completed the analysis of the pre
1809 -- assignment). As usual, the analysis of this post assignment
1810 -- will happen on its own when we "run into" it after finishing
1811 -- the current assignment.
1814 Make_Assignment_Statement (Loc,
1815 Name => New_Copy_Tree (BPAR_Expr),
1816 Expression => New_Occurrence_Of (Tnn, Loc)));
1818 -- At this stage BPAR_Expr is a reference to a bit packed array
1819 -- where the reference was not expanded in the original tree,
1820 -- since it was on the left side of an assignment. But in the
1821 -- pre-assignment statement (the object definition), BPAR_Expr
1822 -- will end up on the right hand side, and must be reexpanded. To
1823 -- achieve this, we reset the analyzed flag of all selected and
1824 -- indexed components down to the actual indexed component for
1825 -- the packed array.
1829 Set_Analyzed (Exp, False);
1832 (Exp, N_Selected_Component, N_Indexed_Component)
1834 Exp := Prefix (Exp);
1840 -- Now we can insert and analyze the pre-assignment
1842 -- If the right-hand side requires a transient scope, it has
1843 -- already been placed on the stack. However, the declaration is
1844 -- inserted in the tree outside of this scope, and must reflect
1845 -- the proper scope for its variable. This awkward bit is forced
1846 -- by the stricter scope discipline imposed by GCC 2.97.
1849 Uses_Transient_Scope : constant Boolean :=
1851 and then N = Node_To_Be_Wrapped;
1854 if Uses_Transient_Scope then
1855 Push_Scope (Scope (Current_Scope));
1858 Insert_Before_And_Analyze (N,
1859 Make_Object_Declaration (Loc,
1860 Defining_Identifier => Tnn,
1861 Object_Definition => New_Occurrence_Of (BPAR_Typ, Loc),
1862 Expression => BPAR_Expr));
1864 if Uses_Transient_Scope then
1869 -- Now fix up the original assignment and continue processing
1871 Rewrite (Prefix (Lhs),
1872 New_Occurrence_Of (Tnn, Loc));
1874 -- We do not need to reanalyze that assignment, and we do not need
1875 -- to worry about references to the temporary, but we do need to
1876 -- make sure that the temporary is not marked as a true constant
1877 -- since we now have a generated assignment to it.
1879 Set_Is_True_Constant (Tnn, False);
1883 -- When we have the appropriate type of aggregate in the expression (it
1884 -- has been determined during analysis of the aggregate by setting the
1885 -- delay flag), let's perform in place assignment and thus avoid
1886 -- creating a temporary.
1888 if Is_Delayed_Aggregate (Rhs) then
1889 Convert_Aggr_In_Assignment (N);
1890 Rewrite (N, Make_Null_Statement (Loc));
1893 Ghost_Mode := Save_Ghost_Mode;
1897 -- Apply discriminant check if required. If Lhs is an access type to a
1898 -- designated type with discriminants, we must always check. If the
1899 -- type has unknown discriminants, more elaborate processing below.
1901 if Has_Discriminants (Etype (Lhs))
1902 and then not Has_Unknown_Discriminants (Etype (Lhs))
1904 -- Skip discriminant check if change of representation. Will be
1905 -- done when the change of representation is expanded out.
1908 Apply_Discriminant_Check (Rhs, Etype (Lhs), Lhs);
1911 -- If the type is private without discriminants, and the full type
1912 -- has discriminants (necessarily with defaults) a check may still be
1913 -- necessary if the Lhs is aliased. The private discriminants must be
1914 -- visible to build the discriminant constraints.
1916 -- Only an explicit dereference that comes from source indicates
1917 -- aliasing. Access to formals of protected operations and entries
1918 -- create dereferences but are not semantic aliasings.
1920 elsif Is_Private_Type (Etype (Lhs))
1921 and then Has_Discriminants (Typ)
1922 and then Nkind (Lhs) = N_Explicit_Dereference
1923 and then Comes_From_Source (Lhs)
1926 Lt : constant Entity_Id := Etype (Lhs);
1927 Ubt : Entity_Id := Base_Type (Typ);
1930 -- In the case of an expander-generated record subtype whose base
1931 -- type still appears private, Typ will have been set to that
1932 -- private type rather than the underlying record type (because
1933 -- Underlying type will have returned the record subtype), so it's
1934 -- necessary to apply Underlying_Type again to the base type to
1935 -- get the record type we need for the discriminant check. Such
1936 -- subtypes can be created for assignments in certain cases, such
1937 -- as within an instantiation passed this kind of private type.
1938 -- It would be good to avoid this special test, but making changes
1939 -- to prevent this odd form of record subtype seems difficult. ???
1941 if Is_Private_Type (Ubt) then
1942 Ubt := Underlying_Type (Ubt);
1945 Set_Etype (Lhs, Ubt);
1946 Rewrite (Rhs, OK_Convert_To (Base_Type (Ubt), Rhs));
1947 Apply_Discriminant_Check (Rhs, Ubt, Lhs);
1948 Set_Etype (Lhs, Lt);
1951 -- If the Lhs has a private type with unknown discriminants, it may
1952 -- have a full view with discriminants, but those are nameable only
1953 -- in the underlying type, so convert the Rhs to it before potential
1954 -- checking. Convert Lhs as well, otherwise the actual subtype might
1955 -- not be constructible.
1957 elsif Has_Unknown_Discriminants (Base_Type (Etype (Lhs)))
1958 and then Has_Discriminants (Typ)
1960 Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
1961 Rewrite (Lhs, OK_Convert_To (Base_Type (Typ), Lhs));
1962 Apply_Discriminant_Check (Rhs, Typ, Lhs);
1964 -- In the access type case, we need the same discriminant check, and
1965 -- also range checks if we have an access to constrained array.
1967 elsif Is_Access_Type (Etype (Lhs))
1968 and then Is_Constrained (Designated_Type (Etype (Lhs)))
1970 if Has_Discriminants (Designated_Type (Etype (Lhs))) then
1972 -- Skip discriminant check if change of representation. Will be
1973 -- done when the change of representation is expanded out.
1976 Apply_Discriminant_Check (Rhs, Etype (Lhs));
1979 elsif Is_Array_Type (Designated_Type (Etype (Lhs))) then
1980 Apply_Range_Check (Rhs, Etype (Lhs));
1982 if Is_Constrained (Etype (Lhs)) then
1983 Apply_Length_Check (Rhs, Etype (Lhs));
1986 if Nkind (Rhs) = N_Allocator then
1988 Target_Typ : constant Entity_Id := Etype (Expression (Rhs));
1989 C_Es : Check_Result;
1996 Etype (Designated_Type (Etype (Lhs))));
2008 -- Apply range check for access type case
2010 elsif Is_Access_Type (Etype (Lhs))
2011 and then Nkind (Rhs) = N_Allocator
2012 and then Nkind (Expression (Rhs)) = N_Qualified_Expression
2014 Analyze_And_Resolve (Expression (Rhs));
2016 (Expression (Rhs), Designated_Type (Etype (Lhs)));
2019 -- Ada 2005 (AI-231): Generate the run-time check
2021 if Is_Access_Type (Typ)
2022 and then Can_Never_Be_Null (Etype (Lhs))
2023 and then not Can_Never_Be_Null (Etype (Rhs))
2025 -- If an actual is an out parameter of a null-excluding access
2026 -- type, there is access check on entry, so we set the flag
2027 -- Suppress_Assignment_Checks on the generated statement to
2028 -- assign the actual to the parameter block, and we do not want
2029 -- to generate an additional check at this point.
2031 and then not Suppress_Assignment_Checks (N)
2033 Apply_Constraint_Check (Rhs, Etype (Lhs));
2036 -- Ada 2012 (AI05-148): Update current accessibility level if Rhs is a
2037 -- stand-alone obj of an anonymous access type.
2039 if Is_Access_Type (Typ)
2040 and then Is_Entity_Name (Lhs)
2041 and then Present (Effective_Extra_Accessibility (Entity (Lhs)))
2044 function Lhs_Entity return Entity_Id;
2045 -- Look through renames to find the underlying entity.
2046 -- For assignment to a rename, we don't care about the
2047 -- Enclosing_Dynamic_Scope of the rename declaration.
2053 function Lhs_Entity return Entity_Id is
2054 Result : Entity_Id := Entity (Lhs);
2057 while Present (Renamed_Object (Result)) loop
2059 -- Renamed_Object must return an Entity_Name here
2060 -- because of preceding "Present (E_E_A (...))" test.
2062 Result := Entity (Renamed_Object (Result));
2068 -- Local Declarations
2070 Access_Check : constant Node_Id :=
2071 Make_Raise_Program_Error (Loc,
2075 Dynamic_Accessibility_Level (Rhs),
2077 Make_Integer_Literal (Loc,
2080 (Enclosing_Dynamic_Scope
2082 Reason => PE_Accessibility_Check_Failed);
2084 Access_Level_Update : constant Node_Id :=
2085 Make_Assignment_Statement (Loc,
2088 (Effective_Extra_Accessibility
2089 (Entity (Lhs)), Loc),
2091 Dynamic_Accessibility_Level (Rhs));
2094 if not Accessibility_Checks_Suppressed (Entity (Lhs)) then
2095 Insert_Action (N, Access_Check);
2098 Insert_Action (N, Access_Level_Update);
2102 -- Case of assignment to a bit packed array element. If there is a
2103 -- change of representation this must be expanded into components,
2104 -- otherwise this is a bit-field assignment.
2106 if Nkind (Lhs) = N_Indexed_Component
2107 and then Is_Bit_Packed_Array (Etype (Prefix (Lhs)))
2109 -- Normal case, no change of representation
2112 Expand_Bit_Packed_Element_Set (N);
2113 Ghost_Mode := Save_Ghost_Mode;
2116 -- Change of representation case
2119 -- Generate the following, to force component-by-component
2120 -- assignments in an efficient way. Otherwise each component
2121 -- will require a temporary and two bit-field manipulations.
2128 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T');
2134 Make_Object_Declaration (Loc,
2135 Defining_Identifier => Tnn,
2136 Object_Definition =>
2137 New_Occurrence_Of (Etype (Lhs), Loc)),
2138 Make_Assignment_Statement (Loc,
2139 Name => New_Occurrence_Of (Tnn, Loc),
2140 Expression => Relocate_Node (Rhs)),
2141 Make_Assignment_Statement (Loc,
2142 Name => Relocate_Node (Lhs),
2143 Expression => New_Occurrence_Of (Tnn, Loc)));
2145 Insert_Actions (N, Stats);
2146 Rewrite (N, Make_Null_Statement (Loc));
2151 -- Build-in-place function call case. Note that we're not yet doing
2152 -- build-in-place for user-written assignment statements (the assignment
2153 -- here came from an aggregate.)
2155 elsif Ada_Version >= Ada_2005
2156 and then Is_Build_In_Place_Function_Call (Rhs)
2158 Make_Build_In_Place_Call_In_Assignment (N, Rhs);
2160 elsif Is_Tagged_Type (Typ)
2161 or else (Needs_Finalization (Typ) and then not Is_Array_Type (Typ))
2163 Tagged_Case : declare
2164 L : List_Id := No_List;
2165 Expand_Ctrl_Actions : constant Boolean := not No_Ctrl_Actions (N);
2168 -- In the controlled case, we ensure that function calls are
2169 -- evaluated before finalizing the target. In all cases, it makes
2170 -- the expansion easier if the side-effects are removed first.
2172 Remove_Side_Effects (Lhs);
2173 Remove_Side_Effects (Rhs);
2175 -- Avoid recursion in the mechanism
2179 -- If dispatching assignment, we need to dispatch to _assign
2181 if Is_Class_Wide_Type (Typ)
2183 -- If the type is tagged, we may as well use the predefined
2184 -- primitive assignment. This avoids inlining a lot of code
2185 -- and in the class-wide case, the assignment is replaced
2186 -- by a dispatching call to _assign. It is suppressed in the
2187 -- case of assignments created by the expander that correspond
2188 -- to initializations, where we do want to copy the tag
2189 -- (Expand_Ctrl_Actions flag is set False in this case). It is
2190 -- also suppressed if restriction No_Dispatching_Calls is in
2191 -- force because in that case predefined primitives are not
2194 or else (Is_Tagged_Type (Typ)
2195 and then Chars (Current_Scope) /= Name_uAssign
2196 and then Expand_Ctrl_Actions
2198 not Restriction_Active (No_Dispatching_Calls))
2200 if Is_Limited_Type (Typ) then
2202 -- This can happen in an instance when the formal is an
2203 -- extension of a limited interface, and the actual is
2204 -- limited. This is an error according to AI05-0087, but
2205 -- is not caught at the point of instantiation in earlier
2208 -- This is wrong, error messages cannot be issued during
2209 -- expansion, since they would be missed in -gnatc mode ???
2211 Error_Msg_N ("assignment not available on limited type", N);
2212 Ghost_Mode := Save_Ghost_Mode;
2216 -- Fetch the primitive op _assign and proper type to call it.
2217 -- Because of possible conflicts between private and full view,
2218 -- fetch the proper type directly from the operation profile.
2221 Op : constant Entity_Id :=
2222 Find_Prim_Op (Typ, Name_uAssign);
2223 F_Typ : Entity_Id := Etype (First_Formal (Op));
2226 -- If the assignment is dispatching, make sure to use the
2229 if Is_Class_Wide_Type (Typ) then
2230 F_Typ := Class_Wide_Type (F_Typ);
2235 -- In case of assignment to a class-wide tagged type, before
2236 -- the assignment we generate run-time check to ensure that
2237 -- the tags of source and target match.
2239 if not Tag_Checks_Suppressed (Typ)
2240 and then Is_Class_Wide_Type (Typ)
2241 and then Is_Tagged_Type (Typ)
2242 and then Is_Tagged_Type (Underlying_Type (Etype (Rhs)))
2245 Make_Raise_Constraint_Error (Loc,
2249 Make_Selected_Component (Loc,
2250 Prefix => Duplicate_Subexpr (Lhs),
2252 Make_Identifier (Loc, Name_uTag)),
2254 Make_Selected_Component (Loc,
2255 Prefix => Duplicate_Subexpr (Rhs),
2257 Make_Identifier (Loc, Name_uTag))),
2258 Reason => CE_Tag_Check_Failed));
2262 Left_N : Node_Id := Duplicate_Subexpr (Lhs);
2263 Right_N : Node_Id := Duplicate_Subexpr (Rhs);
2266 -- In order to dispatch the call to _assign the type of
2267 -- the actuals must match. Add conversion (if required).
2269 if Etype (Lhs) /= F_Typ then
2270 Left_N := Unchecked_Convert_To (F_Typ, Left_N);
2273 if Etype (Rhs) /= F_Typ then
2274 Right_N := Unchecked_Convert_To (F_Typ, Right_N);
2278 Make_Procedure_Call_Statement (Loc,
2279 Name => New_Occurrence_Of (Op, Loc),
2280 Parameter_Associations => New_List (
2282 Node2 => Right_N)));
2287 L := Make_Tag_Ctrl_Assignment (N);
2289 -- We can't afford to have destructive Finalization Actions in
2290 -- the Self assignment case, so if the target and the source
2291 -- are not obviously different, code is generated to avoid the
2292 -- self assignment case:
2294 -- if lhs'address /= rhs'address then
2295 -- <code for controlled and/or tagged assignment>
2298 -- Skip this if Restriction (No_Finalization) is active
2300 if not Statically_Different (Lhs, Rhs)
2301 and then Expand_Ctrl_Actions
2302 and then not Restriction_Active (No_Finalization)
2305 Make_Implicit_If_Statement (N,
2309 Make_Attribute_Reference (Loc,
2310 Prefix => Duplicate_Subexpr (Lhs),
2311 Attribute_Name => Name_Address),
2314 Make_Attribute_Reference (Loc,
2315 Prefix => Duplicate_Subexpr (Rhs),
2316 Attribute_Name => Name_Address)),
2318 Then_Statements => L));
2321 -- We need to set up an exception handler for implementing
2322 -- 7.6.1(18). The remaining adjustments are tackled by the
2323 -- implementation of adjust for record_controllers (see
2326 -- This is skipped if we have no finalization
2328 if Expand_Ctrl_Actions
2329 and then not Restriction_Active (No_Finalization)
2332 Make_Block_Statement (Loc,
2333 Handled_Statement_Sequence =>
2334 Make_Handled_Sequence_Of_Statements (Loc,
2336 Exception_Handlers => New_List (
2337 Make_Handler_For_Ctrl_Operation (Loc)))));
2342 Make_Block_Statement (Loc,
2343 Handled_Statement_Sequence =>
2344 Make_Handled_Sequence_Of_Statements (Loc, Statements => L)));
2346 -- If no restrictions on aborts, protect the whole assignment
2347 -- for controlled objects as per 9.8(11).
2349 if Needs_Finalization (Typ)
2350 and then Expand_Ctrl_Actions
2351 and then Abort_Allowed
2354 Blk : constant Entity_Id :=
2356 (E_Block, Current_Scope, Sloc (N), 'B');
2357 AUD : constant Entity_Id := RTE (RE_Abort_Undefer_Direct);
2360 Set_Scope (Blk, Current_Scope);
2361 Set_Etype (Blk, Standard_Void_Type);
2362 Set_Identifier (N, New_Occurrence_Of (Blk, Sloc (N)));
2364 Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
2365 Set_At_End_Proc (Handled_Statement_Sequence (N),
2366 New_Occurrence_Of (AUD, Loc));
2368 -- Present the Abort_Undefer_Direct function to the backend
2369 -- so that it can inline the call to the function.
2371 Add_Inlined_Body (AUD, N);
2373 Expand_At_End_Handler
2374 (Handled_Statement_Sequence (N), Blk);
2378 -- N has been rewritten to a block statement for which it is
2379 -- known by construction that no checks are necessary: analyze
2380 -- it with all checks suppressed.
2382 Analyze (N, Suppress => All_Checks);
2383 Ghost_Mode := Save_Ghost_Mode;
2389 elsif Is_Array_Type (Typ) then
2391 Actual_Rhs : Node_Id := Rhs;
2394 while Nkind_In (Actual_Rhs, N_Type_Conversion,
2395 N_Qualified_Expression)
2397 Actual_Rhs := Expression (Actual_Rhs);
2400 Expand_Assign_Array (N, Actual_Rhs);
2401 Ghost_Mode := Save_Ghost_Mode;
2407 elsif Is_Record_Type (Typ) then
2408 Expand_Assign_Record (N);
2409 Ghost_Mode := Save_Ghost_Mode;
2412 -- Scalar types. This is where we perform the processing related to the
2413 -- requirements of (RM 13.9.1(9-11)) concerning the handling of invalid
2416 elsif Is_Scalar_Type (Typ) then
2418 -- Case where right side is known valid
2420 if Expr_Known_Valid (Rhs) then
2422 -- Here the right side is valid, so it is fine. The case to deal
2423 -- with is when the left side is a local variable reference whose
2424 -- value is not currently known to be valid. If this is the case,
2425 -- and the assignment appears in an unconditional context, then
2426 -- we can mark the left side as now being valid if one of these
2427 -- conditions holds:
2429 -- The expression of the right side has Do_Range_Check set so
2430 -- that we know a range check will be performed. Note that it
2431 -- can be the case that a range check is omitted because we
2432 -- make the assumption that we can assume validity for operands
2433 -- appearing in the right side in determining whether a range
2434 -- check is required
2436 -- The subtype of the right side matches the subtype of the
2437 -- left side. In this case, even though we have not checked
2438 -- the range of the right side, we know it is in range of its
2439 -- subtype if the expression is valid.
2441 if Is_Local_Variable_Reference (Lhs)
2442 and then not Is_Known_Valid (Entity (Lhs))
2443 and then In_Unconditional_Context (N)
2445 if Do_Range_Check (Rhs)
2446 or else Etype (Lhs) = Etype (Rhs)
2448 Set_Is_Known_Valid (Entity (Lhs), True);
2452 -- Case where right side may be invalid in the sense of the RM
2453 -- reference above. The RM does not require that we check for the
2454 -- validity on an assignment, but it does require that the assignment
2455 -- of an invalid value not cause erroneous behavior.
2457 -- The general approach in GNAT is to use the Is_Known_Valid flag
2458 -- to avoid the need for validity checking on assignments. However
2459 -- in some cases, we have to do validity checking in order to make
2460 -- sure that the setting of this flag is correct.
2463 -- Validate right side if we are validating copies
2465 if Validity_Checks_On
2466 and then Validity_Check_Copies
2468 -- Skip this if left hand side is an array or record component
2469 -- and elementary component validity checks are suppressed.
2471 if Nkind_In (Lhs, N_Selected_Component, N_Indexed_Component)
2472 and then not Validity_Check_Components
2479 -- We can propagate this to the left side where appropriate
2481 if Is_Local_Variable_Reference (Lhs)
2482 and then not Is_Known_Valid (Entity (Lhs))
2483 and then In_Unconditional_Context (N)
2485 Set_Is_Known_Valid (Entity (Lhs), True);
2488 -- Otherwise check to see what should be done
2490 -- If left side is a local variable, then we just set its flag to
2491 -- indicate that its value may no longer be valid, since we are
2492 -- copying a potentially invalid value.
2494 elsif Is_Local_Variable_Reference (Lhs) then
2495 Set_Is_Known_Valid (Entity (Lhs), False);
2497 -- Check for case of a nonlocal variable on the left side which
2498 -- is currently known to be valid. In this case, we simply ensure
2499 -- that the right side is valid. We only play the game of copying
2500 -- validity status for local variables, since we are doing this
2501 -- statically, not by tracing the full flow graph.
2503 elsif Is_Entity_Name (Lhs)
2504 and then Is_Known_Valid (Entity (Lhs))
2506 -- Note: If Validity_Checking mode is set to none, we ignore
2507 -- the Ensure_Valid call so don't worry about that case here.
2511 -- In all other cases, we can safely copy an invalid value without
2512 -- worrying about the status of the left side. Since it is not a
2513 -- variable reference it will not be considered
2514 -- as being known to be valid in any case.
2522 Ghost_Mode := Save_Ghost_Mode;
2525 when RE_Not_Available =>
2526 Ghost_Mode := Save_Ghost_Mode;
2528 end Expand_N_Assignment_Statement;
2530 ------------------------------
2531 -- Expand_N_Block_Statement --
2532 ------------------------------
2534 -- Encode entity names defined in block statement
2536 procedure Expand_N_Block_Statement (N : Node_Id) is
2538 Qualify_Entity_Names (N);
2539 end Expand_N_Block_Statement;
2541 -----------------------------
2542 -- Expand_N_Case_Statement --
2543 -----------------------------
2545 procedure Expand_N_Case_Statement (N : Node_Id) is
2546 Loc : constant Source_Ptr := Sloc (N);
2547 Expr : constant Node_Id := Expression (N);
2555 -- Check for the situation where we know at compile time which branch
2558 -- If the value is static but its subtype is predicated and the value
2559 -- does not obey the predicate, the value is marked non-static, and
2560 -- there can be no corresponding static alternative. In that case we
2561 -- replace the case statement with an exception, regardless of whether
2562 -- assertions are enabled or not.
2564 if Compile_Time_Known_Value (Expr)
2565 and then Has_Predicates (Etype (Expr))
2566 and then not Is_OK_Static_Expression (Expr)
2569 Make_Raise_Constraint_Error (Loc, Reason => CE_Invalid_Data));
2573 elsif Compile_Time_Known_Value (Expr)
2574 and then (not Has_Predicates (Etype (Expr))
2575 or else Is_Static_Expression (Expr))
2577 Alt := Find_Static_Alternative (N);
2579 -- Do not consider controlled objects found in a case statement which
2580 -- actually models a case expression because their early finalization
2581 -- will affect the result of the expression.
2583 if not From_Conditional_Expression (N) then
2584 Process_Statements_For_Controlled_Objects (Alt);
2587 -- Move statements from this alternative after the case statement.
2588 -- They are already analyzed, so will be skipped by the analyzer.
2590 Insert_List_After (N, Statements (Alt));
2592 -- That leaves the case statement as a shell. So now we can kill all
2593 -- other alternatives in the case statement.
2595 Kill_Dead_Code (Expression (N));
2601 -- Loop through case alternatives, skipping pragmas, and skipping
2602 -- the one alternative that we select (and therefore retain).
2604 Dead_Alt := First (Alternatives (N));
2605 while Present (Dead_Alt) loop
2607 and then Nkind (Dead_Alt) = N_Case_Statement_Alternative
2609 Kill_Dead_Code (Statements (Dead_Alt), Warn_On_Deleted_Code);
2616 Rewrite (N, Make_Null_Statement (Loc));
2620 -- Here if the choice is not determined at compile time
2623 Last_Alt : constant Node_Id := Last (Alternatives (N));
2625 Others_Present : Boolean;
2626 Others_Node : Node_Id;
2628 Then_Stms : List_Id;
2629 Else_Stms : List_Id;
2632 if Nkind (First (Discrete_Choices (Last_Alt))) = N_Others_Choice then
2633 Others_Present := True;
2634 Others_Node := Last_Alt;
2636 Others_Present := False;
2639 -- First step is to worry about possible invalid argument. The RM
2640 -- requires (RM 5.4(13)) that if the result is invalid (e.g. it is
2641 -- outside the base range), then Constraint_Error must be raised.
2643 -- Case of validity check required (validity checks are on, the
2644 -- expression is not known to be valid, and the case statement
2645 -- comes from source -- no need to validity check internally
2646 -- generated case statements).
2648 if Validity_Check_Default then
2649 Ensure_Valid (Expr);
2652 -- If there is only a single alternative, just replace it with the
2653 -- sequence of statements since obviously that is what is going to
2654 -- be executed in all cases.
2656 Len := List_Length (Alternatives (N));
2660 -- We still need to evaluate the expression if it has any side
2663 Remove_Side_Effects (Expression (N));
2664 Alt := First (Alternatives (N));
2666 -- Do not consider controlled objects found in a case statement
2667 -- which actually models a case expression because their early
2668 -- finalization will affect the result of the expression.
2670 if not From_Conditional_Expression (N) then
2671 Process_Statements_For_Controlled_Objects (Alt);
2674 Insert_List_After (N, Statements (Alt));
2676 -- That leaves the case statement as a shell. The alternative that
2677 -- will be executed is reset to a null list. So now we can kill
2678 -- the entire case statement.
2680 Kill_Dead_Code (Expression (N));
2681 Rewrite (N, Make_Null_Statement (Loc));
2684 -- An optimization. If there are only two alternatives, and only
2685 -- a single choice, then rewrite the whole case statement as an
2686 -- if statement, since this can result in subsequent optimizations.
2687 -- This helps not only with case statements in the source of a
2688 -- simple form, but also with generated code (discriminant check
2689 -- functions in particular).
2691 -- Note: it is OK to do this before expanding out choices for any
2692 -- static predicates, since the if statement processing will handle
2693 -- the static predicate case fine.
2696 Chlist := Discrete_Choices (First (Alternatives (N)));
2698 if List_Length (Chlist) = 1 then
2699 Choice := First (Chlist);
2701 Then_Stms := Statements (First (Alternatives (N)));
2702 Else_Stms := Statements (Last (Alternatives (N)));
2704 -- For TRUE, generate "expression", not expression = true
2706 if Nkind (Choice) = N_Identifier
2707 and then Entity (Choice) = Standard_True
2709 Cond := Expression (N);
2711 -- For FALSE, generate "expression" and switch then/else
2713 elsif Nkind (Choice) = N_Identifier
2714 and then Entity (Choice) = Standard_False
2716 Cond := Expression (N);
2717 Else_Stms := Statements (First (Alternatives (N)));
2718 Then_Stms := Statements (Last (Alternatives (N)));
2720 -- For a range, generate "expression in range"
2722 elsif Nkind (Choice) = N_Range
2723 or else (Nkind (Choice) = N_Attribute_Reference
2724 and then Attribute_Name (Choice) = Name_Range)
2725 or else (Is_Entity_Name (Choice)
2726 and then Is_Type (Entity (Choice)))
2730 Left_Opnd => Expression (N),
2731 Right_Opnd => Relocate_Node (Choice));
2733 -- A subtype indication is not a legal operator in a membership
2734 -- test, so retrieve its range.
2736 elsif Nkind (Choice) = N_Subtype_Indication then
2739 Left_Opnd => Expression (N),
2742 (Range_Expression (Constraint (Choice))));
2744 -- For any other subexpression "expression = value"
2749 Left_Opnd => Expression (N),
2750 Right_Opnd => Relocate_Node (Choice));
2753 -- Now rewrite the case as an IF
2756 Make_If_Statement (Loc,
2758 Then_Statements => Then_Stms,
2759 Else_Statements => Else_Stms));
2765 -- If the last alternative is not an Others choice, replace it with
2766 -- an N_Others_Choice. Note that we do not bother to call Analyze on
2767 -- the modified case statement, since it's only effect would be to
2768 -- compute the contents of the Others_Discrete_Choices which is not
2769 -- needed by the back end anyway.
2771 -- The reason for this is that the back end always needs some default
2772 -- for a switch, so if we have not supplied one in the processing
2773 -- above for validity checking, then we need to supply one here.
2775 if not Others_Present then
2776 Others_Node := Make_Others_Choice (Sloc (Last_Alt));
2777 Set_Others_Discrete_Choices
2778 (Others_Node, Discrete_Choices (Last_Alt));
2779 Set_Discrete_Choices (Last_Alt, New_List (Others_Node));
2782 -- Deal with possible declarations of controlled objects, and also
2783 -- with rewriting choice sequences for static predicate references.
2785 Alt := First_Non_Pragma (Alternatives (N));
2786 while Present (Alt) loop
2788 -- Do not consider controlled objects found in a case statement
2789 -- which actually models a case expression because their early
2790 -- finalization will affect the result of the expression.
2792 if not From_Conditional_Expression (N) then
2793 Process_Statements_For_Controlled_Objects (Alt);
2796 if Has_SP_Choice (Alt) then
2797 Expand_Static_Predicates_In_Choices (Alt);
2800 Next_Non_Pragma (Alt);
2803 end Expand_N_Case_Statement;
2805 -----------------------------
2806 -- Expand_N_Exit_Statement --
2807 -----------------------------
2809 -- The only processing required is to deal with a possible C/Fortran
2810 -- boolean value used as the condition for the exit statement.
2812 procedure Expand_N_Exit_Statement (N : Node_Id) is
2814 Adjust_Condition (Condition (N));
2815 end Expand_N_Exit_Statement;
2817 ----------------------------------
2818 -- Expand_Formal_Container_Loop --
2819 ----------------------------------
2821 procedure Expand_Formal_Container_Loop (N : Node_Id) is
2822 Loc : constant Source_Ptr := Sloc (N);
2823 Isc : constant Node_Id := Iteration_Scheme (N);
2824 I_Spec : constant Node_Id := Iterator_Specification (Isc);
2825 Cursor : constant Entity_Id := Defining_Identifier (I_Spec);
2826 Container : constant Node_Id := Entity (Name (I_Spec));
2827 Stats : constant List_Id := Statements (N);
2835 -- The expansion resembles the one for Ada containers, but the
2836 -- primitives mention the domain of iteration explicitly, and
2837 -- function First applied to the container yields a cursor directly.
2839 -- Cursor : Cursor_type := First (Container);
2840 -- while Has_Element (Cursor, Container) loop
2841 -- <original loop statements>
2842 -- Cursor := Next (Container, Cursor);
2845 Build_Formal_Container_Iteration
2846 (N, Container, Cursor, Init, Advance, New_Loop);
2848 Set_Ekind (Cursor, E_Variable);
2849 Append_To (Stats, Advance);
2851 -- Build block to capture declaration of cursor entity.
2854 Make_Block_Statement (Loc,
2855 Declarations => New_List (Init),
2856 Handled_Statement_Sequence =>
2857 Make_Handled_Sequence_Of_Statements (Loc,
2858 Statements => New_List (New_Loop)));
2860 Rewrite (N, Blk_Nod);
2862 end Expand_Formal_Container_Loop;
2864 ------------------------------------------
2865 -- Expand_Formal_Container_Element_Loop --
2866 ------------------------------------------
2868 procedure Expand_Formal_Container_Element_Loop (N : Node_Id) is
2869 Loc : constant Source_Ptr := Sloc (N);
2870 Isc : constant Node_Id := Iteration_Scheme (N);
2871 I_Spec : constant Node_Id := Iterator_Specification (Isc);
2872 Element : constant Entity_Id := Defining_Identifier (I_Spec);
2873 Container : constant Node_Id := Entity (Name (I_Spec));
2874 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
2875 Stats : constant List_Id := Statements (N);
2877 Cursor : constant Entity_Id :=
2878 Make_Defining_Identifier (Loc,
2879 Chars => New_External_Name (Chars (Element), 'C'));
2880 Elmt_Decl : Node_Id;
2883 Element_Op : constant Entity_Id :=
2884 Get_Iterable_Type_Primitive (Container_Typ, Name_Element);
2891 -- For an element iterator, the Element aspect must be present,
2892 -- (this is checked during analysis) and the expansion takes the form:
2894 -- Cursor : Cursor_type := First (Container);
2895 -- Elmt : Element_Type;
2896 -- while Has_Element (Cursor, Container) loop
2897 -- Elmt := Element (Container, Cursor);
2898 -- <original loop statements>
2899 -- Cursor := Next (Container, Cursor);
2902 Build_Formal_Container_Iteration
2903 (N, Container, Cursor, Init, Advance, New_Loop);
2905 Set_Ekind (Cursor, E_Variable);
2906 Insert_Action (N, Init);
2908 -- Declaration for Element.
2911 Make_Object_Declaration (Loc,
2912 Defining_Identifier => Element,
2913 Object_Definition => New_Occurrence_Of (Etype (Element_Op), Loc));
2915 -- The element is only modified in expanded code, so it appears as
2916 -- unassigned to the warning machinery. We must suppress this spurious
2917 -- warning explicitly.
2919 Set_Warnings_Off (Element);
2922 Make_Assignment_Statement (Loc,
2923 Name => New_Occurrence_Of (Element, Loc),
2925 Make_Function_Call (Loc,
2926 Name => New_Occurrence_Of (Element_Op, Loc),
2927 Parameter_Associations => New_List (
2928 New_Occurrence_Of (Container, Loc),
2929 New_Occurrence_Of (Cursor, Loc))));
2931 Prepend (Elmt_Ref, Stats);
2932 Append_To (Stats, Advance);
2934 -- The loop is rewritten as a block, to hold the element declaration
2937 Make_Block_Statement (Loc,
2938 Declarations => New_List (Elmt_Decl),
2939 Handled_Statement_Sequence =>
2940 Make_Handled_Sequence_Of_Statements (Loc,
2941 Statements => New_List (New_Loop)));
2943 Rewrite (N, New_Loop);
2945 -- The loop parameter is declared by an object declaration, but within
2946 -- the loop we must prevent user assignments to it, so we analyze the
2947 -- declaration and reset the entity kind, before analyzing the rest of
2950 Analyze (Elmt_Decl);
2951 Set_Ekind (Defining_Identifier (Elmt_Decl), E_Loop_Parameter);
2952 Set_Assignment_OK (Name (Elmt_Ref));
2955 end Expand_Formal_Container_Element_Loop;
2957 -----------------------------
2958 -- Expand_N_Goto_Statement --
2959 -----------------------------
2961 -- Add poll before goto if polling active
2963 procedure Expand_N_Goto_Statement (N : Node_Id) is
2965 Generate_Poll_Call (N);
2966 end Expand_N_Goto_Statement;
2968 ---------------------------
2969 -- Expand_N_If_Statement --
2970 ---------------------------
2972 -- First we deal with the case of C and Fortran convention boolean values,
2973 -- with zero/non-zero semantics.
2975 -- Second, we deal with the obvious rewriting for the cases where the
2976 -- condition of the IF is known at compile time to be True or False.
2978 -- Third, we remove elsif parts which have non-empty Condition_Actions and
2979 -- rewrite as independent if statements. For example:
2990 -- <<condition actions of y>>
2996 -- This rewriting is needed if at least one elsif part has a non-empty
2997 -- Condition_Actions list. We also do the same processing if there is a
2998 -- constant condition in an elsif part (in conjunction with the first
2999 -- processing step mentioned above, for the recursive call made to deal
3000 -- with the created inner if, this deals with properly optimizing the
3001 -- cases of constant elsif conditions).
3003 procedure Expand_N_If_Statement (N : Node_Id) is
3004 Loc : constant Source_Ptr := Sloc (N);
3009 Warn_If_Deleted : constant Boolean :=
3010 Warn_On_Deleted_Code and then Comes_From_Source (N);
3011 -- Indicates whether we want warnings when we delete branches of the
3012 -- if statement based on constant condition analysis. We never want
3013 -- these warnings for expander generated code.
3016 -- Do not consider controlled objects found in an if statement which
3017 -- actually models an if expression because their early finalization
3018 -- will affect the result of the expression.
3020 if not From_Conditional_Expression (N) then
3021 Process_Statements_For_Controlled_Objects (N);
3024 Adjust_Condition (Condition (N));
3026 -- The following loop deals with constant conditions for the IF. We
3027 -- need a loop because as we eliminate False conditions, we grab the
3028 -- first elsif condition and use it as the primary condition.
3030 while Compile_Time_Known_Value (Condition (N)) loop
3032 -- If condition is True, we can simply rewrite the if statement now
3033 -- by replacing it by the series of then statements.
3035 if Is_True (Expr_Value (Condition (N))) then
3037 -- All the else parts can be killed
3039 Kill_Dead_Code (Elsif_Parts (N), Warn_If_Deleted);
3040 Kill_Dead_Code (Else_Statements (N), Warn_If_Deleted);
3042 Hed := Remove_Head (Then_Statements (N));
3043 Insert_List_After (N, Then_Statements (N));
3047 -- If condition is False, then we can delete the condition and
3048 -- the Then statements
3051 -- We do not delete the condition if constant condition warnings
3052 -- are enabled, since otherwise we end up deleting the desired
3053 -- warning. Of course the backend will get rid of this True/False
3054 -- test anyway, so nothing is lost here.
3056 if not Constant_Condition_Warnings then
3057 Kill_Dead_Code (Condition (N));
3060 Kill_Dead_Code (Then_Statements (N), Warn_If_Deleted);
3062 -- If there are no elsif statements, then we simply replace the
3063 -- entire if statement by the sequence of else statements.
3065 if No (Elsif_Parts (N)) then
3066 if No (Else_Statements (N))
3067 or else Is_Empty_List (Else_Statements (N))
3070 Make_Null_Statement (Sloc (N)));
3072 Hed := Remove_Head (Else_Statements (N));
3073 Insert_List_After (N, Else_Statements (N));
3079 -- If there are elsif statements, the first of them becomes the
3080 -- if/then section of the rebuilt if statement This is the case
3081 -- where we loop to reprocess this copied condition.
3084 Hed := Remove_Head (Elsif_Parts (N));
3085 Insert_Actions (N, Condition_Actions (Hed));
3086 Set_Condition (N, Condition (Hed));
3087 Set_Then_Statements (N, Then_Statements (Hed));
3089 -- Hed might have been captured as the condition determining
3090 -- the current value for an entity. Now it is detached from
3091 -- the tree, so a Current_Value pointer in the condition might
3092 -- need to be updated.
3094 Set_Current_Value_Condition (N);
3096 if Is_Empty_List (Elsif_Parts (N)) then
3097 Set_Elsif_Parts (N, No_List);
3103 -- Loop through elsif parts, dealing with constant conditions and
3104 -- possible condition actions that are present.
3106 if Present (Elsif_Parts (N)) then
3107 E := First (Elsif_Parts (N));
3108 while Present (E) loop
3110 -- Do not consider controlled objects found in an if statement
3111 -- which actually models an if expression because their early
3112 -- finalization will affect the result of the expression.
3114 if not From_Conditional_Expression (N) then
3115 Process_Statements_For_Controlled_Objects (E);
3118 Adjust_Condition (Condition (E));
3120 -- If there are condition actions, then rewrite the if statement
3121 -- as indicated above. We also do the same rewrite for a True or
3122 -- False condition. The further processing of this constant
3123 -- condition is then done by the recursive call to expand the
3124 -- newly created if statement
3126 if Present (Condition_Actions (E))
3127 or else Compile_Time_Known_Value (Condition (E))
3129 -- Note this is not an implicit if statement, since it is part
3130 -- of an explicit if statement in the source (or of an implicit
3131 -- if statement that has already been tested).
3134 Make_If_Statement (Sloc (E),
3135 Condition => Condition (E),
3136 Then_Statements => Then_Statements (E),
3137 Elsif_Parts => No_List,
3138 Else_Statements => Else_Statements (N));
3140 -- Elsif parts for new if come from remaining elsif's of parent
3142 while Present (Next (E)) loop
3143 if No (Elsif_Parts (New_If)) then
3144 Set_Elsif_Parts (New_If, New_List);
3147 Append (Remove_Next (E), Elsif_Parts (New_If));
3150 Set_Else_Statements (N, New_List (New_If));
3152 if Present (Condition_Actions (E)) then
3153 Insert_List_Before (New_If, Condition_Actions (E));
3158 if Is_Empty_List (Elsif_Parts (N)) then
3159 Set_Elsif_Parts (N, No_List);
3165 -- No special processing for that elsif part, move to next
3173 -- Some more optimizations applicable if we still have an IF statement
3175 if Nkind (N) /= N_If_Statement then
3179 -- Another optimization, special cases that can be simplified
3181 -- if expression then
3187 -- can be changed to:
3189 -- return expression;
3193 -- if expression then
3199 -- can be changed to:
3201 -- return not (expression);
3203 -- Only do these optimizations if we are at least at -O1 level and
3204 -- do not do them if control flow optimizations are suppressed.
3206 if Optimization_Level > 0
3207 and then not Opt.Suppress_Control_Flow_Optimizations
3209 if Nkind (N) = N_If_Statement
3210 and then No (Elsif_Parts (N))
3211 and then Present (Else_Statements (N))
3212 and then List_Length (Then_Statements (N)) = 1
3213 and then List_Length (Else_Statements (N)) = 1
3216 Then_Stm : constant Node_Id := First (Then_Statements (N));
3217 Else_Stm : constant Node_Id := First (Else_Statements (N));
3220 if Nkind (Then_Stm) = N_Simple_Return_Statement
3222 Nkind (Else_Stm) = N_Simple_Return_Statement
3225 Then_Expr : constant Node_Id := Expression (Then_Stm);
3226 Else_Expr : constant Node_Id := Expression (Else_Stm);
3229 if Nkind (Then_Expr) = N_Identifier
3231 Nkind (Else_Expr) = N_Identifier
3233 if Entity (Then_Expr) = Standard_True
3234 and then Entity (Else_Expr) = Standard_False
3237 Make_Simple_Return_Statement (Loc,
3238 Expression => Relocate_Node (Condition (N))));
3242 elsif Entity (Then_Expr) = Standard_False
3243 and then Entity (Else_Expr) = Standard_True
3246 Make_Simple_Return_Statement (Loc,
3250 Relocate_Node (Condition (N)))));
3260 end Expand_N_If_Statement;
3262 --------------------------
3263 -- Expand_Iterator_Loop --
3264 --------------------------
3266 procedure Expand_Iterator_Loop (N : Node_Id) is
3267 Isc : constant Node_Id := Iteration_Scheme (N);
3268 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3270 Container : constant Node_Id := Name (I_Spec);
3271 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
3274 -- Processing for arrays
3276 if Is_Array_Type (Container_Typ) then
3277 pragma Assert (Of_Present (I_Spec));
3278 Expand_Iterator_Loop_Over_Array (N);
3280 elsif Has_Aspect (Container_Typ, Aspect_Iterable) then
3281 if Of_Present (I_Spec) then
3282 Expand_Formal_Container_Element_Loop (N);
3284 Expand_Formal_Container_Loop (N);
3287 -- Processing for containers
3290 Expand_Iterator_Loop_Over_Container
3291 (N, Isc, I_Spec, Container, Container_Typ);
3293 end Expand_Iterator_Loop;
3295 -------------------------------------
3296 -- Expand_Iterator_Loop_Over_Array --
3297 -------------------------------------
3299 procedure Expand_Iterator_Loop_Over_Array (N : Node_Id) is
3300 Isc : constant Node_Id := Iteration_Scheme (N);
3301 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3302 Array_Node : constant Node_Id := Name (I_Spec);
3303 Array_Typ : constant Entity_Id := Base_Type (Etype (Array_Node));
3304 Array_Dim : constant Pos := Number_Dimensions (Array_Typ);
3305 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3306 Loc : constant Source_Ptr := Sloc (N);
3307 Stats : constant List_Id := Statements (N);
3308 Core_Loop : Node_Id;
3311 Iterator : Entity_Id;
3313 -- Start of processing for Expand_Iterator_Loop_Over_Array
3316 -- for Element of Array loop
3318 -- This case requires an internally generated cursor to iterate over
3321 if Of_Present (I_Spec) then
3322 Iterator := Make_Temporary (Loc, 'C');
3325 -- Element : Component_Type renames Array (Iterator);
3326 -- Iterator is the index value, or a list of index values
3327 -- in the case of a multidimensional array.
3330 Make_Indexed_Component (Loc,
3331 Prefix => Relocate_Node (Array_Node),
3332 Expressions => New_List (New_Occurrence_Of (Iterator, Loc)));
3335 Make_Object_Renaming_Declaration (Loc,
3336 Defining_Identifier => Id,
3338 New_Occurrence_Of (Component_Type (Array_Typ), Loc),
3341 -- Mark the loop variable as needing debug info, so that expansion
3342 -- of the renaming will result in Materialize_Entity getting set via
3343 -- Debug_Renaming_Declaration. (This setting is needed here because
3344 -- the setting in Freeze_Entity comes after the expansion, which is
3347 Set_Debug_Info_Needed (Id);
3349 -- for Index in Array loop
3351 -- This case utilizes the already given iterator name
3359 -- for Iterator in [reverse] Array'Range (Array_Dim) loop
3360 -- Element : Component_Type renames Array (Iterator);
3361 -- <original loop statements>
3364 -- If this is an iteration over a multidimensional array, the
3365 -- innermost loop is over the last dimension in Ada, and over
3366 -- the first dimension in Fortran.
3368 if Convention (Array_Typ) = Convention_Fortran then
3375 Make_Loop_Statement (Loc,
3377 Make_Iteration_Scheme (Loc,
3378 Loop_Parameter_Specification =>
3379 Make_Loop_Parameter_Specification (Loc,
3380 Defining_Identifier => Iterator,
3381 Discrete_Subtype_Definition =>
3382 Make_Attribute_Reference (Loc,
3383 Prefix => Relocate_Node (Array_Node),
3384 Attribute_Name => Name_Range,
3385 Expressions => New_List (
3386 Make_Integer_Literal (Loc, Dim1))),
3387 Reverse_Present => Reverse_Present (I_Spec))),
3388 Statements => Stats,
3389 End_Label => Empty);
3391 -- Processing for multidimensional array. The body of each loop is
3392 -- a loop over a previous dimension, going in decreasing order in Ada
3393 -- and in increasing order in Fortran.
3395 if Array_Dim > 1 then
3396 for Dim in 1 .. Array_Dim - 1 loop
3397 if Convention (Array_Typ) = Convention_Fortran then
3400 Dim1 := Array_Dim - Dim;
3403 Iterator := Make_Temporary (Loc, 'C');
3405 -- Generate the dimension loops starting from the innermost one
3407 -- for Iterator in [reverse] Array'Range (Array_Dim - Dim) loop
3412 Make_Loop_Statement (Loc,
3414 Make_Iteration_Scheme (Loc,
3415 Loop_Parameter_Specification =>
3416 Make_Loop_Parameter_Specification (Loc,
3417 Defining_Identifier => Iterator,
3418 Discrete_Subtype_Definition =>
3419 Make_Attribute_Reference (Loc,
3420 Prefix => Relocate_Node (Array_Node),
3421 Attribute_Name => Name_Range,
3422 Expressions => New_List (
3423 Make_Integer_Literal (Loc, Dim1))),
3424 Reverse_Present => Reverse_Present (I_Spec))),
3425 Statements => New_List (Core_Loop),
3426 End_Label => Empty);
3428 -- Update the previously created object renaming declaration with
3429 -- the new iterator, by adding the index of the next loop to the
3430 -- indexed component, in the order that corresponds to the
3433 if Convention (Array_Typ) = Convention_Fortran then
3434 Append_To (Expressions (Ind_Comp),
3435 New_Occurrence_Of (Iterator, Loc));
3437 Prepend_To (Expressions (Ind_Comp),
3438 New_Occurrence_Of (Iterator, Loc));
3443 -- Inherit the loop identifier from the original loop. This ensures that
3444 -- the scope stack is consistent after the rewriting.
3446 if Present (Identifier (N)) then
3447 Set_Identifier (Core_Loop, Relocate_Node (Identifier (N)));
3450 Rewrite (N, Core_Loop);
3452 end Expand_Iterator_Loop_Over_Array;
3454 -----------------------------------------
3455 -- Expand_Iterator_Loop_Over_Container --
3456 -----------------------------------------
3458 -- For a 'for ... in' loop, such as:
3460 -- for Cursor in Iterator_Function (...) loop
3466 -- Iter : Iterator_Type := Iterator_Function (...);
3467 -- Cursor : Cursor_type := First (Iter); -- or Last for "reverse"
3468 -- while Has_Element (Cursor) loop
3471 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
3474 -- For a 'for ... of' loop, such as:
3476 -- for X of Container loop
3480 -- the RM implies the generation of:
3482 -- Iter : Iterator_Type := Container.Iterate; -- the Default_Iterator
3483 -- Cursor : Cursor_Type := First (Iter); -- or Last for "reverse"
3484 -- while Has_Element (Cursor) loop
3486 -- X : Element_Type renames Element (Cursor).Element.all;
3487 -- -- or Constant_Element
3491 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
3494 -- In the general case, we do what the RM says. However, the operations
3495 -- Element and Iter.Next are slow, which is bad inside a loop, because they
3496 -- involve dispatching via interfaces, secondary stack manipulation,
3497 -- Busy/Lock incr/decr, and adjust/finalization/at-end handling. So for the
3498 -- predefined containers, we use an equivalent but optimized expansion.
3500 -- In the optimized case, we make use of these:
3502 -- procedure Next (Position : in out Cursor); -- instead of Iter.Next
3504 -- function Pseudo_Reference
3505 -- (Container : aliased Vector'Class) return Reference_Control_Type;
3507 -- type Element_Access is access all Element_Type;
3509 -- function Get_Element_Access
3510 -- (Position : Cursor) return not null Element_Access;
3512 -- Next is declared in the visible part of the container packages.
3513 -- The other three are added in the private part. (We're not supposed to
3514 -- pollute the namespace for clients. The compiler has no trouble breaking
3515 -- privacy to call things in the private part of an instance.)
3519 -- for X of My_Vector loop
3520 -- X.Count := X.Count + 1;
3524 -- The compiler will generate:
3526 -- Iter : Reversible_Iterator'Class := Iterate (My_Vector);
3527 -- -- Reversible_Iterator is an interface. Iterate is the
3528 -- -- Default_Iterator aspect of Vector. This increments Lock,
3529 -- -- disallowing tampering with cursors. Unfortunately, it does not
3530 -- -- increment Busy. The result of Iterate is Limited_Controlled;
3531 -- -- finalization will decrement Lock. This is a build-in-place
3532 -- -- dispatching call to Iterate.
3534 -- Cur : Cursor := First (Iter); -- or Last
3535 -- -- Dispatching call via interface.
3537 -- Control : Reference_Control_Type := Pseudo_Reference (My_Vector);
3538 -- -- Pseudo_Reference increments Busy, to detect tampering with
3539 -- -- elements, as required by RM. Also redundantly increment
3540 -- -- Lock. Finalization of Control will decrement both Busy and
3541 -- -- Lock. Pseudo_Reference returns a record containing a pointer to
3542 -- -- My_Vector, used by Finalize.
3544 -- -- Control is not used below, except to finalize it -- it's purely
3545 -- -- an RAII thing. This is needed because we are eliminating the
3546 -- -- call to Reference within the loop.
3548 -- while Has_Element (Cur) loop
3550 -- X : My_Element renames Get_Element_Access (Cur).all;
3551 -- -- Get_Element_Access returns a pointer to the element
3552 -- -- designated by Cur. No dispatching here, and no horsing
3553 -- -- around with access discriminants. This is instead of the
3556 -- -- X : My_Element renames Reference (Cur).Element.all;
3558 -- -- which creates a controlled object.
3560 -- -- Any attempt to tamper with My_Vector here in the loop
3561 -- -- will correctly raise Program_Error, because of the
3564 -- X.Count := X.Count + 1;
3567 -- Next (Cur); -- or Prev
3568 -- -- This is instead of "Cur := Next (Iter, Cur);"
3570 -- -- No finalization here
3572 -- Finalize Iter and Control here, decrementing Lock twice and Busy
3575 -- This optimization makes "for ... of" loops over 30 times faster in cases
3578 procedure Expand_Iterator_Loop_Over_Container
3582 Container : Node_Id;
3583 Container_Typ : Entity_Id)
3585 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3586 Loc : constant Source_Ptr := Sloc (N);
3588 I_Kind : constant Entity_Kind := Ekind (Id);
3590 Iterator : Entity_Id;
3592 Stats : constant List_Id := Statements (N);
3594 Element_Type : constant Entity_Id := Etype (Id);
3595 Iter_Type : Entity_Id;
3598 Name_Init : Name_Id;
3599 Name_Step : Name_Id;
3601 Fast_Element_Access_Op, Fast_Step_Op : Entity_Id := Empty;
3602 -- Only for optimized version of "for ... of"
3605 -- Determine the advancement and initialization steps for the cursor.
3606 -- Analysis of the expanded loop will verify that the container has a
3607 -- reverse iterator.
3609 if Reverse_Present (I_Spec) then
3610 Name_Init := Name_Last;
3611 Name_Step := Name_Previous;
3613 Name_Init := Name_First;
3614 Name_Step := Name_Next;
3617 -- The type of the iterator is the return type of the Iterate function
3618 -- used. For the "of" form this is the default iterator for the type,
3619 -- otherwise it is the type of the explicit function used in the
3620 -- iterator specification. The most common case will be an Iterate
3621 -- function in the container package.
3623 -- The Iterator type is declared in an instance within the container
3624 -- package itself, for example:
3626 -- package Vector_Iterator_Interfaces is new
3627 -- Ada.Iterator_Interfaces (Cursor, Has_Element);
3629 -- If the container type is a derived type, the cursor type is found in
3630 -- the package of the ultimate ancestor type.
3632 if Is_Derived_Type (Container_Typ) then
3633 Pack := Scope (Root_Type (Container_Typ));
3635 Pack := Scope (Container_Typ);
3638 Iter_Type := Etype (Name (I_Spec));
3640 if Of_Present (I_Spec) then
3642 Container_Arg : Node_Id;
3644 function Get_Default_Iterator
3645 (T : Entity_Id) return Entity_Id;
3646 -- If the container is a derived type, the aspect holds the parent
3647 -- operation. The required one is a primitive of the derived type
3648 -- and is either inherited or overridden. Also sets Container_Arg.
3650 --------------------------
3651 -- Get_Default_Iterator --
3652 --------------------------
3654 function Get_Default_Iterator
3655 (T : Entity_Id) return Entity_Id
3657 Iter : constant Entity_Id :=
3658 Entity (Find_Value_Of_Aspect (T, Aspect_Default_Iterator));
3663 Container_Arg := New_Copy_Tree (Container);
3665 -- A previous version of GNAT allowed indexing aspects to
3666 -- be redefined on derived container types, while the
3667 -- default iterator was inherited from the parent type.
3668 -- This non-standard extension is preserved temporarily for
3669 -- use by the modelling project under debug flag d.X.
3671 if Debug_Flag_Dot_XX then
3672 if Base_Type (Etype (Container)) /=
3673 Base_Type (Etype (First_Formal (Iter)))
3676 Make_Type_Conversion (Loc,
3679 (Etype (First_Formal (Iter)), Loc),
3680 Expression => Container_Arg);
3685 elsif Is_Derived_Type (T) then
3687 -- The default iterator must be a primitive operation of the
3688 -- type, at the same dispatch slot position.
3690 Prim := First_Elmt (Primitive_Operations (T));
3691 while Present (Prim) loop
3694 if Chars (Op) = Chars (Iter)
3695 and then DT_Position (Op) = DT_Position (Iter)
3703 -- Default iterator must exist
3705 pragma Assert (False);
3707 -- Otherwise not a derived type
3712 end Get_Default_Iterator;
3714 Default_Iter : Entity_Id;
3717 Reference_Control_Type : Entity_Id := Empty;
3718 Pseudo_Reference : Entity_Id := Empty;
3720 -- Start of processing for Handle_Of
3723 if Is_Class_Wide_Type (Container_Typ) then
3725 Get_Default_Iterator (Etype (Base_Type (Container_Typ)));
3727 Default_Iter := Get_Default_Iterator (Etype (Container));
3730 Cursor := Make_Temporary (Loc, 'C');
3732 -- For a container element iterator, the iterator type is obtained
3733 -- from the corresponding aspect, whose return type is descended
3734 -- from the corresponding interface type in some instance of
3735 -- Ada.Iterator_Interfaces. The actuals of that instantiation
3736 -- are Cursor and Has_Element.
3738 Iter_Type := Etype (Default_Iter);
3740 -- Find declarations needed for "for ... of" optimization
3742 Ent := First_Entity (Pack);
3743 while Present (Ent) loop
3744 if Chars (Ent) = Name_Get_Element_Access then
3745 Fast_Element_Access_Op := Ent;
3747 elsif Chars (Ent) = Name_Step
3748 and then Ekind (Ent) = E_Procedure
3750 Fast_Step_Op := Ent;
3752 elsif Chars (Ent) = Name_Reference_Control_Type then
3753 Reference_Control_Type := Ent;
3755 elsif Chars (Ent) = Name_Pseudo_Reference then
3756 Pseudo_Reference := Ent;
3762 if Present (Reference_Control_Type)
3763 and then Present (Pseudo_Reference)
3766 Make_Object_Declaration (Loc,
3767 Defining_Identifier => Make_Temporary (Loc, 'D'),
3768 Object_Definition =>
3769 New_Occurrence_Of (Reference_Control_Type, Loc),
3771 Make_Function_Call (Loc,
3773 New_Occurrence_Of (Pseudo_Reference, Loc),
3774 Parameter_Associations =>
3775 New_List (New_Copy_Tree (Container_Arg)))));
3778 -- The iterator type, which is a class-wide type, may itself be
3779 -- derived locally, so the desired instantiation is the scope of
3780 -- the root type of the iterator type. Currently, Pack is the
3781 -- container instance; this overwrites it with the iterator
3784 Pack := Scope (Root_Type (Etype (Iter_Type)));
3786 -- Rewrite domain of iteration as a call to the default iterator
3787 -- for the container type.
3789 Rewrite (Name (I_Spec),
3790 Make_Function_Call (Loc,
3792 New_Occurrence_Of (Default_Iter, Loc),
3793 Parameter_Associations => New_List (Container_Arg)));
3794 Analyze_And_Resolve (Name (I_Spec));
3796 -- Find cursor type in proper iterator package, which is an
3797 -- instantiation of Iterator_Interfaces.
3799 Ent := First_Entity (Pack);
3800 while Present (Ent) loop
3801 if Chars (Ent) = Name_Cursor then
3802 Set_Etype (Cursor, Etype (Ent));
3809 if Present (Fast_Element_Access_Op) then
3811 Make_Object_Renaming_Declaration (Loc,
3812 Defining_Identifier => Id,
3814 New_Occurrence_Of (Element_Type, Loc),
3816 Make_Explicit_Dereference (Loc,
3818 Make_Function_Call (Loc,
3820 New_Occurrence_Of (Fast_Element_Access_Op, Loc),
3821 Parameter_Associations =>
3822 New_List (New_Occurrence_Of (Cursor, Loc)))));
3826 Make_Object_Renaming_Declaration (Loc,
3827 Defining_Identifier => Id,
3829 New_Occurrence_Of (Element_Type, Loc),
3831 Make_Indexed_Component (Loc,
3832 Prefix => Relocate_Node (Container_Arg),
3834 New_List (New_Occurrence_Of (Cursor, Loc))));
3837 -- The defining identifier in the iterator is user-visible
3838 -- and must be visible in the debugger.
3840 Set_Debug_Info_Needed (Id);
3842 -- If the container does not have a variable indexing aspect,
3843 -- the element is a constant in the loop.
3845 if No (Find_Value_Of_Aspect
3846 (Container_Typ, Aspect_Variable_Indexing))
3848 Set_Ekind (Id, E_Constant);
3851 Prepend_To (Stats, Decl);
3854 -- X in Iterate (S) : type of iterator is type of explicitly
3855 -- given Iterate function, and the loop variable is the cursor.
3856 -- It will be assigned in the loop and must be a variable.
3862 Iterator := Make_Temporary (Loc, 'I');
3864 -- For both iterator forms, add a call to the step operation to
3865 -- advance the cursor. Generate:
3867 -- Cursor := Iterator.Next (Cursor);
3871 -- Cursor := Next (Cursor);
3873 if Present (Fast_Element_Access_Op) and then Present (Fast_Step_Op) then
3875 Step_Call : Node_Id;
3876 Curs_Name : constant Node_Id := New_Occurrence_Of (Cursor, Loc);
3879 Make_Procedure_Call_Statement (Loc,
3881 New_Occurrence_Of (Fast_Step_Op, Loc),
3882 Parameter_Associations => New_List (Curs_Name));
3884 Append_To (Stats, Step_Call);
3885 Set_Assignment_OK (Curs_Name);
3894 Make_Function_Call (Loc,
3896 Make_Selected_Component (Loc,
3897 Prefix => New_Occurrence_Of (Iterator, Loc),
3898 Selector_Name => Make_Identifier (Loc, Name_Step)),
3899 Parameter_Associations => New_List (
3900 New_Occurrence_Of (Cursor, Loc)));
3903 Make_Assignment_Statement (Loc,
3904 Name => New_Occurrence_Of (Cursor, Loc),
3905 Expression => Rhs));
3906 Set_Assignment_OK (Name (Last (Stats)));
3911 -- while Has_Element (Cursor) loop
3915 -- Has_Element is the second actual in the iterator package
3918 Make_Loop_Statement (Loc,
3920 Make_Iteration_Scheme (Loc,
3922 Make_Function_Call (Loc,
3925 Next_Entity (First_Entity (Pack)), Loc),
3926 Parameter_Associations =>
3927 New_List (New_Occurrence_Of (Cursor, Loc)))),
3929 Statements => Stats,
3930 End_Label => Empty);
3932 -- If present, preserve identifier of loop, which can be used in
3933 -- an exit statement in the body.
3935 if Present (Identifier (N)) then
3936 Set_Identifier (New_Loop, Relocate_Node (Identifier (N)));
3939 -- Create the declarations for Iterator and cursor and insert them
3940 -- before the source loop. Given that the domain of iteration is already
3941 -- an entity, the iterator is just a renaming of that entity. Possible
3945 Make_Object_Renaming_Declaration (Loc,
3946 Defining_Identifier => Iterator,
3947 Subtype_Mark => New_Occurrence_Of (Iter_Type, Loc),
3948 Name => Relocate_Node (Name (I_Spec))));
3950 -- Create declaration for cursor
3953 Cursor_Decl : constant Node_Id :=
3954 Make_Object_Declaration (Loc,
3955 Defining_Identifier => Cursor,
3956 Object_Definition =>
3957 New_Occurrence_Of (Etype (Cursor), Loc),
3959 Make_Selected_Component (Loc,
3960 Prefix => New_Occurrence_Of (Iterator, Loc),
3962 Make_Identifier (Loc, Name_Init)));
3965 -- The cursor is only modified in expanded code, so it appears
3966 -- as unassigned to the warning machinery. We must suppress this
3967 -- spurious warning explicitly. The cursor's kind is that of the
3968 -- original loop parameter (it is a constant if the domain of
3969 -- iteration is constant).
3971 Set_Warnings_Off (Cursor);
3972 Set_Assignment_OK (Cursor_Decl);
3974 Insert_Action (N, Cursor_Decl);
3975 Set_Ekind (Cursor, I_Kind);
3978 -- If the range of iteration is given by a function call that returns
3979 -- a container, the finalization actions have been saved in the
3980 -- Condition_Actions of the iterator. Insert them now at the head of
3983 if Present (Condition_Actions (Isc)) then
3984 Insert_List_Before (N, Condition_Actions (Isc));
3987 Rewrite (N, New_Loop);
3989 end Expand_Iterator_Loop_Over_Container;
3991 -----------------------------
3992 -- Expand_N_Loop_Statement --
3993 -----------------------------
3995 -- 1. Remove null loop entirely
3996 -- 2. Deal with while condition for C/Fortran boolean
3997 -- 3. Deal with loops with a non-standard enumeration type range
3998 -- 4. Deal with while loops where Condition_Actions is set
3999 -- 5. Deal with loops over predicated subtypes
4000 -- 6. Deal with loops with iterators over arrays and containers
4001 -- 7. Insert polling call if required
4003 procedure Expand_N_Loop_Statement (N : Node_Id) is
4004 Loc : constant Source_Ptr := Sloc (N);
4005 Scheme : constant Node_Id := Iteration_Scheme (N);
4011 if Is_Null_Loop (N) then
4012 Rewrite (N, Make_Null_Statement (Loc));
4016 -- Deal with condition for C/Fortran Boolean
4018 if Present (Scheme) then
4019 Adjust_Condition (Condition (Scheme));
4022 -- Generate polling call
4024 if Is_Non_Empty_List (Statements (N)) then
4025 Generate_Poll_Call (First (Statements (N)));
4028 -- Nothing more to do for plain loop with no iteration scheme
4033 -- Case of for loop (Loop_Parameter_Specification present)
4035 -- Note: we do not have to worry about validity checking of the for loop
4036 -- range bounds here, since they were frozen with constant declarations
4037 -- and it is during that process that the validity checking is done.
4039 elsif Present (Loop_Parameter_Specification (Scheme)) then
4041 LPS : constant Node_Id :=
4042 Loop_Parameter_Specification (Scheme);
4043 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4044 Ltype : constant Entity_Id := Etype (Loop_Id);
4045 Btype : constant Entity_Id := Base_Type (Ltype);
4051 -- Deal with loop over predicates
4053 if Is_Discrete_Type (Ltype)
4054 and then Present (Predicate_Function (Ltype))
4056 Expand_Predicated_Loop (N);
4058 -- Handle the case where we have a for loop with the range type
4059 -- being an enumeration type with non-standard representation.
4060 -- In this case we expand:
4062 -- for x in [reverse] a .. b loop
4068 -- for xP in [reverse] integer
4069 -- range etype'Pos (a) .. etype'Pos (b)
4072 -- x : constant etype := Pos_To_Rep (xP);
4078 elsif Is_Enumeration_Type (Btype)
4079 and then Present (Enum_Pos_To_Rep (Btype))
4082 Make_Defining_Identifier (Loc,
4083 Chars => New_External_Name (Chars (Loop_Id), 'P'));
4085 -- If the type has a contiguous representation, successive
4086 -- values can be generated as offsets from the first literal.
4088 if Has_Contiguous_Rep (Btype) then
4090 Unchecked_Convert_To (Btype,
4093 Make_Integer_Literal (Loc,
4094 Enumeration_Rep (First_Literal (Btype))),
4095 Right_Opnd => New_Occurrence_Of (New_Id, Loc)));
4097 -- Use the constructed array Enum_Pos_To_Rep
4100 Make_Indexed_Component (Loc,
4102 New_Occurrence_Of (Enum_Pos_To_Rep (Btype), Loc),
4104 New_List (New_Occurrence_Of (New_Id, Loc)));
4107 -- Build declaration for loop identifier
4111 Make_Object_Declaration (Loc,
4112 Defining_Identifier => Loop_Id,
4113 Constant_Present => True,
4114 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4115 Expression => Expr));
4118 Make_Loop_Statement (Loc,
4119 Identifier => Identifier (N),
4122 Make_Iteration_Scheme (Loc,
4123 Loop_Parameter_Specification =>
4124 Make_Loop_Parameter_Specification (Loc,
4125 Defining_Identifier => New_Id,
4126 Reverse_Present => Reverse_Present (LPS),
4128 Discrete_Subtype_Definition =>
4129 Make_Subtype_Indication (Loc,
4132 New_Occurrence_Of (Standard_Natural, Loc),
4135 Make_Range_Constraint (Loc,
4140 Make_Attribute_Reference (Loc,
4142 New_Occurrence_Of (Btype, Loc),
4144 Attribute_Name => Name_Pos,
4146 Expressions => New_List (
4148 (Type_Low_Bound (Ltype)))),
4151 Make_Attribute_Reference (Loc,
4153 New_Occurrence_Of (Btype, Loc),
4155 Attribute_Name => Name_Pos,
4157 Expressions => New_List (
4162 Statements => New_List (
4163 Make_Block_Statement (Loc,
4164 Declarations => Decls,
4165 Handled_Statement_Sequence =>
4166 Make_Handled_Sequence_Of_Statements (Loc,
4167 Statements => Statements (N)))),
4169 End_Label => End_Label (N)));
4171 -- The loop parameter's entity must be removed from the loop
4172 -- scope's entity list and rendered invisible, since it will
4173 -- now be located in the new block scope. Any other entities
4174 -- already associated with the loop scope, such as the loop
4175 -- parameter's subtype, will remain there.
4177 -- In an element loop, the loop will contain a declaration for
4178 -- a cursor variable; otherwise the loop id is the first entity
4179 -- in the scope constructed for the loop.
4181 if Comes_From_Source (Loop_Id) then
4182 pragma Assert (First_Entity (Scope (Loop_Id)) = Loop_Id);
4186 Set_First_Entity (Scope (Loop_Id), Next_Entity (Loop_Id));
4187 Remove_Homonym (Loop_Id);
4189 if Last_Entity (Scope (Loop_Id)) = Loop_Id then
4190 Set_Last_Entity (Scope (Loop_Id), Empty);
4195 -- Nothing to do with other cases of for loops
4202 -- Second case, if we have a while loop with Condition_Actions set, then
4203 -- we change it into a plain loop:
4212 -- <<condition actions>>
4217 elsif Present (Scheme)
4218 and then Present (Condition_Actions (Scheme))
4219 and then Present (Condition (Scheme))
4226 Make_Exit_Statement (Sloc (Condition (Scheme)),
4228 Make_Op_Not (Sloc (Condition (Scheme)),
4229 Right_Opnd => Condition (Scheme)));
4231 Prepend (ES, Statements (N));
4232 Insert_List_Before (ES, Condition_Actions (Scheme));
4234 -- This is not an implicit loop, since it is generated in response
4235 -- to the loop statement being processed. If this is itself
4236 -- implicit, the restriction has already been checked. If not,
4237 -- it is an explicit loop.
4240 Make_Loop_Statement (Sloc (N),
4241 Identifier => Identifier (N),
4242 Statements => Statements (N),
4243 End_Label => End_Label (N)));
4248 -- Here to deal with iterator case
4250 elsif Present (Scheme)
4251 and then Present (Iterator_Specification (Scheme))
4253 Expand_Iterator_Loop (N);
4255 -- An iterator loop may generate renaming declarations for elements
4256 -- that require debug information. This is the case in particular
4257 -- with element iterators, where debug information must be generated
4258 -- for the temporary that holds the element value. These temporaries
4259 -- are created within a transient block whose local declarations are
4260 -- transferred to the loop, which now has non-trivial local objects.
4262 if Nkind (N) = N_Loop_Statement
4263 and then Present (Identifier (N))
4265 Qualify_Entity_Names (N);
4269 -- When the iteration scheme mentiones attribute 'Loop_Entry, the loop
4270 -- is transformed into a conditional block where the original loop is
4271 -- the sole statement. Inspect the statements of the nested loop for
4272 -- controlled objects.
4276 if Subject_To_Loop_Entry_Attributes (Stmt) then
4277 Stmt := Find_Loop_In_Conditional_Block (Stmt);
4280 Process_Statements_For_Controlled_Objects (Stmt);
4281 end Expand_N_Loop_Statement;
4283 ----------------------------
4284 -- Expand_Predicated_Loop --
4285 ----------------------------
4287 -- Note: the expander can handle generation of loops over predicated
4288 -- subtypes for both the dynamic and static cases. Depending on what
4289 -- we decide is allowed in Ada 2012 mode and/or extensions allowed
4290 -- mode, the semantic analyzer may disallow one or both forms.
4292 procedure Expand_Predicated_Loop (N : Node_Id) is
4293 Loc : constant Source_Ptr := Sloc (N);
4294 Isc : constant Node_Id := Iteration_Scheme (N);
4295 LPS : constant Node_Id := Loop_Parameter_Specification (Isc);
4296 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4297 Ltype : constant Entity_Id := Etype (Loop_Id);
4298 Stat : constant List_Id := Static_Discrete_Predicate (Ltype);
4299 Stmts : constant List_Id := Statements (N);
4302 -- Case of iteration over non-static predicate, should not be possible
4303 -- since this is not allowed by the semantics and should have been
4304 -- caught during analysis of the loop statement.
4307 raise Program_Error;
4309 -- If the predicate list is empty, that corresponds to a predicate of
4310 -- False, in which case the loop won't run at all, and we rewrite the
4311 -- entire loop as a null statement.
4313 elsif Is_Empty_List (Stat) then
4314 Rewrite (N, Make_Null_Statement (Loc));
4317 -- For expansion over a static predicate we generate the following
4320 -- J : Ltype := min-val;
4325 -- when endpoint => J := startpoint;
4326 -- when endpoint => J := startpoint;
4328 -- when max-val => exit;
4329 -- when others => J := Lval'Succ (J);
4334 -- with min-val replaced by max-val and Succ replaced by Pred if the
4335 -- loop parameter specification carries a Reverse indicator.
4337 -- To make this a little clearer, let's take a specific example:
4339 -- type Int is range 1 .. 10;
4340 -- subtype StaticP is Int with
4341 -- predicate => StaticP in 3 | 10 | 5 .. 7;
4343 -- for L in StaticP loop
4344 -- Put_Line ("static:" & J'Img);
4347 -- In this case, the loop is transformed into
4354 -- when 3 => J := 5;
4355 -- when 7 => J := 10;
4357 -- when others => J := L'Succ (J);
4363 Static_Predicate : declare
4370 function Lo_Val (N : Node_Id) return Node_Id;
4371 -- Given static expression or static range, returns an identifier
4372 -- whose value is the low bound of the expression value or range.
4374 function Hi_Val (N : Node_Id) return Node_Id;
4375 -- Given static expression or static range, returns an identifier
4376 -- whose value is the high bound of the expression value or range.
4382 function Hi_Val (N : Node_Id) return Node_Id is
4384 if Is_OK_Static_Expression (N) then
4385 return New_Copy (N);
4387 pragma Assert (Nkind (N) = N_Range);
4388 return New_Copy (High_Bound (N));
4396 function Lo_Val (N : Node_Id) return Node_Id is
4398 if Is_OK_Static_Expression (N) then
4399 return New_Copy (N);
4401 pragma Assert (Nkind (N) = N_Range);
4402 return New_Copy (Low_Bound (N));
4406 -- Start of processing for Static_Predicate
4409 -- Convert loop identifier to normal variable and reanalyze it so
4410 -- that this conversion works. We have to use the same defining
4411 -- identifier, since there may be references in the loop body.
4413 Set_Analyzed (Loop_Id, False);
4414 Set_Ekind (Loop_Id, E_Variable);
4416 -- In most loops the loop variable is assigned in various
4417 -- alternatives in the body. However, in the rare case when
4418 -- the range specifies a single element, the loop variable
4419 -- may trigger a spurious warning that is could be constant.
4420 -- This warning might as well be suppressed.
4422 Set_Warnings_Off (Loop_Id);
4424 -- Loop to create branches of case statement
4428 if Reverse_Present (LPS) then
4430 -- Initial value is largest value in predicate.
4433 Make_Object_Declaration (Loc,
4434 Defining_Identifier => Loop_Id,
4435 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4436 Expression => Hi_Val (Last (Stat)));
4439 while Present (P) loop
4440 if No (Prev (P)) then
4441 S := Make_Exit_Statement (Loc);
4444 Make_Assignment_Statement (Loc,
4445 Name => New_Occurrence_Of (Loop_Id, Loc),
4446 Expression => Hi_Val (Prev (P)));
4447 Set_Suppress_Assignment_Checks (S);
4451 Make_Case_Statement_Alternative (Loc,
4452 Statements => New_List (S),
4453 Discrete_Choices => New_List (Lo_Val (P))));
4460 -- Initial value is smallest value in predicate.
4463 Make_Object_Declaration (Loc,
4464 Defining_Identifier => Loop_Id,
4465 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4466 Expression => Lo_Val (First (Stat)));
4469 while Present (P) loop
4470 if No (Next (P)) then
4471 S := Make_Exit_Statement (Loc);
4474 Make_Assignment_Statement (Loc,
4475 Name => New_Occurrence_Of (Loop_Id, Loc),
4476 Expression => Lo_Val (Next (P)));
4477 Set_Suppress_Assignment_Checks (S);
4481 Make_Case_Statement_Alternative (Loc,
4482 Statements => New_List (S),
4483 Discrete_Choices => New_List (Hi_Val (P))));
4489 -- Add others choice
4492 Name_Next : Name_Id;
4495 if Reverse_Present (LPS) then
4496 Name_Next := Name_Pred;
4498 Name_Next := Name_Succ;
4502 Make_Assignment_Statement (Loc,
4503 Name => New_Occurrence_Of (Loop_Id, Loc),
4505 Make_Attribute_Reference (Loc,
4506 Prefix => New_Occurrence_Of (Ltype, Loc),
4507 Attribute_Name => Name_Next,
4508 Expressions => New_List (
4509 New_Occurrence_Of (Loop_Id, Loc))));
4510 Set_Suppress_Assignment_Checks (S);
4514 Make_Case_Statement_Alternative (Loc,
4515 Discrete_Choices => New_List (Make_Others_Choice (Loc)),
4516 Statements => New_List (S)));
4518 -- Construct case statement and append to body statements
4521 Make_Case_Statement (Loc,
4522 Expression => New_Occurrence_Of (Loop_Id, Loc),
4523 Alternatives => Alts);
4524 Append_To (Stmts, Cstm);
4528 Set_Suppress_Assignment_Checks (D);
4531 Make_Block_Statement (Loc,
4532 Declarations => New_List (D),
4533 Handled_Statement_Sequence =>
4534 Make_Handled_Sequence_Of_Statements (Loc,
4535 Statements => New_List (
4536 Make_Loop_Statement (Loc,
4537 Statements => Stmts,
4538 End_Label => Empty)))));
4541 end Static_Predicate;
4543 end Expand_Predicated_Loop;
4545 ------------------------------
4546 -- Make_Tag_Ctrl_Assignment --
4547 ------------------------------
4549 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
4550 Asn : constant Node_Id := Relocate_Node (N);
4551 L : constant Node_Id := Name (N);
4552 Loc : constant Source_Ptr := Sloc (N);
4553 Res : constant List_Id := New_List;
4554 T : constant Entity_Id := Underlying_Type (Etype (L));
4556 Comp_Asn : constant Boolean := Is_Fully_Repped_Tagged_Type (T);
4557 Ctrl_Act : constant Boolean := Needs_Finalization (T)
4558 and then not No_Ctrl_Actions (N);
4559 Save_Tag : constant Boolean := Is_Tagged_Type (T)
4560 and then not Comp_Asn
4561 and then not No_Ctrl_Actions (N)
4562 and then Tagged_Type_Expansion;
4566 -- Finalize the target of the assignment when controlled
4568 -- We have two exceptions here:
4570 -- 1. If we are in an init proc since it is an initialization more
4571 -- than an assignment.
4573 -- 2. If the left-hand side is a temporary that was not initialized
4574 -- (or the parent part of a temporary since it is the case in
4575 -- extension aggregates). Such a temporary does not come from
4576 -- source. We must examine the original node for the prefix, because
4577 -- it may be a component of an entry formal, in which case it has
4578 -- been rewritten and does not appear to come from source either.
4580 -- Case of init proc
4582 if not Ctrl_Act then
4585 -- The left hand side is an uninitialized temporary object
4587 elsif Nkind (L) = N_Type_Conversion
4588 and then Is_Entity_Name (Expression (L))
4589 and then Nkind (Parent (Entity (Expression (L)))) =
4590 N_Object_Declaration
4591 and then No_Initialization (Parent (Entity (Expression (L))))
4598 (Obj_Ref => Duplicate_Subexpr_No_Checks (L),
4602 -- Save the Tag in a local variable Tag_Id
4605 Tag_Id := Make_Temporary (Loc, 'A');
4608 Make_Object_Declaration (Loc,
4609 Defining_Identifier => Tag_Id,
4610 Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc),
4612 Make_Selected_Component (Loc,
4613 Prefix => Duplicate_Subexpr_No_Checks (L),
4615 New_Occurrence_Of (First_Tag_Component (T), Loc))));
4617 -- Otherwise Tag_Id is not used
4623 -- If the tagged type has a full rep clause, expand the assignment into
4624 -- component-wise assignments. Mark the node as unanalyzed in order to
4625 -- generate the proper code and propagate this scenario by setting a
4626 -- flag to avoid infinite recursion.
4629 Set_Analyzed (Asn, False);
4630 Set_Componentwise_Assignment (Asn, True);
4633 Append_To (Res, Asn);
4639 Make_Assignment_Statement (Loc,
4641 Make_Selected_Component (Loc,
4642 Prefix => Duplicate_Subexpr_No_Checks (L),
4644 New_Occurrence_Of (First_Tag_Component (T), Loc)),
4645 Expression => New_Occurrence_Of (Tag_Id, Loc)));
4648 -- Adjust the target after the assignment when controlled (not in the
4649 -- init proc since it is an initialization more than an assignment).
4654 (Obj_Ref => Duplicate_Subexpr_Move_Checks (L),
4662 -- Could use comment here ???
4664 when RE_Not_Available =>
4666 end Make_Tag_Ctrl_Assignment;