1 ------------------------------------------------------------------------------
3 -- GNAT COMPILER COMPONENTS --
9 -- Copyright (C) 1992-2020, 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 Inline; use Inline;
42 with Namet; use Namet;
43 with Nlists; use Nlists;
44 with Nmake; use Nmake;
46 with Restrict; use Restrict;
47 with Rident; use Rident;
48 with Rtsfind; use Rtsfind;
49 with Sinfo; use Sinfo;
51 with Sem_Aux; use Sem_Aux;
52 with Sem_Ch3; use Sem_Ch3;
53 with Sem_Ch8; use Sem_Ch8;
54 with Sem_Ch13; use Sem_Ch13;
55 with Sem_Eval; use Sem_Eval;
56 with Sem_Res; use Sem_Res;
57 with Sem_Util; use Sem_Util;
58 with Snames; use Snames;
59 with Stand; use Stand;
60 with Stringt; use Stringt;
61 with Tbuild; use Tbuild;
62 with Uintp; use Uintp;
63 with Validsw; use Validsw;
65 package body Exp_Ch5 is
67 procedure Build_Formal_Container_Iteration
69 Container : Entity_Id;
72 Advance : out Node_Id;
73 New_Loop : out Node_Id);
74 -- Utility to create declarations and loop statement for both forms
75 -- of formal container iterators.
77 function Convert_To_Iterable_Type
78 (Container : Entity_Id;
79 Loc : Source_Ptr) return Node_Id;
80 -- Returns New_Occurrence_Of (Container), possibly converted to an ancestor
81 -- type, if the type of Container inherited the Iterable aspect from that
84 function Change_Of_Representation (N : Node_Id) return Boolean;
85 -- Determine if the right-hand side of assignment N is a type conversion
86 -- which requires a change of representation. Called only for the array
89 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id);
90 -- N is an assignment which assigns an array value. This routine process
91 -- the various special cases and checks required for such assignments,
92 -- including change of representation. Rhs is normally simply the right-
93 -- hand side of the assignment, except that if the right-hand side is a
94 -- type conversion or a qualified expression, then the RHS is the actual
95 -- expression inside any such type conversions or qualifications.
97 function Expand_Assign_Array_Loop
104 Rev : Boolean) return Node_Id;
105 -- N is an assignment statement which assigns an array value. This routine
106 -- expands the assignment into a loop (or nested loops for the case of a
107 -- multi-dimensional array) to do the assignment component by component.
108 -- Larray and Rarray are the entities of the actual arrays on the left-hand
109 -- and right-hand sides. L_Type and R_Type are the types of these arrays
110 -- (which may not be the same, due to either sliding, or to a change of
111 -- representation case). Ndim is the number of dimensions and the parameter
112 -- Rev indicates if the loops run normally (Rev = False), or reversed
113 -- (Rev = True). The value returned is the constructed loop statement.
114 -- Auxiliary declarations are inserted before node N using the standard
115 -- Insert_Actions mechanism.
117 function Expand_Assign_Array_Bitfield
123 Rev : Boolean) return Node_Id;
124 -- Alternative to Expand_Assign_Array_Loop for packed bitfields. Generates
125 -- a call to the System.Bitfields.Copy_Bitfield, which is more efficient
126 -- than copying component-by-component.
128 function Expand_Assign_Array_Loop_Or_Bitfield
135 Rev : Boolean) return Node_Id;
136 -- Calls either Expand_Assign_Array_Loop or Expand_Assign_Array_Bitfield as
139 procedure Expand_Assign_Record (N : Node_Id);
140 -- N is an assignment of an untagged record value. This routine handles
141 -- the case where the assignment must be made component by component,
142 -- either because the target is not byte aligned, or there is a change
143 -- of representation, or when we have a tagged type with a representation
144 -- clause (this last case is required because holes in the tagged type
145 -- might be filled with components from child types).
147 procedure Expand_Assign_With_Target_Names (N : Node_Id);
148 -- (AI12-0125): N is an assignment statement whose RHS contains occurrences
149 -- of @ that designate the value of the LHS of the assignment. If the LHS
150 -- is side-effect free the target names can be replaced with a copy of the
151 -- LHS; otherwise the semantics of the assignment is described in terms of
152 -- a procedure with an in-out parameter, and expanded as such.
154 procedure Expand_Formal_Container_Loop (N : Node_Id);
155 -- Use the primitives specified in an Iterable aspect to expand a loop
156 -- over a so-called formal container, primarily for SPARK usage.
158 procedure Expand_Formal_Container_Element_Loop (N : Node_Id);
159 -- Same, for an iterator of the form " For E of C". In this case the
160 -- iterator provides the name of the element, and the cursor is generated
163 procedure Expand_Iterator_Loop (N : Node_Id);
164 -- Expand loop over arrays and containers that uses the form "for X of C"
165 -- with an optional subtype mark, or "for Y in C".
167 procedure Expand_Iterator_Loop_Over_Container
172 Container_Typ : Entity_Id);
173 -- Expand loop over containers that uses the form "for X of C" with an
174 -- optional subtype mark, or "for Y in C". Isc is the iteration scheme.
175 -- I_Spec is the iterator specification and Container is either the
176 -- Container (for OF) or the iterator (for IN).
178 procedure Expand_Predicated_Loop (N : Node_Id);
179 -- Expand for loop over predicated subtype
181 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id;
182 -- Generate the necessary code for controlled and tagged assignment, that
183 -- is to say, finalization of the target before, adjustment of the target
184 -- after and save and restore of the tag and finalization pointers which
185 -- are not 'part of the value' and must not be changed upon assignment. N
186 -- is the original Assignment node.
188 --------------------------------------
189 -- Build_Formal_Container_Iteration --
190 --------------------------------------
192 procedure Build_Formal_Container_Iteration
194 Container : Entity_Id;
197 Advance : out Node_Id;
198 New_Loop : out Node_Id)
200 Loc : constant Source_Ptr := Sloc (N);
201 Stats : constant List_Id := Statements (N);
202 Typ : constant Entity_Id := Base_Type (Etype (Container));
204 Has_Element_Op : constant Entity_Id :=
205 Get_Iterable_Type_Primitive (Typ, Name_Has_Element);
207 First_Op : Entity_Id;
211 -- Use the proper set of primitives depending on the direction of
212 -- iteration. The legality of a reverse iteration has been checked
215 if Reverse_Present (Iterator_Specification (Iteration_Scheme (N))) then
216 First_Op := Get_Iterable_Type_Primitive (Typ, Name_Last);
217 Next_Op := Get_Iterable_Type_Primitive (Typ, Name_Previous);
220 First_Op := Get_Iterable_Type_Primitive (Typ, Name_First);
221 Next_Op := Get_Iterable_Type_Primitive (Typ, Name_Next);
224 -- Declaration for Cursor
227 Make_Object_Declaration (Loc,
228 Defining_Identifier => Cursor,
229 Object_Definition => New_Occurrence_Of (Etype (First_Op), Loc),
231 Make_Function_Call (Loc,
232 Name => New_Occurrence_Of (First_Op, Loc),
233 Parameter_Associations => New_List (
234 Convert_To_Iterable_Type (Container, Loc))));
236 -- Statement that advances (in the right direction) cursor in loop
239 Make_Assignment_Statement (Loc,
240 Name => New_Occurrence_Of (Cursor, Loc),
242 Make_Function_Call (Loc,
243 Name => New_Occurrence_Of (Next_Op, Loc),
244 Parameter_Associations => New_List (
245 Convert_To_Iterable_Type (Container, Loc),
246 New_Occurrence_Of (Cursor, Loc))));
248 -- Iterator is rewritten as a while_loop
251 Make_Loop_Statement (Loc,
253 Make_Iteration_Scheme (Loc,
255 Make_Function_Call (Loc,
256 Name => New_Occurrence_Of (Has_Element_Op, Loc),
257 Parameter_Associations => New_List (
258 Convert_To_Iterable_Type (Container, Loc),
259 New_Occurrence_Of (Cursor, Loc)))),
263 -- If the contruct has a specified loop name, preserve it in the new
264 -- loop, for possible use in exit statements.
266 if Present (Identifier (N))
267 and then Comes_From_Source (Identifier (N))
269 Set_Identifier (New_Loop, Identifier (N));
271 end Build_Formal_Container_Iteration;
273 ------------------------------
274 -- Change_Of_Representation --
275 ------------------------------
277 function Change_Of_Representation (N : Node_Id) return Boolean is
278 Rhs : constant Node_Id := Expression (N);
281 Nkind (Rhs) = N_Type_Conversion
283 not Same_Representation (Etype (Rhs), Etype (Expression (Rhs)));
284 end Change_Of_Representation;
286 ------------------------------
287 -- Convert_To_Iterable_Type --
288 ------------------------------
290 function Convert_To_Iterable_Type
291 (Container : Entity_Id;
292 Loc : Source_Ptr) return Node_Id
294 Typ : constant Entity_Id := Base_Type (Etype (Container));
295 Aspect : constant Node_Id := Find_Aspect (Typ, Aspect_Iterable);
299 Result := New_Occurrence_Of (Container, Loc);
301 if Entity (Aspect) /= Typ then
303 Make_Type_Conversion (Loc,
304 Subtype_Mark => New_Occurrence_Of (Entity (Aspect), Loc),
305 Expression => Result);
309 end Convert_To_Iterable_Type;
311 -------------------------
312 -- Expand_Assign_Array --
313 -------------------------
315 -- There are two issues here. First, do we let Gigi do a block move, or
316 -- do we expand out into a loop? Second, we need to set the two flags
317 -- Forwards_OK and Backwards_OK which show whether the block move (or
318 -- corresponding loops) can be legitimately done in a forwards (low to
319 -- high) or backwards (high to low) manner.
321 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id) is
322 Loc : constant Source_Ptr := Sloc (N);
324 Lhs : constant Node_Id := Name (N);
326 Act_Lhs : constant Node_Id := Get_Referenced_Object (Lhs);
327 Act_Rhs : Node_Id := Get_Referenced_Object (Rhs);
329 L_Type : constant Entity_Id :=
330 Underlying_Type (Get_Actual_Subtype (Act_Lhs));
331 R_Type : Entity_Id :=
332 Underlying_Type (Get_Actual_Subtype (Act_Rhs));
334 L_Slice : constant Boolean := Nkind (Act_Lhs) = N_Slice;
335 R_Slice : constant Boolean := Nkind (Act_Rhs) = N_Slice;
337 Crep : constant Boolean := Change_Of_Representation (N);
341 or else Is_Bit_Packed_Array (L_Type) = Is_Bit_Packed_Array (R_Type));
346 Ndim : constant Pos := Number_Dimensions (L_Type);
348 Loop_Required : Boolean := False;
349 -- This switch is set to True if the array move must be done using
350 -- an explicit front end generated loop.
352 procedure Apply_Dereference (Arg : Node_Id);
353 -- If the argument is an access to an array, and the assignment is
354 -- converted into a procedure call, apply explicit dereference.
356 function Has_Address_Clause (Exp : Node_Id) return Boolean;
357 -- Test if Exp is a reference to an array whose declaration has
358 -- an address clause, or it is a slice of such an array.
360 function Is_Formal_Array (Exp : Node_Id) return Boolean;
361 -- Test if Exp is a reference to an array which is either a formal
362 -- parameter or a slice of a formal parameter. These are the cases
363 -- where hidden aliasing can occur.
365 function Is_Non_Local_Array (Exp : Node_Id) return Boolean;
366 -- Determine if Exp is a reference to an array variable which is other
367 -- than an object defined in the current scope, or a component or a
368 -- slice of such an object. Such objects can be aliased to parameters
369 -- (unlike local array references).
371 -----------------------
372 -- Apply_Dereference --
373 -----------------------
375 procedure Apply_Dereference (Arg : Node_Id) is
376 Typ : constant Entity_Id := Etype (Arg);
378 if Is_Access_Type (Typ) then
379 Rewrite (Arg, Make_Explicit_Dereference (Loc,
380 Prefix => Relocate_Node (Arg)));
381 Analyze_And_Resolve (Arg, Designated_Type (Typ));
383 end Apply_Dereference;
385 ------------------------
386 -- Has_Address_Clause --
387 ------------------------
389 function Has_Address_Clause (Exp : Node_Id) return Boolean is
392 (Is_Entity_Name (Exp) and then
393 Present (Address_Clause (Entity (Exp))))
395 (Nkind (Exp) = N_Slice and then Has_Address_Clause (Prefix (Exp)));
396 end Has_Address_Clause;
398 ---------------------
399 -- Is_Formal_Array --
400 ---------------------
402 function Is_Formal_Array (Exp : Node_Id) return Boolean is
405 (Is_Entity_Name (Exp) and then Is_Formal (Entity (Exp)))
407 (Nkind (Exp) = N_Slice and then Is_Formal_Array (Prefix (Exp)));
410 ------------------------
411 -- Is_Non_Local_Array --
412 ------------------------
414 function Is_Non_Local_Array (Exp : Node_Id) return Boolean is
417 when N_Indexed_Component
418 | N_Selected_Component
421 return Is_Non_Local_Array (Prefix (Exp));
425 not (Is_Entity_Name (Exp)
426 and then Scope (Entity (Exp)) = Current_Scope);
428 end Is_Non_Local_Array;
430 -- Determine if Lhs, Rhs are formal arrays or nonlocal arrays
432 Lhs_Formal : constant Boolean := Is_Formal_Array (Act_Lhs);
433 Rhs_Formal : constant Boolean := Is_Formal_Array (Act_Rhs);
435 Lhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Lhs);
436 Rhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Rhs);
438 -- Start of processing for Expand_Assign_Array
441 -- Deal with length check. Note that the length check is done with
442 -- respect to the right-hand side as given, not a possible underlying
443 -- renamed object, since this would generate incorrect extra checks.
445 Apply_Length_Check (Rhs, L_Type);
447 -- We start by assuming that the move can be done in either direction,
448 -- i.e. that the two sides are completely disjoint.
450 Set_Forwards_OK (N, True);
451 Set_Backwards_OK (N, True);
453 -- Normally it is only the slice case that can lead to overlap, and
454 -- explicit checks for slices are made below. But there is one case
455 -- where the slice can be implicit and invisible to us: when we have a
456 -- one dimensional array, and either both operands are parameters, or
457 -- one is a parameter (which can be a slice passed by reference) and the
458 -- other is a non-local variable. In this case the parameter could be a
459 -- slice that overlaps with the other operand.
461 -- However, if the array subtype is a constrained first subtype in the
462 -- parameter case, then we don't have to worry about overlap, since
463 -- slice assignments aren't possible (other than for a slice denoting
466 -- Note: No overlap is possible if there is a change of representation,
467 -- so we can exclude this case.
472 ((Lhs_Formal and Rhs_Formal)
474 (Lhs_Formal and Rhs_Non_Local_Var)
476 (Rhs_Formal and Lhs_Non_Local_Var))
478 (not Is_Constrained (Etype (Lhs))
479 or else not Is_First_Subtype (Etype (Lhs)))
481 Set_Forwards_OK (N, False);
482 Set_Backwards_OK (N, False);
484 -- Note: the bit-packed case is not worrisome here, since if we have
485 -- a slice passed as a parameter, it is always aligned on a byte
486 -- boundary, and if there are no explicit slices, the assignment
487 -- can be performed directly.
490 -- If either operand has an address clause clear Backwards_OK and
491 -- Forwards_OK, since we cannot tell if the operands overlap. We
492 -- exclude this treatment when Rhs is an aggregate, since we know
493 -- that overlap can't occur.
495 if (Has_Address_Clause (Lhs) and then Nkind (Rhs) /= N_Aggregate)
496 or else Has_Address_Clause (Rhs)
498 Set_Forwards_OK (N, False);
499 Set_Backwards_OK (N, False);
502 -- We certainly must use a loop for change of representation and also
503 -- we use the operand of the conversion on the right-hand side as the
504 -- effective right-hand side (the component types must match in this
508 Act_Rhs := Get_Referenced_Object (Rhs);
509 R_Type := Get_Actual_Subtype (Act_Rhs);
510 Loop_Required := True;
512 -- We require a loop if the left side is possibly bit unaligned
514 elsif Possible_Bit_Aligned_Component (Lhs)
516 Possible_Bit_Aligned_Component (Rhs)
518 Loop_Required := True;
520 -- Arrays with controlled components are expanded into a loop to force
521 -- calls to Adjust at the component level.
523 elsif Has_Controlled_Component (L_Type) then
524 Loop_Required := True;
526 -- If object is atomic/VFA, we cannot tolerate a loop
528 elsif Is_Atomic_Or_VFA_Object (Act_Lhs)
530 Is_Atomic_Or_VFA_Object (Act_Rhs)
534 -- Loop is required if we have atomic components since we have to
535 -- be sure to do any accesses on an element by element basis.
537 elsif Has_Atomic_Components (L_Type)
538 or else Has_Atomic_Components (R_Type)
539 or else Is_Atomic_Or_VFA (Component_Type (L_Type))
540 or else Is_Atomic_Or_VFA (Component_Type (R_Type))
542 Loop_Required := True;
544 -- Case where no slice is involved
546 elsif not L_Slice and not R_Slice then
548 -- The following code deals with the case of unconstrained bit packed
549 -- arrays. The problem is that the template for such arrays contains
550 -- the bounds of the actual source level array, but the copy of an
551 -- entire array requires the bounds of the underlying array. It would
552 -- be nice if the back end could take care of this, but right now it
553 -- does not know how, so if we have such a type, then we expand out
554 -- into a loop, which is inefficient but works correctly. If we don't
555 -- do this, we get the wrong length computed for the array to be
556 -- moved. The two cases we need to worry about are:
558 -- Explicit dereference of an unconstrained packed array type as in
559 -- the following example:
562 -- type BITS is array(INTEGER range <>) of BOOLEAN;
563 -- pragma PACK(BITS);
564 -- type A is access BITS;
567 -- P1 := new BITS (1 .. 65_535);
568 -- P2 := new BITS (1 .. 65_535);
572 -- A formal parameter reference with an unconstrained bit array type
573 -- is the other case we need to worry about (here we assume the same
574 -- BITS type declared above):
576 -- procedure Write_All (File : out BITS; Contents : BITS);
578 -- File.Storage := Contents;
581 -- We expand to a loop in either of these two cases
583 -- Question for future thought. Another potentially more efficient
584 -- approach would be to create the actual subtype, and then do an
585 -- unchecked conversion to this actual subtype ???
587 Check_Unconstrained_Bit_Packed_Array : declare
589 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean;
590 -- Function to perform required test for the first case, above
591 -- (dereference of an unconstrained bit packed array).
593 -----------------------
594 -- Is_UBPA_Reference --
595 -----------------------
597 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean is
598 Typ : constant Entity_Id := Underlying_Type (Etype (Opnd));
600 Des_Type : Entity_Id;
603 if Present (Packed_Array_Impl_Type (Typ))
604 and then Is_Array_Type (Packed_Array_Impl_Type (Typ))
605 and then not Is_Constrained (Packed_Array_Impl_Type (Typ))
609 elsif Nkind (Opnd) = N_Explicit_Dereference then
610 P_Type := Underlying_Type (Etype (Prefix (Opnd)));
612 if not Is_Access_Type (P_Type) then
616 Des_Type := Designated_Type (P_Type);
618 Is_Bit_Packed_Array (Des_Type)
619 and then not Is_Constrained (Des_Type);
625 end Is_UBPA_Reference;
627 -- Start of processing for Check_Unconstrained_Bit_Packed_Array
630 if Is_UBPA_Reference (Lhs)
632 Is_UBPA_Reference (Rhs)
634 Loop_Required := True;
636 -- Here if we do not have the case of a reference to a bit packed
637 -- unconstrained array case. In this case gigi can most certainly
638 -- handle the assignment if a forwards move is allowed.
640 -- (could it handle the backwards case also???)
642 elsif Forwards_OK (N) then
645 end Check_Unconstrained_Bit_Packed_Array;
647 -- The back end can always handle the assignment if the right side is a
648 -- string literal (note that overlap is definitely impossible in this
649 -- case). If the type is packed, a string literal is always converted
650 -- into an aggregate, except in the case of a null slice, for which no
651 -- aggregate can be written. In that case, rewrite the assignment as a
652 -- null statement, a length check has already been emitted to verify
653 -- that the range of the left-hand side is empty.
655 -- Note that this code is not executed if we have an assignment of a
656 -- string literal to a non-bit aligned component of a record, a case
657 -- which cannot be handled by the backend.
659 elsif Nkind (Rhs) = N_String_Literal then
660 if String_Length (Strval (Rhs)) = 0
661 and then Is_Bit_Packed_Array (L_Type)
663 Rewrite (N, Make_Null_Statement (Loc));
669 -- If either operand is bit packed, then we need a loop, since we can't
670 -- be sure that the slice is byte aligned. Similarly, if either operand
671 -- is a possibly unaligned slice, then we need a loop (since the back
672 -- end cannot handle unaligned slices).
674 elsif Is_Bit_Packed_Array (L_Type)
675 or else Is_Bit_Packed_Array (R_Type)
676 or else Is_Possibly_Unaligned_Slice (Lhs)
677 or else Is_Possibly_Unaligned_Slice (Rhs)
679 Loop_Required := True;
681 -- If we are not bit-packed, and we have only one slice, then no overlap
682 -- is possible except in the parameter case, so we can let the back end
685 elsif not (L_Slice and R_Slice) then
686 if Forwards_OK (N) then
691 -- If the right-hand side is a string literal, introduce a temporary for
692 -- it, for use in the generated loop that will follow.
694 if Nkind (Rhs) = N_String_Literal then
696 Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Rhs);
701 Make_Object_Declaration (Loc,
702 Defining_Identifier => Temp,
703 Object_Definition => New_Occurrence_Of (L_Type, Loc),
704 Expression => Relocate_Node (Rhs));
706 Insert_Action (N, Decl);
707 Rewrite (Rhs, New_Occurrence_Of (Temp, Loc));
708 R_Type := Etype (Temp);
712 -- Come here to complete the analysis
714 -- Loop_Required: Set to True if we know that a loop is required
715 -- regardless of overlap considerations.
717 -- Forwards_OK: Set to False if we already know that a forwards
718 -- move is not safe, else set to True.
720 -- Backwards_OK: Set to False if we already know that a backwards
721 -- move is not safe, else set to True
723 -- Our task at this stage is to complete the overlap analysis, which can
724 -- result in possibly setting Forwards_OK or Backwards_OK to False, and
725 -- then generating the final code, either by deciding that it is OK
726 -- after all to let Gigi handle it, or by generating appropriate code
730 L_Index_Typ : constant Node_Id := Etype (First_Index (L_Type));
731 R_Index_Typ : constant Node_Id := Etype (First_Index (R_Type));
733 Left_Lo : constant Node_Id := Type_Low_Bound (L_Index_Typ);
734 Left_Hi : constant Node_Id := Type_High_Bound (L_Index_Typ);
735 Right_Lo : constant Node_Id := Type_Low_Bound (R_Index_Typ);
736 Right_Hi : constant Node_Id := Type_High_Bound (R_Index_Typ);
738 Act_L_Array : Node_Id;
739 Act_R_Array : Node_Id;
745 Cresult : Compare_Result;
748 -- Get the expressions for the arrays. If we are dealing with a
749 -- private type, then convert to the underlying type. We can do
750 -- direct assignments to an array that is a private type, but we
751 -- cannot assign to elements of the array without this extra
752 -- unchecked conversion.
754 -- Note: We propagate Parent to the conversion nodes to generate
755 -- a well-formed subtree.
757 if Nkind (Act_Lhs) = N_Slice then
758 Larray := Prefix (Act_Lhs);
762 if Is_Private_Type (Etype (Larray)) then
764 Par : constant Node_Id := Parent (Larray);
768 (Underlying_Type (Etype (Larray)), Larray);
769 Set_Parent (Larray, Par);
774 if Nkind (Act_Rhs) = N_Slice then
775 Rarray := Prefix (Act_Rhs);
779 if Is_Private_Type (Etype (Rarray)) then
781 Par : constant Node_Id := Parent (Rarray);
785 (Underlying_Type (Etype (Rarray)), Rarray);
786 Set_Parent (Rarray, Par);
791 -- If both sides are slices, we must figure out whether it is safe
792 -- to do the move in one direction or the other. It is always safe
793 -- if there is a change of representation since obviously two arrays
794 -- with different representations cannot possibly overlap.
796 if (not Crep) and L_Slice and R_Slice then
797 Act_L_Array := Get_Referenced_Object (Prefix (Act_Lhs));
798 Act_R_Array := Get_Referenced_Object (Prefix (Act_Rhs));
800 -- If both left- and right-hand arrays are entity names, and refer
801 -- to different entities, then we know that the move is safe (the
802 -- two storage areas are completely disjoint).
804 if Is_Entity_Name (Act_L_Array)
805 and then Is_Entity_Name (Act_R_Array)
806 and then Entity (Act_L_Array) /= Entity (Act_R_Array)
810 -- Otherwise, we assume the worst, which is that the two arrays
811 -- are the same array. There is no need to check if we know that
812 -- is the case, because if we don't know it, we still have to
815 -- Generally if the same array is involved, then we have an
816 -- overlapping case. We will have to really assume the worst (i.e.
817 -- set neither of the OK flags) unless we can determine the lower
818 -- or upper bounds at compile time and compare them.
823 (Left_Lo, Right_Lo, Assume_Valid => True);
825 if Cresult = Unknown then
828 (Left_Hi, Right_Hi, Assume_Valid => True);
833 Set_Backwards_OK (N, False);
836 Set_Forwards_OK (N, False);
839 Set_Backwards_OK (N, False);
840 Set_Forwards_OK (N, False);
845 -- If after that analysis Loop_Required is False, meaning that we
846 -- have not discovered some non-overlap reason for requiring a loop,
847 -- then the outcome depends on the capabilities of the back end.
849 if not Loop_Required then
850 -- Assume the back end can deal with all cases of overlap by
851 -- falling back to memmove if it cannot use a more efficient
857 -- At this stage we have to generate an explicit loop, and we have
858 -- the following cases:
860 -- Forwards_OK = True
862 -- Rnn : right_index := right_index'First;
863 -- for Lnn in left-index loop
864 -- left (Lnn) := right (Rnn);
865 -- Rnn := right_index'Succ (Rnn);
868 -- Note: the above code MUST be analyzed with checks off, because
869 -- otherwise the Succ could overflow. But in any case this is more
872 -- Forwards_OK = False, Backwards_OK = True
874 -- Rnn : right_index := right_index'Last;
875 -- for Lnn in reverse left-index loop
876 -- left (Lnn) := right (Rnn);
877 -- Rnn := right_index'Pred (Rnn);
880 -- Note: the above code MUST be analyzed with checks off, because
881 -- otherwise the Pred could overflow. But in any case this is more
884 -- Forwards_OK = Backwards_OK = False
886 -- This only happens if we have the same array on each side. It is
887 -- possible to create situations using overlays that violate this,
888 -- but we simply do not promise to get this "right" in this case.
890 -- There are two possible subcases. If the No_Implicit_Conditionals
891 -- restriction is set, then we generate the following code:
894 -- T : constant <operand-type> := rhs;
899 -- If implicit conditionals are permitted, then we generate:
901 -- if Left_Lo <= Right_Lo then
902 -- <code for Forwards_OK = True above>
904 -- <code for Backwards_OK = True above>
907 -- In order to detect possible aliasing, we examine the renamed
908 -- expression when the source or target is a renaming. However,
909 -- the renaming may be intended to capture an address that may be
910 -- affected by subsequent code, and therefore we must recover
911 -- the actual entity for the expansion that follows, not the
912 -- object it renames. In particular, if source or target designate
913 -- a portion of a dynamically allocated object, the pointer to it
914 -- may be reassigned but the renaming preserves the proper location.
916 if Is_Entity_Name (Rhs)
918 Nkind (Parent (Entity (Rhs))) = N_Object_Renaming_Declaration
919 and then Nkind (Act_Rhs) = N_Slice
924 if Is_Entity_Name (Lhs)
926 Nkind (Parent (Entity (Lhs))) = N_Object_Renaming_Declaration
927 and then Nkind (Act_Lhs) = N_Slice
932 -- Cases where either Forwards_OK or Backwards_OK is true
934 if Forwards_OK (N) or else Backwards_OK (N) then
935 if Needs_Finalization (Component_Type (L_Type))
936 and then Base_Type (L_Type) = Base_Type (R_Type)
938 and then not No_Ctrl_Actions (N)
941 Proc : constant Entity_Id :=
942 TSS (Base_Type (L_Type), TSS_Slice_Assign);
946 Apply_Dereference (Larray);
947 Apply_Dereference (Rarray);
948 Actuals := New_List (
949 Duplicate_Subexpr (Larray, Name_Req => True),
950 Duplicate_Subexpr (Rarray, Name_Req => True),
951 Duplicate_Subexpr (Left_Lo, Name_Req => True),
952 Duplicate_Subexpr (Left_Hi, Name_Req => True),
953 Duplicate_Subexpr (Right_Lo, Name_Req => True),
954 Duplicate_Subexpr (Right_Hi, Name_Req => True));
958 Boolean_Literals (not Forwards_OK (N)), Loc));
961 Make_Procedure_Call_Statement (Loc,
962 Name => New_Occurrence_Of (Proc, Loc),
963 Parameter_Associations => Actuals));
968 Expand_Assign_Array_Loop_Or_Bitfield
969 (N, Larray, Rarray, L_Type, R_Type, Ndim,
970 Rev => not Forwards_OK (N)));
973 -- Case of both are false with No_Implicit_Conditionals
975 elsif Restriction_Active (No_Implicit_Conditionals) then
977 T : constant Entity_Id :=
978 Make_Defining_Identifier (Loc, Chars => Name_T);
982 Make_Block_Statement (Loc,
983 Declarations => New_List (
984 Make_Object_Declaration (Loc,
985 Defining_Identifier => T,
986 Constant_Present => True,
988 New_Occurrence_Of (Etype (Rhs), Loc),
989 Expression => Relocate_Node (Rhs))),
991 Handled_Statement_Sequence =>
992 Make_Handled_Sequence_Of_Statements (Loc,
993 Statements => New_List (
994 Make_Assignment_Statement (Loc,
995 Name => Relocate_Node (Lhs),
996 Expression => New_Occurrence_Of (T, Loc))))));
999 -- Case of both are false with implicit conditionals allowed
1002 -- Before we generate this code, we must ensure that the left and
1003 -- right side array types are defined. They may be itypes, and we
1004 -- cannot let them be defined inside the if, since the first use
1005 -- in the then may not be executed.
1007 Ensure_Defined (L_Type, N);
1008 Ensure_Defined (R_Type, N);
1010 -- We normally compare addresses to find out which way round to
1011 -- do the loop, since this is reliable, and handles the cases of
1012 -- parameters, conversions etc. But we can't do that in the bit
1013 -- packed case, because addresses don't work there.
1015 if not Is_Bit_Packed_Array (L_Type) then
1019 Unchecked_Convert_To (RTE (RE_Integer_Address),
1020 Make_Attribute_Reference (Loc,
1022 Make_Indexed_Component (Loc,
1024 Duplicate_Subexpr_Move_Checks (Larray, True),
1025 Expressions => New_List (
1026 Make_Attribute_Reference (Loc,
1030 Attribute_Name => Name_First))),
1031 Attribute_Name => Name_Address)),
1034 Unchecked_Convert_To (RTE (RE_Integer_Address),
1035 Make_Attribute_Reference (Loc,
1037 Make_Indexed_Component (Loc,
1039 Duplicate_Subexpr_Move_Checks (Rarray, True),
1040 Expressions => New_List (
1041 Make_Attribute_Reference (Loc,
1045 Attribute_Name => Name_First))),
1046 Attribute_Name => Name_Address)));
1048 -- For the bit packed and VM cases we use the bounds. That's OK,
1049 -- because we don't have to worry about parameters, since they
1050 -- cannot cause overlap. Perhaps we should worry about weird slice
1056 Cleft_Lo := New_Copy_Tree (Left_Lo);
1057 Cright_Lo := New_Copy_Tree (Right_Lo);
1059 -- If the types do not match we add an implicit conversion
1060 -- here to ensure proper match
1062 if Etype (Left_Lo) /= Etype (Right_Lo) then
1064 Unchecked_Convert_To (Etype (Left_Lo), Cright_Lo);
1067 -- Reset the Analyzed flag, because the bounds of the index
1068 -- type itself may be universal, and must be reanalyzed to
1069 -- acquire the proper type for the back end.
1071 Set_Analyzed (Cleft_Lo, False);
1072 Set_Analyzed (Cright_Lo, False);
1076 Left_Opnd => Cleft_Lo,
1077 Right_Opnd => Cright_Lo);
1080 if Needs_Finalization (Component_Type (L_Type))
1081 and then Base_Type (L_Type) = Base_Type (R_Type)
1083 and then not No_Ctrl_Actions (N)
1086 -- Call TSS procedure for array assignment, passing the
1087 -- explicit bounds of right- and left-hand sides.
1090 Proc : constant Entity_Id :=
1091 TSS (Base_Type (L_Type), TSS_Slice_Assign);
1095 Apply_Dereference (Larray);
1096 Apply_Dereference (Rarray);
1097 Actuals := New_List (
1098 Duplicate_Subexpr (Larray, Name_Req => True),
1099 Duplicate_Subexpr (Rarray, Name_Req => True),
1100 Duplicate_Subexpr (Left_Lo, Name_Req => True),
1101 Duplicate_Subexpr (Left_Hi, Name_Req => True),
1102 Duplicate_Subexpr (Right_Lo, Name_Req => True),
1103 Duplicate_Subexpr (Right_Hi, Name_Req => True));
1107 Right_Opnd => Condition));
1110 Make_Procedure_Call_Statement (Loc,
1111 Name => New_Occurrence_Of (Proc, Loc),
1112 Parameter_Associations => Actuals));
1117 Make_Implicit_If_Statement (N,
1118 Condition => Condition,
1120 Then_Statements => New_List (
1121 Expand_Assign_Array_Loop_Or_Bitfield
1122 (N, Larray, Rarray, L_Type, R_Type, Ndim,
1125 Else_Statements => New_List (
1126 Expand_Assign_Array_Loop_Or_Bitfield
1127 (N, Larray, Rarray, L_Type, R_Type, Ndim,
1132 Analyze (N, Suppress => All_Checks);
1136 when RE_Not_Available =>
1138 end Expand_Assign_Array;
1140 ------------------------------
1141 -- Expand_Assign_Array_Loop --
1142 ------------------------------
1144 -- The following is an example of the loop generated for the case of a
1145 -- two-dimensional array:
1148 -- R2b : Tm1X1 := 1;
1150 -- for L1b in 1 .. 100 loop
1152 -- R4b : Tm1X2 := 1;
1154 -- for L3b in 1 .. 100 loop
1155 -- vm1 (L1b, L3b) := vm2 (R2b, R4b);
1156 -- R4b := Tm1X2'succ(R4b);
1159 -- R2b := Tm1X1'succ(R2b);
1163 -- Here Rev is False, and Tm1Xn are the subscript types for the right-hand
1164 -- side. The declarations of R2b and R4b are inserted before the original
1165 -- assignment statement.
1167 function Expand_Assign_Array_Loop
1174 Rev : Boolean) return Node_Id
1176 Loc : constant Source_Ptr := Sloc (N);
1178 Lnn : array (1 .. Ndim) of Entity_Id;
1179 Rnn : array (1 .. Ndim) of Entity_Id;
1180 -- Entities used as subscripts on left and right sides
1182 L_Index_Type : array (1 .. Ndim) of Entity_Id;
1183 R_Index_Type : array (1 .. Ndim) of Entity_Id;
1184 -- Left and right index types
1191 function Build_Step (J : Nat) return Node_Id;
1192 -- The increment step for the index of the right-hand side is written
1193 -- as an attribute reference (Succ or Pred). This function returns
1194 -- the corresponding node, which is placed at the end of the loop body.
1200 function Build_Step (J : Nat) return Node_Id is
1212 Make_Assignment_Statement (Loc,
1213 Name => New_Occurrence_Of (Rnn (J), Loc),
1215 Make_Attribute_Reference (Loc,
1217 New_Occurrence_Of (R_Index_Type (J), Loc),
1218 Attribute_Name => S_Or_P,
1219 Expressions => New_List (
1220 New_Occurrence_Of (Rnn (J), Loc))));
1222 -- Note that on the last iteration of the loop, the index is increased
1223 -- (or decreased) past the corresponding bound. This is consistent with
1224 -- the C semantics of the back-end, where such an off-by-one value on a
1225 -- dead index variable is OK. However, in CodePeer mode this leads to
1226 -- spurious warnings, and thus we place a guard around the attribute
1227 -- reference. For obvious reasons we only do this for CodePeer.
1229 if CodePeer_Mode then
1231 Make_If_Statement (Loc,
1234 Left_Opnd => New_Occurrence_Of (Lnn (J), Loc),
1236 Make_Attribute_Reference (Loc,
1237 Prefix => New_Occurrence_Of (L_Index_Type (J), Loc),
1238 Attribute_Name => Lim)),
1239 Then_Statements => New_List (Step));
1245 -- Start of processing for Expand_Assign_Array_Loop
1249 F_Or_L := Name_Last;
1250 S_Or_P := Name_Pred;
1252 F_Or_L := Name_First;
1253 S_Or_P := Name_Succ;
1256 -- Setup index types and subscript entities
1263 L_Index := First_Index (L_Type);
1264 R_Index := First_Index (R_Type);
1266 for J in 1 .. Ndim loop
1267 Lnn (J) := Make_Temporary (Loc, 'L');
1268 Rnn (J) := Make_Temporary (Loc, 'R');
1270 L_Index_Type (J) := Etype (L_Index);
1271 R_Index_Type (J) := Etype (R_Index);
1273 Next_Index (L_Index);
1274 Next_Index (R_Index);
1278 -- Now construct the assignment statement
1281 ExprL : constant List_Id := New_List;
1282 ExprR : constant List_Id := New_List;
1285 for J in 1 .. Ndim loop
1286 Append_To (ExprL, New_Occurrence_Of (Lnn (J), Loc));
1287 Append_To (ExprR, New_Occurrence_Of (Rnn (J), Loc));
1291 Make_Assignment_Statement (Loc,
1293 Make_Indexed_Component (Loc,
1294 Prefix => Duplicate_Subexpr (Larray, Name_Req => True),
1295 Expressions => ExprL),
1297 Make_Indexed_Component (Loc,
1298 Prefix => Duplicate_Subexpr (Rarray, Name_Req => True),
1299 Expressions => ExprR));
1301 -- We set assignment OK, since there are some cases, e.g. in object
1302 -- declarations, where we are actually assigning into a constant.
1303 -- If there really is an illegality, it was caught long before now,
1304 -- and was flagged when the original assignment was analyzed.
1306 Set_Assignment_OK (Name (Assign));
1308 -- Propagate the No_Ctrl_Actions flag to individual assignments
1310 Set_No_Ctrl_Actions (Assign, No_Ctrl_Actions (N));
1313 -- Now construct the loop from the inside out, with the last subscript
1314 -- varying most rapidly. Note that Assign is first the raw assignment
1315 -- statement, and then subsequently the loop that wraps it up.
1317 for J in reverse 1 .. Ndim loop
1319 Make_Block_Statement (Loc,
1320 Declarations => New_List (
1321 Make_Object_Declaration (Loc,
1322 Defining_Identifier => Rnn (J),
1323 Object_Definition =>
1324 New_Occurrence_Of (R_Index_Type (J), Loc),
1326 Make_Attribute_Reference (Loc,
1327 Prefix => New_Occurrence_Of (R_Index_Type (J), Loc),
1328 Attribute_Name => F_Or_L))),
1330 Handled_Statement_Sequence =>
1331 Make_Handled_Sequence_Of_Statements (Loc,
1332 Statements => New_List (
1333 Make_Implicit_Loop_Statement (N,
1335 Make_Iteration_Scheme (Loc,
1336 Loop_Parameter_Specification =>
1337 Make_Loop_Parameter_Specification (Loc,
1338 Defining_Identifier => Lnn (J),
1339 Reverse_Present => Rev,
1340 Discrete_Subtype_Definition =>
1341 New_Occurrence_Of (L_Index_Type (J), Loc))),
1343 Statements => New_List (Assign, Build_Step (J))))));
1347 end Expand_Assign_Array_Loop;
1349 ----------------------------------
1350 -- Expand_Assign_Array_Bitfield --
1351 ----------------------------------
1353 function Expand_Assign_Array_Bitfield
1359 Rev : Boolean) return Node_Id
1361 pragma Assert (not Rev);
1362 -- Reverse copying is not yet supported by Copy_Bitfield.
1364 pragma Assert (not Change_Of_Representation (N));
1365 -- This won't work, for example, to copy a packed array to an unpacked
1368 Loc : constant Source_Ptr := Sloc (N);
1370 L_Index_Typ : constant Node_Id := Etype (First_Index (L_Type));
1371 R_Index_Typ : constant Node_Id := Etype (First_Index (R_Type));
1372 Left_Lo : constant Node_Id := Type_Low_Bound (L_Index_Typ);
1373 Right_Lo : constant Node_Id := Type_Low_Bound (R_Index_Typ);
1375 L_Addr : constant Node_Id :=
1376 Make_Attribute_Reference (Loc,
1378 Make_Indexed_Component (Loc,
1380 Duplicate_Subexpr (Larray, True),
1381 Expressions => New_List (New_Copy_Tree (Left_Lo))),
1382 Attribute_Name => Name_Address);
1384 L_Bit : constant Node_Id :=
1385 Make_Attribute_Reference (Loc,
1387 Make_Indexed_Component (Loc,
1389 Duplicate_Subexpr (Larray, True),
1390 Expressions => New_List (New_Copy_Tree (Left_Lo))),
1391 Attribute_Name => Name_Bit);
1393 R_Addr : constant Node_Id :=
1394 Make_Attribute_Reference (Loc,
1396 Make_Indexed_Component (Loc,
1398 Duplicate_Subexpr (Rarray, True),
1399 Expressions => New_List (New_Copy_Tree (Right_Lo))),
1400 Attribute_Name => Name_Address);
1402 R_Bit : constant Node_Id :=
1403 Make_Attribute_Reference (Loc,
1405 Make_Indexed_Component (Loc,
1407 Duplicate_Subexpr (Rarray, True),
1408 Expressions => New_List (New_Copy_Tree (Right_Lo))),
1409 Attribute_Name => Name_Bit);
1411 -- Compute the Size of the bitfield
1413 -- Note that the length check has already been done, so we can use the
1414 -- size of either L or R; they are equal. We can't use 'Size here,
1415 -- because sometimes bit fields get copied into a temp, and the 'Size
1416 -- ends up being the size of the temp (e.g. an 8-bit temp containing
1417 -- a 4-bit bit field).
1419 Size : constant Node_Id :=
1420 Make_Op_Multiply (Loc,
1421 Make_Attribute_Reference (Loc,
1423 Duplicate_Subexpr (Name (N), True),
1424 Attribute_Name => Name_Length),
1425 Make_Attribute_Reference (Loc,
1427 Duplicate_Subexpr (Name (N), True),
1428 Attribute_Name => Name_Component_Size));
1431 return Make_Procedure_Call_Statement (Loc,
1432 Name => New_Occurrence_Of (RTE (RE_Copy_Bitfield), Loc),
1433 Parameter_Associations => New_List (
1434 R_Addr, R_Bit, L_Addr, L_Bit, Size));
1435 end Expand_Assign_Array_Bitfield;
1437 ------------------------------------------
1438 -- Expand_Assign_Array_Loop_Or_Bitfield --
1439 ------------------------------------------
1441 function Expand_Assign_Array_Loop_Or_Bitfield
1448 Rev : Boolean) return Node_Id
1450 Slices : constant Boolean :=
1451 Nkind (Name (N)) = N_Slice or else Nkind (Expression (N)) = N_Slice;
1452 L_Prefix_Comp : constant Boolean :=
1453 -- True if the left-hand side is a slice of a component or slice
1454 Nkind (Name (N)) = N_Slice
1455 and then Nkind_In (Prefix (Name (N)),
1456 N_Selected_Component,
1457 N_Indexed_Component,
1459 R_Prefix_Comp : constant Boolean :=
1460 -- Likewise for the right-hand side
1461 Nkind (Expression (N)) = N_Slice
1462 and then Nkind_In (Prefix (Expression (N)),
1463 N_Selected_Component,
1464 N_Indexed_Component,
1467 -- Determine whether Copy_Bitfield is appropriate (will work, and will
1468 -- be more efficient than component-by-component copy). Copy_Bitfield
1469 -- doesn't work for reversed storage orders. It is efficient for slices
1470 -- of bit-packed arrays. Copy_Bitfield can read and write bits that are
1471 -- not part of the objects being copied, so we don't want to use it if
1472 -- there are volatile or independent components. If the Prefix of the
1473 -- slice is a component or slice, then it might be a part of an object
1474 -- with some other volatile or independent components, so we disable the
1475 -- optimization in that case as well. We could complicate this code by
1476 -- actually looking for such volatile and independent components.
1478 if Is_Bit_Packed_Array (L_Type)
1479 and then Is_Bit_Packed_Array (R_Type)
1480 and then not Reverse_Storage_Order (L_Type)
1481 and then not Reverse_Storage_Order (R_Type)
1485 and then not Has_Volatile_Component (L_Type)
1486 and then not Has_Volatile_Component (R_Type)
1487 and then not Has_Independent_Components (L_Type)
1488 and then not Has_Independent_Components (R_Type)
1489 and then not L_Prefix_Comp
1490 and then not R_Prefix_Comp
1491 and then RTE_Available (RE_Copy_Bitfield)
1493 return Expand_Assign_Array_Bitfield
1494 (N, Larray, Rarray, L_Type, R_Type, Rev);
1496 return Expand_Assign_Array_Loop
1497 (N, Larray, Rarray, L_Type, R_Type, Ndim, Rev);
1499 end Expand_Assign_Array_Loop_Or_Bitfield;
1501 --------------------------
1502 -- Expand_Assign_Record --
1503 --------------------------
1505 procedure Expand_Assign_Record (N : Node_Id) is
1506 Lhs : constant Node_Id := Name (N);
1507 Rhs : Node_Id := Expression (N);
1508 L_Typ : constant Entity_Id := Base_Type (Etype (Lhs));
1511 -- If change of representation, then extract the real right-hand side
1512 -- from the type conversion, and proceed with component-wise assignment,
1513 -- since the two types are not the same as far as the back end is
1516 if Change_Of_Representation (N) then
1517 Rhs := Expression (Rhs);
1519 -- If this may be a case of a large bit aligned component, then proceed
1520 -- with component-wise assignment, to avoid possible clobbering of other
1521 -- components sharing bits in the first or last byte of the component to
1524 elsif Possible_Bit_Aligned_Component (Lhs)
1526 Possible_Bit_Aligned_Component (Rhs)
1530 -- If we have a tagged type that has a complete record representation
1531 -- clause, we must do we must do component-wise assignments, since child
1532 -- types may have used gaps for their components, and we might be
1533 -- dealing with a view conversion.
1535 elsif Is_Fully_Repped_Tagged_Type (L_Typ) then
1538 -- If neither condition met, then nothing special to do, the back end
1539 -- can handle assignment of the entire component as a single entity.
1545 -- At this stage we know that we must do a component wise assignment
1548 Loc : constant Source_Ptr := Sloc (N);
1549 R_Typ : constant Entity_Id := Base_Type (Etype (Rhs));
1550 Decl : constant Node_Id := Declaration_Node (R_Typ);
1554 function Find_Component
1556 Comp : Entity_Id) return Entity_Id;
1557 -- Find the component with the given name in the underlying record
1558 -- declaration for Typ. We need to use the actual entity because the
1559 -- type may be private and resolution by identifier alone would fail.
1561 function Make_Component_List_Assign
1563 U_U : Boolean := False) return List_Id;
1564 -- Returns a sequence of statements to assign the components that
1565 -- are referenced in the given component list. The flag U_U is
1566 -- used to force the usage of the inferred value of the variant
1567 -- part expression as the switch for the generated case statement.
1569 function Make_Field_Assign
1571 U_U : Boolean := False) return Node_Id;
1572 -- Given C, the entity for a discriminant or component, build an
1573 -- assignment for the corresponding field values. The flag U_U
1574 -- signals the presence of an Unchecked_Union and forces the usage
1575 -- of the inferred discriminant value of C as the right-hand side
1576 -- of the assignment.
1578 function Make_Field_Assigns (CI : List_Id) return List_Id;
1579 -- Given CI, a component items list, construct series of statements
1580 -- for fieldwise assignment of the corresponding components.
1582 --------------------
1583 -- Find_Component --
1584 --------------------
1586 function Find_Component
1588 Comp : Entity_Id) return Entity_Id
1590 Utyp : constant Entity_Id := Underlying_Type (Typ);
1594 C := First_Entity (Utyp);
1595 while Present (C) loop
1596 if Chars (C) = Chars (Comp) then
1603 raise Program_Error;
1606 --------------------------------
1607 -- Make_Component_List_Assign --
1608 --------------------------------
1610 function Make_Component_List_Assign
1612 U_U : Boolean := False) return List_Id
1614 CI : constant List_Id := Component_Items (CL);
1615 VP : constant Node_Id := Variant_Part (CL);
1625 Result := Make_Field_Assigns (CI);
1627 if Present (VP) then
1628 V := First_Non_Pragma (Variants (VP));
1630 while Present (V) loop
1632 DC := First (Discrete_Choices (V));
1633 while Present (DC) loop
1634 Append_To (DCH, New_Copy_Tree (DC));
1639 Make_Case_Statement_Alternative (Loc,
1640 Discrete_Choices => DCH,
1642 Make_Component_List_Assign (Component_List (V))));
1643 Next_Non_Pragma (V);
1646 -- If we have an Unchecked_Union, use the value of the inferred
1647 -- discriminant of the variant part expression as the switch
1648 -- for the case statement. The case statement may later be
1653 New_Copy (Get_Discriminant_Value (
1656 Discriminant_Constraint (Etype (Rhs))));
1659 Make_Selected_Component (Loc,
1660 Prefix => Duplicate_Subexpr (Rhs),
1662 Make_Identifier (Loc, Chars (Name (VP))));
1666 Make_Case_Statement (Loc,
1668 Alternatives => Alts));
1672 end Make_Component_List_Assign;
1674 -----------------------
1675 -- Make_Field_Assign --
1676 -----------------------
1678 function Make_Field_Assign
1680 U_U : Boolean := False) return Node_Id
1687 -- The discriminant entity to be used in the retrieval below must
1688 -- be one in the corresponding type, given that the assignment may
1689 -- be between derived and parent types.
1691 if Is_Derived_Type (Etype (Rhs)) then
1692 Disc := Find_Component (R_Typ, C);
1697 -- In the case of an Unchecked_Union, use the discriminant
1698 -- constraint value as on the right-hand side of the assignment.
1702 New_Copy (Get_Discriminant_Value (C,
1704 Discriminant_Constraint (Etype (Rhs))));
1707 Make_Selected_Component (Loc,
1708 Prefix => Duplicate_Subexpr (Rhs),
1709 Selector_Name => New_Occurrence_Of (Disc, Loc));
1712 -- Generate the assignment statement. When the left-hand side
1713 -- is an object with an address clause present, force generated
1714 -- temporaries to be renamings so as to correctly assign to any
1715 -- overlaid objects.
1718 Make_Assignment_Statement (Loc,
1720 Make_Selected_Component (Loc,
1726 Is_Entity_Name (Lhs)
1727 and then Present (Address_Clause (Entity (Lhs)))),
1729 New_Occurrence_Of (Find_Component (L_Typ, C), Loc)),
1730 Expression => Expr);
1732 -- Set Assignment_OK, so discriminants can be assigned
1734 Set_Assignment_OK (Name (A), True);
1736 if Componentwise_Assignment (N)
1737 and then Nkind (Name (A)) = N_Selected_Component
1738 and then Chars (Selector_Name (Name (A))) = Name_uParent
1740 Set_Componentwise_Assignment (A);
1744 end Make_Field_Assign;
1746 ------------------------
1747 -- Make_Field_Assigns --
1748 ------------------------
1750 function Make_Field_Assigns (CI : List_Id) return List_Id is
1758 while Present (Item) loop
1760 -- Look for components, but exclude _tag field assignment if
1761 -- the special Componentwise_Assignment flag is set.
1763 if Nkind (Item) = N_Component_Declaration
1764 and then not (Is_Tag (Defining_Identifier (Item))
1765 and then Componentwise_Assignment (N))
1768 (Result, Make_Field_Assign (Defining_Identifier (Item)));
1775 end Make_Field_Assigns;
1777 -- Start of processing for Expand_Assign_Record
1780 -- Note that we use the base types for this processing. This results
1781 -- in some extra work in the constrained case, but the change of
1782 -- representation case is so unusual that it is not worth the effort.
1784 -- First copy the discriminants. This is done unconditionally. It
1785 -- is required in the unconstrained left side case, and also in the
1786 -- case where this assignment was constructed during the expansion
1787 -- of a type conversion (since initialization of discriminants is
1788 -- suppressed in this case). It is unnecessary but harmless in
1791 -- Special case: no copy if the target has no discriminants
1793 if Has_Discriminants (L_Typ)
1794 and then Is_Unchecked_Union (Base_Type (L_Typ))
1798 elsif Has_Discriminants (L_Typ) then
1799 F := First_Discriminant (R_Typ);
1800 while Present (F) loop
1802 -- If we are expanding the initialization of a derived record
1803 -- that constrains or renames discriminants of the parent, we
1804 -- must use the corresponding discriminant in the parent.
1811 and then Present (Corresponding_Discriminant (F))
1813 CF := Corresponding_Discriminant (F);
1818 if Is_Unchecked_Union (Base_Type (R_Typ)) then
1820 -- Within an initialization procedure this is the
1821 -- assignment to an unchecked union component, in which
1822 -- case there is no discriminant to initialize.
1824 if Inside_Init_Proc then
1828 -- The assignment is part of a conversion from a
1829 -- derived unchecked union type with an inferable
1830 -- discriminant, to a parent type.
1832 Insert_Action (N, Make_Field_Assign (CF, True));
1836 Insert_Action (N, Make_Field_Assign (CF));
1839 Next_Discriminant (F);
1843 -- If the derived type has a stored constraint, assign the value
1844 -- of the corresponding discriminants explicitly, skipping those
1845 -- that are renamed discriminants. We cannot just retrieve them
1846 -- from the Rhs by selected component because they are invisible
1847 -- in the type of the right-hand side.
1849 if Stored_Constraint (R_Typ) /= No_Elist then
1852 Discr_Val : Elmt_Id;
1855 Discr_Val := First_Elmt (Stored_Constraint (R_Typ));
1856 F := First_Entity (R_Typ);
1857 while Present (F) loop
1858 if Ekind (F) = E_Discriminant
1859 and then Is_Completely_Hidden (F)
1860 and then Present (Corresponding_Record_Component (F))
1862 (not Is_Entity_Name (Node (Discr_Val))
1863 or else Ekind (Entity (Node (Discr_Val))) /=
1867 Make_Assignment_Statement (Loc,
1869 Make_Selected_Component (Loc,
1870 Prefix => Duplicate_Subexpr (Lhs),
1873 (Corresponding_Record_Component (F), Loc)),
1874 Expression => New_Copy (Node (Discr_Val)));
1876 Set_Assignment_OK (Name (Assign));
1877 Insert_Action (N, Assign);
1878 Next_Elmt (Discr_Val);
1887 -- We know the underlying type is a record, but its current view
1888 -- may be private. We must retrieve the usable record declaration.
1890 if Nkind_In (Decl, N_Private_Type_Declaration,
1891 N_Private_Extension_Declaration)
1892 and then Present (Full_View (R_Typ))
1894 RDef := Type_Definition (Declaration_Node (Full_View (R_Typ)));
1896 RDef := Type_Definition (Decl);
1899 if Nkind (RDef) = N_Derived_Type_Definition then
1900 RDef := Record_Extension_Part (RDef);
1903 if Nkind (RDef) = N_Record_Definition
1904 and then Present (Component_List (RDef))
1906 if Is_Unchecked_Union (R_Typ) then
1908 Make_Component_List_Assign (Component_List (RDef), True));
1911 (N, Make_Component_List_Assign (Component_List (RDef)));
1914 Rewrite (N, Make_Null_Statement (Loc));
1917 end Expand_Assign_Record;
1919 -------------------------------------
1920 -- Expand_Assign_With_Target_Names --
1921 -------------------------------------
1923 procedure Expand_Assign_With_Target_Names (N : Node_Id) is
1924 LHS : constant Node_Id := Name (N);
1925 LHS_Typ : constant Entity_Id := Etype (LHS);
1926 Loc : constant Source_Ptr := Sloc (N);
1927 RHS : constant Node_Id := Expression (N);
1930 -- The entity of the left-hand side
1932 function Replace_Target (N : Node_Id) return Traverse_Result;
1933 -- Replace occurrences of the target name by the proper entity: either
1934 -- the entity of the LHS in simple cases, or the formal of the
1935 -- constructed procedure otherwise.
1937 --------------------
1938 -- Replace_Target --
1939 --------------------
1941 function Replace_Target (N : Node_Id) return Traverse_Result is
1943 if Nkind (N) = N_Target_Name then
1944 Rewrite (N, New_Occurrence_Of (Ent, Sloc (N)));
1946 -- The expression will be reanalyzed when the enclosing assignment
1947 -- is reanalyzed, so reset the entity, which may be a temporary
1948 -- created during analysis, e.g. a loop variable for an iterated
1949 -- component association. However, if entity is callable then
1950 -- resolution has established its proper identity (including in
1951 -- rewritten prefixed calls) so we must preserve it.
1953 elsif Is_Entity_Name (N) then
1954 if Present (Entity (N))
1955 and then not Is_Overloadable (Entity (N))
1957 Set_Entity (N, Empty);
1961 Set_Analyzed (N, False);
1965 procedure Replace_Target_Name is new Traverse_Proc (Replace_Target);
1970 Proc_Id : Entity_Id;
1972 -- Start of processing for Expand_Assign_With_Target_Names
1975 New_RHS := New_Copy_Tree (RHS);
1977 -- The left-hand side is a direct name
1979 if Is_Entity_Name (LHS)
1980 and then not Is_Renaming_Of_Object (Entity (LHS))
1982 Ent := Entity (LHS);
1983 Replace_Target_Name (New_RHS);
1986 -- LHS := ... LHS ...;
1989 Make_Assignment_Statement (Loc,
1990 Name => Relocate_Node (LHS),
1991 Expression => New_RHS));
1993 -- The left-hand side is not a direct name, but is side-effect free.
1994 -- Capture its value in a temporary to avoid multiple evaluations.
1996 elsif Side_Effect_Free (LHS) then
1997 Ent := Make_Temporary (Loc, 'T');
1998 Replace_Target_Name (New_RHS);
2001 -- T : LHS_Typ := LHS;
2003 Insert_Before_And_Analyze (N,
2004 Make_Object_Declaration (Loc,
2005 Defining_Identifier => Ent,
2006 Object_Definition => New_Occurrence_Of (LHS_Typ, Loc),
2007 Expression => New_Copy_Tree (LHS)));
2010 -- LHS := ... T ...;
2013 Make_Assignment_Statement (Loc,
2014 Name => Relocate_Node (LHS),
2015 Expression => New_RHS));
2017 -- Otherwise wrap the whole assignment statement in a procedure with an
2018 -- IN OUT parameter. The original assignment then becomes a call to the
2019 -- procedure with the left-hand side as an actual.
2022 Ent := Make_Temporary (Loc, 'T');
2023 Replace_Target_Name (New_RHS);
2026 -- procedure P (T : in out LHS_Typ) is
2031 Proc_Id := Make_Temporary (Loc, 'P');
2033 Insert_Before_And_Analyze (N,
2034 Make_Subprogram_Body (Loc,
2036 Make_Procedure_Specification (Loc,
2037 Defining_Unit_Name => Proc_Id,
2038 Parameter_Specifications => New_List (
2039 Make_Parameter_Specification (Loc,
2040 Defining_Identifier => Ent,
2042 Out_Present => True,
2044 New_Occurrence_Of (LHS_Typ, Loc)))),
2046 Declarations => Empty_List,
2048 Handled_Statement_Sequence =>
2049 Make_Handled_Sequence_Of_Statements (Loc,
2050 Statements => New_List (
2051 Make_Assignment_Statement (Loc,
2052 Name => New_Occurrence_Of (Ent, Loc),
2053 Expression => New_RHS)))));
2059 Make_Procedure_Call_Statement (Loc,
2060 Name => New_Occurrence_Of (Proc_Id, Loc),
2061 Parameter_Associations => New_List (Relocate_Node (LHS))));
2064 -- Analyze rewritten node, either as assignment or procedure call
2067 end Expand_Assign_With_Target_Names;
2069 -----------------------------------
2070 -- Expand_N_Assignment_Statement --
2071 -----------------------------------
2073 -- This procedure implements various cases where an assignment statement
2074 -- cannot just be passed on to the back end in untransformed state.
2076 procedure Expand_N_Assignment_Statement (N : Node_Id) is
2077 Crep : constant Boolean := Change_Of_Representation (N);
2078 Lhs : constant Node_Id := Name (N);
2079 Loc : constant Source_Ptr := Sloc (N);
2080 Rhs : constant Node_Id := Expression (N);
2081 Typ : constant Entity_Id := Underlying_Type (Etype (Lhs));
2085 -- Special case to check right away, if the Componentwise_Assignment
2086 -- flag is set, this is a reanalysis from the expansion of the primitive
2087 -- assignment procedure for a tagged type, and all we need to do is to
2088 -- expand to assignment of components, because otherwise, we would get
2089 -- infinite recursion (since this looks like a tagged assignment which
2090 -- would normally try to *call* the primitive assignment procedure).
2092 if Componentwise_Assignment (N) then
2093 Expand_Assign_Record (N);
2097 -- Defend against invalid subscripts on left side if we are in standard
2098 -- validity checking mode. No need to do this if we are checking all
2101 -- Note that we do this right away, because there are some early return
2102 -- paths in this procedure, and this is required on all paths.
2104 if Validity_Checks_On
2105 and then Validity_Check_Default
2106 and then not Validity_Check_Subscripts
2108 Check_Valid_Lvalue_Subscripts (Lhs);
2111 -- Separate expansion if RHS contain target names. Note that assignment
2112 -- may already have been expanded if RHS is aggregate.
2114 if Nkind (N) = N_Assignment_Statement and then Has_Target_Names (N) then
2115 Expand_Assign_With_Target_Names (N);
2119 -- Ada 2005 (AI-327): Handle assignment to priority of protected object
2121 -- Rewrite an assignment to X'Priority into a run-time call
2123 -- For example: X'Priority := New_Prio_Expr;
2124 -- ...is expanded into Set_Ceiling (X._Object, New_Prio_Expr);
2126 -- Note that although X'Priority is notionally an object, it is quite
2127 -- deliberately not defined as an aliased object in the RM. This means
2128 -- that it works fine to rewrite it as a call, without having to worry
2129 -- about complications that would other arise from X'Priority'Access,
2130 -- which is illegal, because of the lack of aliasing.
2132 if Ada_Version >= Ada_2005 then
2135 Conctyp : Entity_Id;
2138 RT_Subprg_Name : Node_Id;
2141 -- Handle chains of renamings
2144 while Nkind (Ent) in N_Has_Entity
2145 and then Present (Entity (Ent))
2146 and then Present (Renamed_Object (Entity (Ent)))
2148 Ent := Renamed_Object (Entity (Ent));
2151 -- The attribute Priority applied to protected objects has been
2152 -- previously expanded into a call to the Get_Ceiling run-time
2153 -- subprogram. In restricted profiles this is not available.
2155 if Is_Expanded_Priority_Attribute (Ent) then
2157 -- Look for the enclosing concurrent type
2159 Conctyp := Current_Scope;
2160 while not Is_Concurrent_Type (Conctyp) loop
2161 Conctyp := Scope (Conctyp);
2164 pragma Assert (Is_Protected_Type (Conctyp));
2166 -- Generate the first actual of the call
2168 Subprg := Current_Scope;
2169 while not Present (Protected_Body_Subprogram (Subprg)) loop
2170 Subprg := Scope (Subprg);
2173 -- Select the appropriate run-time call
2175 if Number_Entries (Conctyp) = 0 then
2177 New_Occurrence_Of (RTE (RE_Set_Ceiling), Loc);
2180 New_Occurrence_Of (RTE (RO_PE_Set_Ceiling), Loc);
2184 Make_Procedure_Call_Statement (Loc,
2185 Name => RT_Subprg_Name,
2186 Parameter_Associations => New_List (
2187 New_Copy_Tree (First (Parameter_Associations (Ent))),
2188 Relocate_Node (Expression (N))));
2198 -- Deal with assignment checks unless suppressed
2200 if not Suppress_Assignment_Checks (N) then
2202 -- First deal with generation of range check if required,
2203 -- and then predicate checks if the type carries a predicate.
2204 -- If the Rhs is an expression these tests may have been applied
2205 -- already. This is the case if the RHS is a type conversion.
2206 -- Other such redundant checks could be removed ???
2208 if Nkind (Rhs) /= N_Type_Conversion
2209 or else Entity (Subtype_Mark (Rhs)) /= Typ
2211 if Do_Range_Check (Rhs) then
2212 Generate_Range_Check (Rhs, Typ, CE_Range_Check_Failed);
2215 Apply_Predicate_Check (Rhs, Typ);
2219 -- Check for a special case where a high level transformation is
2220 -- required. If we have either of:
2225 -- where P is a reference to a bit packed array, then we have to unwind
2226 -- the assignment. The exact meaning of being a reference to a bit
2227 -- packed array is as follows:
2229 -- An indexed component whose prefix is a bit packed array is a
2230 -- reference to a bit packed array.
2232 -- An indexed component or selected component whose prefix is a
2233 -- reference to a bit packed array is itself a reference ot a
2234 -- bit packed array.
2236 -- The required transformation is
2238 -- Tnn : prefix_type := P;
2239 -- Tnn.field := rhs;
2244 -- Tnn : prefix_type := P;
2245 -- Tnn (subscr) := rhs;
2248 -- Since P is going to be evaluated more than once, any subscripts
2249 -- in P must have their evaluation forced.
2251 if Nkind_In (Lhs, N_Indexed_Component, N_Selected_Component)
2252 and then Is_Ref_To_Bit_Packed_Array (Prefix (Lhs))
2255 BPAR_Expr : constant Node_Id := Relocate_Node (Prefix (Lhs));
2256 BPAR_Typ : constant Entity_Id := Etype (BPAR_Expr);
2257 Tnn : constant Entity_Id :=
2258 Make_Temporary (Loc, 'T', BPAR_Expr);
2261 -- Insert the post assignment first, because we want to copy the
2262 -- BPAR_Expr tree before it gets analyzed in the context of the
2263 -- pre assignment. Note that we do not analyze the post assignment
2264 -- yet (we cannot till we have completed the analysis of the pre
2265 -- assignment). As usual, the analysis of this post assignment
2266 -- will happen on its own when we "run into" it after finishing
2267 -- the current assignment.
2270 Make_Assignment_Statement (Loc,
2271 Name => New_Copy_Tree (BPAR_Expr),
2272 Expression => New_Occurrence_Of (Tnn, Loc)));
2274 -- At this stage BPAR_Expr is a reference to a bit packed array
2275 -- where the reference was not expanded in the original tree,
2276 -- since it was on the left side of an assignment. But in the
2277 -- pre-assignment statement (the object definition), BPAR_Expr
2278 -- will end up on the right-hand side, and must be reexpanded. To
2279 -- achieve this, we reset the analyzed flag of all selected and
2280 -- indexed components down to the actual indexed component for
2281 -- the packed array.
2285 Set_Analyzed (Exp, False);
2287 if Nkind_In (Exp, N_Indexed_Component,
2288 N_Selected_Component)
2290 Exp := Prefix (Exp);
2296 -- Now we can insert and analyze the pre-assignment
2298 -- If the right-hand side requires a transient scope, it has
2299 -- already been placed on the stack. However, the declaration is
2300 -- inserted in the tree outside of this scope, and must reflect
2301 -- the proper scope for its variable. This awkward bit is forced
2302 -- by the stricter scope discipline imposed by GCC 2.97.
2305 Uses_Transient_Scope : constant Boolean :=
2307 and then N = Node_To_Be_Wrapped;
2310 if Uses_Transient_Scope then
2311 Push_Scope (Scope (Current_Scope));
2314 Insert_Before_And_Analyze (N,
2315 Make_Object_Declaration (Loc,
2316 Defining_Identifier => Tnn,
2317 Object_Definition => New_Occurrence_Of (BPAR_Typ, Loc),
2318 Expression => BPAR_Expr));
2320 if Uses_Transient_Scope then
2325 -- Now fix up the original assignment and continue processing
2327 Rewrite (Prefix (Lhs),
2328 New_Occurrence_Of (Tnn, Loc));
2330 -- We do not need to reanalyze that assignment, and we do not need
2331 -- to worry about references to the temporary, but we do need to
2332 -- make sure that the temporary is not marked as a true constant
2333 -- since we now have a generated assignment to it.
2335 Set_Is_True_Constant (Tnn, False);
2339 -- When we have the appropriate type of aggregate in the expression (it
2340 -- has been determined during analysis of the aggregate by setting the
2341 -- delay flag), let's perform in place assignment and thus avoid
2342 -- creating a temporary.
2344 if Is_Delayed_Aggregate (Rhs) then
2345 Convert_Aggr_In_Assignment (N);
2346 Rewrite (N, Make_Null_Statement (Loc));
2352 -- Apply discriminant check if required. If Lhs is an access type to a
2353 -- designated type with discriminants, we must always check. If the
2354 -- type has unknown discriminants, more elaborate processing below.
2356 if Has_Discriminants (Etype (Lhs))
2357 and then not Has_Unknown_Discriminants (Etype (Lhs))
2359 -- Skip discriminant check if change of representation. Will be
2360 -- done when the change of representation is expanded out.
2363 Apply_Discriminant_Check (Rhs, Etype (Lhs), Lhs);
2366 -- If the type is private without discriminants, and the full type
2367 -- has discriminants (necessarily with defaults) a check may still be
2368 -- necessary if the Lhs is aliased. The private discriminants must be
2369 -- visible to build the discriminant constraints.
2371 -- Only an explicit dereference that comes from source indicates
2372 -- aliasing. Access to formals of protected operations and entries
2373 -- create dereferences but are not semantic aliasings.
2375 elsif Is_Private_Type (Etype (Lhs))
2376 and then Has_Discriminants (Typ)
2377 and then Nkind (Lhs) = N_Explicit_Dereference
2378 and then Comes_From_Source (Lhs)
2381 Lt : constant Entity_Id := Etype (Lhs);
2382 Ubt : Entity_Id := Base_Type (Typ);
2385 -- In the case of an expander-generated record subtype whose base
2386 -- type still appears private, Typ will have been set to that
2387 -- private type rather than the underlying record type (because
2388 -- Underlying type will have returned the record subtype), so it's
2389 -- necessary to apply Underlying_Type again to the base type to
2390 -- get the record type we need for the discriminant check. Such
2391 -- subtypes can be created for assignments in certain cases, such
2392 -- as within an instantiation passed this kind of private type.
2393 -- It would be good to avoid this special test, but making changes
2394 -- to prevent this odd form of record subtype seems difficult. ???
2396 if Is_Private_Type (Ubt) then
2397 Ubt := Underlying_Type (Ubt);
2400 Set_Etype (Lhs, Ubt);
2401 Rewrite (Rhs, OK_Convert_To (Base_Type (Ubt), Rhs));
2402 Apply_Discriminant_Check (Rhs, Ubt, Lhs);
2403 Set_Etype (Lhs, Lt);
2406 -- If the Lhs has a private type with unknown discriminants, it may
2407 -- have a full view with discriminants, but those are nameable only
2408 -- in the underlying type, so convert the Rhs to it before potential
2409 -- checking. Convert Lhs as well, otherwise the actual subtype might
2410 -- not be constructible. If the discriminants have defaults the type
2411 -- is unconstrained and there is nothing to check.
2412 -- Ditto if a private type with unknown discriminants has a full view
2413 -- that is an unconstrained array, in which case a length check is
2416 elsif Has_Unknown_Discriminants (Base_Type (Etype (Lhs))) then
2417 if Has_Discriminants (Typ)
2418 and then not Has_Defaulted_Discriminants (Typ)
2420 Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
2421 Rewrite (Lhs, OK_Convert_To (Base_Type (Typ), Lhs));
2422 Apply_Discriminant_Check (Rhs, Typ, Lhs);
2424 elsif Is_Array_Type (Typ) and then Is_Constrained (Typ) then
2425 Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
2426 Rewrite (Lhs, OK_Convert_To (Base_Type (Typ), Lhs));
2427 Apply_Length_Check (Rhs, Typ);
2430 -- In the access type case, we need the same discriminant check, and
2431 -- also range checks if we have an access to constrained array.
2433 elsif Is_Access_Type (Etype (Lhs))
2434 and then Is_Constrained (Designated_Type (Etype (Lhs)))
2436 if Has_Discriminants (Designated_Type (Etype (Lhs))) then
2438 -- Skip discriminant check if change of representation. Will be
2439 -- done when the change of representation is expanded out.
2442 Apply_Discriminant_Check (Rhs, Etype (Lhs));
2445 elsif Is_Array_Type (Designated_Type (Etype (Lhs))) then
2446 Apply_Range_Check (Rhs, Etype (Lhs));
2448 if Is_Constrained (Etype (Lhs)) then
2449 Apply_Length_Check (Rhs, Etype (Lhs));
2452 if Nkind (Rhs) = N_Allocator then
2454 Target_Typ : constant Entity_Id := Etype (Expression (Rhs));
2455 C_Es : Check_Result;
2462 Etype (Designated_Type (Etype (Lhs))));
2474 -- Apply range check for access type case
2476 elsif Is_Access_Type (Etype (Lhs))
2477 and then Nkind (Rhs) = N_Allocator
2478 and then Nkind (Expression (Rhs)) = N_Qualified_Expression
2480 Analyze_And_Resolve (Expression (Rhs));
2482 (Expression (Rhs), Designated_Type (Etype (Lhs)));
2485 -- Ada 2005 (AI-231): Generate the run-time check
2487 if Is_Access_Type (Typ)
2488 and then Can_Never_Be_Null (Etype (Lhs))
2489 and then not Can_Never_Be_Null (Etype (Rhs))
2491 -- If an actual is an out parameter of a null-excluding access
2492 -- type, there is access check on entry, so we set the flag
2493 -- Suppress_Assignment_Checks on the generated statement to
2494 -- assign the actual to the parameter block, and we do not want
2495 -- to generate an additional check at this point.
2497 and then not Suppress_Assignment_Checks (N)
2499 Apply_Constraint_Check (Rhs, Etype (Lhs));
2502 -- Ada 2012 (AI05-148): Update current accessibility level if Rhs is a
2503 -- stand-alone obj of an anonymous access type. Do not install the check
2504 -- when the Lhs denotes a container cursor and the Next function employs
2505 -- an access type, because this can never result in a dangling pointer.
2507 if Is_Access_Type (Typ)
2508 and then Is_Entity_Name (Lhs)
2509 and then Ekind (Entity (Lhs)) /= E_Loop_Parameter
2510 and then Present (Effective_Extra_Accessibility (Entity (Lhs)))
2513 function Lhs_Entity return Entity_Id;
2514 -- Look through renames to find the underlying entity.
2515 -- For assignment to a rename, we don't care about the
2516 -- Enclosing_Dynamic_Scope of the rename declaration.
2522 function Lhs_Entity return Entity_Id is
2523 Result : Entity_Id := Entity (Lhs);
2526 while Present (Renamed_Object (Result)) loop
2528 -- Renamed_Object must return an Entity_Name here
2529 -- because of preceding "Present (E_E_A (...))" test.
2531 Result := Entity (Renamed_Object (Result));
2537 -- Local Declarations
2539 Access_Check : constant Node_Id :=
2540 Make_Raise_Program_Error (Loc,
2544 Dynamic_Accessibility_Level (Rhs),
2546 Make_Integer_Literal (Loc,
2549 (Enclosing_Dynamic_Scope
2551 Reason => PE_Accessibility_Check_Failed);
2553 Access_Level_Update : constant Node_Id :=
2554 Make_Assignment_Statement (Loc,
2557 (Effective_Extra_Accessibility
2558 (Entity (Lhs)), Loc),
2560 Dynamic_Accessibility_Level (Rhs));
2563 if not Accessibility_Checks_Suppressed (Entity (Lhs)) then
2564 Insert_Action (N, Access_Check);
2567 Insert_Action (N, Access_Level_Update);
2571 -- Case of assignment to a bit packed array element. If there is a
2572 -- change of representation this must be expanded into components,
2573 -- otherwise this is a bit-field assignment.
2575 if Nkind (Lhs) = N_Indexed_Component
2576 and then Is_Bit_Packed_Array (Etype (Prefix (Lhs)))
2578 -- Normal case, no change of representation
2581 Expand_Bit_Packed_Element_Set (N);
2584 -- Change of representation case
2587 -- Generate the following, to force component-by-component
2588 -- assignments in an efficient way. Otherwise each component
2589 -- will require a temporary and two bit-field manipulations.
2596 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T');
2602 Make_Object_Declaration (Loc,
2603 Defining_Identifier => Tnn,
2604 Object_Definition =>
2605 New_Occurrence_Of (Etype (Lhs), Loc)),
2606 Make_Assignment_Statement (Loc,
2607 Name => New_Occurrence_Of (Tnn, Loc),
2608 Expression => Relocate_Node (Rhs)),
2609 Make_Assignment_Statement (Loc,
2610 Name => Relocate_Node (Lhs),
2611 Expression => New_Occurrence_Of (Tnn, Loc)));
2613 Insert_Actions (N, Stats);
2614 Rewrite (N, Make_Null_Statement (Loc));
2619 -- Build-in-place function call case. This is for assignment statements
2620 -- that come from aggregate component associations or from init procs.
2621 -- User-written assignment statements with b-i-p calls are handled
2624 elsif Is_Build_In_Place_Function_Call (Rhs) then
2625 pragma Assert (not Comes_From_Source (N));
2626 Make_Build_In_Place_Call_In_Assignment (N, Rhs);
2628 elsif Is_Tagged_Type (Typ)
2629 or else (Needs_Finalization (Typ) and then not Is_Array_Type (Typ))
2631 Tagged_Case : declare
2632 L : List_Id := No_List;
2633 Expand_Ctrl_Actions : constant Boolean := not No_Ctrl_Actions (N);
2636 -- In the controlled case, we ensure that function calls are
2637 -- evaluated before finalizing the target. In all cases, it makes
2638 -- the expansion easier if the side effects are removed first.
2640 Remove_Side_Effects (Lhs);
2641 Remove_Side_Effects (Rhs);
2643 -- Avoid recursion in the mechanism
2647 -- If dispatching assignment, we need to dispatch to _assign
2649 if Is_Class_Wide_Type (Typ)
2651 -- If the type is tagged, we may as well use the predefined
2652 -- primitive assignment. This avoids inlining a lot of code
2653 -- and in the class-wide case, the assignment is replaced
2654 -- by a dispatching call to _assign. It is suppressed in the
2655 -- case of assignments created by the expander that correspond
2656 -- to initializations, where we do want to copy the tag
2657 -- (Expand_Ctrl_Actions flag is set False in this case). It is
2658 -- also suppressed if restriction No_Dispatching_Calls is in
2659 -- force because in that case predefined primitives are not
2662 or else (Is_Tagged_Type (Typ)
2663 and then Chars (Current_Scope) /= Name_uAssign
2664 and then Expand_Ctrl_Actions
2666 not Restriction_Active (No_Dispatching_Calls))
2668 if Is_Limited_Type (Typ) then
2670 -- This can happen in an instance when the formal is an
2671 -- extension of a limited interface, and the actual is
2672 -- limited. This is an error according to AI05-0087, but
2673 -- is not caught at the point of instantiation in earlier
2674 -- versions. We also must verify that the limited type does
2675 -- not come from source as corner cases may exist where
2676 -- an assignment was not intended like the pathological case
2677 -- of a raise expression within a return statement.
2679 -- This is wrong, error messages cannot be issued during
2680 -- expansion, since they would be missed in -gnatc mode ???
2682 if Comes_From_Source (N) then
2684 ("assignment not available on limited type", N);
2690 -- Fetch the primitive op _assign and proper type to call it.
2691 -- Because of possible conflicts between private and full view,
2692 -- fetch the proper type directly from the operation profile.
2695 Op : constant Entity_Id :=
2696 Find_Prim_Op (Typ, Name_uAssign);
2697 F_Typ : Entity_Id := Etype (First_Formal (Op));
2700 -- If the assignment is dispatching, make sure to use the
2703 if Is_Class_Wide_Type (Typ) then
2704 F_Typ := Class_Wide_Type (F_Typ);
2709 -- In case of assignment to a class-wide tagged type, before
2710 -- the assignment we generate run-time check to ensure that
2711 -- the tags of source and target match.
2713 if not Tag_Checks_Suppressed (Typ)
2714 and then Is_Class_Wide_Type (Typ)
2715 and then Is_Tagged_Type (Typ)
2716 and then Is_Tagged_Type (Underlying_Type (Etype (Rhs)))
2723 if not Is_Interface (Typ) then
2725 Make_Selected_Component (Loc,
2726 Prefix => Duplicate_Subexpr (Lhs),
2728 Make_Identifier (Loc, Name_uTag));
2730 Make_Selected_Component (Loc,
2731 Prefix => Duplicate_Subexpr (Rhs),
2733 Make_Identifier (Loc, Name_uTag));
2735 -- Displace the pointer to the base of the objects
2736 -- applying 'Address, which is later expanded into
2737 -- a call to RE_Base_Address.
2740 Make_Explicit_Dereference (Loc,
2742 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
2743 Make_Attribute_Reference (Loc,
2744 Prefix => Duplicate_Subexpr (Lhs),
2745 Attribute_Name => Name_Address)));
2747 Make_Explicit_Dereference (Loc,
2749 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
2750 Make_Attribute_Reference (Loc,
2751 Prefix => Duplicate_Subexpr (Rhs),
2752 Attribute_Name => Name_Address)));
2756 Make_Raise_Constraint_Error (Loc,
2759 Left_Opnd => Lhs_Tag,
2760 Right_Opnd => Rhs_Tag),
2761 Reason => CE_Tag_Check_Failed));
2766 Left_N : Node_Id := Duplicate_Subexpr (Lhs);
2767 Right_N : Node_Id := Duplicate_Subexpr (Rhs);
2770 -- In order to dispatch the call to _assign the type of
2771 -- the actuals must match. Add conversion (if required).
2773 if Etype (Lhs) /= F_Typ then
2774 Left_N := Unchecked_Convert_To (F_Typ, Left_N);
2777 if Etype (Rhs) /= F_Typ then
2778 Right_N := Unchecked_Convert_To (F_Typ, Right_N);
2782 Make_Procedure_Call_Statement (Loc,
2783 Name => New_Occurrence_Of (Op, Loc),
2784 Parameter_Associations => New_List (
2786 Node2 => Right_N)));
2791 L := Make_Tag_Ctrl_Assignment (N);
2793 -- We can't afford to have destructive Finalization Actions in
2794 -- the Self assignment case, so if the target and the source
2795 -- are not obviously different, code is generated to avoid the
2796 -- self assignment case:
2798 -- if lhs'address /= rhs'address then
2799 -- <code for controlled and/or tagged assignment>
2802 -- Skip this if Restriction (No_Finalization) is active
2804 if not Statically_Different (Lhs, Rhs)
2805 and then Expand_Ctrl_Actions
2806 and then not Restriction_Active (No_Finalization)
2809 Make_Implicit_If_Statement (N,
2813 Make_Attribute_Reference (Loc,
2814 Prefix => Duplicate_Subexpr (Lhs),
2815 Attribute_Name => Name_Address),
2818 Make_Attribute_Reference (Loc,
2819 Prefix => Duplicate_Subexpr (Rhs),
2820 Attribute_Name => Name_Address)),
2822 Then_Statements => L));
2825 -- We need to set up an exception handler for implementing
2826 -- 7.6.1(18). The remaining adjustments are tackled by the
2827 -- implementation of adjust for record_controllers (see
2830 -- This is skipped if we have no finalization
2832 if Expand_Ctrl_Actions
2833 and then not Restriction_Active (No_Finalization)
2836 Make_Block_Statement (Loc,
2837 Handled_Statement_Sequence =>
2838 Make_Handled_Sequence_Of_Statements (Loc,
2840 Exception_Handlers => New_List (
2841 Make_Handler_For_Ctrl_Operation (Loc)))));
2846 Make_Block_Statement (Loc,
2847 Handled_Statement_Sequence =>
2848 Make_Handled_Sequence_Of_Statements (Loc, Statements => L)));
2850 -- If no restrictions on aborts, protect the whole assignment
2851 -- for controlled objects as per 9.8(11).
2853 if Needs_Finalization (Typ)
2854 and then Expand_Ctrl_Actions
2855 and then Abort_Allowed
2858 Blk : constant Entity_Id :=
2860 (E_Block, Current_Scope, Sloc (N), 'B');
2861 AUD : constant Entity_Id := RTE (RE_Abort_Undefer_Direct);
2864 Set_Is_Abort_Block (N);
2866 Set_Scope (Blk, Current_Scope);
2867 Set_Etype (Blk, Standard_Void_Type);
2868 Set_Identifier (N, New_Occurrence_Of (Blk, Sloc (N)));
2870 Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
2871 Set_At_End_Proc (Handled_Statement_Sequence (N),
2872 New_Occurrence_Of (AUD, Loc));
2874 -- Present the Abort_Undefer_Direct function to the backend
2875 -- so that it can inline the call to the function.
2877 Add_Inlined_Body (AUD, N);
2879 Expand_At_End_Handler
2880 (Handled_Statement_Sequence (N), Blk);
2884 -- N has been rewritten to a block statement for which it is
2885 -- known by construction that no checks are necessary: analyze
2886 -- it with all checks suppressed.
2888 Analyze (N, Suppress => All_Checks);
2894 elsif Is_Array_Type (Typ) then
2896 Actual_Rhs : Node_Id := Rhs;
2899 while Nkind_In (Actual_Rhs, N_Type_Conversion,
2900 N_Qualified_Expression)
2902 Actual_Rhs := Expression (Actual_Rhs);
2905 Expand_Assign_Array (N, Actual_Rhs);
2911 elsif Is_Record_Type (Typ) then
2912 Expand_Assign_Record (N);
2915 -- Scalar types. This is where we perform the processing related to the
2916 -- requirements of (RM 13.9.1(9-11)) concerning the handling of invalid
2919 elsif Is_Scalar_Type (Typ) then
2921 -- Case where right side is known valid
2923 if Expr_Known_Valid (Rhs) then
2925 -- Here the right side is valid, so it is fine. The case to deal
2926 -- with is when the left side is a local variable reference whose
2927 -- value is not currently known to be valid. If this is the case,
2928 -- and the assignment appears in an unconditional context, then
2929 -- we can mark the left side as now being valid if one of these
2930 -- conditions holds:
2932 -- The expression of the right side has Do_Range_Check set so
2933 -- that we know a range check will be performed. Note that it
2934 -- can be the case that a range check is omitted because we
2935 -- make the assumption that we can assume validity for operands
2936 -- appearing in the right side in determining whether a range
2937 -- check is required
2939 -- The subtype of the right side matches the subtype of the
2940 -- left side. In this case, even though we have not checked
2941 -- the range of the right side, we know it is in range of its
2942 -- subtype if the expression is valid.
2944 if Is_Local_Variable_Reference (Lhs)
2945 and then not Is_Known_Valid (Entity (Lhs))
2946 and then In_Unconditional_Context (N)
2948 if Do_Range_Check (Rhs)
2949 or else Etype (Lhs) = Etype (Rhs)
2951 Set_Is_Known_Valid (Entity (Lhs), True);
2955 -- Case where right side may be invalid in the sense of the RM
2956 -- reference above. The RM does not require that we check for the
2957 -- validity on an assignment, but it does require that the assignment
2958 -- of an invalid value not cause erroneous behavior.
2960 -- The general approach in GNAT is to use the Is_Known_Valid flag
2961 -- to avoid the need for validity checking on assignments. However
2962 -- in some cases, we have to do validity checking in order to make
2963 -- sure that the setting of this flag is correct.
2966 -- Validate right side if we are validating copies
2968 if Validity_Checks_On
2969 and then Validity_Check_Copies
2971 -- Skip this if left-hand side is an array or record component
2972 -- and elementary component validity checks are suppressed.
2974 if Nkind_In (Lhs, N_Selected_Component, N_Indexed_Component)
2975 and then not Validity_Check_Components
2982 -- We can propagate this to the left side where appropriate
2984 if Is_Local_Variable_Reference (Lhs)
2985 and then not Is_Known_Valid (Entity (Lhs))
2986 and then In_Unconditional_Context (N)
2988 Set_Is_Known_Valid (Entity (Lhs), True);
2991 -- Otherwise check to see what should be done
2993 -- If left side is a local variable, then we just set its flag to
2994 -- indicate that its value may no longer be valid, since we are
2995 -- copying a potentially invalid value.
2997 elsif Is_Local_Variable_Reference (Lhs) then
2998 Set_Is_Known_Valid (Entity (Lhs), False);
3000 -- Check for case of a nonlocal variable on the left side which
3001 -- is currently known to be valid. In this case, we simply ensure
3002 -- that the right side is valid. We only play the game of copying
3003 -- validity status for local variables, since we are doing this
3004 -- statically, not by tracing the full flow graph.
3006 elsif Is_Entity_Name (Lhs)
3007 and then Is_Known_Valid (Entity (Lhs))
3009 -- Note: If Validity_Checking mode is set to none, we ignore
3010 -- the Ensure_Valid call so don't worry about that case here.
3014 -- In all other cases, we can safely copy an invalid value without
3015 -- worrying about the status of the left side. Since it is not a
3016 -- variable reference it will not be considered
3017 -- as being known to be valid in any case.
3026 when RE_Not_Available =>
3028 end Expand_N_Assignment_Statement;
3030 ------------------------------
3031 -- Expand_N_Block_Statement --
3032 ------------------------------
3034 -- Encode entity names defined in block statement
3036 procedure Expand_N_Block_Statement (N : Node_Id) is
3038 Qualify_Entity_Names (N);
3039 end Expand_N_Block_Statement;
3041 -----------------------------
3042 -- Expand_N_Case_Statement --
3043 -----------------------------
3045 procedure Expand_N_Case_Statement (N : Node_Id) is
3046 Loc : constant Source_Ptr := Sloc (N);
3047 Expr : constant Node_Id := Expression (N);
3048 From_Cond_Expr : constant Boolean := From_Conditional_Expression (N);
3056 -- Check for the situation where we know at compile time which branch
3059 -- If the value is static but its subtype is predicated and the value
3060 -- does not obey the predicate, the value is marked non-static, and
3061 -- there can be no corresponding static alternative. In that case we
3062 -- replace the case statement with an exception, regardless of whether
3063 -- assertions are enabled or not, unless predicates are ignored.
3065 if Compile_Time_Known_Value (Expr)
3066 and then Has_Predicates (Etype (Expr))
3067 and then not Predicates_Ignored (Etype (Expr))
3068 and then not Is_OK_Static_Expression (Expr)
3071 Make_Raise_Constraint_Error (Loc, Reason => CE_Invalid_Data));
3075 elsif Compile_Time_Known_Value (Expr)
3076 and then (not Has_Predicates (Etype (Expr))
3077 or else Is_Static_Expression (Expr))
3079 Alt := Find_Static_Alternative (N);
3081 -- Do not consider controlled objects found in a case statement which
3082 -- actually models a case expression because their early finalization
3083 -- will affect the result of the expression.
3085 if not From_Conditional_Expression (N) then
3086 Process_Statements_For_Controlled_Objects (Alt);
3089 -- Move statements from this alternative after the case statement.
3090 -- They are already analyzed, so will be skipped by the analyzer.
3092 Insert_List_After (N, Statements (Alt));
3094 -- That leaves the case statement as a shell. So now we can kill all
3095 -- other alternatives in the case statement.
3097 Kill_Dead_Code (Expression (N));
3103 -- Loop through case alternatives, skipping pragmas, and skipping
3104 -- the one alternative that we select (and therefore retain).
3106 Dead_Alt := First (Alternatives (N));
3107 while Present (Dead_Alt) loop
3109 and then Nkind (Dead_Alt) = N_Case_Statement_Alternative
3111 Kill_Dead_Code (Statements (Dead_Alt), Warn_On_Deleted_Code);
3118 Rewrite (N, Make_Null_Statement (Loc));
3122 -- Here if the choice is not determined at compile time
3125 Last_Alt : constant Node_Id := Last (Alternatives (N));
3127 Others_Present : Boolean;
3128 Others_Node : Node_Id;
3130 Then_Stms : List_Id;
3131 Else_Stms : List_Id;
3134 if Nkind (First (Discrete_Choices (Last_Alt))) = N_Others_Choice then
3135 Others_Present := True;
3136 Others_Node := Last_Alt;
3138 Others_Present := False;
3141 -- First step is to worry about possible invalid argument. The RM
3142 -- requires (RM 5.4(13)) that if the result is invalid (e.g. it is
3143 -- outside the base range), then Constraint_Error must be raised.
3145 -- Case of validity check required (validity checks are on, the
3146 -- expression is not known to be valid, and the case statement
3147 -- comes from source -- no need to validity check internally
3148 -- generated case statements).
3150 if Validity_Check_Default
3151 and then not Predicates_Ignored (Etype (Expr))
3153 Ensure_Valid (Expr);
3156 -- If there is only a single alternative, just replace it with the
3157 -- sequence of statements since obviously that is what is going to
3158 -- be executed in all cases.
3160 Len := List_Length (Alternatives (N));
3164 -- We still need to evaluate the expression if it has any side
3167 Remove_Side_Effects (Expression (N));
3168 Alt := First (Alternatives (N));
3170 -- Do not consider controlled objects found in a case statement
3171 -- which actually models a case expression because their early
3172 -- finalization will affect the result of the expression.
3174 if not From_Conditional_Expression (N) then
3175 Process_Statements_For_Controlled_Objects (Alt);
3178 Insert_List_After (N, Statements (Alt));
3180 -- That leaves the case statement as a shell. The alternative that
3181 -- will be executed is reset to a null list. So now we can kill
3182 -- the entire case statement.
3184 Kill_Dead_Code (Expression (N));
3185 Rewrite (N, Make_Null_Statement (Loc));
3188 -- An optimization. If there are only two alternatives, and only
3189 -- a single choice, then rewrite the whole case statement as an
3190 -- if statement, since this can result in subsequent optimizations.
3191 -- This helps not only with case statements in the source of a
3192 -- simple form, but also with generated code (discriminant check
3193 -- functions in particular).
3195 -- Note: it is OK to do this before expanding out choices for any
3196 -- static predicates, since the if statement processing will handle
3197 -- the static predicate case fine.
3200 Chlist := Discrete_Choices (First (Alternatives (N)));
3202 if List_Length (Chlist) = 1 then
3203 Choice := First (Chlist);
3205 Then_Stms := Statements (First (Alternatives (N)));
3206 Else_Stms := Statements (Last (Alternatives (N)));
3208 -- For TRUE, generate "expression", not expression = true
3210 if Nkind (Choice) = N_Identifier
3211 and then Entity (Choice) = Standard_True
3213 Cond := Expression (N);
3215 -- For FALSE, generate "expression" and switch then/else
3217 elsif Nkind (Choice) = N_Identifier
3218 and then Entity (Choice) = Standard_False
3220 Cond := Expression (N);
3221 Else_Stms := Statements (First (Alternatives (N)));
3222 Then_Stms := Statements (Last (Alternatives (N)));
3224 -- For a range, generate "expression in range"
3226 elsif Nkind (Choice) = N_Range
3227 or else (Nkind (Choice) = N_Attribute_Reference
3228 and then Attribute_Name (Choice) = Name_Range)
3229 or else (Is_Entity_Name (Choice)
3230 and then Is_Type (Entity (Choice)))
3234 Left_Opnd => Expression (N),
3235 Right_Opnd => Relocate_Node (Choice));
3237 -- A subtype indication is not a legal operator in a membership
3238 -- test, so retrieve its range.
3240 elsif Nkind (Choice) = N_Subtype_Indication then
3243 Left_Opnd => Expression (N),
3246 (Range_Expression (Constraint (Choice))));
3248 -- For any other subexpression "expression = value"
3253 Left_Opnd => Expression (N),
3254 Right_Opnd => Relocate_Node (Choice));
3257 -- Now rewrite the case as an IF
3260 Make_If_Statement (Loc,
3262 Then_Statements => Then_Stms,
3263 Else_Statements => Else_Stms));
3265 -- The rewritten if statement needs to inherit whether the
3266 -- case statement was expanded from a conditional expression,
3267 -- for proper handling of nested controlled objects.
3269 Set_From_Conditional_Expression (N, From_Cond_Expr);
3277 -- If the last alternative is not an Others choice, replace it with
3278 -- an N_Others_Choice. Note that we do not bother to call Analyze on
3279 -- the modified case statement, since it's only effect would be to
3280 -- compute the contents of the Others_Discrete_Choices which is not
3281 -- needed by the back end anyway.
3283 -- The reason for this is that the back end always needs some default
3284 -- for a switch, so if we have not supplied one in the processing
3285 -- above for validity checking, then we need to supply one here.
3287 if not Others_Present then
3288 Others_Node := Make_Others_Choice (Sloc (Last_Alt));
3290 -- If Predicates_Ignored is true the value does not satisfy the
3291 -- predicate, and there is no Others choice, Constraint_Error
3292 -- must be raised (4.5.7 (21/3)).
3294 if Predicates_Ignored (Etype (Expr)) then
3296 Except : constant Node_Id :=
3297 Make_Raise_Constraint_Error (Loc,
3298 Reason => CE_Invalid_Data);
3299 New_Alt : constant Node_Id :=
3300 Make_Case_Statement_Alternative (Loc,
3301 Discrete_Choices => New_List (
3302 Make_Others_Choice (Loc)),
3303 Statements => New_List (Except));
3306 Append (New_Alt, Alternatives (N));
3307 Analyze_And_Resolve (Except);
3311 Set_Others_Discrete_Choices
3312 (Others_Node, Discrete_Choices (Last_Alt));
3313 Set_Discrete_Choices (Last_Alt, New_List (Others_Node));
3318 -- Deal with possible declarations of controlled objects, and also
3319 -- with rewriting choice sequences for static predicate references.
3321 Alt := First_Non_Pragma (Alternatives (N));
3322 while Present (Alt) loop
3324 -- Do not consider controlled objects found in a case statement
3325 -- which actually models a case expression because their early
3326 -- finalization will affect the result of the expression.
3328 if not From_Conditional_Expression (N) then
3329 Process_Statements_For_Controlled_Objects (Alt);
3332 if Has_SP_Choice (Alt) then
3333 Expand_Static_Predicates_In_Choices (Alt);
3336 Next_Non_Pragma (Alt);
3339 end Expand_N_Case_Statement;
3341 -----------------------------
3342 -- Expand_N_Exit_Statement --
3343 -----------------------------
3345 -- The only processing required is to deal with a possible C/Fortran
3346 -- boolean value used as the condition for the exit statement.
3348 procedure Expand_N_Exit_Statement (N : Node_Id) is
3350 Adjust_Condition (Condition (N));
3351 end Expand_N_Exit_Statement;
3353 ----------------------------------
3354 -- Expand_Formal_Container_Loop --
3355 ----------------------------------
3357 procedure Expand_Formal_Container_Loop (N : Node_Id) is
3358 Loc : constant Source_Ptr := Sloc (N);
3359 Isc : constant Node_Id := Iteration_Scheme (N);
3360 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3361 Cursor : constant Entity_Id := Defining_Identifier (I_Spec);
3362 Container : constant Node_Id := Entity (Name (I_Spec));
3363 Stats : constant List_Id := Statements (N);
3366 Init_Decl : Node_Id;
3367 Init_Name : Entity_Id;
3371 -- The expansion of a formal container loop resembles the one for Ada
3372 -- containers. The only difference is that the primitives mention the
3373 -- domain of iteration explicitly, and function First applied to the
3374 -- container yields a cursor directly.
3376 -- Cursor : Cursor_type := First (Container);
3377 -- while Has_Element (Cursor, Container) loop
3378 -- <original loop statements>
3379 -- Cursor := Next (Container, Cursor);
3382 Build_Formal_Container_Iteration
3383 (N, Container, Cursor, Init_Decl, Advance, New_Loop);
3385 Append_To (Stats, Advance);
3387 -- Build a block to capture declaration of the cursor
3390 Make_Block_Statement (Loc,
3391 Declarations => New_List (Init_Decl),
3392 Handled_Statement_Sequence =>
3393 Make_Handled_Sequence_Of_Statements (Loc,
3394 Statements => New_List (New_Loop))));
3396 -- The loop parameter is declared by an object declaration, but within
3397 -- the loop we must prevent user assignments to it, so we analyze the
3398 -- declaration and reset the entity kind, before analyzing the rest of
3401 Analyze (Init_Decl);
3402 Init_Name := Defining_Identifier (Init_Decl);
3403 Set_Ekind (Init_Name, E_Loop_Parameter);
3405 -- The cursor was marked as a loop parameter to prevent user assignments
3406 -- to it, however this renders the advancement step illegal as it is not
3407 -- possible to change the value of a constant. Flag the advancement step
3408 -- as a legal form of assignment to remedy this side effect.
3410 Set_Assignment_OK (Name (Advance));
3413 -- Because we have to analyze the initial declaration of the loop
3414 -- parameter multiple times its scope is incorrectly set at this point
3415 -- to the one surrounding the block statement - so set the scope
3416 -- manually to be the actual block statement, and indicate that it is
3417 -- not visible after the block has been analyzed.
3419 Set_Scope (Init_Name, Entity (Identifier (N)));
3420 Set_Is_Immediately_Visible (Init_Name, False);
3421 end Expand_Formal_Container_Loop;
3423 ------------------------------------------
3424 -- Expand_Formal_Container_Element_Loop --
3425 ------------------------------------------
3427 procedure Expand_Formal_Container_Element_Loop (N : Node_Id) is
3428 Loc : constant Source_Ptr := Sloc (N);
3429 Isc : constant Node_Id := Iteration_Scheme (N);
3430 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3431 Element : constant Entity_Id := Defining_Identifier (I_Spec);
3432 Container : constant Node_Id := Entity (Name (I_Spec));
3433 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
3434 Stats : constant List_Id := Statements (N);
3436 Cursor : constant Entity_Id :=
3437 Make_Defining_Identifier (Loc,
3438 Chars => New_External_Name (Chars (Element), 'C'));
3439 Elmt_Decl : Node_Id;
3442 Element_Op : constant Entity_Id :=
3443 Get_Iterable_Type_Primitive (Container_Typ, Name_Element);
3450 -- For an element iterator, the Element aspect must be present,
3451 -- (this is checked during analysis) and the expansion takes the form:
3453 -- Cursor : Cursor_Type := First (Container);
3454 -- Elmt : Element_Type;
3455 -- while Has_Element (Cursor, Container) loop
3456 -- Elmt := Element (Container, Cursor);
3457 -- <original loop statements>
3458 -- Cursor := Next (Container, Cursor);
3461 -- However this expansion is not legal if the element is indefinite.
3462 -- In that case we create a block to hold a variable declaration
3463 -- initialized with a call to Element, and generate:
3465 -- Cursor : Cursor_Type := First (Container);
3466 -- while Has_Element (Cursor, Container) loop
3468 -- Elmt : Element_Type := Element (Container, Cursor);
3470 -- <original loop statements>
3471 -- Cursor := Next (Container, Cursor);
3475 Build_Formal_Container_Iteration
3476 (N, Container, Cursor, Init, Advance, New_Loop);
3477 Append_To (Stats, Advance);
3479 Set_Ekind (Cursor, E_Variable);
3480 Insert_Action (N, Init);
3482 -- The loop parameter is declared by an object declaration, but within
3483 -- the loop we must prevent user assignments to it; the following flag
3484 -- accomplishes that.
3486 Set_Is_Loop_Parameter (Element);
3488 -- Declaration for Element
3491 Make_Object_Declaration (Loc,
3492 Defining_Identifier => Element,
3493 Object_Definition => New_Occurrence_Of (Etype (Element_Op), Loc));
3495 if not Is_Constrained (Etype (Element_Op)) then
3496 Set_Expression (Elmt_Decl,
3497 Make_Function_Call (Loc,
3498 Name => New_Occurrence_Of (Element_Op, Loc),
3499 Parameter_Associations => New_List (
3500 Convert_To_Iterable_Type (Container, Loc),
3501 New_Occurrence_Of (Cursor, Loc))));
3503 Set_Statements (New_Loop,
3505 (Make_Block_Statement (Loc,
3506 Declarations => New_List (Elmt_Decl),
3507 Handled_Statement_Sequence =>
3508 Make_Handled_Sequence_Of_Statements (Loc,
3509 Statements => Stats))));
3513 Make_Assignment_Statement (Loc,
3514 Name => New_Occurrence_Of (Element, Loc),
3516 Make_Function_Call (Loc,
3517 Name => New_Occurrence_Of (Element_Op, Loc),
3518 Parameter_Associations => New_List (
3519 Convert_To_Iterable_Type (Container, Loc),
3520 New_Occurrence_Of (Cursor, Loc))));
3522 Prepend (Elmt_Ref, Stats);
3524 -- The element is assignable in the expanded code
3526 Set_Assignment_OK (Name (Elmt_Ref));
3528 -- The loop is rewritten as a block, to hold the element declaration
3531 Make_Block_Statement (Loc,
3532 Declarations => New_List (Elmt_Decl),
3533 Handled_Statement_Sequence =>
3534 Make_Handled_Sequence_Of_Statements (Loc,
3535 Statements => New_List (New_Loop)));
3538 -- The element is only modified in expanded code, so it appears as
3539 -- unassigned to the warning machinery. We must suppress this spurious
3540 -- warning explicitly.
3542 Set_Warnings_Off (Element);
3544 Rewrite (N, New_Loop);
3546 end Expand_Formal_Container_Element_Loop;
3548 -----------------------------
3549 -- Expand_N_Goto_Statement --
3550 -----------------------------
3552 -- Add poll before goto if polling active
3554 procedure Expand_N_Goto_Statement (N : Node_Id) is
3556 Generate_Poll_Call (N);
3557 end Expand_N_Goto_Statement;
3559 ---------------------------
3560 -- Expand_N_If_Statement --
3561 ---------------------------
3563 -- First we deal with the case of C and Fortran convention boolean values,
3564 -- with zero/non-zero semantics.
3566 -- Second, we deal with the obvious rewriting for the cases where the
3567 -- condition of the IF is known at compile time to be True or False.
3569 -- Third, we remove elsif parts which have non-empty Condition_Actions and
3570 -- rewrite as independent if statements. For example:
3581 -- <<condition actions of y>>
3587 -- This rewriting is needed if at least one elsif part has a non-empty
3588 -- Condition_Actions list. We also do the same processing if there is a
3589 -- constant condition in an elsif part (in conjunction with the first
3590 -- processing step mentioned above, for the recursive call made to deal
3591 -- with the created inner if, this deals with properly optimizing the
3592 -- cases of constant elsif conditions).
3594 procedure Expand_N_If_Statement (N : Node_Id) is
3595 Loc : constant Source_Ptr := Sloc (N);
3600 Warn_If_Deleted : constant Boolean :=
3601 Warn_On_Deleted_Code and then Comes_From_Source (N);
3602 -- Indicates whether we want warnings when we delete branches of the
3603 -- if statement based on constant condition analysis. We never want
3604 -- these warnings for expander generated code.
3607 -- Do not consider controlled objects found in an if statement which
3608 -- actually models an if expression because their early finalization
3609 -- will affect the result of the expression.
3611 if not From_Conditional_Expression (N) then
3612 Process_Statements_For_Controlled_Objects (N);
3615 Adjust_Condition (Condition (N));
3617 -- The following loop deals with constant conditions for the IF. We
3618 -- need a loop because as we eliminate False conditions, we grab the
3619 -- first elsif condition and use it as the primary condition.
3621 while Compile_Time_Known_Value (Condition (N)) loop
3623 -- If condition is True, we can simply rewrite the if statement now
3624 -- by replacing it by the series of then statements.
3626 if Is_True (Expr_Value (Condition (N))) then
3628 -- All the else parts can be killed
3630 Kill_Dead_Code (Elsif_Parts (N), Warn_If_Deleted);
3631 Kill_Dead_Code (Else_Statements (N), Warn_If_Deleted);
3633 Hed := Remove_Head (Then_Statements (N));
3634 Insert_List_After (N, Then_Statements (N));
3638 -- If condition is False, then we can delete the condition and
3639 -- the Then statements
3642 -- We do not delete the condition if constant condition warnings
3643 -- are enabled, since otherwise we end up deleting the desired
3644 -- warning. Of course the backend will get rid of this True/False
3645 -- test anyway, so nothing is lost here.
3647 if not Constant_Condition_Warnings then
3648 Kill_Dead_Code (Condition (N));
3651 Kill_Dead_Code (Then_Statements (N), Warn_If_Deleted);
3653 -- If there are no elsif statements, then we simply replace the
3654 -- entire if statement by the sequence of else statements.
3656 if No (Elsif_Parts (N)) then
3657 if No (Else_Statements (N))
3658 or else Is_Empty_List (Else_Statements (N))
3661 Make_Null_Statement (Sloc (N)));
3663 Hed := Remove_Head (Else_Statements (N));
3664 Insert_List_After (N, Else_Statements (N));
3670 -- If there are elsif statements, the first of them becomes the
3671 -- if/then section of the rebuilt if statement This is the case
3672 -- where we loop to reprocess this copied condition.
3675 Hed := Remove_Head (Elsif_Parts (N));
3676 Insert_Actions (N, Condition_Actions (Hed));
3677 Set_Condition (N, Condition (Hed));
3678 Set_Then_Statements (N, Then_Statements (Hed));
3680 -- Hed might have been captured as the condition determining
3681 -- the current value for an entity. Now it is detached from
3682 -- the tree, so a Current_Value pointer in the condition might
3683 -- need to be updated.
3685 Set_Current_Value_Condition (N);
3687 if Is_Empty_List (Elsif_Parts (N)) then
3688 Set_Elsif_Parts (N, No_List);
3694 -- Loop through elsif parts, dealing with constant conditions and
3695 -- possible condition actions that are present.
3697 if Present (Elsif_Parts (N)) then
3698 E := First (Elsif_Parts (N));
3699 while Present (E) loop
3701 -- Do not consider controlled objects found in an if statement
3702 -- which actually models an if expression because their early
3703 -- finalization will affect the result of the expression.
3705 if not From_Conditional_Expression (N) then
3706 Process_Statements_For_Controlled_Objects (E);
3709 Adjust_Condition (Condition (E));
3711 -- If there are condition actions, then rewrite the if statement
3712 -- as indicated above. We also do the same rewrite for a True or
3713 -- False condition. The further processing of this constant
3714 -- condition is then done by the recursive call to expand the
3715 -- newly created if statement
3717 if Present (Condition_Actions (E))
3718 or else Compile_Time_Known_Value (Condition (E))
3721 Make_If_Statement (Sloc (E),
3722 Condition => Condition (E),
3723 Then_Statements => Then_Statements (E),
3724 Elsif_Parts => No_List,
3725 Else_Statements => Else_Statements (N));
3727 -- Elsif parts for new if come from remaining elsif's of parent
3729 while Present (Next (E)) loop
3730 if No (Elsif_Parts (New_If)) then
3731 Set_Elsif_Parts (New_If, New_List);
3734 Append (Remove_Next (E), Elsif_Parts (New_If));
3737 Set_Else_Statements (N, New_List (New_If));
3739 if Present (Condition_Actions (E)) then
3740 Insert_List_Before (New_If, Condition_Actions (E));
3745 if Is_Empty_List (Elsif_Parts (N)) then
3746 Set_Elsif_Parts (N, No_List);
3751 -- Note this is not an implicit if statement, since it is part
3752 -- of an explicit if statement in the source (or of an implicit
3753 -- if statement that has already been tested). We set the flag
3754 -- after calling Analyze to avoid generating extra warnings
3755 -- specific to pure if statements, however (see
3756 -- Sem_Ch5.Analyze_If_Statement).
3758 Set_Comes_From_Source (New_If, Comes_From_Source (N));
3761 -- No special processing for that elsif part, move to next
3769 -- Some more optimizations applicable if we still have an IF statement
3771 if Nkind (N) /= N_If_Statement then
3775 -- Another optimization, special cases that can be simplified
3777 -- if expression then
3783 -- can be changed to:
3785 -- return expression;
3789 -- if expression then
3795 -- can be changed to:
3797 -- return not (expression);
3799 -- Only do these optimizations if we are at least at -O1 level and
3800 -- do not do them if control flow optimizations are suppressed.
3802 if Optimization_Level > 0
3803 and then not Opt.Suppress_Control_Flow_Optimizations
3805 if Nkind (N) = N_If_Statement
3806 and then No (Elsif_Parts (N))
3807 and then Present (Else_Statements (N))
3808 and then List_Length (Then_Statements (N)) = 1
3809 and then List_Length (Else_Statements (N)) = 1
3812 Then_Stm : constant Node_Id := First (Then_Statements (N));
3813 Else_Stm : constant Node_Id := First (Else_Statements (N));
3816 if Nkind (Then_Stm) = N_Simple_Return_Statement
3818 Nkind (Else_Stm) = N_Simple_Return_Statement
3821 Then_Expr : constant Node_Id := Expression (Then_Stm);
3822 Else_Expr : constant Node_Id := Expression (Else_Stm);
3825 if Nkind (Then_Expr) = N_Identifier
3827 Nkind (Else_Expr) = N_Identifier
3829 if Entity (Then_Expr) = Standard_True
3830 and then Entity (Else_Expr) = Standard_False
3833 Make_Simple_Return_Statement (Loc,
3834 Expression => Relocate_Node (Condition (N))));
3838 elsif Entity (Then_Expr) = Standard_False
3839 and then Entity (Else_Expr) = Standard_True
3842 Make_Simple_Return_Statement (Loc,
3846 Relocate_Node (Condition (N)))));
3856 end Expand_N_If_Statement;
3858 --------------------------
3859 -- Expand_Iterator_Loop --
3860 --------------------------
3862 procedure Expand_Iterator_Loop (N : Node_Id) is
3863 Isc : constant Node_Id := Iteration_Scheme (N);
3864 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3866 Container : constant Node_Id := Name (I_Spec);
3867 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
3870 -- Processing for arrays
3872 if Is_Array_Type (Container_Typ) then
3873 pragma Assert (Of_Present (I_Spec));
3874 Expand_Iterator_Loop_Over_Array (N);
3876 elsif Has_Aspect (Container_Typ, Aspect_Iterable) then
3877 if Of_Present (I_Spec) then
3878 Expand_Formal_Container_Element_Loop (N);
3880 Expand_Formal_Container_Loop (N);
3883 -- Processing for containers
3886 Expand_Iterator_Loop_Over_Container
3887 (N, Isc, I_Spec, Container, Container_Typ);
3889 end Expand_Iterator_Loop;
3891 -------------------------------------
3892 -- Expand_Iterator_Loop_Over_Array --
3893 -------------------------------------
3895 procedure Expand_Iterator_Loop_Over_Array (N : Node_Id) is
3896 Isc : constant Node_Id := Iteration_Scheme (N);
3897 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3898 Array_Node : constant Node_Id := Name (I_Spec);
3899 Array_Typ : constant Entity_Id := Base_Type (Etype (Array_Node));
3900 Array_Dim : constant Pos := Number_Dimensions (Array_Typ);
3901 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3902 Loc : constant Source_Ptr := Sloc (Isc);
3903 Stats : constant List_Id := Statements (N);
3904 Core_Loop : Node_Id;
3907 Iterator : Entity_Id;
3909 -- Start of processing for Expand_Iterator_Loop_Over_Array
3912 -- for Element of Array loop
3914 -- It requires an internally generated cursor to iterate over the array
3916 pragma Assert (Of_Present (I_Spec));
3918 Iterator := Make_Temporary (Loc, 'C');
3921 -- Element : Component_Type renames Array (Iterator);
3922 -- Iterator is the index value, or a list of index values
3923 -- in the case of a multidimensional array.
3926 Make_Indexed_Component (Loc,
3927 Prefix => New_Copy_Tree (Array_Node),
3928 Expressions => New_List (New_Occurrence_Of (Iterator, Loc)));
3930 -- Propagate the original node to the copy since the analysis of the
3931 -- following object renaming declaration relies on the original node.
3933 Set_Original_Node (Prefix (Ind_Comp), Original_Node (Array_Node));
3936 Make_Object_Renaming_Declaration (Loc,
3937 Defining_Identifier => Id,
3939 New_Occurrence_Of (Component_Type (Array_Typ), Loc),
3942 -- Mark the loop variable as needing debug info, so that expansion
3943 -- of the renaming will result in Materialize_Entity getting set via
3944 -- Debug_Renaming_Declaration. (This setting is needed here because
3945 -- the setting in Freeze_Entity comes after the expansion, which is
3948 Set_Debug_Info_Needed (Id);
3952 -- for Iterator in [reverse] Array'Range (Array_Dim) loop
3953 -- Element : Component_Type renames Array (Iterator);
3954 -- <original loop statements>
3957 -- If this is an iteration over a multidimensional array, the
3958 -- innermost loop is over the last dimension in Ada, and over
3959 -- the first dimension in Fortran.
3961 if Convention (Array_Typ) = Convention_Fortran then
3968 Make_Loop_Statement (Sloc (N),
3970 Make_Iteration_Scheme (Loc,
3971 Loop_Parameter_Specification =>
3972 Make_Loop_Parameter_Specification (Loc,
3973 Defining_Identifier => Iterator,
3974 Discrete_Subtype_Definition =>
3975 Make_Attribute_Reference (Loc,
3976 Prefix => New_Copy_Tree (Array_Node),
3977 Attribute_Name => Name_Range,
3978 Expressions => New_List (
3979 Make_Integer_Literal (Loc, Dim1))),
3980 Reverse_Present => Reverse_Present (I_Spec))),
3981 Statements => Stats,
3982 End_Label => Empty);
3984 -- Processing for multidimensional array. The body of each loop is
3985 -- a loop over a previous dimension, going in decreasing order in Ada
3986 -- and in increasing order in Fortran.
3988 if Array_Dim > 1 then
3989 for Dim in 1 .. Array_Dim - 1 loop
3990 if Convention (Array_Typ) = Convention_Fortran then
3993 Dim1 := Array_Dim - Dim;
3996 Iterator := Make_Temporary (Loc, 'C');
3998 -- Generate the dimension loops starting from the innermost one
4000 -- for Iterator in [reverse] Array'Range (Array_Dim - Dim) loop
4005 Make_Loop_Statement (Sloc (N),
4007 Make_Iteration_Scheme (Loc,
4008 Loop_Parameter_Specification =>
4009 Make_Loop_Parameter_Specification (Loc,
4010 Defining_Identifier => Iterator,
4011 Discrete_Subtype_Definition =>
4012 Make_Attribute_Reference (Loc,
4013 Prefix => New_Copy_Tree (Array_Node),
4014 Attribute_Name => Name_Range,
4015 Expressions => New_List (
4016 Make_Integer_Literal (Loc, Dim1))),
4017 Reverse_Present => Reverse_Present (I_Spec))),
4018 Statements => New_List (Core_Loop),
4019 End_Label => Empty);
4021 -- Update the previously created object renaming declaration with
4022 -- the new iterator, by adding the index of the next loop to the
4023 -- indexed component, in the order that corresponds to the
4026 if Convention (Array_Typ) = Convention_Fortran then
4027 Append_To (Expressions (Ind_Comp),
4028 New_Occurrence_Of (Iterator, Loc));
4030 Prepend_To (Expressions (Ind_Comp),
4031 New_Occurrence_Of (Iterator, Loc));
4036 -- Inherit the loop identifier from the original loop. This ensures that
4037 -- the scope stack is consistent after the rewriting.
4039 if Present (Identifier (N)) then
4040 Set_Identifier (Core_Loop, Relocate_Node (Identifier (N)));
4043 Rewrite (N, Core_Loop);
4045 end Expand_Iterator_Loop_Over_Array;
4047 -----------------------------------------
4048 -- Expand_Iterator_Loop_Over_Container --
4049 -----------------------------------------
4051 -- For a 'for ... in' loop, such as:
4053 -- for Cursor in Iterator_Function (...) loop
4059 -- Iter : Iterator_Type := Iterator_Function (...);
4060 -- Cursor : Cursor_type := First (Iter); -- or Last for "reverse"
4061 -- while Has_Element (Cursor) loop
4064 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
4067 -- For a 'for ... of' loop, such as:
4069 -- for X of Container loop
4073 -- the RM implies the generation of:
4075 -- Iter : Iterator_Type := Container.Iterate; -- the Default_Iterator
4076 -- Cursor : Cursor_Type := First (Iter); -- or Last for "reverse"
4077 -- while Has_Element (Cursor) loop
4079 -- X : Element_Type renames Element (Cursor).Element.all;
4080 -- -- or Constant_Element
4084 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
4087 -- In the general case, we do what the RM says. However, the operations
4088 -- Element and Iter.Next are slow, which is bad inside a loop, because they
4089 -- involve dispatching via interfaces, secondary stack manipulation,
4090 -- Busy/Lock incr/decr, and adjust/finalization/at-end handling. So for the
4091 -- predefined containers, we use an equivalent but optimized expansion.
4093 -- In the optimized case, we make use of these:
4095 -- procedure Next (Position : in out Cursor); -- instead of Iter.Next
4097 -- function Pseudo_Reference
4098 -- (Container : aliased Vector'Class) return Reference_Control_Type;
4100 -- type Element_Access is access all Element_Type;
4102 -- function Get_Element_Access
4103 -- (Position : Cursor) return not null Element_Access;
4105 -- Next is declared in the visible part of the container packages.
4106 -- The other three are added in the private part. (We're not supposed to
4107 -- pollute the namespace for clients. The compiler has no trouble breaking
4108 -- privacy to call things in the private part of an instance.)
4112 -- for X of My_Vector loop
4113 -- X.Count := X.Count + 1;
4117 -- The compiler will generate:
4119 -- Iter : Reversible_Iterator'Class := Iterate (My_Vector);
4120 -- -- Reversible_Iterator is an interface. Iterate is the
4121 -- -- Default_Iterator aspect of Vector. This increments Lock,
4122 -- -- disallowing tampering with cursors. Unfortunately, it does not
4123 -- -- increment Busy. The result of Iterate is Limited_Controlled;
4124 -- -- finalization will decrement Lock. This is a build-in-place
4125 -- -- dispatching call to Iterate.
4127 -- Cur : Cursor := First (Iter); -- or Last
4128 -- -- Dispatching call via interface.
4130 -- Control : Reference_Control_Type := Pseudo_Reference (My_Vector);
4131 -- -- Pseudo_Reference increments Busy, to detect tampering with
4132 -- -- elements, as required by RM. Also redundantly increment
4133 -- -- Lock. Finalization of Control will decrement both Busy and
4134 -- -- Lock. Pseudo_Reference returns a record containing a pointer to
4135 -- -- My_Vector, used by Finalize.
4137 -- -- Control is not used below, except to finalize it -- it's purely
4138 -- -- an RAII thing. This is needed because we are eliminating the
4139 -- -- call to Reference within the loop.
4141 -- while Has_Element (Cur) loop
4143 -- X : My_Element renames Get_Element_Access (Cur).all;
4144 -- -- Get_Element_Access returns a pointer to the element
4145 -- -- designated by Cur. No dispatching here, and no horsing
4146 -- -- around with access discriminants. This is instead of the
4149 -- -- X : My_Element renames Reference (Cur).Element.all;
4151 -- -- which creates a controlled object.
4153 -- -- Any attempt to tamper with My_Vector here in the loop
4154 -- -- will correctly raise Program_Error, because of the
4157 -- X.Count := X.Count + 1;
4160 -- Next (Cur); -- or Prev
4161 -- -- This is instead of "Cur := Next (Iter, Cur);"
4163 -- -- No finalization here
4165 -- Finalize Iter and Control here, decrementing Lock twice and Busy
4168 -- This optimization makes "for ... of" loops over 30 times faster in cases
4171 procedure Expand_Iterator_Loop_Over_Container
4175 Container : Node_Id;
4176 Container_Typ : Entity_Id)
4178 Id : constant Entity_Id := Defining_Identifier (I_Spec);
4179 Elem_Typ : constant Entity_Id := Etype (Id);
4180 Id_Kind : constant Entity_Kind := Ekind (Id);
4181 Loc : constant Source_Ptr := Sloc (N);
4182 Stats : constant List_Id := Statements (N);
4186 Iter_Type : Entity_Id;
4187 Iterator : Entity_Id;
4188 Name_Init : Name_Id;
4189 Name_Step : Name_Id;
4192 Fast_Element_Access_Op : Entity_Id := Empty;
4193 Fast_Step_Op : Entity_Id := Empty;
4194 -- Only for optimized version of "for ... of"
4196 Iter_Pack : Entity_Id;
4197 -- The package in which the iterator interface is instantiated. This is
4198 -- typically an instance within the container package.
4201 -- The package in which the container type is declared
4204 -- Determine the advancement and initialization steps for the cursor.
4205 -- Analysis of the expanded loop will verify that the container has a
4206 -- reverse iterator.
4208 if Reverse_Present (I_Spec) then
4209 Name_Init := Name_Last;
4210 Name_Step := Name_Previous;
4212 Name_Init := Name_First;
4213 Name_Step := Name_Next;
4216 -- The type of the iterator is the return type of the Iterate function
4217 -- used. For the "of" form this is the default iterator for the type,
4218 -- otherwise it is the type of the explicit function used in the
4219 -- iterator specification. The most common case will be an Iterate
4220 -- function in the container package.
4222 -- The Iterator type is declared in an instance within the container
4223 -- package itself, for example:
4225 -- package Vector_Iterator_Interfaces is new
4226 -- Ada.Iterator_Interfaces (Cursor, Has_Element);
4228 -- If the container type is a derived type, the cursor type is found in
4229 -- the package of the ultimate ancestor type.
4231 if Is_Derived_Type (Container_Typ) then
4232 Pack := Scope (Root_Type (Container_Typ));
4234 Pack := Scope (Container_Typ);
4237 if Of_Present (I_Spec) then
4239 Container_Arg : Node_Id;
4241 function Get_Default_Iterator
4242 (T : Entity_Id) return Entity_Id;
4243 -- Return the default iterator for a specific type. If the type is
4244 -- derived, we return the inherited or overridden one if
4247 --------------------------
4248 -- Get_Default_Iterator --
4249 --------------------------
4251 function Get_Default_Iterator
4252 (T : Entity_Id) return Entity_Id
4254 Iter : constant Entity_Id :=
4255 Entity (Find_Value_Of_Aspect (T, Aspect_Default_Iterator));
4260 Container_Arg := New_Copy_Tree (Container);
4262 -- A previous version of GNAT allowed indexing aspects to be
4263 -- redefined on derived container types, while the default
4264 -- iterator was inherited from the parent type. This
4265 -- nonstandard extension is preserved for use by the
4266 -- modeling project under debug flag -gnatd.X.
4268 if Debug_Flag_Dot_XX then
4269 if Base_Type (Etype (Container)) /=
4270 Base_Type (Etype (First_Formal (Iter)))
4273 Make_Type_Conversion (Loc,
4276 (Etype (First_Formal (Iter)), Loc),
4277 Expression => Container_Arg);
4282 elsif Is_Derived_Type (T) then
4284 -- The default iterator must be a primitive operation of the
4285 -- type, at the same dispatch slot position. The DT position
4286 -- may not be established if type is not frozen yet.
4288 Prim := First_Elmt (Primitive_Operations (T));
4289 while Present (Prim) loop
4292 if Alias (Op) = Iter
4294 (Chars (Op) = Chars (Iter)
4295 and then Present (DTC_Entity (Op))
4296 and then DT_Position (Op) = DT_Position (Iter))
4304 -- If we didn't find it, then our parent type is not
4305 -- iterable, so we return the Default_Iterator aspect of
4310 -- Otherwise not a derived type
4315 end Get_Default_Iterator;
4319 Default_Iter : Entity_Id;
4322 Reference_Control_Type : Entity_Id := Empty;
4323 Pseudo_Reference : Entity_Id := Empty;
4325 -- Start of processing for Handle_Of
4328 if Is_Class_Wide_Type (Container_Typ) then
4330 Get_Default_Iterator (Etype (Base_Type (Container_Typ)));
4332 Default_Iter := Get_Default_Iterator (Etype (Container));
4335 Cursor := Make_Temporary (Loc, 'C');
4337 -- For a container element iterator, the iterator type is obtained
4338 -- from the corresponding aspect, whose return type is descended
4339 -- from the corresponding interface type in some instance of
4340 -- Ada.Iterator_Interfaces. The actuals of that instantiation
4341 -- are Cursor and Has_Element.
4343 Iter_Type := Etype (Default_Iter);
4345 -- The iterator type, which is a class-wide type, may itself be
4346 -- derived locally, so the desired instantiation is the scope of
4347 -- the root type of the iterator type.
4349 Iter_Pack := Scope (Root_Type (Etype (Iter_Type)));
4351 -- Find declarations needed for "for ... of" optimization
4353 Ent := First_Entity (Pack);
4354 while Present (Ent) loop
4355 if Chars (Ent) = Name_Get_Element_Access then
4356 Fast_Element_Access_Op := Ent;
4358 elsif Chars (Ent) = Name_Step
4359 and then Ekind (Ent) = E_Procedure
4361 Fast_Step_Op := Ent;
4363 elsif Chars (Ent) = Name_Reference_Control_Type then
4364 Reference_Control_Type := Ent;
4366 elsif Chars (Ent) = Name_Pseudo_Reference then
4367 Pseudo_Reference := Ent;
4373 if Present (Reference_Control_Type)
4374 and then Present (Pseudo_Reference)
4377 Make_Object_Declaration (Loc,
4378 Defining_Identifier => Make_Temporary (Loc, 'D'),
4379 Object_Definition =>
4380 New_Occurrence_Of (Reference_Control_Type, Loc),
4382 Make_Function_Call (Loc,
4384 New_Occurrence_Of (Pseudo_Reference, Loc),
4385 Parameter_Associations =>
4386 New_List (New_Copy_Tree (Container_Arg)))));
4389 -- Rewrite domain of iteration as a call to the default iterator
4390 -- for the container type. The formal may be an access parameter
4391 -- in which case we must build a reference to the container.
4396 if Is_Access_Type (Etype (First_Entity (Default_Iter))) then
4398 Make_Attribute_Reference (Loc,
4399 Prefix => Container_Arg,
4400 Attribute_Name => Name_Unrestricted_Access);
4402 Arg := Container_Arg;
4405 Rewrite (Name (I_Spec),
4406 Make_Function_Call (Loc,
4408 New_Occurrence_Of (Default_Iter, Loc),
4409 Parameter_Associations => New_List (Arg)));
4412 Analyze_And_Resolve (Name (I_Spec));
4414 -- Find cursor type in proper iterator package, which is an
4415 -- instantiation of Iterator_Interfaces.
4417 Ent := First_Entity (Iter_Pack);
4418 while Present (Ent) loop
4419 if Chars (Ent) = Name_Cursor then
4420 Set_Etype (Cursor, Etype (Ent));
4427 if Present (Fast_Element_Access_Op) then
4429 Make_Object_Renaming_Declaration (Loc,
4430 Defining_Identifier => Id,
4432 New_Occurrence_Of (Elem_Typ, Loc),
4434 Make_Explicit_Dereference (Loc,
4436 Make_Function_Call (Loc,
4438 New_Occurrence_Of (Fast_Element_Access_Op, Loc),
4439 Parameter_Associations =>
4440 New_List (New_Occurrence_Of (Cursor, Loc)))));
4444 Make_Object_Renaming_Declaration (Loc,
4445 Defining_Identifier => Id,
4447 New_Occurrence_Of (Elem_Typ, Loc),
4449 Make_Indexed_Component (Loc,
4450 Prefix => Relocate_Node (Container_Arg),
4452 New_List (New_Occurrence_Of (Cursor, Loc))));
4455 -- The defining identifier in the iterator is user-visible and
4456 -- must be visible in the debugger.
4458 Set_Debug_Info_Needed (Id);
4460 -- If the container does not have a variable indexing aspect,
4461 -- the element is a constant in the loop. The container itself
4462 -- may be constant, in which case the element is a constant as
4463 -- well. The container has been rewritten as a call to Iterate,
4464 -- so examine original node.
4466 if No (Find_Value_Of_Aspect
4467 (Container_Typ, Aspect_Variable_Indexing))
4468 or else not Is_Variable (Original_Node (Container))
4470 Set_Ekind (Id, E_Constant);
4473 Prepend_To (Stats, Decl);
4476 -- X in Iterate (S) : type of iterator is type of explicitly given
4477 -- Iterate function, and the loop variable is the cursor. It will be
4478 -- assigned in the loop and must be a variable.
4481 Iter_Type := Etype (Name (I_Spec));
4483 -- The iterator type, which is a class-wide type, may itself be
4484 -- derived locally, so the desired instantiation is the scope of
4485 -- the root type of the iterator type, as in the "of" case.
4487 Iter_Pack := Scope (Root_Type (Etype (Iter_Type)));
4491 Iterator := Make_Temporary (Loc, 'I');
4493 -- For both iterator forms, add a call to the step operation to advance
4494 -- the cursor. Generate:
4496 -- Cursor := Iterator.Next (Cursor);
4500 -- Cursor := Next (Cursor);
4502 if Present (Fast_Element_Access_Op) and then Present (Fast_Step_Op) then
4504 Curs_Name : constant Node_Id := New_Occurrence_Of (Cursor, Loc);
4505 Step_Call : Node_Id;
4509 Make_Procedure_Call_Statement (Loc,
4511 New_Occurrence_Of (Fast_Step_Op, Loc),
4512 Parameter_Associations => New_List (Curs_Name));
4514 Append_To (Stats, Step_Call);
4515 Set_Assignment_OK (Curs_Name);
4524 Make_Function_Call (Loc,
4526 Make_Selected_Component (Loc,
4527 Prefix => New_Occurrence_Of (Iterator, Loc),
4528 Selector_Name => Make_Identifier (Loc, Name_Step)),
4529 Parameter_Associations => New_List (
4530 New_Occurrence_Of (Cursor, Loc)));
4533 Make_Assignment_Statement (Loc,
4534 Name => New_Occurrence_Of (Cursor, Loc),
4535 Expression => Rhs));
4536 Set_Assignment_OK (Name (Last (Stats)));
4541 -- while Has_Element (Cursor) loop
4545 -- Has_Element is the second actual in the iterator package
4548 Make_Loop_Statement (Loc,
4550 Make_Iteration_Scheme (Loc,
4552 Make_Function_Call (Loc,
4555 (Next_Entity (First_Entity (Iter_Pack)), Loc),
4556 Parameter_Associations => New_List (
4557 New_Occurrence_Of (Cursor, Loc)))),
4559 Statements => Stats,
4560 End_Label => Empty);
4562 -- If present, preserve identifier of loop, which can be used in an exit
4563 -- statement in the body.
4565 if Present (Identifier (N)) then
4566 Set_Identifier (New_Loop, Relocate_Node (Identifier (N)));
4569 -- Create the declarations for Iterator and cursor and insert them
4570 -- before the source loop. Given that the domain of iteration is already
4571 -- an entity, the iterator is just a renaming of that entity. Possible
4575 Make_Object_Renaming_Declaration (Loc,
4576 Defining_Identifier => Iterator,
4577 Subtype_Mark => New_Occurrence_Of (Iter_Type, Loc),
4578 Name => Relocate_Node (Name (I_Spec))));
4580 -- Create declaration for cursor
4583 Cursor_Decl : constant Node_Id :=
4584 Make_Object_Declaration (Loc,
4585 Defining_Identifier => Cursor,
4586 Object_Definition =>
4587 New_Occurrence_Of (Etype (Cursor), Loc),
4589 Make_Selected_Component (Loc,
4591 New_Occurrence_Of (Iterator, Loc),
4593 Make_Identifier (Loc, Name_Init)));
4596 -- The cursor is only modified in expanded code, so it appears
4597 -- as unassigned to the warning machinery. We must suppress this
4598 -- spurious warning explicitly. The cursor's kind is that of the
4599 -- original loop parameter (it is a constant if the domain of
4600 -- iteration is constant).
4602 Set_Warnings_Off (Cursor);
4603 Set_Assignment_OK (Cursor_Decl);
4605 Insert_Action (N, Cursor_Decl);
4606 Set_Ekind (Cursor, Id_Kind);
4609 -- If the range of iteration is given by a function call that returns
4610 -- a container, the finalization actions have been saved in the
4611 -- Condition_Actions of the iterator. Insert them now at the head of
4614 if Present (Condition_Actions (Isc)) then
4615 Insert_List_Before (N, Condition_Actions (Isc));
4618 Rewrite (N, New_Loop);
4620 end Expand_Iterator_Loop_Over_Container;
4622 -----------------------------
4623 -- Expand_N_Loop_Statement --
4624 -----------------------------
4626 -- 1. Remove null loop entirely
4627 -- 2. Deal with while condition for C/Fortran boolean
4628 -- 3. Deal with loops with a non-standard enumeration type range
4629 -- 4. Deal with while loops where Condition_Actions is set
4630 -- 5. Deal with loops over predicated subtypes
4631 -- 6. Deal with loops with iterators over arrays and containers
4632 -- 7. Insert polling call if required
4634 procedure Expand_N_Loop_Statement (N : Node_Id) is
4635 Loc : constant Source_Ptr := Sloc (N);
4636 Scheme : constant Node_Id := Iteration_Scheme (N);
4642 if Is_Null_Loop (N) then
4643 Rewrite (N, Make_Null_Statement (Loc));
4647 -- Deal with condition for C/Fortran Boolean
4649 if Present (Scheme) then
4650 Adjust_Condition (Condition (Scheme));
4653 -- Generate polling call
4655 if Is_Non_Empty_List (Statements (N)) then
4656 Generate_Poll_Call (First (Statements (N)));
4659 -- Nothing more to do for plain loop with no iteration scheme
4664 -- Case of for loop (Loop_Parameter_Specification present)
4666 -- Note: we do not have to worry about validity checking of the for loop
4667 -- range bounds here, since they were frozen with constant declarations
4668 -- and it is during that process that the validity checking is done.
4670 elsif Present (Loop_Parameter_Specification (Scheme)) then
4672 LPS : constant Node_Id :=
4673 Loop_Parameter_Specification (Scheme);
4674 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4675 Ltype : constant Entity_Id := Etype (Loop_Id);
4676 Btype : constant Entity_Id := Base_Type (Ltype);
4682 -- Deal with loop over predicates
4684 if Is_Discrete_Type (Ltype)
4685 and then Present (Predicate_Function (Ltype))
4687 Expand_Predicated_Loop (N);
4689 -- Handle the case where we have a for loop with the range type
4690 -- being an enumeration type with non-standard representation.
4691 -- In this case we expand:
4693 -- for x in [reverse] a .. b loop
4699 -- for xP in [reverse] integer
4700 -- range etype'Pos (a) .. etype'Pos (b)
4703 -- x : constant etype := Pos_To_Rep (xP);
4709 elsif Is_Enumeration_Type (Btype)
4710 and then Present (Enum_Pos_To_Rep (Btype))
4713 Make_Defining_Identifier (Loc,
4714 Chars => New_External_Name (Chars (Loop_Id), 'P'));
4716 -- If the type has a contiguous representation, successive
4717 -- values can be generated as offsets from the first literal.
4719 if Has_Contiguous_Rep (Btype) then
4721 Unchecked_Convert_To (Btype,
4724 Make_Integer_Literal (Loc,
4725 Enumeration_Rep (First_Literal (Btype))),
4726 Right_Opnd => New_Occurrence_Of (New_Id, Loc)));
4728 -- Use the constructed array Enum_Pos_To_Rep
4731 Make_Indexed_Component (Loc,
4733 New_Occurrence_Of (Enum_Pos_To_Rep (Btype), Loc),
4735 New_List (New_Occurrence_Of (New_Id, Loc)));
4738 -- Build declaration for loop identifier
4742 Make_Object_Declaration (Loc,
4743 Defining_Identifier => Loop_Id,
4744 Constant_Present => True,
4745 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4746 Expression => Expr));
4749 Make_Loop_Statement (Loc,
4750 Identifier => Identifier (N),
4753 Make_Iteration_Scheme (Loc,
4754 Loop_Parameter_Specification =>
4755 Make_Loop_Parameter_Specification (Loc,
4756 Defining_Identifier => New_Id,
4757 Reverse_Present => Reverse_Present (LPS),
4759 Discrete_Subtype_Definition =>
4760 Make_Subtype_Indication (Loc,
4763 New_Occurrence_Of (Standard_Natural, Loc),
4766 Make_Range_Constraint (Loc,
4771 Make_Attribute_Reference (Loc,
4773 New_Occurrence_Of (Btype, Loc),
4775 Attribute_Name => Name_Pos,
4777 Expressions => New_List (
4779 (Type_Low_Bound (Ltype)))),
4782 Make_Attribute_Reference (Loc,
4784 New_Occurrence_Of (Btype, Loc),
4786 Attribute_Name => Name_Pos,
4788 Expressions => New_List (
4793 Statements => New_List (
4794 Make_Block_Statement (Loc,
4795 Declarations => Decls,
4796 Handled_Statement_Sequence =>
4797 Make_Handled_Sequence_Of_Statements (Loc,
4798 Statements => Statements (N)))),
4800 End_Label => End_Label (N)));
4802 -- The loop parameter's entity must be removed from the loop
4803 -- scope's entity list and rendered invisible, since it will
4804 -- now be located in the new block scope. Any other entities
4805 -- already associated with the loop scope, such as the loop
4806 -- parameter's subtype, will remain there.
4808 -- In an element loop, the loop will contain a declaration for
4809 -- a cursor variable; otherwise the loop id is the first entity
4810 -- in the scope constructed for the loop.
4812 if Comes_From_Source (Loop_Id) then
4813 pragma Assert (First_Entity (Scope (Loop_Id)) = Loop_Id);
4817 Set_First_Entity (Scope (Loop_Id), Next_Entity (Loop_Id));
4818 Remove_Homonym (Loop_Id);
4820 if Last_Entity (Scope (Loop_Id)) = Loop_Id then
4821 Set_Last_Entity (Scope (Loop_Id), Empty);
4826 -- Nothing to do with other cases of for loops
4833 -- Second case, if we have a while loop with Condition_Actions set, then
4834 -- we change it into a plain loop:
4843 -- <<condition actions>>
4848 elsif Present (Scheme)
4849 and then Present (Condition_Actions (Scheme))
4850 and then Present (Condition (Scheme))
4857 Make_Exit_Statement (Sloc (Condition (Scheme)),
4859 Make_Op_Not (Sloc (Condition (Scheme)),
4860 Right_Opnd => Condition (Scheme)));
4862 Prepend (ES, Statements (N));
4863 Insert_List_Before (ES, Condition_Actions (Scheme));
4865 -- This is not an implicit loop, since it is generated in response
4866 -- to the loop statement being processed. If this is itself
4867 -- implicit, the restriction has already been checked. If not,
4868 -- it is an explicit loop.
4871 Make_Loop_Statement (Sloc (N),
4872 Identifier => Identifier (N),
4873 Statements => Statements (N),
4874 End_Label => End_Label (N)));
4879 -- Here to deal with iterator case
4881 elsif Present (Scheme)
4882 and then Present (Iterator_Specification (Scheme))
4884 Expand_Iterator_Loop (N);
4886 -- An iterator loop may generate renaming declarations for elements
4887 -- that require debug information. This is the case in particular
4888 -- with element iterators, where debug information must be generated
4889 -- for the temporary that holds the element value. These temporaries
4890 -- are created within a transient block whose local declarations are
4891 -- transferred to the loop, which now has nontrivial local objects.
4893 if Nkind (N) = N_Loop_Statement
4894 and then Present (Identifier (N))
4896 Qualify_Entity_Names (N);
4900 -- When the iteration scheme mentiones attribute 'Loop_Entry, the loop
4901 -- is transformed into a conditional block where the original loop is
4902 -- the sole statement. Inspect the statements of the nested loop for
4903 -- controlled objects.
4907 if Subject_To_Loop_Entry_Attributes (Stmt) then
4908 Stmt := Find_Loop_In_Conditional_Block (Stmt);
4911 Process_Statements_For_Controlled_Objects (Stmt);
4912 end Expand_N_Loop_Statement;
4914 ----------------------------
4915 -- Expand_Predicated_Loop --
4916 ----------------------------
4918 -- Note: the expander can handle generation of loops over predicated
4919 -- subtypes for both the dynamic and static cases. Depending on what
4920 -- we decide is allowed in Ada 2012 mode and/or extensions allowed
4921 -- mode, the semantic analyzer may disallow one or both forms.
4923 procedure Expand_Predicated_Loop (N : Node_Id) is
4924 Loc : constant Source_Ptr := Sloc (N);
4925 Isc : constant Node_Id := Iteration_Scheme (N);
4926 LPS : constant Node_Id := Loop_Parameter_Specification (Isc);
4927 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4928 Ltype : constant Entity_Id := Etype (Loop_Id);
4929 Stat : constant List_Id := Static_Discrete_Predicate (Ltype);
4930 Stmts : constant List_Id := Statements (N);
4933 -- Case of iteration over non-static predicate, should not be possible
4934 -- since this is not allowed by the semantics and should have been
4935 -- caught during analysis of the loop statement.
4938 raise Program_Error;
4940 -- If the predicate list is empty, that corresponds to a predicate of
4941 -- False, in which case the loop won't run at all, and we rewrite the
4942 -- entire loop as a null statement.
4944 elsif Is_Empty_List (Stat) then
4945 Rewrite (N, Make_Null_Statement (Loc));
4948 -- For expansion over a static predicate we generate the following
4951 -- J : Ltype := min-val;
4956 -- when endpoint => J := startpoint;
4957 -- when endpoint => J := startpoint;
4959 -- when max-val => exit;
4960 -- when others => J := Lval'Succ (J);
4965 -- with min-val replaced by max-val and Succ replaced by Pred if the
4966 -- loop parameter specification carries a Reverse indicator.
4968 -- To make this a little clearer, let's take a specific example:
4970 -- type Int is range 1 .. 10;
4971 -- subtype StaticP is Int with
4972 -- predicate => StaticP in 3 | 10 | 5 .. 7;
4974 -- for L in StaticP loop
4975 -- Put_Line ("static:" & J'Img);
4978 -- In this case, the loop is transformed into
4985 -- when 3 => J := 5;
4986 -- when 7 => J := 10;
4988 -- when others => J := L'Succ (J);
4993 -- In addition, if the loop specification is given by a subtype
4994 -- indication that constrains a predicated type, the bounds of
4995 -- iteration are given by those of the subtype indication.
4998 Static_Predicate : declare
5005 -- If the domain is an itype, note the bounds of its range.
5007 L_Hi : Node_Id := Empty;
5008 L_Lo : Node_Id := Empty;
5010 function Lo_Val (N : Node_Id) return Node_Id;
5011 -- Given static expression or static range, returns an identifier
5012 -- whose value is the low bound of the expression value or range.
5014 function Hi_Val (N : Node_Id) return Node_Id;
5015 -- Given static expression or static range, returns an identifier
5016 -- whose value is the high bound of the expression value or range.
5022 function Hi_Val (N : Node_Id) return Node_Id is
5024 if Is_OK_Static_Expression (N) then
5025 return New_Copy (N);
5027 pragma Assert (Nkind (N) = N_Range);
5028 return New_Copy (High_Bound (N));
5036 function Lo_Val (N : Node_Id) return Node_Id is
5038 if Is_OK_Static_Expression (N) then
5039 return New_Copy (N);
5041 pragma Assert (Nkind (N) = N_Range);
5042 return New_Copy (Low_Bound (N));
5046 -- Start of processing for Static_Predicate
5049 -- Convert loop identifier to normal variable and reanalyze it so
5050 -- that this conversion works. We have to use the same defining
5051 -- identifier, since there may be references in the loop body.
5053 Set_Analyzed (Loop_Id, False);
5054 Set_Ekind (Loop_Id, E_Variable);
5056 -- In most loops the loop variable is assigned in various
5057 -- alternatives in the body. However, in the rare case when
5058 -- the range specifies a single element, the loop variable
5059 -- may trigger a spurious warning that is could be constant.
5060 -- This warning might as well be suppressed.
5062 Set_Warnings_Off (Loop_Id);
5064 if Is_Itype (Ltype) then
5065 L_Hi := High_Bound (Scalar_Range (Ltype));
5066 L_Lo := Low_Bound (Scalar_Range (Ltype));
5069 -- Loop to create branches of case statement
5073 if Reverse_Present (LPS) then
5075 -- Initial value is largest value in predicate.
5077 if Is_Itype (Ltype) then
5079 Make_Object_Declaration (Loc,
5080 Defining_Identifier => Loop_Id,
5081 Object_Definition => New_Occurrence_Of (Ltype, Loc),
5082 Expression => L_Hi);
5086 Make_Object_Declaration (Loc,
5087 Defining_Identifier => Loop_Id,
5088 Object_Definition => New_Occurrence_Of (Ltype, Loc),
5089 Expression => Hi_Val (Last (Stat)));
5093 while Present (P) loop
5094 if No (Prev (P)) then
5095 S := Make_Exit_Statement (Loc);
5098 Make_Assignment_Statement (Loc,
5099 Name => New_Occurrence_Of (Loop_Id, Loc),
5100 Expression => Hi_Val (Prev (P)));
5101 Set_Suppress_Assignment_Checks (S);
5105 Make_Case_Statement_Alternative (Loc,
5106 Statements => New_List (S),
5107 Discrete_Choices => New_List (Lo_Val (P))));
5113 and then Is_OK_Static_Expression (L_Lo)
5115 Expr_Value (L_Lo) /= Expr_Value (Lo_Val (First (Stat)))
5118 Make_Case_Statement_Alternative (Loc,
5119 Statements => New_List (Make_Exit_Statement (Loc)),
5120 Discrete_Choices => New_List (L_Lo)));
5124 -- Initial value is smallest value in predicate
5126 if Is_Itype (Ltype) then
5128 Make_Object_Declaration (Loc,
5129 Defining_Identifier => Loop_Id,
5130 Object_Definition => New_Occurrence_Of (Ltype, Loc),
5131 Expression => L_Lo);
5134 Make_Object_Declaration (Loc,
5135 Defining_Identifier => Loop_Id,
5136 Object_Definition => New_Occurrence_Of (Ltype, Loc),
5137 Expression => Lo_Val (First (Stat)));
5141 while Present (P) loop
5142 if No (Next (P)) then
5143 S := Make_Exit_Statement (Loc);
5146 Make_Assignment_Statement (Loc,
5147 Name => New_Occurrence_Of (Loop_Id, Loc),
5148 Expression => Lo_Val (Next (P)));
5149 Set_Suppress_Assignment_Checks (S);
5153 Make_Case_Statement_Alternative (Loc,
5154 Statements => New_List (S),
5155 Discrete_Choices => New_List (Hi_Val (P))));
5161 and then Is_OK_Static_Expression (L_Hi)
5163 Expr_Value (L_Hi) /= Expr_Value (Lo_Val (Last (Stat)))
5166 Make_Case_Statement_Alternative (Loc,
5167 Statements => New_List (Make_Exit_Statement (Loc)),
5168 Discrete_Choices => New_List (L_Hi)));
5172 -- Add others choice
5175 Name_Next : Name_Id;
5178 if Reverse_Present (LPS) then
5179 Name_Next := Name_Pred;
5181 Name_Next := Name_Succ;
5185 Make_Assignment_Statement (Loc,
5186 Name => New_Occurrence_Of (Loop_Id, Loc),
5188 Make_Attribute_Reference (Loc,
5189 Prefix => New_Occurrence_Of (Ltype, Loc),
5190 Attribute_Name => Name_Next,
5191 Expressions => New_List (
5192 New_Occurrence_Of (Loop_Id, Loc))));
5193 Set_Suppress_Assignment_Checks (S);
5197 Make_Case_Statement_Alternative (Loc,
5198 Discrete_Choices => New_List (Make_Others_Choice (Loc)),
5199 Statements => New_List (S)));
5201 -- Construct case statement and append to body statements
5204 Make_Case_Statement (Loc,
5205 Expression => New_Occurrence_Of (Loop_Id, Loc),
5206 Alternatives => Alts);
5207 Append_To (Stmts, Cstm);
5211 Set_Suppress_Assignment_Checks (D);
5214 Make_Block_Statement (Loc,
5215 Declarations => New_List (D),
5216 Handled_Statement_Sequence =>
5217 Make_Handled_Sequence_Of_Statements (Loc,
5218 Statements => New_List (
5219 Make_Loop_Statement (Loc,
5220 Statements => Stmts,
5221 End_Label => Empty)))));
5224 end Static_Predicate;
5226 end Expand_Predicated_Loop;
5228 ------------------------------
5229 -- Make_Tag_Ctrl_Assignment --
5230 ------------------------------
5232 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
5233 Asn : constant Node_Id := Relocate_Node (N);
5234 L : constant Node_Id := Name (N);
5235 Loc : constant Source_Ptr := Sloc (N);
5236 Res : constant List_Id := New_List;
5237 T : constant Entity_Id := Underlying_Type (Etype (L));
5239 Comp_Asn : constant Boolean := Is_Fully_Repped_Tagged_Type (T);
5240 Ctrl_Act : constant Boolean := Needs_Finalization (T)
5241 and then not No_Ctrl_Actions (N);
5242 Save_Tag : constant Boolean := Is_Tagged_Type (T)
5243 and then not Comp_Asn
5244 and then not No_Ctrl_Actions (N)
5245 and then Tagged_Type_Expansion;
5251 -- Finalize the target of the assignment when controlled
5253 -- We have two exceptions here:
5255 -- 1. If we are in an init proc since it is an initialization more
5256 -- than an assignment.
5258 -- 2. If the left-hand side is a temporary that was not initialized
5259 -- (or the parent part of a temporary since it is the case in
5260 -- extension aggregates). Such a temporary does not come from
5261 -- source. We must examine the original node for the prefix, because
5262 -- it may be a component of an entry formal, in which case it has
5263 -- been rewritten and does not appear to come from source either.
5265 -- Case of init proc
5267 if not Ctrl_Act then
5270 -- The left-hand side is an uninitialized temporary object
5272 elsif Nkind (L) = N_Type_Conversion
5273 and then Is_Entity_Name (Expression (L))
5274 and then Nkind (Parent (Entity (Expression (L)))) =
5275 N_Object_Declaration
5276 and then No_Initialization (Parent (Entity (Expression (L))))
5283 (Obj_Ref => Duplicate_Subexpr_No_Checks (L),
5286 if Present (Fin_Call) then
5287 Append_To (Res, Fin_Call);
5291 -- Save the Tag in a local variable Tag_Id
5294 Tag_Id := Make_Temporary (Loc, 'A');
5297 Make_Object_Declaration (Loc,
5298 Defining_Identifier => Tag_Id,
5299 Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc),
5301 Make_Selected_Component (Loc,
5302 Prefix => Duplicate_Subexpr_No_Checks (L),
5304 New_Occurrence_Of (First_Tag_Component (T), Loc))));
5306 -- Otherwise Tag_Id is not used
5312 -- If the tagged type has a full rep clause, expand the assignment into
5313 -- component-wise assignments. Mark the node as unanalyzed in order to
5314 -- generate the proper code and propagate this scenario by setting a
5315 -- flag to avoid infinite recursion.
5318 Set_Analyzed (Asn, False);
5319 Set_Componentwise_Assignment (Asn, True);
5322 Append_To (Res, Asn);
5328 Make_Assignment_Statement (Loc,
5330 Make_Selected_Component (Loc,
5331 Prefix => Duplicate_Subexpr_No_Checks (L),
5333 New_Occurrence_Of (First_Tag_Component (T), Loc)),
5334 Expression => New_Occurrence_Of (Tag_Id, Loc)));
5337 -- Adjust the target after the assignment when controlled (not in the
5338 -- init proc since it is an initialization more than an assignment).
5343 (Obj_Ref => Duplicate_Subexpr_Move_Checks (L),
5346 if Present (Adj_Call) then
5347 Append_To (Res, Adj_Call);
5355 -- Could use comment here ???
5357 when RE_Not_Available =>
5359 end Make_Tag_Ctrl_Assignment;