re PR c++/84691 (internal compiler error: in poplevel_class, at cp/name-lookup.c...
[official-gcc.git] / gcc / ada / exp_ch5.adb
blob4552a3b0c6fa98679839c4b85b12f521b5c63e11
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT COMPILER COMPONENTS --
4 -- --
5 -- E X P _ C H 5 --
6 -- --
7 -- B o d y --
8 -- --
9 -- Copyright (C) 1992-2018, Free Software Foundation, Inc. --
10 -- --
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. --
20 -- --
21 -- GNAT was originally developed by the GNAT team at New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc. --
23 -- --
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;
45 with Opt; use Opt;
46 with Restrict; use Restrict;
47 with Rident; use Rident;
48 with Rtsfind; use Rtsfind;
49 with Sinfo; use Sinfo;
50 with Sem; use Sem;
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
68 (N : Node_Id;
69 Container : Entity_Id;
70 Cursor : Entity_Id;
71 Init : out Node_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
82 -- ancestor.
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
87 -- and record cases.
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
98 (N : Node_Id;
99 Larray : Entity_Id;
100 Rarray : Entity_Id;
101 L_Type : Entity_Id;
102 R_Type : Entity_Id;
103 Ndim : Pos;
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 procedure Expand_Assign_Record (N : Node_Id);
118 -- N is an assignment of an untagged record value. This routine handles
119 -- the case where the assignment must be made component by component,
120 -- either because the target is not byte aligned, or there is a change
121 -- of representation, or when we have a tagged type with a representation
122 -- clause (this last case is required because holes in the tagged type
123 -- might be filled with components from child types).
125 procedure Expand_Assign_With_Target_Names (N : Node_Id);
126 -- (AI12-0125): N is an assignment statement whose RHS contains occurrences
127 -- of @ that designate the value of the LHS of the assignment. If the LHS
128 -- is side-effect free the target names can be replaced with a copy of the
129 -- LHS; otherwise the semantics of the assignment is described in terms of
130 -- a procedure with an in-out parameter, and expanded as such.
132 procedure Expand_Formal_Container_Loop (N : Node_Id);
133 -- Use the primitives specified in an Iterable aspect to expand a loop
134 -- over a so-called formal container, primarily for SPARK usage.
136 procedure Expand_Formal_Container_Element_Loop (N : Node_Id);
137 -- Same, for an iterator of the form " For E of C". In this case the
138 -- iterator provides the name of the element, and the cursor is generated
139 -- internally.
141 procedure Expand_Iterator_Loop (N : Node_Id);
142 -- Expand loop over arrays and containers that uses the form "for X of C"
143 -- with an optional subtype mark, or "for Y in C".
145 procedure Expand_Iterator_Loop_Over_Container
146 (N : Node_Id;
147 Isc : Node_Id;
148 I_Spec : Node_Id;
149 Container : Node_Id;
150 Container_Typ : Entity_Id);
151 -- Expand loop over containers that uses the form "for X of C" with an
152 -- optional subtype mark, or "for Y in C". Isc is the iteration scheme.
153 -- I_Spec is the iterator specification and Container is either the
154 -- Container (for OF) or the iterator (for IN).
156 procedure Expand_Predicated_Loop (N : Node_Id);
157 -- Expand for loop over predicated subtype
159 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id;
160 -- Generate the necessary code for controlled and tagged assignment, that
161 -- is to say, finalization of the target before, adjustment of the target
162 -- after and save and restore of the tag and finalization pointers which
163 -- are not 'part of the value' and must not be changed upon assignment. N
164 -- is the original Assignment node.
166 --------------------------------------
167 -- Build_Formal_Container_iteration --
168 --------------------------------------
170 procedure Build_Formal_Container_Iteration
171 (N : Node_Id;
172 Container : Entity_Id;
173 Cursor : Entity_Id;
174 Init : out Node_Id;
175 Advance : out Node_Id;
176 New_Loop : out Node_Id)
178 Loc : constant Source_Ptr := Sloc (N);
179 Stats : constant List_Id := Statements (N);
180 Typ : constant Entity_Id := Base_Type (Etype (Container));
182 Has_Element_Op : constant Entity_Id :=
183 Get_Iterable_Type_Primitive (Typ, Name_Has_Element);
185 First_Op : Entity_Id;
186 Next_Op : Entity_Id;
188 begin
189 -- Use the proper set of primitives depending on the direction of
190 -- iteration. The legality of a reverse iteration has been checked
191 -- during analysis.
193 if Reverse_Present (Iterator_Specification (Iteration_Scheme (N))) then
194 First_Op := Get_Iterable_Type_Primitive (Typ, Name_Last);
195 Next_Op := Get_Iterable_Type_Primitive (Typ, Name_Previous);
197 else
198 First_Op := Get_Iterable_Type_Primitive (Typ, Name_First);
199 Next_Op := Get_Iterable_Type_Primitive (Typ, Name_Next);
200 end if;
202 -- Declaration for Cursor
204 Init :=
205 Make_Object_Declaration (Loc,
206 Defining_Identifier => Cursor,
207 Object_Definition => New_Occurrence_Of (Etype (First_Op), Loc),
208 Expression =>
209 Make_Function_Call (Loc,
210 Name => New_Occurrence_Of (First_Op, Loc),
211 Parameter_Associations => New_List (
212 Convert_To_Iterable_Type (Container, Loc))));
214 -- Statement that advances (in the right direction) cursor in loop
216 Advance :=
217 Make_Assignment_Statement (Loc,
218 Name => New_Occurrence_Of (Cursor, Loc),
219 Expression =>
220 Make_Function_Call (Loc,
221 Name => New_Occurrence_Of (Next_Op, Loc),
222 Parameter_Associations => New_List (
223 Convert_To_Iterable_Type (Container, Loc),
224 New_Occurrence_Of (Cursor, Loc))));
226 -- Iterator is rewritten as a while_loop
228 New_Loop :=
229 Make_Loop_Statement (Loc,
230 Iteration_Scheme =>
231 Make_Iteration_Scheme (Loc,
232 Condition =>
233 Make_Function_Call (Loc,
234 Name => New_Occurrence_Of (Has_Element_Op, Loc),
235 Parameter_Associations => New_List (
236 Convert_To_Iterable_Type (Container, Loc),
237 New_Occurrence_Of (Cursor, Loc)))),
238 Statements => Stats,
239 End_Label => Empty);
240 end Build_Formal_Container_Iteration;
242 ------------------------------
243 -- Change_Of_Representation --
244 ------------------------------
246 function Change_Of_Representation (N : Node_Id) return Boolean is
247 Rhs : constant Node_Id := Expression (N);
248 begin
249 return
250 Nkind (Rhs) = N_Type_Conversion
251 and then
252 not Same_Representation (Etype (Rhs), Etype (Expression (Rhs)));
253 end Change_Of_Representation;
255 ------------------------------
256 -- Convert_To_Iterable_Type --
257 ------------------------------
259 function Convert_To_Iterable_Type
260 (Container : Entity_Id;
261 Loc : Source_Ptr) return Node_Id
263 Typ : constant Entity_Id := Base_Type (Etype (Container));
264 Aspect : constant Node_Id := Find_Aspect (Typ, Aspect_Iterable);
265 Result : Node_Id;
267 begin
268 Result := New_Occurrence_Of (Container, Loc);
270 if Entity (Aspect) /= Typ then
271 Result :=
272 Make_Type_Conversion (Loc,
273 Subtype_Mark => New_Occurrence_Of (Entity (Aspect), Loc),
274 Expression => Result);
275 end if;
277 return Result;
278 end Convert_To_Iterable_Type;
280 -------------------------
281 -- Expand_Assign_Array --
282 -------------------------
284 -- There are two issues here. First, do we let Gigi do a block move, or
285 -- do we expand out into a loop? Second, we need to set the two flags
286 -- Forwards_OK and Backwards_OK which show whether the block move (or
287 -- corresponding loops) can be legitimately done in a forwards (low to
288 -- high) or backwards (high to low) manner.
290 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id) is
291 Loc : constant Source_Ptr := Sloc (N);
293 Lhs : constant Node_Id := Name (N);
295 Act_Lhs : constant Node_Id := Get_Referenced_Object (Lhs);
296 Act_Rhs : Node_Id := Get_Referenced_Object (Rhs);
298 L_Type : constant Entity_Id :=
299 Underlying_Type (Get_Actual_Subtype (Act_Lhs));
300 R_Type : Entity_Id :=
301 Underlying_Type (Get_Actual_Subtype (Act_Rhs));
303 L_Slice : constant Boolean := Nkind (Act_Lhs) = N_Slice;
304 R_Slice : constant Boolean := Nkind (Act_Rhs) = N_Slice;
306 Crep : constant Boolean := Change_Of_Representation (N);
308 Larray : Node_Id;
309 Rarray : Node_Id;
311 Ndim : constant Pos := Number_Dimensions (L_Type);
313 Loop_Required : Boolean := False;
314 -- This switch is set to True if the array move must be done using
315 -- an explicit front end generated loop.
317 procedure Apply_Dereference (Arg : Node_Id);
318 -- If the argument is an access to an array, and the assignment is
319 -- converted into a procedure call, apply explicit dereference.
321 function Has_Address_Clause (Exp : Node_Id) return Boolean;
322 -- Test if Exp is a reference to an array whose declaration has
323 -- an address clause, or it is a slice of such an array.
325 function Is_Formal_Array (Exp : Node_Id) return Boolean;
326 -- Test if Exp is a reference to an array which is either a formal
327 -- parameter or a slice of a formal parameter. These are the cases
328 -- where hidden aliasing can occur.
330 function Is_Non_Local_Array (Exp : Node_Id) return Boolean;
331 -- Determine if Exp is a reference to an array variable which is other
332 -- than an object defined in the current scope, or a component or a
333 -- slice of such an object. Such objects can be aliased to parameters
334 -- (unlike local array references).
336 -----------------------
337 -- Apply_Dereference --
338 -----------------------
340 procedure Apply_Dereference (Arg : Node_Id) is
341 Typ : constant Entity_Id := Etype (Arg);
342 begin
343 if Is_Access_Type (Typ) then
344 Rewrite (Arg, Make_Explicit_Dereference (Loc,
345 Prefix => Relocate_Node (Arg)));
346 Analyze_And_Resolve (Arg, Designated_Type (Typ));
347 end if;
348 end Apply_Dereference;
350 ------------------------
351 -- Has_Address_Clause --
352 ------------------------
354 function Has_Address_Clause (Exp : Node_Id) return Boolean is
355 begin
356 return
357 (Is_Entity_Name (Exp) and then
358 Present (Address_Clause (Entity (Exp))))
359 or else
360 (Nkind (Exp) = N_Slice and then Has_Address_Clause (Prefix (Exp)));
361 end Has_Address_Clause;
363 ---------------------
364 -- Is_Formal_Array --
365 ---------------------
367 function Is_Formal_Array (Exp : Node_Id) return Boolean is
368 begin
369 return
370 (Is_Entity_Name (Exp) and then Is_Formal (Entity (Exp)))
371 or else
372 (Nkind (Exp) = N_Slice and then Is_Formal_Array (Prefix (Exp)));
373 end Is_Formal_Array;
375 ------------------------
376 -- Is_Non_Local_Array --
377 ------------------------
379 function Is_Non_Local_Array (Exp : Node_Id) return Boolean is
380 begin
381 case Nkind (Exp) is
382 when N_Indexed_Component
383 | N_Selected_Component
384 | N_Slice
386 return Is_Non_Local_Array (Prefix (Exp));
388 when others =>
389 return
390 not (Is_Entity_Name (Exp)
391 and then Scope (Entity (Exp)) = Current_Scope);
392 end case;
393 end Is_Non_Local_Array;
395 -- Determine if Lhs, Rhs are formal arrays or nonlocal arrays
397 Lhs_Formal : constant Boolean := Is_Formal_Array (Act_Lhs);
398 Rhs_Formal : constant Boolean := Is_Formal_Array (Act_Rhs);
400 Lhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Lhs);
401 Rhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Rhs);
403 -- Start of processing for Expand_Assign_Array
405 begin
406 -- Deal with length check. Note that the length check is done with
407 -- respect to the right-hand side as given, not a possible underlying
408 -- renamed object, since this would generate incorrect extra checks.
410 Apply_Length_Check (Rhs, L_Type);
412 -- We start by assuming that the move can be done in either direction,
413 -- i.e. that the two sides are completely disjoint.
415 Set_Forwards_OK (N, True);
416 Set_Backwards_OK (N, True);
418 -- Normally it is only the slice case that can lead to overlap, and
419 -- explicit checks for slices are made below. But there is one case
420 -- where the slice can be implicit and invisible to us: when we have a
421 -- one dimensional array, and either both operands are parameters, or
422 -- one is a parameter (which can be a slice passed by reference) and the
423 -- other is a non-local variable. In this case the parameter could be a
424 -- slice that overlaps with the other operand.
426 -- However, if the array subtype is a constrained first subtype in the
427 -- parameter case, then we don't have to worry about overlap, since
428 -- slice assignments aren't possible (other than for a slice denoting
429 -- the whole array).
431 -- Note: No overlap is possible if there is a change of representation,
432 -- so we can exclude this case.
434 if Ndim = 1
435 and then not Crep
436 and then
437 ((Lhs_Formal and Rhs_Formal)
438 or else
439 (Lhs_Formal and Rhs_Non_Local_Var)
440 or else
441 (Rhs_Formal and Lhs_Non_Local_Var))
442 and then
443 (not Is_Constrained (Etype (Lhs))
444 or else not Is_First_Subtype (Etype (Lhs)))
445 then
446 Set_Forwards_OK (N, False);
447 Set_Backwards_OK (N, False);
449 -- Note: the bit-packed case is not worrisome here, since if we have
450 -- a slice passed as a parameter, it is always aligned on a byte
451 -- boundary, and if there are no explicit slices, the assignment
452 -- can be performed directly.
453 end if;
455 -- If either operand has an address clause clear Backwards_OK and
456 -- Forwards_OK, since we cannot tell if the operands overlap. We
457 -- exclude this treatment when Rhs is an aggregate, since we know
458 -- that overlap can't occur.
460 if (Has_Address_Clause (Lhs) and then Nkind (Rhs) /= N_Aggregate)
461 or else Has_Address_Clause (Rhs)
462 then
463 Set_Forwards_OK (N, False);
464 Set_Backwards_OK (N, False);
465 end if;
467 -- We certainly must use a loop for change of representation and also
468 -- we use the operand of the conversion on the right-hand side as the
469 -- effective right-hand side (the component types must match in this
470 -- situation).
472 if Crep then
473 Act_Rhs := Get_Referenced_Object (Rhs);
474 R_Type := Get_Actual_Subtype (Act_Rhs);
475 Loop_Required := True;
477 -- We require a loop if the left side is possibly bit unaligned
479 elsif Possible_Bit_Aligned_Component (Lhs)
480 or else
481 Possible_Bit_Aligned_Component (Rhs)
482 then
483 Loop_Required := True;
485 -- Arrays with controlled components are expanded into a loop to force
486 -- calls to Adjust at the component level.
488 elsif Has_Controlled_Component (L_Type) then
489 Loop_Required := True;
491 -- If object is atomic/VFA, we cannot tolerate a loop
493 elsif Is_Atomic_Or_VFA_Object (Act_Lhs)
494 or else
495 Is_Atomic_Or_VFA_Object (Act_Rhs)
496 then
497 return;
499 -- Loop is required if we have atomic components since we have to
500 -- be sure to do any accesses on an element by element basis.
502 elsif Has_Atomic_Components (L_Type)
503 or else Has_Atomic_Components (R_Type)
504 or else Is_Atomic_Or_VFA (Component_Type (L_Type))
505 or else Is_Atomic_Or_VFA (Component_Type (R_Type))
506 then
507 Loop_Required := True;
509 -- Case where no slice is involved
511 elsif not L_Slice and not R_Slice then
513 -- The following code deals with the case of unconstrained bit packed
514 -- arrays. The problem is that the template for such arrays contains
515 -- the bounds of the actual source level array, but the copy of an
516 -- entire array requires the bounds of the underlying array. It would
517 -- be nice if the back end could take care of this, but right now it
518 -- does not know how, so if we have such a type, then we expand out
519 -- into a loop, which is inefficient but works correctly. If we don't
520 -- do this, we get the wrong length computed for the array to be
521 -- moved. The two cases we need to worry about are:
523 -- Explicit dereference of an unconstrained packed array type as in
524 -- the following example:
526 -- procedure C52 is
527 -- type BITS is array(INTEGER range <>) of BOOLEAN;
528 -- pragma PACK(BITS);
529 -- type A is access BITS;
530 -- P1,P2 : A;
531 -- begin
532 -- P1 := new BITS (1 .. 65_535);
533 -- P2 := new BITS (1 .. 65_535);
534 -- P2.ALL := P1.ALL;
535 -- end C52;
537 -- A formal parameter reference with an unconstrained bit array type
538 -- is the other case we need to worry about (here we assume the same
539 -- BITS type declared above):
541 -- procedure Write_All (File : out BITS; Contents : BITS);
542 -- begin
543 -- File.Storage := Contents;
544 -- end Write_All;
546 -- We expand to a loop in either of these two cases
548 -- Question for future thought. Another potentially more efficient
549 -- approach would be to create the actual subtype, and then do an
550 -- unchecked conversion to this actual subtype ???
552 Check_Unconstrained_Bit_Packed_Array : declare
554 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean;
555 -- Function to perform required test for the first case, above
556 -- (dereference of an unconstrained bit packed array).
558 -----------------------
559 -- Is_UBPA_Reference --
560 -----------------------
562 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean is
563 Typ : constant Entity_Id := Underlying_Type (Etype (Opnd));
564 P_Type : Entity_Id;
565 Des_Type : Entity_Id;
567 begin
568 if Present (Packed_Array_Impl_Type (Typ))
569 and then Is_Array_Type (Packed_Array_Impl_Type (Typ))
570 and then not Is_Constrained (Packed_Array_Impl_Type (Typ))
571 then
572 return True;
574 elsif Nkind (Opnd) = N_Explicit_Dereference then
575 P_Type := Underlying_Type (Etype (Prefix (Opnd)));
577 if not Is_Access_Type (P_Type) then
578 return False;
580 else
581 Des_Type := Designated_Type (P_Type);
582 return
583 Is_Bit_Packed_Array (Des_Type)
584 and then not Is_Constrained (Des_Type);
585 end if;
587 else
588 return False;
589 end if;
590 end Is_UBPA_Reference;
592 -- Start of processing for Check_Unconstrained_Bit_Packed_Array
594 begin
595 if Is_UBPA_Reference (Lhs)
596 or else
597 Is_UBPA_Reference (Rhs)
598 then
599 Loop_Required := True;
601 -- Here if we do not have the case of a reference to a bit packed
602 -- unconstrained array case. In this case gigi can most certainly
603 -- handle the assignment if a forwards move is allowed.
605 -- (could it handle the backwards case also???)
607 elsif Forwards_OK (N) then
608 return;
609 end if;
610 end Check_Unconstrained_Bit_Packed_Array;
612 -- The back end can always handle the assignment if the right side is a
613 -- string literal (note that overlap is definitely impossible in this
614 -- case). If the type is packed, a string literal is always converted
615 -- into an aggregate, except in the case of a null slice, for which no
616 -- aggregate can be written. In that case, rewrite the assignment as a
617 -- null statement, a length check has already been emitted to verify
618 -- that the range of the left-hand side is empty.
620 -- Note that this code is not executed if we have an assignment of a
621 -- string literal to a non-bit aligned component of a record, a case
622 -- which cannot be handled by the backend.
624 elsif Nkind (Rhs) = N_String_Literal then
625 if String_Length (Strval (Rhs)) = 0
626 and then Is_Bit_Packed_Array (L_Type)
627 then
628 Rewrite (N, Make_Null_Statement (Loc));
629 Analyze (N);
630 end if;
632 return;
634 -- If either operand is bit packed, then we need a loop, since we can't
635 -- be sure that the slice is byte aligned. Similarly, if either operand
636 -- is a possibly unaligned slice, then we need a loop (since the back
637 -- end cannot handle unaligned slices).
639 elsif Is_Bit_Packed_Array (L_Type)
640 or else Is_Bit_Packed_Array (R_Type)
641 or else Is_Possibly_Unaligned_Slice (Lhs)
642 or else Is_Possibly_Unaligned_Slice (Rhs)
643 then
644 Loop_Required := True;
646 -- If we are not bit-packed, and we have only one slice, then no overlap
647 -- is possible except in the parameter case, so we can let the back end
648 -- handle things.
650 elsif not (L_Slice and R_Slice) then
651 if Forwards_OK (N) then
652 return;
653 end if;
654 end if;
656 -- If the right-hand side is a string literal, introduce a temporary for
657 -- it, for use in the generated loop that will follow.
659 if Nkind (Rhs) = N_String_Literal then
660 declare
661 Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Rhs);
662 Decl : Node_Id;
664 begin
665 Decl :=
666 Make_Object_Declaration (Loc,
667 Defining_Identifier => Temp,
668 Object_Definition => New_Occurrence_Of (L_Type, Loc),
669 Expression => Relocate_Node (Rhs));
671 Insert_Action (N, Decl);
672 Rewrite (Rhs, New_Occurrence_Of (Temp, Loc));
673 R_Type := Etype (Temp);
674 end;
675 end if;
677 -- Come here to complete the analysis
679 -- Loop_Required: Set to True if we know that a loop is required
680 -- regardless of overlap considerations.
682 -- Forwards_OK: Set to False if we already know that a forwards
683 -- move is not safe, else set to True.
685 -- Backwards_OK: Set to False if we already know that a backwards
686 -- move is not safe, else set to True
688 -- Our task at this stage is to complete the overlap analysis, which can
689 -- result in possibly setting Forwards_OK or Backwards_OK to False, and
690 -- then generating the final code, either by deciding that it is OK
691 -- after all to let Gigi handle it, or by generating appropriate code
692 -- in the front end.
694 declare
695 L_Index_Typ : constant Node_Id := Etype (First_Index (L_Type));
696 R_Index_Typ : constant Node_Id := Etype (First_Index (R_Type));
698 Left_Lo : constant Node_Id := Type_Low_Bound (L_Index_Typ);
699 Left_Hi : constant Node_Id := Type_High_Bound (L_Index_Typ);
700 Right_Lo : constant Node_Id := Type_Low_Bound (R_Index_Typ);
701 Right_Hi : constant Node_Id := Type_High_Bound (R_Index_Typ);
703 Act_L_Array : Node_Id;
704 Act_R_Array : Node_Id;
706 Cleft_Lo : Node_Id;
707 Cright_Lo : Node_Id;
708 Condition : Node_Id;
710 Cresult : Compare_Result;
712 begin
713 -- Get the expressions for the arrays. If we are dealing with a
714 -- private type, then convert to the underlying type. We can do
715 -- direct assignments to an array that is a private type, but we
716 -- cannot assign to elements of the array without this extra
717 -- unchecked conversion.
719 -- Note: We propagate Parent to the conversion nodes to generate
720 -- a well-formed subtree.
722 if Nkind (Act_Lhs) = N_Slice then
723 Larray := Prefix (Act_Lhs);
724 else
725 Larray := Act_Lhs;
727 if Is_Private_Type (Etype (Larray)) then
728 declare
729 Par : constant Node_Id := Parent (Larray);
730 begin
731 Larray :=
732 Unchecked_Convert_To
733 (Underlying_Type (Etype (Larray)), Larray);
734 Set_Parent (Larray, Par);
735 end;
736 end if;
737 end if;
739 if Nkind (Act_Rhs) = N_Slice then
740 Rarray := Prefix (Act_Rhs);
741 else
742 Rarray := Act_Rhs;
744 if Is_Private_Type (Etype (Rarray)) then
745 declare
746 Par : constant Node_Id := Parent (Rarray);
747 begin
748 Rarray :=
749 Unchecked_Convert_To
750 (Underlying_Type (Etype (Rarray)), Rarray);
751 Set_Parent (Rarray, Par);
752 end;
753 end if;
754 end if;
756 -- If both sides are slices, we must figure out whether it is safe
757 -- to do the move in one direction or the other. It is always safe
758 -- if there is a change of representation since obviously two arrays
759 -- with different representations cannot possibly overlap.
761 if (not Crep) and L_Slice and R_Slice then
762 Act_L_Array := Get_Referenced_Object (Prefix (Act_Lhs));
763 Act_R_Array := Get_Referenced_Object (Prefix (Act_Rhs));
765 -- If both left- and right-hand arrays are entity names, and refer
766 -- to different entities, then we know that the move is safe (the
767 -- two storage areas are completely disjoint).
769 if Is_Entity_Name (Act_L_Array)
770 and then Is_Entity_Name (Act_R_Array)
771 and then Entity (Act_L_Array) /= Entity (Act_R_Array)
772 then
773 null;
775 -- Otherwise, we assume the worst, which is that the two arrays
776 -- are the same array. There is no need to check if we know that
777 -- is the case, because if we don't know it, we still have to
778 -- assume it.
780 -- Generally if the same array is involved, then we have an
781 -- overlapping case. We will have to really assume the worst (i.e.
782 -- set neither of the OK flags) unless we can determine the lower
783 -- or upper bounds at compile time and compare them.
785 else
786 Cresult :=
787 Compile_Time_Compare
788 (Left_Lo, Right_Lo, Assume_Valid => True);
790 if Cresult = Unknown then
791 Cresult :=
792 Compile_Time_Compare
793 (Left_Hi, Right_Hi, Assume_Valid => True);
794 end if;
796 case Cresult is
797 when EQ | LE | LT =>
798 Set_Backwards_OK (N, False);
800 when GE | GT =>
801 Set_Forwards_OK (N, False);
803 when NE | Unknown =>
804 Set_Backwards_OK (N, False);
805 Set_Forwards_OK (N, False);
806 end case;
807 end if;
808 end if;
810 -- If after that analysis Loop_Required is False, meaning that we
811 -- have not discovered some non-overlap reason for requiring a loop,
812 -- then the outcome depends on the capabilities of the back end.
814 if not Loop_Required then
815 -- Assume the back end can deal with all cases of overlap by
816 -- falling back to memmove if it cannot use a more efficient
817 -- approach.
819 return;
820 end if;
822 -- At this stage we have to generate an explicit loop, and we have
823 -- the following cases:
825 -- Forwards_OK = True
827 -- Rnn : right_index := right_index'First;
828 -- for Lnn in left-index loop
829 -- left (Lnn) := right (Rnn);
830 -- Rnn := right_index'Succ (Rnn);
831 -- end loop;
833 -- Note: the above code MUST be analyzed with checks off, because
834 -- otherwise the Succ could overflow. But in any case this is more
835 -- efficient.
837 -- Forwards_OK = False, Backwards_OK = True
839 -- Rnn : right_index := right_index'Last;
840 -- for Lnn in reverse left-index loop
841 -- left (Lnn) := right (Rnn);
842 -- Rnn := right_index'Pred (Rnn);
843 -- end loop;
845 -- Note: the above code MUST be analyzed with checks off, because
846 -- otherwise the Pred could overflow. But in any case this is more
847 -- efficient.
849 -- Forwards_OK = Backwards_OK = False
851 -- This only happens if we have the same array on each side. It is
852 -- possible to create situations using overlays that violate this,
853 -- but we simply do not promise to get this "right" in this case.
855 -- There are two possible subcases. If the No_Implicit_Conditionals
856 -- restriction is set, then we generate the following code:
858 -- declare
859 -- T : constant <operand-type> := rhs;
860 -- begin
861 -- lhs := T;
862 -- end;
864 -- If implicit conditionals are permitted, then we generate:
866 -- if Left_Lo <= Right_Lo then
867 -- <code for Forwards_OK = True above>
868 -- else
869 -- <code for Backwards_OK = True above>
870 -- end if;
872 -- In order to detect possible aliasing, we examine the renamed
873 -- expression when the source or target is a renaming. However,
874 -- the renaming may be intended to capture an address that may be
875 -- affected by subsequent code, and therefore we must recover
876 -- the actual entity for the expansion that follows, not the
877 -- object it renames. In particular, if source or target designate
878 -- a portion of a dynamically allocated object, the pointer to it
879 -- may be reassigned but the renaming preserves the proper location.
881 if Is_Entity_Name (Rhs)
882 and then
883 Nkind (Parent (Entity (Rhs))) = N_Object_Renaming_Declaration
884 and then Nkind (Act_Rhs) = N_Slice
885 then
886 Rarray := Rhs;
887 end if;
889 if Is_Entity_Name (Lhs)
890 and then
891 Nkind (Parent (Entity (Lhs))) = N_Object_Renaming_Declaration
892 and then Nkind (Act_Lhs) = N_Slice
893 then
894 Larray := Lhs;
895 end if;
897 -- Cases where either Forwards_OK or Backwards_OK is true
899 if Forwards_OK (N) or else Backwards_OK (N) then
900 if Needs_Finalization (Component_Type (L_Type))
901 and then Base_Type (L_Type) = Base_Type (R_Type)
902 and then Ndim = 1
903 and then not No_Ctrl_Actions (N)
904 then
905 declare
906 Proc : constant Entity_Id :=
907 TSS (Base_Type (L_Type), TSS_Slice_Assign);
908 Actuals : List_Id;
910 begin
911 Apply_Dereference (Larray);
912 Apply_Dereference (Rarray);
913 Actuals := New_List (
914 Duplicate_Subexpr (Larray, Name_Req => True),
915 Duplicate_Subexpr (Rarray, Name_Req => True),
916 Duplicate_Subexpr (Left_Lo, Name_Req => True),
917 Duplicate_Subexpr (Left_Hi, Name_Req => True),
918 Duplicate_Subexpr (Right_Lo, Name_Req => True),
919 Duplicate_Subexpr (Right_Hi, Name_Req => True));
921 Append_To (Actuals,
922 New_Occurrence_Of (
923 Boolean_Literals (not Forwards_OK (N)), Loc));
925 Rewrite (N,
926 Make_Procedure_Call_Statement (Loc,
927 Name => New_Occurrence_Of (Proc, Loc),
928 Parameter_Associations => Actuals));
929 end;
931 else
932 Rewrite (N,
933 Expand_Assign_Array_Loop
934 (N, Larray, Rarray, L_Type, R_Type, Ndim,
935 Rev => not Forwards_OK (N)));
936 end if;
938 -- Case of both are false with No_Implicit_Conditionals
940 elsif Restriction_Active (No_Implicit_Conditionals) then
941 declare
942 T : constant Entity_Id :=
943 Make_Defining_Identifier (Loc, Chars => Name_T);
945 begin
946 Rewrite (N,
947 Make_Block_Statement (Loc,
948 Declarations => New_List (
949 Make_Object_Declaration (Loc,
950 Defining_Identifier => T,
951 Constant_Present => True,
952 Object_Definition =>
953 New_Occurrence_Of (Etype (Rhs), Loc),
954 Expression => Relocate_Node (Rhs))),
956 Handled_Statement_Sequence =>
957 Make_Handled_Sequence_Of_Statements (Loc,
958 Statements => New_List (
959 Make_Assignment_Statement (Loc,
960 Name => Relocate_Node (Lhs),
961 Expression => New_Occurrence_Of (T, Loc))))));
962 end;
964 -- Case of both are false with implicit conditionals allowed
966 else
967 -- Before we generate this code, we must ensure that the left and
968 -- right side array types are defined. They may be itypes, and we
969 -- cannot let them be defined inside the if, since the first use
970 -- in the then may not be executed.
972 Ensure_Defined (L_Type, N);
973 Ensure_Defined (R_Type, N);
975 -- We normally compare addresses to find out which way round to
976 -- do the loop, since this is reliable, and handles the cases of
977 -- parameters, conversions etc. But we can't do that in the bit
978 -- packed case, because addresses don't work there.
980 if not Is_Bit_Packed_Array (L_Type) then
981 Condition :=
982 Make_Op_Le (Loc,
983 Left_Opnd =>
984 Unchecked_Convert_To (RTE (RE_Integer_Address),
985 Make_Attribute_Reference (Loc,
986 Prefix =>
987 Make_Indexed_Component (Loc,
988 Prefix =>
989 Duplicate_Subexpr_Move_Checks (Larray, True),
990 Expressions => New_List (
991 Make_Attribute_Reference (Loc,
992 Prefix =>
993 New_Occurrence_Of
994 (L_Index_Typ, Loc),
995 Attribute_Name => Name_First))),
996 Attribute_Name => Name_Address)),
998 Right_Opnd =>
999 Unchecked_Convert_To (RTE (RE_Integer_Address),
1000 Make_Attribute_Reference (Loc,
1001 Prefix =>
1002 Make_Indexed_Component (Loc,
1003 Prefix =>
1004 Duplicate_Subexpr_Move_Checks (Rarray, True),
1005 Expressions => New_List (
1006 Make_Attribute_Reference (Loc,
1007 Prefix =>
1008 New_Occurrence_Of
1009 (R_Index_Typ, Loc),
1010 Attribute_Name => Name_First))),
1011 Attribute_Name => Name_Address)));
1013 -- For the bit packed and VM cases we use the bounds. That's OK,
1014 -- because we don't have to worry about parameters, since they
1015 -- cannot cause overlap. Perhaps we should worry about weird slice
1016 -- conversions ???
1018 else
1019 -- Copy the bounds
1021 Cleft_Lo := New_Copy_Tree (Left_Lo);
1022 Cright_Lo := New_Copy_Tree (Right_Lo);
1024 -- If the types do not match we add an implicit conversion
1025 -- here to ensure proper match
1027 if Etype (Left_Lo) /= Etype (Right_Lo) then
1028 Cright_Lo :=
1029 Unchecked_Convert_To (Etype (Left_Lo), Cright_Lo);
1030 end if;
1032 -- Reset the Analyzed flag, because the bounds of the index
1033 -- type itself may be universal, and must must be reanalyzed
1034 -- to acquire the proper type for the back end.
1036 Set_Analyzed (Cleft_Lo, False);
1037 Set_Analyzed (Cright_Lo, False);
1039 Condition :=
1040 Make_Op_Le (Loc,
1041 Left_Opnd => Cleft_Lo,
1042 Right_Opnd => Cright_Lo);
1043 end if;
1045 if Needs_Finalization (Component_Type (L_Type))
1046 and then Base_Type (L_Type) = Base_Type (R_Type)
1047 and then Ndim = 1
1048 and then not No_Ctrl_Actions (N)
1049 then
1051 -- Call TSS procedure for array assignment, passing the
1052 -- explicit bounds of right- and left-hand sides.
1054 declare
1055 Proc : constant Entity_Id :=
1056 TSS (Base_Type (L_Type), TSS_Slice_Assign);
1057 Actuals : List_Id;
1059 begin
1060 Apply_Dereference (Larray);
1061 Apply_Dereference (Rarray);
1062 Actuals := New_List (
1063 Duplicate_Subexpr (Larray, Name_Req => True),
1064 Duplicate_Subexpr (Rarray, Name_Req => True),
1065 Duplicate_Subexpr (Left_Lo, Name_Req => True),
1066 Duplicate_Subexpr (Left_Hi, Name_Req => True),
1067 Duplicate_Subexpr (Right_Lo, Name_Req => True),
1068 Duplicate_Subexpr (Right_Hi, Name_Req => True));
1070 Append_To (Actuals,
1071 Make_Op_Not (Loc,
1072 Right_Opnd => Condition));
1074 Rewrite (N,
1075 Make_Procedure_Call_Statement (Loc,
1076 Name => New_Occurrence_Of (Proc, Loc),
1077 Parameter_Associations => Actuals));
1078 end;
1080 else
1081 Rewrite (N,
1082 Make_Implicit_If_Statement (N,
1083 Condition => Condition,
1085 Then_Statements => New_List (
1086 Expand_Assign_Array_Loop
1087 (N, Larray, Rarray, L_Type, R_Type, Ndim,
1088 Rev => False)),
1090 Else_Statements => New_List (
1091 Expand_Assign_Array_Loop
1092 (N, Larray, Rarray, L_Type, R_Type, Ndim,
1093 Rev => True))));
1094 end if;
1095 end if;
1097 Analyze (N, Suppress => All_Checks);
1098 end;
1100 exception
1101 when RE_Not_Available =>
1102 return;
1103 end Expand_Assign_Array;
1105 ------------------------------
1106 -- Expand_Assign_Array_Loop --
1107 ------------------------------
1109 -- The following is an example of the loop generated for the case of a
1110 -- two-dimensional array:
1112 -- declare
1113 -- R2b : Tm1X1 := 1;
1114 -- begin
1115 -- for L1b in 1 .. 100 loop
1116 -- declare
1117 -- R4b : Tm1X2 := 1;
1118 -- begin
1119 -- for L3b in 1 .. 100 loop
1120 -- vm1 (L1b, L3b) := vm2 (R2b, R4b);
1121 -- R4b := Tm1X2'succ(R4b);
1122 -- end loop;
1123 -- end;
1124 -- R2b := Tm1X1'succ(R2b);
1125 -- end loop;
1126 -- end;
1128 -- Here Rev is False, and Tm1Xn are the subscript types for the right-hand
1129 -- side. The declarations of R2b and R4b are inserted before the original
1130 -- assignment statement.
1132 function Expand_Assign_Array_Loop
1133 (N : Node_Id;
1134 Larray : Entity_Id;
1135 Rarray : Entity_Id;
1136 L_Type : Entity_Id;
1137 R_Type : Entity_Id;
1138 Ndim : Pos;
1139 Rev : Boolean) return Node_Id
1141 Loc : constant Source_Ptr := Sloc (N);
1143 Lnn : array (1 .. Ndim) of Entity_Id;
1144 Rnn : array (1 .. Ndim) of Entity_Id;
1145 -- Entities used as subscripts on left and right sides
1147 L_Index_Type : array (1 .. Ndim) of Entity_Id;
1148 R_Index_Type : array (1 .. Ndim) of Entity_Id;
1149 -- Left and right index types
1151 Assign : Node_Id;
1153 F_Or_L : Name_Id;
1154 S_Or_P : Name_Id;
1156 function Build_Step (J : Nat) return Node_Id;
1157 -- The increment step for the index of the right-hand side is written
1158 -- as an attribute reference (Succ or Pred). This function returns
1159 -- the corresponding node, which is placed at the end of the loop body.
1161 ----------------
1162 -- Build_Step --
1163 ----------------
1165 function Build_Step (J : Nat) return Node_Id is
1166 Step : Node_Id;
1167 Lim : Name_Id;
1169 begin
1170 if Rev then
1171 Lim := Name_First;
1172 else
1173 Lim := Name_Last;
1174 end if;
1176 Step :=
1177 Make_Assignment_Statement (Loc,
1178 Name => New_Occurrence_Of (Rnn (J), Loc),
1179 Expression =>
1180 Make_Attribute_Reference (Loc,
1181 Prefix =>
1182 New_Occurrence_Of (R_Index_Type (J), Loc),
1183 Attribute_Name => S_Or_P,
1184 Expressions => New_List (
1185 New_Occurrence_Of (Rnn (J), Loc))));
1187 -- Note that on the last iteration of the loop, the index is increased
1188 -- (or decreased) past the corresponding bound. This is consistent with
1189 -- the C semantics of the back-end, where such an off-by-one value on a
1190 -- dead index variable is OK. However, in CodePeer mode this leads to
1191 -- spurious warnings, and thus we place a guard around the attribute
1192 -- reference. For obvious reasons we only do this for CodePeer.
1194 if CodePeer_Mode then
1195 Step :=
1196 Make_If_Statement (Loc,
1197 Condition =>
1198 Make_Op_Ne (Loc,
1199 Left_Opnd => New_Occurrence_Of (Lnn (J), Loc),
1200 Right_Opnd =>
1201 Make_Attribute_Reference (Loc,
1202 Prefix => New_Occurrence_Of (L_Index_Type (J), Loc),
1203 Attribute_Name => Lim)),
1204 Then_Statements => New_List (Step));
1205 end if;
1207 return Step;
1208 end Build_Step;
1210 -- Start of processing for Expand_Assign_Array_Loop
1212 begin
1213 if Rev then
1214 F_Or_L := Name_Last;
1215 S_Or_P := Name_Pred;
1216 else
1217 F_Or_L := Name_First;
1218 S_Or_P := Name_Succ;
1219 end if;
1221 -- Setup index types and subscript entities
1223 declare
1224 L_Index : Node_Id;
1225 R_Index : Node_Id;
1227 begin
1228 L_Index := First_Index (L_Type);
1229 R_Index := First_Index (R_Type);
1231 for J in 1 .. Ndim loop
1232 Lnn (J) := Make_Temporary (Loc, 'L');
1233 Rnn (J) := Make_Temporary (Loc, 'R');
1235 L_Index_Type (J) := Etype (L_Index);
1236 R_Index_Type (J) := Etype (R_Index);
1238 Next_Index (L_Index);
1239 Next_Index (R_Index);
1240 end loop;
1241 end;
1243 -- Now construct the assignment statement
1245 declare
1246 ExprL : constant List_Id := New_List;
1247 ExprR : constant List_Id := New_List;
1249 begin
1250 for J in 1 .. Ndim loop
1251 Append_To (ExprL, New_Occurrence_Of (Lnn (J), Loc));
1252 Append_To (ExprR, New_Occurrence_Of (Rnn (J), Loc));
1253 end loop;
1255 Assign :=
1256 Make_Assignment_Statement (Loc,
1257 Name =>
1258 Make_Indexed_Component (Loc,
1259 Prefix => Duplicate_Subexpr (Larray, Name_Req => True),
1260 Expressions => ExprL),
1261 Expression =>
1262 Make_Indexed_Component (Loc,
1263 Prefix => Duplicate_Subexpr (Rarray, Name_Req => True),
1264 Expressions => ExprR));
1266 -- We set assignment OK, since there are some cases, e.g. in object
1267 -- declarations, where we are actually assigning into a constant.
1268 -- If there really is an illegality, it was caught long before now,
1269 -- and was flagged when the original assignment was analyzed.
1271 Set_Assignment_OK (Name (Assign));
1273 -- Propagate the No_Ctrl_Actions flag to individual assignments
1275 Set_No_Ctrl_Actions (Assign, No_Ctrl_Actions (N));
1276 end;
1278 -- Now construct the loop from the inside out, with the last subscript
1279 -- varying most rapidly. Note that Assign is first the raw assignment
1280 -- statement, and then subsequently the loop that wraps it up.
1282 for J in reverse 1 .. Ndim loop
1283 Assign :=
1284 Make_Block_Statement (Loc,
1285 Declarations => New_List (
1286 Make_Object_Declaration (Loc,
1287 Defining_Identifier => Rnn (J),
1288 Object_Definition =>
1289 New_Occurrence_Of (R_Index_Type (J), Loc),
1290 Expression =>
1291 Make_Attribute_Reference (Loc,
1292 Prefix => New_Occurrence_Of (R_Index_Type (J), Loc),
1293 Attribute_Name => F_Or_L))),
1295 Handled_Statement_Sequence =>
1296 Make_Handled_Sequence_Of_Statements (Loc,
1297 Statements => New_List (
1298 Make_Implicit_Loop_Statement (N,
1299 Iteration_Scheme =>
1300 Make_Iteration_Scheme (Loc,
1301 Loop_Parameter_Specification =>
1302 Make_Loop_Parameter_Specification (Loc,
1303 Defining_Identifier => Lnn (J),
1304 Reverse_Present => Rev,
1305 Discrete_Subtype_Definition =>
1306 New_Occurrence_Of (L_Index_Type (J), Loc))),
1308 Statements => New_List (Assign, Build_Step (J))))));
1309 end loop;
1311 return Assign;
1312 end Expand_Assign_Array_Loop;
1314 --------------------------
1315 -- Expand_Assign_Record --
1316 --------------------------
1318 procedure Expand_Assign_Record (N : Node_Id) is
1319 Lhs : constant Node_Id := Name (N);
1320 Rhs : Node_Id := Expression (N);
1321 L_Typ : constant Entity_Id := Base_Type (Etype (Lhs));
1323 begin
1324 -- If change of representation, then extract the real right-hand side
1325 -- from the type conversion, and proceed with component-wise assignment,
1326 -- since the two types are not the same as far as the back end is
1327 -- concerned.
1329 if Change_Of_Representation (N) then
1330 Rhs := Expression (Rhs);
1332 -- If this may be a case of a large bit aligned component, then proceed
1333 -- with component-wise assignment, to avoid possible clobbering of other
1334 -- components sharing bits in the first or last byte of the component to
1335 -- be assigned.
1337 elsif Possible_Bit_Aligned_Component (Lhs)
1339 Possible_Bit_Aligned_Component (Rhs)
1340 then
1341 null;
1343 -- If we have a tagged type that has a complete record representation
1344 -- clause, we must do we must do component-wise assignments, since child
1345 -- types may have used gaps for their components, and we might be
1346 -- dealing with a view conversion.
1348 elsif Is_Fully_Repped_Tagged_Type (L_Typ) then
1349 null;
1351 -- If neither condition met, then nothing special to do, the back end
1352 -- can handle assignment of the entire component as a single entity.
1354 else
1355 return;
1356 end if;
1358 -- At this stage we know that we must do a component wise assignment
1360 declare
1361 Loc : constant Source_Ptr := Sloc (N);
1362 R_Typ : constant Entity_Id := Base_Type (Etype (Rhs));
1363 Decl : constant Node_Id := Declaration_Node (R_Typ);
1364 RDef : Node_Id;
1365 F : Entity_Id;
1367 function Find_Component
1368 (Typ : Entity_Id;
1369 Comp : Entity_Id) return Entity_Id;
1370 -- Find the component with the given name in the underlying record
1371 -- declaration for Typ. We need to use the actual entity because the
1372 -- type may be private and resolution by identifier alone would fail.
1374 function Make_Component_List_Assign
1375 (CL : Node_Id;
1376 U_U : Boolean := False) return List_Id;
1377 -- Returns a sequence of statements to assign the components that
1378 -- are referenced in the given component list. The flag U_U is
1379 -- used to force the usage of the inferred value of the variant
1380 -- part expression as the switch for the generated case statement.
1382 function Make_Field_Assign
1383 (C : Entity_Id;
1384 U_U : Boolean := False) return Node_Id;
1385 -- Given C, the entity for a discriminant or component, build an
1386 -- assignment for the corresponding field values. The flag U_U
1387 -- signals the presence of an Unchecked_Union and forces the usage
1388 -- of the inferred discriminant value of C as the right-hand side
1389 -- of the assignment.
1391 function Make_Field_Assigns (CI : List_Id) return List_Id;
1392 -- Given CI, a component items list, construct series of statements
1393 -- for fieldwise assignment of the corresponding components.
1395 --------------------
1396 -- Find_Component --
1397 --------------------
1399 function Find_Component
1400 (Typ : Entity_Id;
1401 Comp : Entity_Id) return Entity_Id
1403 Utyp : constant Entity_Id := Underlying_Type (Typ);
1404 C : Entity_Id;
1406 begin
1407 C := First_Entity (Utyp);
1408 while Present (C) loop
1409 if Chars (C) = Chars (Comp) then
1410 return C;
1411 end if;
1413 Next_Entity (C);
1414 end loop;
1416 raise Program_Error;
1417 end Find_Component;
1419 --------------------------------
1420 -- Make_Component_List_Assign --
1421 --------------------------------
1423 function Make_Component_List_Assign
1424 (CL : Node_Id;
1425 U_U : Boolean := False) return List_Id
1427 CI : constant List_Id := Component_Items (CL);
1428 VP : constant Node_Id := Variant_Part (CL);
1430 Alts : List_Id;
1431 DC : Node_Id;
1432 DCH : List_Id;
1433 Expr : Node_Id;
1434 Result : List_Id;
1435 V : Node_Id;
1437 begin
1438 Result := Make_Field_Assigns (CI);
1440 if Present (VP) then
1441 V := First_Non_Pragma (Variants (VP));
1442 Alts := New_List;
1443 while Present (V) loop
1444 DCH := New_List;
1445 DC := First (Discrete_Choices (V));
1446 while Present (DC) loop
1447 Append_To (DCH, New_Copy_Tree (DC));
1448 Next (DC);
1449 end loop;
1451 Append_To (Alts,
1452 Make_Case_Statement_Alternative (Loc,
1453 Discrete_Choices => DCH,
1454 Statements =>
1455 Make_Component_List_Assign (Component_List (V))));
1456 Next_Non_Pragma (V);
1457 end loop;
1459 -- If we have an Unchecked_Union, use the value of the inferred
1460 -- discriminant of the variant part expression as the switch
1461 -- for the case statement. The case statement may later be
1462 -- folded.
1464 if U_U then
1465 Expr :=
1466 New_Copy (Get_Discriminant_Value (
1467 Entity (Name (VP)),
1468 Etype (Rhs),
1469 Discriminant_Constraint (Etype (Rhs))));
1470 else
1471 Expr :=
1472 Make_Selected_Component (Loc,
1473 Prefix => Duplicate_Subexpr (Rhs),
1474 Selector_Name =>
1475 Make_Identifier (Loc, Chars (Name (VP))));
1476 end if;
1478 Append_To (Result,
1479 Make_Case_Statement (Loc,
1480 Expression => Expr,
1481 Alternatives => Alts));
1482 end if;
1484 return Result;
1485 end Make_Component_List_Assign;
1487 -----------------------
1488 -- Make_Field_Assign --
1489 -----------------------
1491 function Make_Field_Assign
1492 (C : Entity_Id;
1493 U_U : Boolean := False) return Node_Id
1495 A : Node_Id;
1496 Disc : Entity_Id;
1497 Expr : Node_Id;
1499 begin
1500 -- The discriminant entity to be used in the retrieval below must
1501 -- be one in the corresponding type, given that the assignment may
1502 -- be between derived and parent types.
1504 if Is_Derived_Type (Etype (Rhs)) then
1505 Disc := Find_Component (R_Typ, C);
1506 else
1507 Disc := C;
1508 end if;
1510 -- In the case of an Unchecked_Union, use the discriminant
1511 -- constraint value as on the right-hand side of the assignment.
1513 if U_U then
1514 Expr :=
1515 New_Copy (Get_Discriminant_Value (C,
1516 Etype (Rhs),
1517 Discriminant_Constraint (Etype (Rhs))));
1518 else
1519 Expr :=
1520 Make_Selected_Component (Loc,
1521 Prefix => Duplicate_Subexpr (Rhs),
1522 Selector_Name => New_Occurrence_Of (Disc, Loc));
1523 end if;
1525 A :=
1526 Make_Assignment_Statement (Loc,
1527 Name =>
1528 Make_Selected_Component (Loc,
1529 Prefix => Duplicate_Subexpr (Lhs),
1530 Selector_Name =>
1531 New_Occurrence_Of (Find_Component (L_Typ, C), Loc)),
1532 Expression => Expr);
1534 -- Set Assignment_OK, so discriminants can be assigned
1536 Set_Assignment_OK (Name (A), True);
1538 if Componentwise_Assignment (N)
1539 and then Nkind (Name (A)) = N_Selected_Component
1540 and then Chars (Selector_Name (Name (A))) = Name_uParent
1541 then
1542 Set_Componentwise_Assignment (A);
1543 end if;
1545 return A;
1546 end Make_Field_Assign;
1548 ------------------------
1549 -- Make_Field_Assigns --
1550 ------------------------
1552 function Make_Field_Assigns (CI : List_Id) return List_Id is
1553 Item : Node_Id;
1554 Result : List_Id;
1556 begin
1557 Item := First (CI);
1558 Result := New_List;
1560 while Present (Item) loop
1562 -- Look for components, but exclude _tag field assignment if
1563 -- the special Componentwise_Assignment flag is set.
1565 if Nkind (Item) = N_Component_Declaration
1566 and then not (Is_Tag (Defining_Identifier (Item))
1567 and then Componentwise_Assignment (N))
1568 then
1569 Append_To
1570 (Result, Make_Field_Assign (Defining_Identifier (Item)));
1571 end if;
1573 Next (Item);
1574 end loop;
1576 return Result;
1577 end Make_Field_Assigns;
1579 -- Start of processing for Expand_Assign_Record
1581 begin
1582 -- Note that we use the base types for this processing. This results
1583 -- in some extra work in the constrained case, but the change of
1584 -- representation case is so unusual that it is not worth the effort.
1586 -- First copy the discriminants. This is done unconditionally. It
1587 -- is required in the unconstrained left side case, and also in the
1588 -- case where this assignment was constructed during the expansion
1589 -- of a type conversion (since initialization of discriminants is
1590 -- suppressed in this case). It is unnecessary but harmless in
1591 -- other cases.
1593 -- Special case: no copy if the target has no discriminants
1595 if Has_Discriminants (L_Typ)
1596 and then Is_Unchecked_Union (Base_Type (L_Typ))
1597 then
1598 null;
1600 elsif Has_Discriminants (L_Typ) then
1601 F := First_Discriminant (R_Typ);
1602 while Present (F) loop
1604 -- If we are expanding the initialization of a derived record
1605 -- that constrains or renames discriminants of the parent, we
1606 -- must use the corresponding discriminant in the parent.
1608 declare
1609 CF : Entity_Id;
1611 begin
1612 if Inside_Init_Proc
1613 and then Present (Corresponding_Discriminant (F))
1614 then
1615 CF := Corresponding_Discriminant (F);
1616 else
1617 CF := F;
1618 end if;
1620 if Is_Unchecked_Union (Base_Type (R_Typ)) then
1622 -- Within an initialization procedure this is the
1623 -- assignment to an unchecked union component, in which
1624 -- case there is no discriminant to initialize.
1626 if Inside_Init_Proc then
1627 null;
1629 else
1630 -- The assignment is part of a conversion from a
1631 -- derived unchecked union type with an inferable
1632 -- discriminant, to a parent type.
1634 Insert_Action (N, Make_Field_Assign (CF, True));
1635 end if;
1637 else
1638 Insert_Action (N, Make_Field_Assign (CF));
1639 end if;
1641 Next_Discriminant (F);
1642 end;
1643 end loop;
1645 -- If the derived type has a stored constraint, assign the value
1646 -- of the corresponding discriminants explicitly, skipping those
1647 -- that are renamed discriminants. We cannot just retrieve them
1648 -- from the Rhs by selected component because they are invisible
1649 -- in the type of the right-hand side.
1651 if Stored_Constraint (R_Typ) /= No_Elist then
1652 declare
1653 Assign : Node_Id;
1654 Discr_Val : Elmt_Id;
1656 begin
1657 Discr_Val := First_Elmt (Stored_Constraint (R_Typ));
1658 F := First_Entity (R_Typ);
1659 while Present (F) loop
1660 if Ekind (F) = E_Discriminant
1661 and then Is_Completely_Hidden (F)
1662 and then Present (Corresponding_Record_Component (F))
1663 and then
1664 (not Is_Entity_Name (Node (Discr_Val))
1665 or else Ekind (Entity (Node (Discr_Val))) /=
1666 E_Discriminant)
1667 then
1668 Assign :=
1669 Make_Assignment_Statement (Loc,
1670 Name =>
1671 Make_Selected_Component (Loc,
1672 Prefix => Duplicate_Subexpr (Lhs),
1673 Selector_Name =>
1674 New_Occurrence_Of
1675 (Corresponding_Record_Component (F), Loc)),
1676 Expression => New_Copy (Node (Discr_Val)));
1678 Set_Assignment_OK (Name (Assign));
1679 Insert_Action (N, Assign);
1680 Next_Elmt (Discr_Val);
1681 end if;
1683 Next_Entity (F);
1684 end loop;
1685 end;
1686 end if;
1687 end if;
1689 -- We know the underlying type is a record, but its current view
1690 -- may be private. We must retrieve the usable record declaration.
1692 if Nkind_In (Decl, N_Private_Type_Declaration,
1693 N_Private_Extension_Declaration)
1694 and then Present (Full_View (R_Typ))
1695 then
1696 RDef := Type_Definition (Declaration_Node (Full_View (R_Typ)));
1697 else
1698 RDef := Type_Definition (Decl);
1699 end if;
1701 if Nkind (RDef) = N_Derived_Type_Definition then
1702 RDef := Record_Extension_Part (RDef);
1703 end if;
1705 if Nkind (RDef) = N_Record_Definition
1706 and then Present (Component_List (RDef))
1707 then
1708 if Is_Unchecked_Union (R_Typ) then
1709 Insert_Actions (N,
1710 Make_Component_List_Assign (Component_List (RDef), True));
1711 else
1712 Insert_Actions
1713 (N, Make_Component_List_Assign (Component_List (RDef)));
1714 end if;
1716 Rewrite (N, Make_Null_Statement (Loc));
1717 end if;
1718 end;
1719 end Expand_Assign_Record;
1721 -------------------------------------
1722 -- Expand_Assign_With_Target_Names --
1723 -------------------------------------
1725 procedure Expand_Assign_With_Target_Names (N : Node_Id) is
1726 LHS : constant Node_Id := Name (N);
1727 LHS_Typ : constant Entity_Id := Etype (LHS);
1728 Loc : constant Source_Ptr := Sloc (N);
1729 RHS : constant Node_Id := Expression (N);
1731 Ent : Entity_Id;
1732 -- The entity of the left-hand side
1734 function Replace_Target (N : Node_Id) return Traverse_Result;
1735 -- Replace occurrences of the target name by the proper entity: either
1736 -- the entity of the LHS in simple cases, or the formal of the
1737 -- constructed procedure otherwise.
1739 --------------------
1740 -- Replace_Target --
1741 --------------------
1743 function Replace_Target (N : Node_Id) return Traverse_Result is
1744 begin
1745 if Nkind (N) = N_Target_Name then
1746 Rewrite (N, New_Occurrence_Of (Ent, Sloc (N)));
1748 -- The expression will be reanalyzed when the enclosing assignment
1749 -- is reanalyzed, so reset the entity, which may be a temporary
1750 -- created during analysis, e.g. a loop variable for an iterated
1751 -- component association. However, if entity is callable then
1752 -- resolution has established its proper identity (including in
1753 -- rewritten prefixed calls) so we must preserve it.
1755 elsif Is_Entity_Name (N) then
1756 if Present (Entity (N))
1757 and then not Is_Overloadable (Entity (N))
1758 then
1759 Set_Entity (N, Empty);
1760 end if;
1761 end if;
1763 Set_Analyzed (N, False);
1764 return OK;
1765 end Replace_Target;
1767 procedure Replace_Target_Name is new Traverse_Proc (Replace_Target);
1769 -- Local variables
1771 New_RHS : Node_Id;
1772 Proc_Id : Entity_Id;
1774 -- Start of processing for Expand_Assign_With_Target_Names
1776 begin
1777 New_RHS := New_Copy_Tree (RHS);
1779 -- The left-hand side is a direct name
1781 if Is_Entity_Name (LHS)
1782 and then not Is_Renaming_Of_Object (Entity (LHS))
1783 then
1784 Ent := Entity (LHS);
1785 Replace_Target_Name (New_RHS);
1787 -- Generate:
1788 -- LHS := ... LHS ...;
1790 Rewrite (N,
1791 Make_Assignment_Statement (Loc,
1792 Name => Relocate_Node (LHS),
1793 Expression => New_RHS));
1795 -- The left-hand side is not a direct name, but is side-effect free.
1796 -- Capture its value in a temporary to avoid multiple evaluations.
1798 elsif Side_Effect_Free (LHS) then
1799 Ent := Make_Temporary (Loc, 'T');
1800 Replace_Target_Name (New_RHS);
1802 -- Generate:
1803 -- T : LHS_Typ := LHS;
1805 Insert_Before_And_Analyze (N,
1806 Make_Object_Declaration (Loc,
1807 Defining_Identifier => Ent,
1808 Object_Definition => New_Occurrence_Of (LHS_Typ, Loc),
1809 Expression => New_Copy_Tree (LHS)));
1811 -- Generate:
1812 -- LHS := ... T ...;
1814 Rewrite (N,
1815 Make_Assignment_Statement (Loc,
1816 Name => Relocate_Node (LHS),
1817 Expression => New_RHS));
1819 -- Otherwise wrap the whole assignment statement in a procedure with an
1820 -- IN OUT parameter. The original assignment then becomes a call to the
1821 -- procedure with the left-hand side as an actual.
1823 else
1824 Ent := Make_Temporary (Loc, 'T');
1825 Replace_Target_Name (New_RHS);
1827 -- Generate:
1828 -- procedure P (T : in out LHS_Typ) is
1829 -- begin
1830 -- T := ... T ...;
1831 -- end P;
1833 Proc_Id := Make_Temporary (Loc, 'P');
1835 Insert_Before_And_Analyze (N,
1836 Make_Subprogram_Body (Loc,
1837 Specification =>
1838 Make_Procedure_Specification (Loc,
1839 Defining_Unit_Name => Proc_Id,
1840 Parameter_Specifications => New_List (
1841 Make_Parameter_Specification (Loc,
1842 Defining_Identifier => Ent,
1843 In_Present => True,
1844 Out_Present => True,
1845 Parameter_Type =>
1846 New_Occurrence_Of (LHS_Typ, Loc)))),
1848 Declarations => Empty_List,
1850 Handled_Statement_Sequence =>
1851 Make_Handled_Sequence_Of_Statements (Loc,
1852 Statements => New_List (
1853 Make_Assignment_Statement (Loc,
1854 Name => New_Occurrence_Of (Ent, Loc),
1855 Expression => New_RHS)))));
1857 -- Generate:
1858 -- P (LHS);
1860 Rewrite (N,
1861 Make_Procedure_Call_Statement (Loc,
1862 Name => New_Occurrence_Of (Proc_Id, Loc),
1863 Parameter_Associations => New_List (Relocate_Node (LHS))));
1864 end if;
1866 -- Analyze rewritten node, either as assignment or procedure call
1868 Analyze (N);
1869 end Expand_Assign_With_Target_Names;
1871 -----------------------------------
1872 -- Expand_N_Assignment_Statement --
1873 -----------------------------------
1875 -- This procedure implements various cases where an assignment statement
1876 -- cannot just be passed on to the back end in untransformed state.
1878 procedure Expand_N_Assignment_Statement (N : Node_Id) is
1879 Crep : constant Boolean := Change_Of_Representation (N);
1880 Lhs : constant Node_Id := Name (N);
1881 Loc : constant Source_Ptr := Sloc (N);
1882 Rhs : constant Node_Id := Expression (N);
1883 Typ : constant Entity_Id := Underlying_Type (Etype (Lhs));
1884 Exp : Node_Id;
1886 begin
1887 -- Special case to check right away, if the Componentwise_Assignment
1888 -- flag is set, this is a reanalysis from the expansion of the primitive
1889 -- assignment procedure for a tagged type, and all we need to do is to
1890 -- expand to assignment of components, because otherwise, we would get
1891 -- infinite recursion (since this looks like a tagged assignment which
1892 -- would normally try to *call* the primitive assignment procedure).
1894 if Componentwise_Assignment (N) then
1895 Expand_Assign_Record (N);
1896 return;
1897 end if;
1899 -- Defend against invalid subscripts on left side if we are in standard
1900 -- validity checking mode. No need to do this if we are checking all
1901 -- subscripts.
1903 -- Note that we do this right away, because there are some early return
1904 -- paths in this procedure, and this is required on all paths.
1906 if Validity_Checks_On
1907 and then Validity_Check_Default
1908 and then not Validity_Check_Subscripts
1909 then
1910 Check_Valid_Lvalue_Subscripts (Lhs);
1911 end if;
1913 -- Separate expansion if RHS contain target names. Note that assignment
1914 -- may already have been expanded if RHS is aggregate.
1916 if Nkind (N) = N_Assignment_Statement and then Has_Target_Names (N) then
1917 Expand_Assign_With_Target_Names (N);
1918 return;
1919 end if;
1921 -- Ada 2005 (AI-327): Handle assignment to priority of protected object
1923 -- Rewrite an assignment to X'Priority into a run-time call
1925 -- For example: X'Priority := New_Prio_Expr;
1926 -- ...is expanded into Set_Ceiling (X._Object, New_Prio_Expr);
1928 -- Note that although X'Priority is notionally an object, it is quite
1929 -- deliberately not defined as an aliased object in the RM. This means
1930 -- that it works fine to rewrite it as a call, without having to worry
1931 -- about complications that would other arise from X'Priority'Access,
1932 -- which is illegal, because of the lack of aliasing.
1934 if Ada_Version >= Ada_2005 then
1935 declare
1936 Call : Node_Id;
1937 Conctyp : Entity_Id;
1938 Ent : Entity_Id;
1939 Subprg : Entity_Id;
1940 RT_Subprg_Name : Node_Id;
1942 begin
1943 -- Handle chains of renamings
1945 Ent := Name (N);
1946 while Nkind (Ent) in N_Has_Entity
1947 and then Present (Entity (Ent))
1948 and then Present (Renamed_Object (Entity (Ent)))
1949 loop
1950 Ent := Renamed_Object (Entity (Ent));
1951 end loop;
1953 -- The attribute Priority applied to protected objects has been
1954 -- previously expanded into a call to the Get_Ceiling run-time
1955 -- subprogram. In restricted profiles this is not available.
1957 if Is_Expanded_Priority_Attribute (Ent) then
1959 -- Look for the enclosing concurrent type
1961 Conctyp := Current_Scope;
1962 while not Is_Concurrent_Type (Conctyp) loop
1963 Conctyp := Scope (Conctyp);
1964 end loop;
1966 pragma Assert (Is_Protected_Type (Conctyp));
1968 -- Generate the first actual of the call
1970 Subprg := Current_Scope;
1971 while not Present (Protected_Body_Subprogram (Subprg)) loop
1972 Subprg := Scope (Subprg);
1973 end loop;
1975 -- Select the appropriate run-time call
1977 if Number_Entries (Conctyp) = 0 then
1978 RT_Subprg_Name :=
1979 New_Occurrence_Of (RTE (RE_Set_Ceiling), Loc);
1980 else
1981 RT_Subprg_Name :=
1982 New_Occurrence_Of (RTE (RO_PE_Set_Ceiling), Loc);
1983 end if;
1985 Call :=
1986 Make_Procedure_Call_Statement (Loc,
1987 Name => RT_Subprg_Name,
1988 Parameter_Associations => New_List (
1989 New_Copy_Tree (First (Parameter_Associations (Ent))),
1990 Relocate_Node (Expression (N))));
1992 Rewrite (N, Call);
1993 Analyze (N);
1995 return;
1996 end if;
1997 end;
1998 end if;
2000 -- Deal with assignment checks unless suppressed
2002 if not Suppress_Assignment_Checks (N) then
2004 -- First deal with generation of range check if required
2006 if Do_Range_Check (Rhs) then
2007 Generate_Range_Check (Rhs, Typ, CE_Range_Check_Failed);
2008 end if;
2010 -- Then generate predicate check if required
2012 Apply_Predicate_Check (Rhs, Typ);
2013 end if;
2015 -- Check for a special case where a high level transformation is
2016 -- required. If we have either of:
2018 -- P.field := rhs;
2019 -- P (sub) := rhs;
2021 -- where P is a reference to a bit packed array, then we have to unwind
2022 -- the assignment. The exact meaning of being a reference to a bit
2023 -- packed array is as follows:
2025 -- An indexed component whose prefix is a bit packed array is a
2026 -- reference to a bit packed array.
2028 -- An indexed component or selected component whose prefix is a
2029 -- reference to a bit packed array is itself a reference ot a
2030 -- bit packed array.
2032 -- The required transformation is
2034 -- Tnn : prefix_type := P;
2035 -- Tnn.field := rhs;
2036 -- P := Tnn;
2038 -- or
2040 -- Tnn : prefix_type := P;
2041 -- Tnn (subscr) := rhs;
2042 -- P := Tnn;
2044 -- Since P is going to be evaluated more than once, any subscripts
2045 -- in P must have their evaluation forced.
2047 if Nkind_In (Lhs, N_Indexed_Component, N_Selected_Component)
2048 and then Is_Ref_To_Bit_Packed_Array (Prefix (Lhs))
2049 then
2050 declare
2051 BPAR_Expr : constant Node_Id := Relocate_Node (Prefix (Lhs));
2052 BPAR_Typ : constant Entity_Id := Etype (BPAR_Expr);
2053 Tnn : constant Entity_Id :=
2054 Make_Temporary (Loc, 'T', BPAR_Expr);
2056 begin
2057 -- Insert the post assignment first, because we want to copy the
2058 -- BPAR_Expr tree before it gets analyzed in the context of the
2059 -- pre assignment. Note that we do not analyze the post assignment
2060 -- yet (we cannot till we have completed the analysis of the pre
2061 -- assignment). As usual, the analysis of this post assignment
2062 -- will happen on its own when we "run into" it after finishing
2063 -- the current assignment.
2065 Insert_After (N,
2066 Make_Assignment_Statement (Loc,
2067 Name => New_Copy_Tree (BPAR_Expr),
2068 Expression => New_Occurrence_Of (Tnn, Loc)));
2070 -- At this stage BPAR_Expr is a reference to a bit packed array
2071 -- where the reference was not expanded in the original tree,
2072 -- since it was on the left side of an assignment. But in the
2073 -- pre-assignment statement (the object definition), BPAR_Expr
2074 -- will end up on the right-hand side, and must be reexpanded. To
2075 -- achieve this, we reset the analyzed flag of all selected and
2076 -- indexed components down to the actual indexed component for
2077 -- the packed array.
2079 Exp := BPAR_Expr;
2080 loop
2081 Set_Analyzed (Exp, False);
2083 if Nkind_In (Exp, N_Indexed_Component,
2084 N_Selected_Component)
2085 then
2086 Exp := Prefix (Exp);
2087 else
2088 exit;
2089 end if;
2090 end loop;
2092 -- Now we can insert and analyze the pre-assignment
2094 -- If the right-hand side requires a transient scope, it has
2095 -- already been placed on the stack. However, the declaration is
2096 -- inserted in the tree outside of this scope, and must reflect
2097 -- the proper scope for its variable. This awkward bit is forced
2098 -- by the stricter scope discipline imposed by GCC 2.97.
2100 declare
2101 Uses_Transient_Scope : constant Boolean :=
2102 Scope_Is_Transient
2103 and then N = Node_To_Be_Wrapped;
2105 begin
2106 if Uses_Transient_Scope then
2107 Push_Scope (Scope (Current_Scope));
2108 end if;
2110 Insert_Before_And_Analyze (N,
2111 Make_Object_Declaration (Loc,
2112 Defining_Identifier => Tnn,
2113 Object_Definition => New_Occurrence_Of (BPAR_Typ, Loc),
2114 Expression => BPAR_Expr));
2116 if Uses_Transient_Scope then
2117 Pop_Scope;
2118 end if;
2119 end;
2121 -- Now fix up the original assignment and continue processing
2123 Rewrite (Prefix (Lhs),
2124 New_Occurrence_Of (Tnn, Loc));
2126 -- We do not need to reanalyze that assignment, and we do not need
2127 -- to worry about references to the temporary, but we do need to
2128 -- make sure that the temporary is not marked as a true constant
2129 -- since we now have a generated assignment to it.
2131 Set_Is_True_Constant (Tnn, False);
2132 end;
2133 end if;
2135 -- When we have the appropriate type of aggregate in the expression (it
2136 -- has been determined during analysis of the aggregate by setting the
2137 -- delay flag), let's perform in place assignment and thus avoid
2138 -- creating a temporary.
2140 if Is_Delayed_Aggregate (Rhs) then
2141 Convert_Aggr_In_Assignment (N);
2142 Rewrite (N, Make_Null_Statement (Loc));
2143 Analyze (N);
2145 return;
2146 end if;
2148 -- Apply discriminant check if required. If Lhs is an access type to a
2149 -- designated type with discriminants, we must always check. If the
2150 -- type has unknown discriminants, more elaborate processing below.
2152 if Has_Discriminants (Etype (Lhs))
2153 and then not Has_Unknown_Discriminants (Etype (Lhs))
2154 then
2155 -- Skip discriminant check if change of representation. Will be
2156 -- done when the change of representation is expanded out.
2158 if not Crep then
2159 Apply_Discriminant_Check (Rhs, Etype (Lhs), Lhs);
2160 end if;
2162 -- If the type is private without discriminants, and the full type
2163 -- has discriminants (necessarily with defaults) a check may still be
2164 -- necessary if the Lhs is aliased. The private discriminants must be
2165 -- visible to build the discriminant constraints.
2167 -- Only an explicit dereference that comes from source indicates
2168 -- aliasing. Access to formals of protected operations and entries
2169 -- create dereferences but are not semantic aliasings.
2171 elsif Is_Private_Type (Etype (Lhs))
2172 and then Has_Discriminants (Typ)
2173 and then Nkind (Lhs) = N_Explicit_Dereference
2174 and then Comes_From_Source (Lhs)
2175 then
2176 declare
2177 Lt : constant Entity_Id := Etype (Lhs);
2178 Ubt : Entity_Id := Base_Type (Typ);
2180 begin
2181 -- In the case of an expander-generated record subtype whose base
2182 -- type still appears private, Typ will have been set to that
2183 -- private type rather than the underlying record type (because
2184 -- Underlying type will have returned the record subtype), so it's
2185 -- necessary to apply Underlying_Type again to the base type to
2186 -- get the record type we need for the discriminant check. Such
2187 -- subtypes can be created for assignments in certain cases, such
2188 -- as within an instantiation passed this kind of private type.
2189 -- It would be good to avoid this special test, but making changes
2190 -- to prevent this odd form of record subtype seems difficult. ???
2192 if Is_Private_Type (Ubt) then
2193 Ubt := Underlying_Type (Ubt);
2194 end if;
2196 Set_Etype (Lhs, Ubt);
2197 Rewrite (Rhs, OK_Convert_To (Base_Type (Ubt), Rhs));
2198 Apply_Discriminant_Check (Rhs, Ubt, Lhs);
2199 Set_Etype (Lhs, Lt);
2200 end;
2202 -- If the Lhs has a private type with unknown discriminants, it may
2203 -- have a full view with discriminants, but those are nameable only
2204 -- in the underlying type, so convert the Rhs to it before potential
2205 -- checking. Convert Lhs as well, otherwise the actual subtype might
2206 -- not be constructible. If the discriminants have defaults the type
2207 -- is unconstrained and there is nothing to check.
2209 elsif Has_Unknown_Discriminants (Base_Type (Etype (Lhs)))
2210 and then Has_Discriminants (Typ)
2211 and then not Has_Defaulted_Discriminants (Typ)
2212 then
2213 Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
2214 Rewrite (Lhs, OK_Convert_To (Base_Type (Typ), Lhs));
2215 Apply_Discriminant_Check (Rhs, Typ, Lhs);
2217 -- In the access type case, we need the same discriminant check, and
2218 -- also range checks if we have an access to constrained array.
2220 elsif Is_Access_Type (Etype (Lhs))
2221 and then Is_Constrained (Designated_Type (Etype (Lhs)))
2222 then
2223 if Has_Discriminants (Designated_Type (Etype (Lhs))) then
2225 -- Skip discriminant check if change of representation. Will be
2226 -- done when the change of representation is expanded out.
2228 if not Crep then
2229 Apply_Discriminant_Check (Rhs, Etype (Lhs));
2230 end if;
2232 elsif Is_Array_Type (Designated_Type (Etype (Lhs))) then
2233 Apply_Range_Check (Rhs, Etype (Lhs));
2235 if Is_Constrained (Etype (Lhs)) then
2236 Apply_Length_Check (Rhs, Etype (Lhs));
2237 end if;
2239 if Nkind (Rhs) = N_Allocator then
2240 declare
2241 Target_Typ : constant Entity_Id := Etype (Expression (Rhs));
2242 C_Es : Check_Result;
2244 begin
2245 C_Es :=
2246 Get_Range_Checks
2247 (Lhs,
2248 Target_Typ,
2249 Etype (Designated_Type (Etype (Lhs))));
2251 Insert_Range_Checks
2252 (C_Es,
2254 Target_Typ,
2255 Sloc (Lhs),
2256 Lhs);
2257 end;
2258 end if;
2259 end if;
2261 -- Apply range check for access type case
2263 elsif Is_Access_Type (Etype (Lhs))
2264 and then Nkind (Rhs) = N_Allocator
2265 and then Nkind (Expression (Rhs)) = N_Qualified_Expression
2266 then
2267 Analyze_And_Resolve (Expression (Rhs));
2268 Apply_Range_Check
2269 (Expression (Rhs), Designated_Type (Etype (Lhs)));
2270 end if;
2272 -- Ada 2005 (AI-231): Generate the run-time check
2274 if Is_Access_Type (Typ)
2275 and then Can_Never_Be_Null (Etype (Lhs))
2276 and then not Can_Never_Be_Null (Etype (Rhs))
2278 -- If an actual is an out parameter of a null-excluding access
2279 -- type, there is access check on entry, so we set the flag
2280 -- Suppress_Assignment_Checks on the generated statement to
2281 -- assign the actual to the parameter block, and we do not want
2282 -- to generate an additional check at this point.
2284 and then not Suppress_Assignment_Checks (N)
2285 then
2286 Apply_Constraint_Check (Rhs, Etype (Lhs));
2287 end if;
2289 -- Ada 2012 (AI05-148): Update current accessibility level if Rhs is a
2290 -- stand-alone obj of an anonymous access type. Do not install the check
2291 -- when the Lhs denotes a container cursor and the Next function employs
2292 -- an access type, because this can never result in a dangling pointer.
2294 if Is_Access_Type (Typ)
2295 and then Is_Entity_Name (Lhs)
2296 and then Ekind (Entity (Lhs)) /= E_Loop_Parameter
2297 and then Present (Effective_Extra_Accessibility (Entity (Lhs)))
2298 then
2299 declare
2300 function Lhs_Entity return Entity_Id;
2301 -- Look through renames to find the underlying entity.
2302 -- For assignment to a rename, we don't care about the
2303 -- Enclosing_Dynamic_Scope of the rename declaration.
2305 ----------------
2306 -- Lhs_Entity --
2307 ----------------
2309 function Lhs_Entity return Entity_Id is
2310 Result : Entity_Id := Entity (Lhs);
2312 begin
2313 while Present (Renamed_Object (Result)) loop
2315 -- Renamed_Object must return an Entity_Name here
2316 -- because of preceding "Present (E_E_A (...))" test.
2318 Result := Entity (Renamed_Object (Result));
2319 end loop;
2321 return Result;
2322 end Lhs_Entity;
2324 -- Local Declarations
2326 Access_Check : constant Node_Id :=
2327 Make_Raise_Program_Error (Loc,
2328 Condition =>
2329 Make_Op_Gt (Loc,
2330 Left_Opnd =>
2331 Dynamic_Accessibility_Level (Rhs),
2332 Right_Opnd =>
2333 Make_Integer_Literal (Loc,
2334 Intval =>
2335 Scope_Depth
2336 (Enclosing_Dynamic_Scope
2337 (Lhs_Entity)))),
2338 Reason => PE_Accessibility_Check_Failed);
2340 Access_Level_Update : constant Node_Id :=
2341 Make_Assignment_Statement (Loc,
2342 Name =>
2343 New_Occurrence_Of
2344 (Effective_Extra_Accessibility
2345 (Entity (Lhs)), Loc),
2346 Expression =>
2347 Dynamic_Accessibility_Level (Rhs));
2349 begin
2350 if not Accessibility_Checks_Suppressed (Entity (Lhs)) then
2351 Insert_Action (N, Access_Check);
2352 end if;
2354 Insert_Action (N, Access_Level_Update);
2355 end;
2356 end if;
2358 -- Case of assignment to a bit packed array element. If there is a
2359 -- change of representation this must be expanded into components,
2360 -- otherwise this is a bit-field assignment.
2362 if Nkind (Lhs) = N_Indexed_Component
2363 and then Is_Bit_Packed_Array (Etype (Prefix (Lhs)))
2364 then
2365 -- Normal case, no change of representation
2367 if not Crep then
2368 Expand_Bit_Packed_Element_Set (N);
2369 return;
2371 -- Change of representation case
2373 else
2374 -- Generate the following, to force component-by-component
2375 -- assignments in an efficient way. Otherwise each component
2376 -- will require a temporary and two bit-field manipulations.
2378 -- T1 : Elmt_Type;
2379 -- T1 := RhS;
2380 -- Lhs := T1;
2382 declare
2383 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T');
2384 Stats : List_Id;
2386 begin
2387 Stats :=
2388 New_List (
2389 Make_Object_Declaration (Loc,
2390 Defining_Identifier => Tnn,
2391 Object_Definition =>
2392 New_Occurrence_Of (Etype (Lhs), Loc)),
2393 Make_Assignment_Statement (Loc,
2394 Name => New_Occurrence_Of (Tnn, Loc),
2395 Expression => Relocate_Node (Rhs)),
2396 Make_Assignment_Statement (Loc,
2397 Name => Relocate_Node (Lhs),
2398 Expression => New_Occurrence_Of (Tnn, Loc)));
2400 Insert_Actions (N, Stats);
2401 Rewrite (N, Make_Null_Statement (Loc));
2402 Analyze (N);
2403 end;
2404 end if;
2406 -- Build-in-place function call case. This is for assignment statements
2407 -- that come from aggregate component associations or from init procs.
2408 -- User-written assignment statements with b-i-p calls are handled
2409 -- elsewhere.
2411 elsif Is_Build_In_Place_Function_Call (Rhs) then
2412 pragma Assert (not Comes_From_Source (N));
2413 Make_Build_In_Place_Call_In_Assignment (N, Rhs);
2415 elsif Is_Tagged_Type (Typ)
2416 or else (Needs_Finalization (Typ) and then not Is_Array_Type (Typ))
2417 then
2418 Tagged_Case : declare
2419 L : List_Id := No_List;
2420 Expand_Ctrl_Actions : constant Boolean := not No_Ctrl_Actions (N);
2422 begin
2423 -- In the controlled case, we ensure that function calls are
2424 -- evaluated before finalizing the target. In all cases, it makes
2425 -- the expansion easier if the side effects are removed first.
2427 Remove_Side_Effects (Lhs);
2428 Remove_Side_Effects (Rhs);
2430 -- Avoid recursion in the mechanism
2432 Set_Analyzed (N);
2434 -- If dispatching assignment, we need to dispatch to _assign
2436 if Is_Class_Wide_Type (Typ)
2438 -- If the type is tagged, we may as well use the predefined
2439 -- primitive assignment. This avoids inlining a lot of code
2440 -- and in the class-wide case, the assignment is replaced
2441 -- by a dispatching call to _assign. It is suppressed in the
2442 -- case of assignments created by the expander that correspond
2443 -- to initializations, where we do want to copy the tag
2444 -- (Expand_Ctrl_Actions flag is set False in this case). It is
2445 -- also suppressed if restriction No_Dispatching_Calls is in
2446 -- force because in that case predefined primitives are not
2447 -- generated.
2449 or else (Is_Tagged_Type (Typ)
2450 and then Chars (Current_Scope) /= Name_uAssign
2451 and then Expand_Ctrl_Actions
2452 and then
2453 not Restriction_Active (No_Dispatching_Calls))
2454 then
2455 if Is_Limited_Type (Typ) then
2457 -- This can happen in an instance when the formal is an
2458 -- extension of a limited interface, and the actual is
2459 -- limited. This is an error according to AI05-0087, but
2460 -- is not caught at the point of instantiation in earlier
2461 -- versions.
2463 -- This is wrong, error messages cannot be issued during
2464 -- expansion, since they would be missed in -gnatc mode ???
2466 Error_Msg_N ("assignment not available on limited type", N);
2467 return;
2468 end if;
2470 -- Fetch the primitive op _assign and proper type to call it.
2471 -- Because of possible conflicts between private and full view,
2472 -- fetch the proper type directly from the operation profile.
2474 declare
2475 Op : constant Entity_Id :=
2476 Find_Prim_Op (Typ, Name_uAssign);
2477 F_Typ : Entity_Id := Etype (First_Formal (Op));
2479 begin
2480 -- If the assignment is dispatching, make sure to use the
2481 -- proper type.
2483 if Is_Class_Wide_Type (Typ) then
2484 F_Typ := Class_Wide_Type (F_Typ);
2485 end if;
2487 L := New_List;
2489 -- In case of assignment to a class-wide tagged type, before
2490 -- the assignment we generate run-time check to ensure that
2491 -- the tags of source and target match.
2493 if not Tag_Checks_Suppressed (Typ)
2494 and then Is_Class_Wide_Type (Typ)
2495 and then Is_Tagged_Type (Typ)
2496 and then Is_Tagged_Type (Underlying_Type (Etype (Rhs)))
2497 then
2498 declare
2499 Lhs_Tag : Node_Id;
2500 Rhs_Tag : Node_Id;
2502 begin
2503 if not Is_Interface (Typ) then
2504 Lhs_Tag :=
2505 Make_Selected_Component (Loc,
2506 Prefix => Duplicate_Subexpr (Lhs),
2507 Selector_Name =>
2508 Make_Identifier (Loc, Name_uTag));
2509 Rhs_Tag :=
2510 Make_Selected_Component (Loc,
2511 Prefix => Duplicate_Subexpr (Rhs),
2512 Selector_Name =>
2513 Make_Identifier (Loc, Name_uTag));
2514 else
2515 -- Displace the pointer to the base of the objects
2516 -- applying 'Address, which is later expanded into
2517 -- a call to RE_Base_Address.
2519 Lhs_Tag :=
2520 Make_Explicit_Dereference (Loc,
2521 Prefix =>
2522 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
2523 Make_Attribute_Reference (Loc,
2524 Prefix => Duplicate_Subexpr (Lhs),
2525 Attribute_Name => Name_Address)));
2526 Rhs_Tag :=
2527 Make_Explicit_Dereference (Loc,
2528 Prefix =>
2529 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
2530 Make_Attribute_Reference (Loc,
2531 Prefix => Duplicate_Subexpr (Rhs),
2532 Attribute_Name => Name_Address)));
2533 end if;
2535 Append_To (L,
2536 Make_Raise_Constraint_Error (Loc,
2537 Condition =>
2538 Make_Op_Ne (Loc,
2539 Left_Opnd => Lhs_Tag,
2540 Right_Opnd => Rhs_Tag),
2541 Reason => CE_Tag_Check_Failed));
2542 end;
2543 end if;
2545 declare
2546 Left_N : Node_Id := Duplicate_Subexpr (Lhs);
2547 Right_N : Node_Id := Duplicate_Subexpr (Rhs);
2549 begin
2550 -- In order to dispatch the call to _assign the type of
2551 -- the actuals must match. Add conversion (if required).
2553 if Etype (Lhs) /= F_Typ then
2554 Left_N := Unchecked_Convert_To (F_Typ, Left_N);
2555 end if;
2557 if Etype (Rhs) /= F_Typ then
2558 Right_N := Unchecked_Convert_To (F_Typ, Right_N);
2559 end if;
2561 Append_To (L,
2562 Make_Procedure_Call_Statement (Loc,
2563 Name => New_Occurrence_Of (Op, Loc),
2564 Parameter_Associations => New_List (
2565 Node1 => Left_N,
2566 Node2 => Right_N)));
2567 end;
2568 end;
2570 else
2571 L := Make_Tag_Ctrl_Assignment (N);
2573 -- We can't afford to have destructive Finalization Actions in
2574 -- the Self assignment case, so if the target and the source
2575 -- are not obviously different, code is generated to avoid the
2576 -- self assignment case:
2578 -- if lhs'address /= rhs'address then
2579 -- <code for controlled and/or tagged assignment>
2580 -- end if;
2582 -- Skip this if Restriction (No_Finalization) is active
2584 if not Statically_Different (Lhs, Rhs)
2585 and then Expand_Ctrl_Actions
2586 and then not Restriction_Active (No_Finalization)
2587 then
2588 L := New_List (
2589 Make_Implicit_If_Statement (N,
2590 Condition =>
2591 Make_Op_Ne (Loc,
2592 Left_Opnd =>
2593 Make_Attribute_Reference (Loc,
2594 Prefix => Duplicate_Subexpr (Lhs),
2595 Attribute_Name => Name_Address),
2597 Right_Opnd =>
2598 Make_Attribute_Reference (Loc,
2599 Prefix => Duplicate_Subexpr (Rhs),
2600 Attribute_Name => Name_Address)),
2602 Then_Statements => L));
2603 end if;
2605 -- We need to set up an exception handler for implementing
2606 -- 7.6.1(18). The remaining adjustments are tackled by the
2607 -- implementation of adjust for record_controllers (see
2608 -- s-finimp.adb).
2610 -- This is skipped if we have no finalization
2612 if Expand_Ctrl_Actions
2613 and then not Restriction_Active (No_Finalization)
2614 then
2615 L := New_List (
2616 Make_Block_Statement (Loc,
2617 Handled_Statement_Sequence =>
2618 Make_Handled_Sequence_Of_Statements (Loc,
2619 Statements => L,
2620 Exception_Handlers => New_List (
2621 Make_Handler_For_Ctrl_Operation (Loc)))));
2622 end if;
2623 end if;
2625 Rewrite (N,
2626 Make_Block_Statement (Loc,
2627 Handled_Statement_Sequence =>
2628 Make_Handled_Sequence_Of_Statements (Loc, Statements => L)));
2630 -- If no restrictions on aborts, protect the whole assignment
2631 -- for controlled objects as per 9.8(11).
2633 if Needs_Finalization (Typ)
2634 and then Expand_Ctrl_Actions
2635 and then Abort_Allowed
2636 then
2637 declare
2638 Blk : constant Entity_Id :=
2639 New_Internal_Entity
2640 (E_Block, Current_Scope, Sloc (N), 'B');
2641 AUD : constant Entity_Id := RTE (RE_Abort_Undefer_Direct);
2643 begin
2644 Set_Is_Abort_Block (N);
2646 Set_Scope (Blk, Current_Scope);
2647 Set_Etype (Blk, Standard_Void_Type);
2648 Set_Identifier (N, New_Occurrence_Of (Blk, Sloc (N)));
2650 Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
2651 Set_At_End_Proc (Handled_Statement_Sequence (N),
2652 New_Occurrence_Of (AUD, Loc));
2654 -- Present the Abort_Undefer_Direct function to the backend
2655 -- so that it can inline the call to the function.
2657 Add_Inlined_Body (AUD, N);
2659 Expand_At_End_Handler
2660 (Handled_Statement_Sequence (N), Blk);
2661 end;
2662 end if;
2664 -- N has been rewritten to a block statement for which it is
2665 -- known by construction that no checks are necessary: analyze
2666 -- it with all checks suppressed.
2668 Analyze (N, Suppress => All_Checks);
2669 return;
2670 end Tagged_Case;
2672 -- Array types
2674 elsif Is_Array_Type (Typ) then
2675 declare
2676 Actual_Rhs : Node_Id := Rhs;
2678 begin
2679 while Nkind_In (Actual_Rhs, N_Type_Conversion,
2680 N_Qualified_Expression)
2681 loop
2682 Actual_Rhs := Expression (Actual_Rhs);
2683 end loop;
2685 Expand_Assign_Array (N, Actual_Rhs);
2686 return;
2687 end;
2689 -- Record types
2691 elsif Is_Record_Type (Typ) then
2692 Expand_Assign_Record (N);
2693 return;
2695 -- Scalar types. This is where we perform the processing related to the
2696 -- requirements of (RM 13.9.1(9-11)) concerning the handling of invalid
2697 -- scalar values.
2699 elsif Is_Scalar_Type (Typ) then
2701 -- Case where right side is known valid
2703 if Expr_Known_Valid (Rhs) then
2705 -- Here the right side is valid, so it is fine. The case to deal
2706 -- with is when the left side is a local variable reference whose
2707 -- value is not currently known to be valid. If this is the case,
2708 -- and the assignment appears in an unconditional context, then
2709 -- we can mark the left side as now being valid if one of these
2710 -- conditions holds:
2712 -- The expression of the right side has Do_Range_Check set so
2713 -- that we know a range check will be performed. Note that it
2714 -- can be the case that a range check is omitted because we
2715 -- make the assumption that we can assume validity for operands
2716 -- appearing in the right side in determining whether a range
2717 -- check is required
2719 -- The subtype of the right side matches the subtype of the
2720 -- left side. In this case, even though we have not checked
2721 -- the range of the right side, we know it is in range of its
2722 -- subtype if the expression is valid.
2724 if Is_Local_Variable_Reference (Lhs)
2725 and then not Is_Known_Valid (Entity (Lhs))
2726 and then In_Unconditional_Context (N)
2727 then
2728 if Do_Range_Check (Rhs)
2729 or else Etype (Lhs) = Etype (Rhs)
2730 then
2731 Set_Is_Known_Valid (Entity (Lhs), True);
2732 end if;
2733 end if;
2735 -- Case where right side may be invalid in the sense of the RM
2736 -- reference above. The RM does not require that we check for the
2737 -- validity on an assignment, but it does require that the assignment
2738 -- of an invalid value not cause erroneous behavior.
2740 -- The general approach in GNAT is to use the Is_Known_Valid flag
2741 -- to avoid the need for validity checking on assignments. However
2742 -- in some cases, we have to do validity checking in order to make
2743 -- sure that the setting of this flag is correct.
2745 else
2746 -- Validate right side if we are validating copies
2748 if Validity_Checks_On
2749 and then Validity_Check_Copies
2750 then
2751 -- Skip this if left-hand side is an array or record component
2752 -- and elementary component validity checks are suppressed.
2754 if Nkind_In (Lhs, N_Selected_Component, N_Indexed_Component)
2755 and then not Validity_Check_Components
2756 then
2757 null;
2758 else
2759 Ensure_Valid (Rhs);
2760 end if;
2762 -- We can propagate this to the left side where appropriate
2764 if Is_Local_Variable_Reference (Lhs)
2765 and then not Is_Known_Valid (Entity (Lhs))
2766 and then In_Unconditional_Context (N)
2767 then
2768 Set_Is_Known_Valid (Entity (Lhs), True);
2769 end if;
2771 -- Otherwise check to see what should be done
2773 -- If left side is a local variable, then we just set its flag to
2774 -- indicate that its value may no longer be valid, since we are
2775 -- copying a potentially invalid value.
2777 elsif Is_Local_Variable_Reference (Lhs) then
2778 Set_Is_Known_Valid (Entity (Lhs), False);
2780 -- Check for case of a nonlocal variable on the left side which
2781 -- is currently known to be valid. In this case, we simply ensure
2782 -- that the right side is valid. We only play the game of copying
2783 -- validity status for local variables, since we are doing this
2784 -- statically, not by tracing the full flow graph.
2786 elsif Is_Entity_Name (Lhs)
2787 and then Is_Known_Valid (Entity (Lhs))
2788 then
2789 -- Note: If Validity_Checking mode is set to none, we ignore
2790 -- the Ensure_Valid call so don't worry about that case here.
2792 Ensure_Valid (Rhs);
2794 -- In all other cases, we can safely copy an invalid value without
2795 -- worrying about the status of the left side. Since it is not a
2796 -- variable reference it will not be considered
2797 -- as being known to be valid in any case.
2799 else
2800 null;
2801 end if;
2802 end if;
2803 end if;
2805 exception
2806 when RE_Not_Available =>
2807 return;
2808 end Expand_N_Assignment_Statement;
2810 ------------------------------
2811 -- Expand_N_Block_Statement --
2812 ------------------------------
2814 -- Encode entity names defined in block statement
2816 procedure Expand_N_Block_Statement (N : Node_Id) is
2817 begin
2818 Qualify_Entity_Names (N);
2819 end Expand_N_Block_Statement;
2821 -----------------------------
2822 -- Expand_N_Case_Statement --
2823 -----------------------------
2825 procedure Expand_N_Case_Statement (N : Node_Id) is
2826 Loc : constant Source_Ptr := Sloc (N);
2827 Expr : constant Node_Id := Expression (N);
2828 Alt : Node_Id;
2829 Len : Nat;
2830 Cond : Node_Id;
2831 Choice : Node_Id;
2832 Chlist : List_Id;
2834 begin
2835 -- Check for the situation where we know at compile time which branch
2836 -- will be taken.
2838 -- If the value is static but its subtype is predicated and the value
2839 -- does not obey the predicate, the value is marked non-static, and
2840 -- there can be no corresponding static alternative. In that case we
2841 -- replace the case statement with an exception, regardless of whether
2842 -- assertions are enabled or not, unless predicates are ignored.
2844 if Compile_Time_Known_Value (Expr)
2845 and then Has_Predicates (Etype (Expr))
2846 and then not Predicates_Ignored (Etype (Expr))
2847 and then not Is_OK_Static_Expression (Expr)
2848 then
2849 Rewrite (N,
2850 Make_Raise_Constraint_Error (Loc, Reason => CE_Invalid_Data));
2851 Analyze (N);
2852 return;
2854 elsif Compile_Time_Known_Value (Expr)
2855 and then (not Has_Predicates (Etype (Expr))
2856 or else Is_Static_Expression (Expr))
2857 then
2858 Alt := Find_Static_Alternative (N);
2860 -- Do not consider controlled objects found in a case statement which
2861 -- actually models a case expression because their early finalization
2862 -- will affect the result of the expression.
2864 if not From_Conditional_Expression (N) then
2865 Process_Statements_For_Controlled_Objects (Alt);
2866 end if;
2868 -- Move statements from this alternative after the case statement.
2869 -- They are already analyzed, so will be skipped by the analyzer.
2871 Insert_List_After (N, Statements (Alt));
2873 -- That leaves the case statement as a shell. So now we can kill all
2874 -- other alternatives in the case statement.
2876 Kill_Dead_Code (Expression (N));
2878 declare
2879 Dead_Alt : Node_Id;
2881 begin
2882 -- Loop through case alternatives, skipping pragmas, and skipping
2883 -- the one alternative that we select (and therefore retain).
2885 Dead_Alt := First (Alternatives (N));
2886 while Present (Dead_Alt) loop
2887 if Dead_Alt /= Alt
2888 and then Nkind (Dead_Alt) = N_Case_Statement_Alternative
2889 then
2890 Kill_Dead_Code (Statements (Dead_Alt), Warn_On_Deleted_Code);
2891 end if;
2893 Next (Dead_Alt);
2894 end loop;
2895 end;
2897 Rewrite (N, Make_Null_Statement (Loc));
2898 return;
2899 end if;
2901 -- Here if the choice is not determined at compile time
2903 declare
2904 Last_Alt : constant Node_Id := Last (Alternatives (N));
2906 Others_Present : Boolean;
2907 Others_Node : Node_Id;
2909 Then_Stms : List_Id;
2910 Else_Stms : List_Id;
2912 begin
2913 if Nkind (First (Discrete_Choices (Last_Alt))) = N_Others_Choice then
2914 Others_Present := True;
2915 Others_Node := Last_Alt;
2916 else
2917 Others_Present := False;
2918 end if;
2920 -- First step is to worry about possible invalid argument. The RM
2921 -- requires (RM 5.4(13)) that if the result is invalid (e.g. it is
2922 -- outside the base range), then Constraint_Error must be raised.
2924 -- Case of validity check required (validity checks are on, the
2925 -- expression is not known to be valid, and the case statement
2926 -- comes from source -- no need to validity check internally
2927 -- generated case statements).
2929 if Validity_Check_Default
2930 and then not Predicates_Ignored (Etype (Expr))
2931 then
2932 Ensure_Valid (Expr);
2933 end if;
2935 -- If there is only a single alternative, just replace it with the
2936 -- sequence of statements since obviously that is what is going to
2937 -- be executed in all cases.
2939 Len := List_Length (Alternatives (N));
2941 if Len = 1 then
2943 -- We still need to evaluate the expression if it has any side
2944 -- effects.
2946 Remove_Side_Effects (Expression (N));
2947 Alt := First (Alternatives (N));
2949 -- Do not consider controlled objects found in a case statement
2950 -- which actually models a case expression because their early
2951 -- finalization will affect the result of the expression.
2953 if not From_Conditional_Expression (N) then
2954 Process_Statements_For_Controlled_Objects (Alt);
2955 end if;
2957 Insert_List_After (N, Statements (Alt));
2959 -- That leaves the case statement as a shell. The alternative that
2960 -- will be executed is reset to a null list. So now we can kill
2961 -- the entire case statement.
2963 Kill_Dead_Code (Expression (N));
2964 Rewrite (N, Make_Null_Statement (Loc));
2965 return;
2967 -- An optimization. If there are only two alternatives, and only
2968 -- a single choice, then rewrite the whole case statement as an
2969 -- if statement, since this can result in subsequent optimizations.
2970 -- This helps not only with case statements in the source of a
2971 -- simple form, but also with generated code (discriminant check
2972 -- functions in particular).
2974 -- Note: it is OK to do this before expanding out choices for any
2975 -- static predicates, since the if statement processing will handle
2976 -- the static predicate case fine.
2978 elsif Len = 2 then
2979 Chlist := Discrete_Choices (First (Alternatives (N)));
2981 if List_Length (Chlist) = 1 then
2982 Choice := First (Chlist);
2984 Then_Stms := Statements (First (Alternatives (N)));
2985 Else_Stms := Statements (Last (Alternatives (N)));
2987 -- For TRUE, generate "expression", not expression = true
2989 if Nkind (Choice) = N_Identifier
2990 and then Entity (Choice) = Standard_True
2991 then
2992 Cond := Expression (N);
2994 -- For FALSE, generate "expression" and switch then/else
2996 elsif Nkind (Choice) = N_Identifier
2997 and then Entity (Choice) = Standard_False
2998 then
2999 Cond := Expression (N);
3000 Else_Stms := Statements (First (Alternatives (N)));
3001 Then_Stms := Statements (Last (Alternatives (N)));
3003 -- For a range, generate "expression in range"
3005 elsif Nkind (Choice) = N_Range
3006 or else (Nkind (Choice) = N_Attribute_Reference
3007 and then Attribute_Name (Choice) = Name_Range)
3008 or else (Is_Entity_Name (Choice)
3009 and then Is_Type (Entity (Choice)))
3010 then
3011 Cond :=
3012 Make_In (Loc,
3013 Left_Opnd => Expression (N),
3014 Right_Opnd => Relocate_Node (Choice));
3016 -- A subtype indication is not a legal operator in a membership
3017 -- test, so retrieve its range.
3019 elsif Nkind (Choice) = N_Subtype_Indication then
3020 Cond :=
3021 Make_In (Loc,
3022 Left_Opnd => Expression (N),
3023 Right_Opnd =>
3024 Relocate_Node
3025 (Range_Expression (Constraint (Choice))));
3027 -- For any other subexpression "expression = value"
3029 else
3030 Cond :=
3031 Make_Op_Eq (Loc,
3032 Left_Opnd => Expression (N),
3033 Right_Opnd => Relocate_Node (Choice));
3034 end if;
3036 -- Now rewrite the case as an IF
3038 Rewrite (N,
3039 Make_If_Statement (Loc,
3040 Condition => Cond,
3041 Then_Statements => Then_Stms,
3042 Else_Statements => Else_Stms));
3043 Analyze (N);
3044 return;
3045 end if;
3046 end if;
3048 -- If the last alternative is not an Others choice, replace it with
3049 -- an N_Others_Choice. Note that we do not bother to call Analyze on
3050 -- the modified case statement, since it's only effect would be to
3051 -- compute the contents of the Others_Discrete_Choices which is not
3052 -- needed by the back end anyway.
3054 -- The reason for this is that the back end always needs some default
3055 -- for a switch, so if we have not supplied one in the processing
3056 -- above for validity checking, then we need to supply one here.
3058 if not Others_Present then
3059 Others_Node := Make_Others_Choice (Sloc (Last_Alt));
3061 -- If Predicates_Ignored is true the value does not satisfy the
3062 -- predicate, and there is no Others choice, Constraint_Error
3063 -- must be raised (4.5.7 (21/3)).
3065 if Predicates_Ignored (Etype (Expr)) then
3066 declare
3067 Except : constant Node_Id :=
3068 Make_Raise_Constraint_Error (Loc,
3069 Reason => CE_Invalid_Data);
3070 New_Alt : constant Node_Id :=
3071 Make_Case_Statement_Alternative (Loc,
3072 Discrete_Choices => New_List (
3073 Make_Others_Choice (Loc)),
3074 Statements => New_List (Except));
3076 begin
3077 Append (New_Alt, Alternatives (N));
3078 Analyze_And_Resolve (Except);
3079 end;
3081 else
3082 Set_Others_Discrete_Choices
3083 (Others_Node, Discrete_Choices (Last_Alt));
3084 Set_Discrete_Choices (Last_Alt, New_List (Others_Node));
3085 end if;
3087 end if;
3089 -- Deal with possible declarations of controlled objects, and also
3090 -- with rewriting choice sequences for static predicate references.
3092 Alt := First_Non_Pragma (Alternatives (N));
3093 while Present (Alt) loop
3095 -- Do not consider controlled objects found in a case statement
3096 -- which actually models a case expression because their early
3097 -- finalization will affect the result of the expression.
3099 if not From_Conditional_Expression (N) then
3100 Process_Statements_For_Controlled_Objects (Alt);
3101 end if;
3103 if Has_SP_Choice (Alt) then
3104 Expand_Static_Predicates_In_Choices (Alt);
3105 end if;
3107 Next_Non_Pragma (Alt);
3108 end loop;
3109 end;
3110 end Expand_N_Case_Statement;
3112 -----------------------------
3113 -- Expand_N_Exit_Statement --
3114 -----------------------------
3116 -- The only processing required is to deal with a possible C/Fortran
3117 -- boolean value used as the condition for the exit statement.
3119 procedure Expand_N_Exit_Statement (N : Node_Id) is
3120 begin
3121 Adjust_Condition (Condition (N));
3122 end Expand_N_Exit_Statement;
3124 ----------------------------------
3125 -- Expand_Formal_Container_Loop --
3126 ----------------------------------
3128 procedure Expand_Formal_Container_Loop (N : Node_Id) is
3129 Loc : constant Source_Ptr := Sloc (N);
3130 Isc : constant Node_Id := Iteration_Scheme (N);
3131 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3132 Cursor : constant Entity_Id := Defining_Identifier (I_Spec);
3133 Container : constant Node_Id := Entity (Name (I_Spec));
3134 Stats : constant List_Id := Statements (N);
3136 Advance : Node_Id;
3137 Init_Decl : Node_Id;
3138 Init_Name : Entity_Id;
3139 New_Loop : Node_Id;
3141 begin
3142 -- The expansion of a formal container loop resembles the one for Ada
3143 -- containers. The only difference is that the primitives mention the
3144 -- domain of iteration explicitly, and function First applied to the
3145 -- container yields a cursor directly.
3147 -- Cursor : Cursor_type := First (Container);
3148 -- while Has_Element (Cursor, Container) loop
3149 -- <original loop statements>
3150 -- Cursor := Next (Container, Cursor);
3151 -- end loop;
3153 Build_Formal_Container_Iteration
3154 (N, Container, Cursor, Init_Decl, Advance, New_Loop);
3156 Append_To (Stats, Advance);
3158 -- Build a block to capture declaration of the cursor
3160 Rewrite (N,
3161 Make_Block_Statement (Loc,
3162 Declarations => New_List (Init_Decl),
3163 Handled_Statement_Sequence =>
3164 Make_Handled_Sequence_Of_Statements (Loc,
3165 Statements => New_List (New_Loop))));
3167 -- The loop parameter is declared by an object declaration, but within
3168 -- the loop we must prevent user assignments to it, so we analyze the
3169 -- declaration and reset the entity kind, before analyzing the rest of
3170 -- the loop.
3172 Analyze (Init_Decl);
3173 Init_Name := Defining_Identifier (Init_Decl);
3174 Set_Ekind (Init_Name, E_Loop_Parameter);
3176 -- The cursor was marked as a loop parameter to prevent user assignments
3177 -- to it, however this renders the advancement step illegal as it is not
3178 -- possible to change the value of a constant. Flag the advancement step
3179 -- as a legal form of assignment to remedy this side effect.
3181 Set_Assignment_OK (Name (Advance));
3182 Analyze (N);
3184 -- Because we have to analyze the initial declaration of the loop
3185 -- parameter multiple times its scope is incorrectly set at this point
3186 -- to the one surrounding the block statement - so set the scope
3187 -- manually to be the actual block statement, and indicate that it is
3188 -- not visible after the block has been analyzed.
3190 Set_Scope (Init_Name, Entity (Identifier (N)));
3191 Set_Is_Immediately_Visible (Init_Name, False);
3192 end Expand_Formal_Container_Loop;
3194 ------------------------------------------
3195 -- Expand_Formal_Container_Element_Loop --
3196 ------------------------------------------
3198 procedure Expand_Formal_Container_Element_Loop (N : Node_Id) is
3199 Loc : constant Source_Ptr := Sloc (N);
3200 Isc : constant Node_Id := Iteration_Scheme (N);
3201 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3202 Element : constant Entity_Id := Defining_Identifier (I_Spec);
3203 Container : constant Node_Id := Entity (Name (I_Spec));
3204 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
3205 Stats : constant List_Id := Statements (N);
3207 Cursor : constant Entity_Id :=
3208 Make_Defining_Identifier (Loc,
3209 Chars => New_External_Name (Chars (Element), 'C'));
3210 Elmt_Decl : Node_Id;
3211 Elmt_Ref : Node_Id;
3213 Element_Op : constant Entity_Id :=
3214 Get_Iterable_Type_Primitive (Container_Typ, Name_Element);
3216 Advance : Node_Id;
3217 Init : Node_Id;
3218 New_Loop : Node_Id;
3220 begin
3221 -- For an element iterator, the Element aspect must be present,
3222 -- (this is checked during analysis) and the expansion takes the form:
3224 -- Cursor : Cursor_Type := First (Container);
3225 -- Elmt : Element_Type;
3226 -- while Has_Element (Cursor, Container) loop
3227 -- Elmt := Element (Container, Cursor);
3228 -- <original loop statements>
3229 -- Cursor := Next (Container, Cursor);
3230 -- end loop;
3232 -- However this expansion is not legal if the element is indefinite.
3233 -- In that case we create a block to hold a variable declaration
3234 -- initialized with a call to Element, and generate:
3236 -- Cursor : Cursor_Type := First (Container);
3237 -- while Has_Element (Cursor, Container) loop
3238 -- declare
3239 -- Elmt : Element_Type := Element (Container, Cursor);
3240 -- begin
3241 -- <original loop statements>
3242 -- Cursor := Next (Container, Cursor);
3243 -- end;
3244 -- end loop;
3246 Build_Formal_Container_Iteration
3247 (N, Container, Cursor, Init, Advance, New_Loop);
3248 Append_To (Stats, Advance);
3250 Set_Ekind (Cursor, E_Variable);
3251 Insert_Action (N, Init);
3253 -- Declaration for Element
3255 Elmt_Decl :=
3256 Make_Object_Declaration (Loc,
3257 Defining_Identifier => Element,
3258 Object_Definition => New_Occurrence_Of (Etype (Element_Op), Loc));
3260 if not Is_Constrained (Etype (Element_Op)) then
3261 Set_Expression (Elmt_Decl,
3262 Make_Function_Call (Loc,
3263 Name => New_Occurrence_Of (Element_Op, Loc),
3264 Parameter_Associations => New_List (
3265 Convert_To_Iterable_Type (Container, Loc),
3266 New_Occurrence_Of (Cursor, Loc))));
3268 Set_Statements (New_Loop,
3269 New_List
3270 (Make_Block_Statement (Loc,
3271 Declarations => New_List (Elmt_Decl),
3272 Handled_Statement_Sequence =>
3273 Make_Handled_Sequence_Of_Statements (Loc,
3274 Statements => Stats))));
3276 else
3277 Elmt_Ref :=
3278 Make_Assignment_Statement (Loc,
3279 Name => New_Occurrence_Of (Element, Loc),
3280 Expression =>
3281 Make_Function_Call (Loc,
3282 Name => New_Occurrence_Of (Element_Op, Loc),
3283 Parameter_Associations => New_List (
3284 Convert_To_Iterable_Type (Container, Loc),
3285 New_Occurrence_Of (Cursor, Loc))));
3287 Prepend (Elmt_Ref, Stats);
3289 -- The element is assignable in the expanded code
3291 Set_Assignment_OK (Name (Elmt_Ref));
3293 -- The loop is rewritten as a block, to hold the element declaration
3295 New_Loop :=
3296 Make_Block_Statement (Loc,
3297 Declarations => New_List (Elmt_Decl),
3298 Handled_Statement_Sequence =>
3299 Make_Handled_Sequence_Of_Statements (Loc,
3300 Statements => New_List (New_Loop)));
3301 end if;
3303 -- The element is only modified in expanded code, so it appears as
3304 -- unassigned to the warning machinery. We must suppress this spurious
3305 -- warning explicitly.
3307 Set_Warnings_Off (Element);
3309 Rewrite (N, New_Loop);
3311 -- The loop parameter is declared by an object declaration, but within
3312 -- the loop we must prevent user assignments to it, so we analyze the
3313 -- declaration and reset the entity kind, before analyzing the rest of
3314 -- the loop.
3316 Analyze (Elmt_Decl);
3317 Set_Ekind (Defining_Identifier (Elmt_Decl), E_Loop_Parameter);
3319 Analyze (N);
3320 end Expand_Formal_Container_Element_Loop;
3322 -----------------------------
3323 -- Expand_N_Goto_Statement --
3324 -----------------------------
3326 -- Add poll before goto if polling active
3328 procedure Expand_N_Goto_Statement (N : Node_Id) is
3329 begin
3330 Generate_Poll_Call (N);
3331 end Expand_N_Goto_Statement;
3333 ---------------------------
3334 -- Expand_N_If_Statement --
3335 ---------------------------
3337 -- First we deal with the case of C and Fortran convention boolean values,
3338 -- with zero/non-zero semantics.
3340 -- Second, we deal with the obvious rewriting for the cases where the
3341 -- condition of the IF is known at compile time to be True or False.
3343 -- Third, we remove elsif parts which have non-empty Condition_Actions and
3344 -- rewrite as independent if statements. For example:
3346 -- if x then xs
3347 -- elsif y then ys
3348 -- ...
3349 -- end if;
3351 -- becomes
3353 -- if x then xs
3354 -- else
3355 -- <<condition actions of y>>
3356 -- if y then ys
3357 -- ...
3358 -- end if;
3359 -- end if;
3361 -- This rewriting is needed if at least one elsif part has a non-empty
3362 -- Condition_Actions list. We also do the same processing if there is a
3363 -- constant condition in an elsif part (in conjunction with the first
3364 -- processing step mentioned above, for the recursive call made to deal
3365 -- with the created inner if, this deals with properly optimizing the
3366 -- cases of constant elsif conditions).
3368 procedure Expand_N_If_Statement (N : Node_Id) is
3369 Loc : constant Source_Ptr := Sloc (N);
3370 Hed : Node_Id;
3371 E : Node_Id;
3372 New_If : Node_Id;
3374 Warn_If_Deleted : constant Boolean :=
3375 Warn_On_Deleted_Code and then Comes_From_Source (N);
3376 -- Indicates whether we want warnings when we delete branches of the
3377 -- if statement based on constant condition analysis. We never want
3378 -- these warnings for expander generated code.
3380 begin
3381 -- Do not consider controlled objects found in an if statement which
3382 -- actually models an if expression because their early finalization
3383 -- will affect the result of the expression.
3385 if not From_Conditional_Expression (N) then
3386 Process_Statements_For_Controlled_Objects (N);
3387 end if;
3389 Adjust_Condition (Condition (N));
3391 -- The following loop deals with constant conditions for the IF. We
3392 -- need a loop because as we eliminate False conditions, we grab the
3393 -- first elsif condition and use it as the primary condition.
3395 while Compile_Time_Known_Value (Condition (N)) loop
3397 -- If condition is True, we can simply rewrite the if statement now
3398 -- by replacing it by the series of then statements.
3400 if Is_True (Expr_Value (Condition (N))) then
3402 -- All the else parts can be killed
3404 Kill_Dead_Code (Elsif_Parts (N), Warn_If_Deleted);
3405 Kill_Dead_Code (Else_Statements (N), Warn_If_Deleted);
3407 Hed := Remove_Head (Then_Statements (N));
3408 Insert_List_After (N, Then_Statements (N));
3409 Rewrite (N, Hed);
3410 return;
3412 -- If condition is False, then we can delete the condition and
3413 -- the Then statements
3415 else
3416 -- We do not delete the condition if constant condition warnings
3417 -- are enabled, since otherwise we end up deleting the desired
3418 -- warning. Of course the backend will get rid of this True/False
3419 -- test anyway, so nothing is lost here.
3421 if not Constant_Condition_Warnings then
3422 Kill_Dead_Code (Condition (N));
3423 end if;
3425 Kill_Dead_Code (Then_Statements (N), Warn_If_Deleted);
3427 -- If there are no elsif statements, then we simply replace the
3428 -- entire if statement by the sequence of else statements.
3430 if No (Elsif_Parts (N)) then
3431 if No (Else_Statements (N))
3432 or else Is_Empty_List (Else_Statements (N))
3433 then
3434 Rewrite (N,
3435 Make_Null_Statement (Sloc (N)));
3436 else
3437 Hed := Remove_Head (Else_Statements (N));
3438 Insert_List_After (N, Else_Statements (N));
3439 Rewrite (N, Hed);
3440 end if;
3442 return;
3444 -- If there are elsif statements, the first of them becomes the
3445 -- if/then section of the rebuilt if statement This is the case
3446 -- where we loop to reprocess this copied condition.
3448 else
3449 Hed := Remove_Head (Elsif_Parts (N));
3450 Insert_Actions (N, Condition_Actions (Hed));
3451 Set_Condition (N, Condition (Hed));
3452 Set_Then_Statements (N, Then_Statements (Hed));
3454 -- Hed might have been captured as the condition determining
3455 -- the current value for an entity. Now it is detached from
3456 -- the tree, so a Current_Value pointer in the condition might
3457 -- need to be updated.
3459 Set_Current_Value_Condition (N);
3461 if Is_Empty_List (Elsif_Parts (N)) then
3462 Set_Elsif_Parts (N, No_List);
3463 end if;
3464 end if;
3465 end if;
3466 end loop;
3468 -- Loop through elsif parts, dealing with constant conditions and
3469 -- possible condition actions that are present.
3471 if Present (Elsif_Parts (N)) then
3472 E := First (Elsif_Parts (N));
3473 while Present (E) loop
3475 -- Do not consider controlled objects found in an if statement
3476 -- which actually models an if expression because their early
3477 -- finalization will affect the result of the expression.
3479 if not From_Conditional_Expression (N) then
3480 Process_Statements_For_Controlled_Objects (E);
3481 end if;
3483 Adjust_Condition (Condition (E));
3485 -- If there are condition actions, then rewrite the if statement
3486 -- as indicated above. We also do the same rewrite for a True or
3487 -- False condition. The further processing of this constant
3488 -- condition is then done by the recursive call to expand the
3489 -- newly created if statement
3491 if Present (Condition_Actions (E))
3492 or else Compile_Time_Known_Value (Condition (E))
3493 then
3494 New_If :=
3495 Make_If_Statement (Sloc (E),
3496 Condition => Condition (E),
3497 Then_Statements => Then_Statements (E),
3498 Elsif_Parts => No_List,
3499 Else_Statements => Else_Statements (N));
3501 -- Elsif parts for new if come from remaining elsif's of parent
3503 while Present (Next (E)) loop
3504 if No (Elsif_Parts (New_If)) then
3505 Set_Elsif_Parts (New_If, New_List);
3506 end if;
3508 Append (Remove_Next (E), Elsif_Parts (New_If));
3509 end loop;
3511 Set_Else_Statements (N, New_List (New_If));
3513 if Present (Condition_Actions (E)) then
3514 Insert_List_Before (New_If, Condition_Actions (E));
3515 end if;
3517 Remove (E);
3519 if Is_Empty_List (Elsif_Parts (N)) then
3520 Set_Elsif_Parts (N, No_List);
3521 end if;
3523 Analyze (New_If);
3525 -- Note this is not an implicit if statement, since it is part
3526 -- of an explicit if statement in the source (or of an implicit
3527 -- if statement that has already been tested). We set the flag
3528 -- after calling Analyze to avoid generating extra warnings
3529 -- specific to pure if statements, however (see
3530 -- Sem_Ch5.Analyze_If_Statement).
3532 Set_Comes_From_Source (New_If, Comes_From_Source (N));
3533 return;
3535 -- No special processing for that elsif part, move to next
3537 else
3538 Next (E);
3539 end if;
3540 end loop;
3541 end if;
3543 -- Some more optimizations applicable if we still have an IF statement
3545 if Nkind (N) /= N_If_Statement then
3546 return;
3547 end if;
3549 -- Another optimization, special cases that can be simplified
3551 -- if expression then
3552 -- return true;
3553 -- else
3554 -- return false;
3555 -- end if;
3557 -- can be changed to:
3559 -- return expression;
3561 -- and
3563 -- if expression then
3564 -- return false;
3565 -- else
3566 -- return true;
3567 -- end if;
3569 -- can be changed to:
3571 -- return not (expression);
3573 -- Only do these optimizations if we are at least at -O1 level and
3574 -- do not do them if control flow optimizations are suppressed.
3576 if Optimization_Level > 0
3577 and then not Opt.Suppress_Control_Flow_Optimizations
3578 then
3579 if Nkind (N) = N_If_Statement
3580 and then No (Elsif_Parts (N))
3581 and then Present (Else_Statements (N))
3582 and then List_Length (Then_Statements (N)) = 1
3583 and then List_Length (Else_Statements (N)) = 1
3584 then
3585 declare
3586 Then_Stm : constant Node_Id := First (Then_Statements (N));
3587 Else_Stm : constant Node_Id := First (Else_Statements (N));
3589 begin
3590 if Nkind (Then_Stm) = N_Simple_Return_Statement
3591 and then
3592 Nkind (Else_Stm) = N_Simple_Return_Statement
3593 then
3594 declare
3595 Then_Expr : constant Node_Id := Expression (Then_Stm);
3596 Else_Expr : constant Node_Id := Expression (Else_Stm);
3598 begin
3599 if Nkind (Then_Expr) = N_Identifier
3600 and then
3601 Nkind (Else_Expr) = N_Identifier
3602 then
3603 if Entity (Then_Expr) = Standard_True
3604 and then Entity (Else_Expr) = Standard_False
3605 then
3606 Rewrite (N,
3607 Make_Simple_Return_Statement (Loc,
3608 Expression => Relocate_Node (Condition (N))));
3609 Analyze (N);
3610 return;
3612 elsif Entity (Then_Expr) = Standard_False
3613 and then Entity (Else_Expr) = Standard_True
3614 then
3615 Rewrite (N,
3616 Make_Simple_Return_Statement (Loc,
3617 Expression =>
3618 Make_Op_Not (Loc,
3619 Right_Opnd =>
3620 Relocate_Node (Condition (N)))));
3621 Analyze (N);
3622 return;
3623 end if;
3624 end if;
3625 end;
3626 end if;
3627 end;
3628 end if;
3629 end if;
3630 end Expand_N_If_Statement;
3632 --------------------------
3633 -- Expand_Iterator_Loop --
3634 --------------------------
3636 procedure Expand_Iterator_Loop (N : Node_Id) is
3637 Isc : constant Node_Id := Iteration_Scheme (N);
3638 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3640 Container : constant Node_Id := Name (I_Spec);
3641 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
3643 begin
3644 -- Processing for arrays
3646 if Is_Array_Type (Container_Typ) then
3647 pragma Assert (Of_Present (I_Spec));
3648 Expand_Iterator_Loop_Over_Array (N);
3650 elsif Has_Aspect (Container_Typ, Aspect_Iterable) then
3651 if Of_Present (I_Spec) then
3652 Expand_Formal_Container_Element_Loop (N);
3653 else
3654 Expand_Formal_Container_Loop (N);
3655 end if;
3657 -- Processing for containers
3659 else
3660 Expand_Iterator_Loop_Over_Container
3661 (N, Isc, I_Spec, Container, Container_Typ);
3662 end if;
3663 end Expand_Iterator_Loop;
3665 -------------------------------------
3666 -- Expand_Iterator_Loop_Over_Array --
3667 -------------------------------------
3669 procedure Expand_Iterator_Loop_Over_Array (N : Node_Id) is
3670 Isc : constant Node_Id := Iteration_Scheme (N);
3671 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3672 Array_Node : constant Node_Id := Name (I_Spec);
3673 Array_Typ : constant Entity_Id := Base_Type (Etype (Array_Node));
3674 Array_Dim : constant Pos := Number_Dimensions (Array_Typ);
3675 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3676 Loc : constant Source_Ptr := Sloc (Isc);
3677 Stats : constant List_Id := Statements (N);
3678 Core_Loop : Node_Id;
3679 Dim1 : Int;
3680 Ind_Comp : Node_Id;
3681 Iterator : Entity_Id;
3683 -- Start of processing for Expand_Iterator_Loop_Over_Array
3685 begin
3686 -- for Element of Array loop
3688 -- It requires an internally generated cursor to iterate over the array
3690 pragma Assert (Of_Present (I_Spec));
3692 Iterator := Make_Temporary (Loc, 'C');
3694 -- Generate:
3695 -- Element : Component_Type renames Array (Iterator);
3696 -- Iterator is the index value, or a list of index values
3697 -- in the case of a multidimensional array.
3699 Ind_Comp :=
3700 Make_Indexed_Component (Loc,
3701 Prefix => Relocate_Node (Array_Node),
3702 Expressions => New_List (New_Occurrence_Of (Iterator, Loc)));
3704 Prepend_To (Stats,
3705 Make_Object_Renaming_Declaration (Loc,
3706 Defining_Identifier => Id,
3707 Subtype_Mark =>
3708 New_Occurrence_Of (Component_Type (Array_Typ), Loc),
3709 Name => Ind_Comp));
3711 -- Mark the loop variable as needing debug info, so that expansion
3712 -- of the renaming will result in Materialize_Entity getting set via
3713 -- Debug_Renaming_Declaration. (This setting is needed here because
3714 -- the setting in Freeze_Entity comes after the expansion, which is
3715 -- too late. ???)
3717 Set_Debug_Info_Needed (Id);
3719 -- Generate:
3721 -- for Iterator in [reverse] Array'Range (Array_Dim) loop
3722 -- Element : Component_Type renames Array (Iterator);
3723 -- <original loop statements>
3724 -- end loop;
3726 -- If this is an iteration over a multidimensional array, the
3727 -- innermost loop is over the last dimension in Ada, and over
3728 -- the first dimension in Fortran.
3730 if Convention (Array_Typ) = Convention_Fortran then
3731 Dim1 := 1;
3732 else
3733 Dim1 := Array_Dim;
3734 end if;
3736 Core_Loop :=
3737 Make_Loop_Statement (Sloc (N),
3738 Iteration_Scheme =>
3739 Make_Iteration_Scheme (Loc,
3740 Loop_Parameter_Specification =>
3741 Make_Loop_Parameter_Specification (Loc,
3742 Defining_Identifier => Iterator,
3743 Discrete_Subtype_Definition =>
3744 Make_Attribute_Reference (Loc,
3745 Prefix => Relocate_Node (Array_Node),
3746 Attribute_Name => Name_Range,
3747 Expressions => New_List (
3748 Make_Integer_Literal (Loc, Dim1))),
3749 Reverse_Present => Reverse_Present (I_Spec))),
3750 Statements => Stats,
3751 End_Label => Empty);
3753 -- Processing for multidimensional array. The body of each loop is
3754 -- a loop over a previous dimension, going in decreasing order in Ada
3755 -- and in increasing order in Fortran.
3757 if Array_Dim > 1 then
3758 for Dim in 1 .. Array_Dim - 1 loop
3759 if Convention (Array_Typ) = Convention_Fortran then
3760 Dim1 := Dim + 1;
3761 else
3762 Dim1 := Array_Dim - Dim;
3763 end if;
3765 Iterator := Make_Temporary (Loc, 'C');
3767 -- Generate the dimension loops starting from the innermost one
3769 -- for Iterator in [reverse] Array'Range (Array_Dim - Dim) loop
3770 -- <core loop>
3771 -- end loop;
3773 Core_Loop :=
3774 Make_Loop_Statement (Sloc (N),
3775 Iteration_Scheme =>
3776 Make_Iteration_Scheme (Loc,
3777 Loop_Parameter_Specification =>
3778 Make_Loop_Parameter_Specification (Loc,
3779 Defining_Identifier => Iterator,
3780 Discrete_Subtype_Definition =>
3781 Make_Attribute_Reference (Loc,
3782 Prefix => Relocate_Node (Array_Node),
3783 Attribute_Name => Name_Range,
3784 Expressions => New_List (
3785 Make_Integer_Literal (Loc, Dim1))),
3786 Reverse_Present => Reverse_Present (I_Spec))),
3787 Statements => New_List (Core_Loop),
3788 End_Label => Empty);
3790 -- Update the previously created object renaming declaration with
3791 -- the new iterator, by adding the index of the next loop to the
3792 -- indexed component, in the order that corresponds to the
3793 -- convention.
3795 if Convention (Array_Typ) = Convention_Fortran then
3796 Append_To (Expressions (Ind_Comp),
3797 New_Occurrence_Of (Iterator, Loc));
3798 else
3799 Prepend_To (Expressions (Ind_Comp),
3800 New_Occurrence_Of (Iterator, Loc));
3801 end if;
3802 end loop;
3803 end if;
3805 -- Inherit the loop identifier from the original loop. This ensures that
3806 -- the scope stack is consistent after the rewriting.
3808 if Present (Identifier (N)) then
3809 Set_Identifier (Core_Loop, Relocate_Node (Identifier (N)));
3810 end if;
3812 Rewrite (N, Core_Loop);
3813 Analyze (N);
3814 end Expand_Iterator_Loop_Over_Array;
3816 -----------------------------------------
3817 -- Expand_Iterator_Loop_Over_Container --
3818 -----------------------------------------
3820 -- For a 'for ... in' loop, such as:
3822 -- for Cursor in Iterator_Function (...) loop
3823 -- ...
3824 -- end loop;
3826 -- we generate:
3828 -- Iter : Iterator_Type := Iterator_Function (...);
3829 -- Cursor : Cursor_type := First (Iter); -- or Last for "reverse"
3830 -- while Has_Element (Cursor) loop
3831 -- ...
3833 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
3834 -- end loop;
3836 -- For a 'for ... of' loop, such as:
3838 -- for X of Container loop
3839 -- ...
3840 -- end loop;
3842 -- the RM implies the generation of:
3844 -- Iter : Iterator_Type := Container.Iterate; -- the Default_Iterator
3845 -- Cursor : Cursor_Type := First (Iter); -- or Last for "reverse"
3846 -- while Has_Element (Cursor) loop
3847 -- declare
3848 -- X : Element_Type renames Element (Cursor).Element.all;
3849 -- -- or Constant_Element
3850 -- begin
3851 -- ...
3852 -- end;
3853 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
3854 -- end loop;
3856 -- In the general case, we do what the RM says. However, the operations
3857 -- Element and Iter.Next are slow, which is bad inside a loop, because they
3858 -- involve dispatching via interfaces, secondary stack manipulation,
3859 -- Busy/Lock incr/decr, and adjust/finalization/at-end handling. So for the
3860 -- predefined containers, we use an equivalent but optimized expansion.
3862 -- In the optimized case, we make use of these:
3864 -- procedure Next (Position : in out Cursor); -- instead of Iter.Next
3866 -- function Pseudo_Reference
3867 -- (Container : aliased Vector'Class) return Reference_Control_Type;
3869 -- type Element_Access is access all Element_Type;
3871 -- function Get_Element_Access
3872 -- (Position : Cursor) return not null Element_Access;
3874 -- Next is declared in the visible part of the container packages.
3875 -- The other three are added in the private part. (We're not supposed to
3876 -- pollute the namespace for clients. The compiler has no trouble breaking
3877 -- privacy to call things in the private part of an instance.)
3879 -- Source:
3881 -- for X of My_Vector loop
3882 -- X.Count := X.Count + 1;
3883 -- ...
3884 -- end loop;
3886 -- The compiler will generate:
3888 -- Iter : Reversible_Iterator'Class := Iterate (My_Vector);
3889 -- -- Reversible_Iterator is an interface. Iterate is the
3890 -- -- Default_Iterator aspect of Vector. This increments Lock,
3891 -- -- disallowing tampering with cursors. Unfortunately, it does not
3892 -- -- increment Busy. The result of Iterate is Limited_Controlled;
3893 -- -- finalization will decrement Lock. This is a build-in-place
3894 -- -- dispatching call to Iterate.
3896 -- Cur : Cursor := First (Iter); -- or Last
3897 -- -- Dispatching call via interface.
3899 -- Control : Reference_Control_Type := Pseudo_Reference (My_Vector);
3900 -- -- Pseudo_Reference increments Busy, to detect tampering with
3901 -- -- elements, as required by RM. Also redundantly increment
3902 -- -- Lock. Finalization of Control will decrement both Busy and
3903 -- -- Lock. Pseudo_Reference returns a record containing a pointer to
3904 -- -- My_Vector, used by Finalize.
3905 -- --
3906 -- -- Control is not used below, except to finalize it -- it's purely
3907 -- -- an RAII thing. This is needed because we are eliminating the
3908 -- -- call to Reference within the loop.
3910 -- while Has_Element (Cur) loop
3911 -- declare
3912 -- X : My_Element renames Get_Element_Access (Cur).all;
3913 -- -- Get_Element_Access returns a pointer to the element
3914 -- -- designated by Cur. No dispatching here, and no horsing
3915 -- -- around with access discriminants. This is instead of the
3916 -- -- existing
3917 -- --
3918 -- -- X : My_Element renames Reference (Cur).Element.all;
3919 -- --
3920 -- -- which creates a controlled object.
3921 -- begin
3922 -- -- Any attempt to tamper with My_Vector here in the loop
3923 -- -- will correctly raise Program_Error, because of the
3924 -- -- Control.
3926 -- X.Count := X.Count + 1;
3927 -- ...
3929 -- Next (Cur); -- or Prev
3930 -- -- This is instead of "Cur := Next (Iter, Cur);"
3931 -- end;
3932 -- -- No finalization here
3933 -- end loop;
3934 -- Finalize Iter and Control here, decrementing Lock twice and Busy
3935 -- once.
3937 -- This optimization makes "for ... of" loops over 30 times faster in cases
3938 -- measured.
3940 procedure Expand_Iterator_Loop_Over_Container
3941 (N : Node_Id;
3942 Isc : Node_Id;
3943 I_Spec : Node_Id;
3944 Container : Node_Id;
3945 Container_Typ : Entity_Id)
3947 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3948 Elem_Typ : constant Entity_Id := Etype (Id);
3949 Id_Kind : constant Entity_Kind := Ekind (Id);
3950 Loc : constant Source_Ptr := Sloc (N);
3951 Stats : constant List_Id := Statements (N);
3953 Cursor : Entity_Id;
3954 Decl : Node_Id;
3955 Iter_Type : Entity_Id;
3956 Iterator : Entity_Id;
3957 Name_Init : Name_Id;
3958 Name_Step : Name_Id;
3959 New_Loop : Node_Id;
3961 Fast_Element_Access_Op : Entity_Id := Empty;
3962 Fast_Step_Op : Entity_Id := Empty;
3963 -- Only for optimized version of "for ... of"
3965 Iter_Pack : Entity_Id;
3966 -- The package in which the iterator interface is instantiated. This is
3967 -- typically an instance within the container package.
3969 Pack : Entity_Id;
3970 -- The package in which the container type is declared
3972 begin
3973 -- Determine the advancement and initialization steps for the cursor.
3974 -- Analysis of the expanded loop will verify that the container has a
3975 -- reverse iterator.
3977 if Reverse_Present (I_Spec) then
3978 Name_Init := Name_Last;
3979 Name_Step := Name_Previous;
3980 else
3981 Name_Init := Name_First;
3982 Name_Step := Name_Next;
3983 end if;
3985 -- The type of the iterator is the return type of the Iterate function
3986 -- used. For the "of" form this is the default iterator for the type,
3987 -- otherwise it is the type of the explicit function used in the
3988 -- iterator specification. The most common case will be an Iterate
3989 -- function in the container package.
3991 -- The Iterator type is declared in an instance within the container
3992 -- package itself, for example:
3994 -- package Vector_Iterator_Interfaces is new
3995 -- Ada.Iterator_Interfaces (Cursor, Has_Element);
3997 -- If the container type is a derived type, the cursor type is found in
3998 -- the package of the ultimate ancestor type.
4000 if Is_Derived_Type (Container_Typ) then
4001 Pack := Scope (Root_Type (Container_Typ));
4002 else
4003 Pack := Scope (Container_Typ);
4004 end if;
4006 if Of_Present (I_Spec) then
4007 Handle_Of : declare
4008 Container_Arg : Node_Id;
4010 function Get_Default_Iterator
4011 (T : Entity_Id) return Entity_Id;
4012 -- Return the default iterator for a specific type. If the type is
4013 -- derived, we return the inherited or overridden one if
4014 -- appropriate.
4016 --------------------------
4017 -- Get_Default_Iterator --
4018 --------------------------
4020 function Get_Default_Iterator
4021 (T : Entity_Id) return Entity_Id
4023 Iter : constant Entity_Id :=
4024 Entity (Find_Value_Of_Aspect (T, Aspect_Default_Iterator));
4025 Prim : Elmt_Id;
4026 Op : Entity_Id;
4028 begin
4029 Container_Arg := New_Copy_Tree (Container);
4031 -- A previous version of GNAT allowed indexing aspects to be
4032 -- redefined on derived container types, while the default
4033 -- iterator was inherited from the parent type. This
4034 -- nonstandard extension is preserved for use by the
4035 -- modeling project under debug flag -gnatd.X.
4037 if Debug_Flag_Dot_XX then
4038 if Base_Type (Etype (Container)) /=
4039 Base_Type (Etype (First_Formal (Iter)))
4040 then
4041 Container_Arg :=
4042 Make_Type_Conversion (Loc,
4043 Subtype_Mark =>
4044 New_Occurrence_Of
4045 (Etype (First_Formal (Iter)), Loc),
4046 Expression => Container_Arg);
4047 end if;
4049 return Iter;
4051 elsif Is_Derived_Type (T) then
4053 -- The default iterator must be a primitive operation of the
4054 -- type, at the same dispatch slot position. The DT position
4055 -- may not be established if type is not frozen yet.
4057 Prim := First_Elmt (Primitive_Operations (T));
4058 while Present (Prim) loop
4059 Op := Node (Prim);
4061 if Alias (Op) = Iter
4062 or else
4063 (Chars (Op) = Chars (Iter)
4064 and then Present (DTC_Entity (Op))
4065 and then DT_Position (Op) = DT_Position (Iter))
4066 then
4067 return Op;
4068 end if;
4070 Next_Elmt (Prim);
4071 end loop;
4073 -- If we didn't find it, then our parent type is not
4074 -- iterable, so we return the Default_Iterator aspect of
4075 -- this type.
4077 return Iter;
4079 -- Otherwise not a derived type
4081 else
4082 return Iter;
4083 end if;
4084 end Get_Default_Iterator;
4086 -- Local variables
4088 Default_Iter : Entity_Id;
4089 Ent : Entity_Id;
4091 Reference_Control_Type : Entity_Id := Empty;
4092 Pseudo_Reference : Entity_Id := Empty;
4094 -- Start of processing for Handle_Of
4096 begin
4097 if Is_Class_Wide_Type (Container_Typ) then
4098 Default_Iter :=
4099 Get_Default_Iterator (Etype (Base_Type (Container_Typ)));
4100 else
4101 Default_Iter := Get_Default_Iterator (Etype (Container));
4102 end if;
4104 Cursor := Make_Temporary (Loc, 'C');
4106 -- For a container element iterator, the iterator type is obtained
4107 -- from the corresponding aspect, whose return type is descended
4108 -- from the corresponding interface type in some instance of
4109 -- Ada.Iterator_Interfaces. The actuals of that instantiation
4110 -- are Cursor and Has_Element.
4112 Iter_Type := Etype (Default_Iter);
4114 -- The iterator type, which is a class-wide type, may itself be
4115 -- derived locally, so the desired instantiation is the scope of
4116 -- the root type of the iterator type.
4118 Iter_Pack := Scope (Root_Type (Etype (Iter_Type)));
4120 -- Find declarations needed for "for ... of" optimization
4122 Ent := First_Entity (Pack);
4123 while Present (Ent) loop
4124 if Chars (Ent) = Name_Get_Element_Access then
4125 Fast_Element_Access_Op := Ent;
4127 elsif Chars (Ent) = Name_Step
4128 and then Ekind (Ent) = E_Procedure
4129 then
4130 Fast_Step_Op := Ent;
4132 elsif Chars (Ent) = Name_Reference_Control_Type then
4133 Reference_Control_Type := Ent;
4135 elsif Chars (Ent) = Name_Pseudo_Reference then
4136 Pseudo_Reference := Ent;
4137 end if;
4139 Next_Entity (Ent);
4140 end loop;
4142 if Present (Reference_Control_Type)
4143 and then Present (Pseudo_Reference)
4144 then
4145 Insert_Action (N,
4146 Make_Object_Declaration (Loc,
4147 Defining_Identifier => Make_Temporary (Loc, 'D'),
4148 Object_Definition =>
4149 New_Occurrence_Of (Reference_Control_Type, Loc),
4150 Expression =>
4151 Make_Function_Call (Loc,
4152 Name =>
4153 New_Occurrence_Of (Pseudo_Reference, Loc),
4154 Parameter_Associations =>
4155 New_List (New_Copy_Tree (Container_Arg)))));
4156 end if;
4158 -- Rewrite domain of iteration as a call to the default iterator
4159 -- for the container type. The formal may be an access parameter
4160 -- in which case we must build a reference to the container.
4162 declare
4163 Arg : Node_Id;
4164 begin
4165 if Is_Access_Type (Etype (First_Entity (Default_Iter))) then
4166 Arg :=
4167 Make_Attribute_Reference (Loc,
4168 Prefix => Container_Arg,
4169 Attribute_Name => Name_Unrestricted_Access);
4170 else
4171 Arg := Container_Arg;
4172 end if;
4174 Rewrite (Name (I_Spec),
4175 Make_Function_Call (Loc,
4176 Name =>
4177 New_Occurrence_Of (Default_Iter, Loc),
4178 Parameter_Associations => New_List (Arg)));
4179 end;
4181 Analyze_And_Resolve (Name (I_Spec));
4183 -- Find cursor type in proper iterator package, which is an
4184 -- instantiation of Iterator_Interfaces.
4186 Ent := First_Entity (Iter_Pack);
4187 while Present (Ent) loop
4188 if Chars (Ent) = Name_Cursor then
4189 Set_Etype (Cursor, Etype (Ent));
4190 exit;
4191 end if;
4193 Next_Entity (Ent);
4194 end loop;
4196 if Present (Fast_Element_Access_Op) then
4197 Decl :=
4198 Make_Object_Renaming_Declaration (Loc,
4199 Defining_Identifier => Id,
4200 Subtype_Mark =>
4201 New_Occurrence_Of (Elem_Typ, Loc),
4202 Name =>
4203 Make_Explicit_Dereference (Loc,
4204 Prefix =>
4205 Make_Function_Call (Loc,
4206 Name =>
4207 New_Occurrence_Of (Fast_Element_Access_Op, Loc),
4208 Parameter_Associations =>
4209 New_List (New_Occurrence_Of (Cursor, Loc)))));
4211 else
4212 Decl :=
4213 Make_Object_Renaming_Declaration (Loc,
4214 Defining_Identifier => Id,
4215 Subtype_Mark =>
4216 New_Occurrence_Of (Elem_Typ, Loc),
4217 Name =>
4218 Make_Indexed_Component (Loc,
4219 Prefix => Relocate_Node (Container_Arg),
4220 Expressions =>
4221 New_List (New_Occurrence_Of (Cursor, Loc))));
4222 end if;
4224 -- The defining identifier in the iterator is user-visible and
4225 -- must be visible in the debugger.
4227 Set_Debug_Info_Needed (Id);
4229 -- If the container does not have a variable indexing aspect,
4230 -- the element is a constant in the loop. The container itself
4231 -- may be constant, in which case the element is a constant as
4232 -- well. The container has been rewritten as a call to Iterate,
4233 -- so examine original node.
4235 if No (Find_Value_Of_Aspect
4236 (Container_Typ, Aspect_Variable_Indexing))
4237 or else not Is_Variable (Original_Node (Container))
4238 then
4239 Set_Ekind (Id, E_Constant);
4240 end if;
4242 Prepend_To (Stats, Decl);
4243 end Handle_Of;
4245 -- X in Iterate (S) : type of iterator is type of explicitly given
4246 -- Iterate function, and the loop variable is the cursor. It will be
4247 -- assigned in the loop and must be a variable.
4249 else
4250 Iter_Type := Etype (Name (I_Spec));
4252 -- The iterator type, which is a class-wide type, may itself be
4253 -- derived locally, so the desired instantiation is the scope of
4254 -- the root type of the iterator type, as in the "of" case.
4256 Iter_Pack := Scope (Root_Type (Etype (Iter_Type)));
4257 Cursor := Id;
4258 end if;
4260 Iterator := Make_Temporary (Loc, 'I');
4262 -- For both iterator forms, add a call to the step operation to advance
4263 -- the cursor. Generate:
4265 -- Cursor := Iterator.Next (Cursor);
4267 -- or else
4269 -- Cursor := Next (Cursor);
4271 if Present (Fast_Element_Access_Op) and then Present (Fast_Step_Op) then
4272 declare
4273 Curs_Name : constant Node_Id := New_Occurrence_Of (Cursor, Loc);
4274 Step_Call : Node_Id;
4276 begin
4277 Step_Call :=
4278 Make_Procedure_Call_Statement (Loc,
4279 Name =>
4280 New_Occurrence_Of (Fast_Step_Op, Loc),
4281 Parameter_Associations => New_List (Curs_Name));
4283 Append_To (Stats, Step_Call);
4284 Set_Assignment_OK (Curs_Name);
4285 end;
4287 else
4288 declare
4289 Rhs : Node_Id;
4291 begin
4292 Rhs :=
4293 Make_Function_Call (Loc,
4294 Name =>
4295 Make_Selected_Component (Loc,
4296 Prefix => New_Occurrence_Of (Iterator, Loc),
4297 Selector_Name => Make_Identifier (Loc, Name_Step)),
4298 Parameter_Associations => New_List (
4299 New_Occurrence_Of (Cursor, Loc)));
4301 Append_To (Stats,
4302 Make_Assignment_Statement (Loc,
4303 Name => New_Occurrence_Of (Cursor, Loc),
4304 Expression => Rhs));
4305 Set_Assignment_OK (Name (Last (Stats)));
4306 end;
4307 end if;
4309 -- Generate:
4310 -- while Has_Element (Cursor) loop
4311 -- <Stats>
4312 -- end loop;
4314 -- Has_Element is the second actual in the iterator package
4316 New_Loop :=
4317 Make_Loop_Statement (Loc,
4318 Iteration_Scheme =>
4319 Make_Iteration_Scheme (Loc,
4320 Condition =>
4321 Make_Function_Call (Loc,
4322 Name =>
4323 New_Occurrence_Of
4324 (Next_Entity (First_Entity (Iter_Pack)), Loc),
4325 Parameter_Associations => New_List (
4326 New_Occurrence_Of (Cursor, Loc)))),
4328 Statements => Stats,
4329 End_Label => Empty);
4331 -- If present, preserve identifier of loop, which can be used in an exit
4332 -- statement in the body.
4334 if Present (Identifier (N)) then
4335 Set_Identifier (New_Loop, Relocate_Node (Identifier (N)));
4336 end if;
4338 -- Create the declarations for Iterator and cursor and insert them
4339 -- before the source loop. Given that the domain of iteration is already
4340 -- an entity, the iterator is just a renaming of that entity. Possible
4341 -- optimization ???
4343 Insert_Action (N,
4344 Make_Object_Renaming_Declaration (Loc,
4345 Defining_Identifier => Iterator,
4346 Subtype_Mark => New_Occurrence_Of (Iter_Type, Loc),
4347 Name => Relocate_Node (Name (I_Spec))));
4349 -- Create declaration for cursor
4351 declare
4352 Cursor_Decl : constant Node_Id :=
4353 Make_Object_Declaration (Loc,
4354 Defining_Identifier => Cursor,
4355 Object_Definition =>
4356 New_Occurrence_Of (Etype (Cursor), Loc),
4357 Expression =>
4358 Make_Selected_Component (Loc,
4359 Prefix =>
4360 New_Occurrence_Of (Iterator, Loc),
4361 Selector_Name =>
4362 Make_Identifier (Loc, Name_Init)));
4364 begin
4365 -- The cursor is only modified in expanded code, so it appears
4366 -- as unassigned to the warning machinery. We must suppress this
4367 -- spurious warning explicitly. The cursor's kind is that of the
4368 -- original loop parameter (it is a constant if the domain of
4369 -- iteration is constant).
4371 Set_Warnings_Off (Cursor);
4372 Set_Assignment_OK (Cursor_Decl);
4374 Insert_Action (N, Cursor_Decl);
4375 Set_Ekind (Cursor, Id_Kind);
4376 end;
4378 -- If the range of iteration is given by a function call that returns
4379 -- a container, the finalization actions have been saved in the
4380 -- Condition_Actions of the iterator. Insert them now at the head of
4381 -- the loop.
4383 if Present (Condition_Actions (Isc)) then
4384 Insert_List_Before (N, Condition_Actions (Isc));
4385 end if;
4387 Rewrite (N, New_Loop);
4388 Analyze (N);
4389 end Expand_Iterator_Loop_Over_Container;
4391 -----------------------------
4392 -- Expand_N_Loop_Statement --
4393 -----------------------------
4395 -- 1. Remove null loop entirely
4396 -- 2. Deal with while condition for C/Fortran boolean
4397 -- 3. Deal with loops with a non-standard enumeration type range
4398 -- 4. Deal with while loops where Condition_Actions is set
4399 -- 5. Deal with loops over predicated subtypes
4400 -- 6. Deal with loops with iterators over arrays and containers
4401 -- 7. Insert polling call if required
4403 procedure Expand_N_Loop_Statement (N : Node_Id) is
4404 Loc : constant Source_Ptr := Sloc (N);
4405 Scheme : constant Node_Id := Iteration_Scheme (N);
4406 Stmt : Node_Id;
4408 begin
4409 -- Delete null loop
4411 if Is_Null_Loop (N) then
4412 Rewrite (N, Make_Null_Statement (Loc));
4413 return;
4414 end if;
4416 -- Deal with condition for C/Fortran Boolean
4418 if Present (Scheme) then
4419 Adjust_Condition (Condition (Scheme));
4420 end if;
4422 -- Generate polling call
4424 if Is_Non_Empty_List (Statements (N)) then
4425 Generate_Poll_Call (First (Statements (N)));
4426 end if;
4428 -- Nothing more to do for plain loop with no iteration scheme
4430 if No (Scheme) then
4431 null;
4433 -- Case of for loop (Loop_Parameter_Specification present)
4435 -- Note: we do not have to worry about validity checking of the for loop
4436 -- range bounds here, since they were frozen with constant declarations
4437 -- and it is during that process that the validity checking is done.
4439 elsif Present (Loop_Parameter_Specification (Scheme)) then
4440 declare
4441 LPS : constant Node_Id :=
4442 Loop_Parameter_Specification (Scheme);
4443 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4444 Ltype : constant Entity_Id := Etype (Loop_Id);
4445 Btype : constant Entity_Id := Base_Type (Ltype);
4446 Expr : Node_Id;
4447 Decls : List_Id;
4448 New_Id : Entity_Id;
4450 begin
4451 -- Deal with loop over predicates
4453 if Is_Discrete_Type (Ltype)
4454 and then Present (Predicate_Function (Ltype))
4455 then
4456 Expand_Predicated_Loop (N);
4458 -- Handle the case where we have a for loop with the range type
4459 -- being an enumeration type with non-standard representation.
4460 -- In this case we expand:
4462 -- for x in [reverse] a .. b loop
4463 -- ...
4464 -- end loop;
4466 -- to
4468 -- for xP in [reverse] integer
4469 -- range etype'Pos (a) .. etype'Pos (b)
4470 -- loop
4471 -- declare
4472 -- x : constant etype := Pos_To_Rep (xP);
4473 -- begin
4474 -- ...
4475 -- end;
4476 -- end loop;
4478 elsif Is_Enumeration_Type (Btype)
4479 and then Present (Enum_Pos_To_Rep (Btype))
4480 then
4481 New_Id :=
4482 Make_Defining_Identifier (Loc,
4483 Chars => New_External_Name (Chars (Loop_Id), 'P'));
4485 -- If the type has a contiguous representation, successive
4486 -- values can be generated as offsets from the first literal.
4488 if Has_Contiguous_Rep (Btype) then
4489 Expr :=
4490 Unchecked_Convert_To (Btype,
4491 Make_Op_Add (Loc,
4492 Left_Opnd =>
4493 Make_Integer_Literal (Loc,
4494 Enumeration_Rep (First_Literal (Btype))),
4495 Right_Opnd => New_Occurrence_Of (New_Id, Loc)));
4496 else
4497 -- Use the constructed array Enum_Pos_To_Rep
4499 Expr :=
4500 Make_Indexed_Component (Loc,
4501 Prefix =>
4502 New_Occurrence_Of (Enum_Pos_To_Rep (Btype), Loc),
4503 Expressions =>
4504 New_List (New_Occurrence_Of (New_Id, Loc)));
4505 end if;
4507 -- Build declaration for loop identifier
4509 Decls :=
4510 New_List (
4511 Make_Object_Declaration (Loc,
4512 Defining_Identifier => Loop_Id,
4513 Constant_Present => True,
4514 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4515 Expression => Expr));
4517 Rewrite (N,
4518 Make_Loop_Statement (Loc,
4519 Identifier => Identifier (N),
4521 Iteration_Scheme =>
4522 Make_Iteration_Scheme (Loc,
4523 Loop_Parameter_Specification =>
4524 Make_Loop_Parameter_Specification (Loc,
4525 Defining_Identifier => New_Id,
4526 Reverse_Present => Reverse_Present (LPS),
4528 Discrete_Subtype_Definition =>
4529 Make_Subtype_Indication (Loc,
4531 Subtype_Mark =>
4532 New_Occurrence_Of (Standard_Natural, Loc),
4534 Constraint =>
4535 Make_Range_Constraint (Loc,
4536 Range_Expression =>
4537 Make_Range (Loc,
4539 Low_Bound =>
4540 Make_Attribute_Reference (Loc,
4541 Prefix =>
4542 New_Occurrence_Of (Btype, Loc),
4544 Attribute_Name => Name_Pos,
4546 Expressions => New_List (
4547 Relocate_Node
4548 (Type_Low_Bound (Ltype)))),
4550 High_Bound =>
4551 Make_Attribute_Reference (Loc,
4552 Prefix =>
4553 New_Occurrence_Of (Btype, Loc),
4555 Attribute_Name => Name_Pos,
4557 Expressions => New_List (
4558 Relocate_Node
4559 (Type_High_Bound
4560 (Ltype))))))))),
4562 Statements => New_List (
4563 Make_Block_Statement (Loc,
4564 Declarations => Decls,
4565 Handled_Statement_Sequence =>
4566 Make_Handled_Sequence_Of_Statements (Loc,
4567 Statements => Statements (N)))),
4569 End_Label => End_Label (N)));
4571 -- The loop parameter's entity must be removed from the loop
4572 -- scope's entity list and rendered invisible, since it will
4573 -- now be located in the new block scope. Any other entities
4574 -- already associated with the loop scope, such as the loop
4575 -- parameter's subtype, will remain there.
4577 -- In an element loop, the loop will contain a declaration for
4578 -- a cursor variable; otherwise the loop id is the first entity
4579 -- in the scope constructed for the loop.
4581 if Comes_From_Source (Loop_Id) then
4582 pragma Assert (First_Entity (Scope (Loop_Id)) = Loop_Id);
4583 null;
4584 end if;
4586 Set_First_Entity (Scope (Loop_Id), Next_Entity (Loop_Id));
4587 Remove_Homonym (Loop_Id);
4589 if Last_Entity (Scope (Loop_Id)) = Loop_Id then
4590 Set_Last_Entity (Scope (Loop_Id), Empty);
4591 end if;
4593 Analyze (N);
4595 -- Nothing to do with other cases of for loops
4597 else
4598 null;
4599 end if;
4600 end;
4602 -- Second case, if we have a while loop with Condition_Actions set, then
4603 -- we change it into a plain loop:
4605 -- while C loop
4606 -- ...
4607 -- end loop;
4609 -- changed to:
4611 -- loop
4612 -- <<condition actions>>
4613 -- exit when not C;
4614 -- ...
4615 -- end loop
4617 elsif Present (Scheme)
4618 and then Present (Condition_Actions (Scheme))
4619 and then Present (Condition (Scheme))
4620 then
4621 declare
4622 ES : Node_Id;
4624 begin
4625 ES :=
4626 Make_Exit_Statement (Sloc (Condition (Scheme)),
4627 Condition =>
4628 Make_Op_Not (Sloc (Condition (Scheme)),
4629 Right_Opnd => Condition (Scheme)));
4631 Prepend (ES, Statements (N));
4632 Insert_List_Before (ES, Condition_Actions (Scheme));
4634 -- This is not an implicit loop, since it is generated in response
4635 -- to the loop statement being processed. If this is itself
4636 -- implicit, the restriction has already been checked. If not,
4637 -- it is an explicit loop.
4639 Rewrite (N,
4640 Make_Loop_Statement (Sloc (N),
4641 Identifier => Identifier (N),
4642 Statements => Statements (N),
4643 End_Label => End_Label (N)));
4645 Analyze (N);
4646 end;
4648 -- Here to deal with iterator case
4650 elsif Present (Scheme)
4651 and then Present (Iterator_Specification (Scheme))
4652 then
4653 Expand_Iterator_Loop (N);
4655 -- An iterator loop may generate renaming declarations for elements
4656 -- that require debug information. This is the case in particular
4657 -- with element iterators, where debug information must be generated
4658 -- for the temporary that holds the element value. These temporaries
4659 -- are created within a transient block whose local declarations are
4660 -- transferred to the loop, which now has nontrivial local objects.
4662 if Nkind (N) = N_Loop_Statement
4663 and then Present (Identifier (N))
4664 then
4665 Qualify_Entity_Names (N);
4666 end if;
4667 end if;
4669 -- When the iteration scheme mentiones attribute 'Loop_Entry, the loop
4670 -- is transformed into a conditional block where the original loop is
4671 -- the sole statement. Inspect the statements of the nested loop for
4672 -- controlled objects.
4674 Stmt := N;
4676 if Subject_To_Loop_Entry_Attributes (Stmt) then
4677 Stmt := Find_Loop_In_Conditional_Block (Stmt);
4678 end if;
4680 Process_Statements_For_Controlled_Objects (Stmt);
4681 end Expand_N_Loop_Statement;
4683 ----------------------------
4684 -- Expand_Predicated_Loop --
4685 ----------------------------
4687 -- Note: the expander can handle generation of loops over predicated
4688 -- subtypes for both the dynamic and static cases. Depending on what
4689 -- we decide is allowed in Ada 2012 mode and/or extensions allowed
4690 -- mode, the semantic analyzer may disallow one or both forms.
4692 procedure Expand_Predicated_Loop (N : Node_Id) is
4693 Loc : constant Source_Ptr := Sloc (N);
4694 Isc : constant Node_Id := Iteration_Scheme (N);
4695 LPS : constant Node_Id := Loop_Parameter_Specification (Isc);
4696 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4697 Ltype : constant Entity_Id := Etype (Loop_Id);
4698 Stat : constant List_Id := Static_Discrete_Predicate (Ltype);
4699 Stmts : constant List_Id := Statements (N);
4701 begin
4702 -- Case of iteration over non-static predicate, should not be possible
4703 -- since this is not allowed by the semantics and should have been
4704 -- caught during analysis of the loop statement.
4706 if No (Stat) then
4707 raise Program_Error;
4709 -- If the predicate list is empty, that corresponds to a predicate of
4710 -- False, in which case the loop won't run at all, and we rewrite the
4711 -- entire loop as a null statement.
4713 elsif Is_Empty_List (Stat) then
4714 Rewrite (N, Make_Null_Statement (Loc));
4715 Analyze (N);
4717 -- For expansion over a static predicate we generate the following
4719 -- declare
4720 -- J : Ltype := min-val;
4721 -- begin
4722 -- loop
4723 -- body
4724 -- case J is
4725 -- when endpoint => J := startpoint;
4726 -- when endpoint => J := startpoint;
4727 -- ...
4728 -- when max-val => exit;
4729 -- when others => J := Lval'Succ (J);
4730 -- end case;
4731 -- end loop;
4732 -- end;
4734 -- with min-val replaced by max-val and Succ replaced by Pred if the
4735 -- loop parameter specification carries a Reverse indicator.
4737 -- To make this a little clearer, let's take a specific example:
4739 -- type Int is range 1 .. 10;
4740 -- subtype StaticP is Int with
4741 -- predicate => StaticP in 3 | 10 | 5 .. 7;
4742 -- ...
4743 -- for L in StaticP loop
4744 -- Put_Line ("static:" & J'Img);
4745 -- end loop;
4747 -- In this case, the loop is transformed into
4749 -- begin
4750 -- J : L := 3;
4751 -- loop
4752 -- body
4753 -- case J is
4754 -- when 3 => J := 5;
4755 -- when 7 => J := 10;
4756 -- when 10 => exit;
4757 -- when others => J := L'Succ (J);
4758 -- end case;
4759 -- end loop;
4760 -- end;
4762 -- In addition, if the loop specification is given by a subtype
4763 -- indication that constrains a predicated type, the bounds of
4764 -- iteration are given by those of the subtype indication.
4766 else
4767 Static_Predicate : declare
4768 S : Node_Id;
4769 D : Node_Id;
4770 P : Node_Id;
4771 Alts : List_Id;
4772 Cstm : Node_Id;
4774 -- If the domain is an itype, note the bounds of its range.
4776 L_Hi : Node_Id := Empty;
4777 L_Lo : Node_Id := Empty;
4779 function Lo_Val (N : Node_Id) return Node_Id;
4780 -- Given static expression or static range, returns an identifier
4781 -- whose value is the low bound of the expression value or range.
4783 function Hi_Val (N : Node_Id) return Node_Id;
4784 -- Given static expression or static range, returns an identifier
4785 -- whose value is the high bound of the expression value or range.
4787 ------------
4788 -- Hi_Val --
4789 ------------
4791 function Hi_Val (N : Node_Id) return Node_Id is
4792 begin
4793 if Is_OK_Static_Expression (N) then
4794 return New_Copy (N);
4795 else
4796 pragma Assert (Nkind (N) = N_Range);
4797 return New_Copy (High_Bound (N));
4798 end if;
4799 end Hi_Val;
4801 ------------
4802 -- Lo_Val --
4803 ------------
4805 function Lo_Val (N : Node_Id) return Node_Id is
4806 begin
4807 if Is_OK_Static_Expression (N) then
4808 return New_Copy (N);
4809 else
4810 pragma Assert (Nkind (N) = N_Range);
4811 return New_Copy (Low_Bound (N));
4812 end if;
4813 end Lo_Val;
4815 -- Start of processing for Static_Predicate
4817 begin
4818 -- Convert loop identifier to normal variable and reanalyze it so
4819 -- that this conversion works. We have to use the same defining
4820 -- identifier, since there may be references in the loop body.
4822 Set_Analyzed (Loop_Id, False);
4823 Set_Ekind (Loop_Id, E_Variable);
4825 -- In most loops the loop variable is assigned in various
4826 -- alternatives in the body. However, in the rare case when
4827 -- the range specifies a single element, the loop variable
4828 -- may trigger a spurious warning that is could be constant.
4829 -- This warning might as well be suppressed.
4831 Set_Warnings_Off (Loop_Id);
4833 if Is_Itype (Ltype) then
4834 L_Hi := High_Bound (Scalar_Range (Ltype));
4835 L_Lo := Low_Bound (Scalar_Range (Ltype));
4836 end if;
4838 -- Loop to create branches of case statement
4840 Alts := New_List;
4842 if Reverse_Present (LPS) then
4844 -- Initial value is largest value in predicate.
4846 if Is_Itype (Ltype) then
4847 D :=
4848 Make_Object_Declaration (Loc,
4849 Defining_Identifier => Loop_Id,
4850 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4851 Expression => L_Hi);
4853 else
4854 D :=
4855 Make_Object_Declaration (Loc,
4856 Defining_Identifier => Loop_Id,
4857 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4858 Expression => Hi_Val (Last (Stat)));
4859 end if;
4861 P := Last (Stat);
4862 while Present (P) loop
4863 if No (Prev (P)) then
4864 S := Make_Exit_Statement (Loc);
4865 else
4866 S :=
4867 Make_Assignment_Statement (Loc,
4868 Name => New_Occurrence_Of (Loop_Id, Loc),
4869 Expression => Hi_Val (Prev (P)));
4870 Set_Suppress_Assignment_Checks (S);
4871 end if;
4873 Append_To (Alts,
4874 Make_Case_Statement_Alternative (Loc,
4875 Statements => New_List (S),
4876 Discrete_Choices => New_List (Lo_Val (P))));
4878 Prev (P);
4879 end loop;
4881 if Is_Itype (Ltype)
4882 and then Is_OK_Static_Expression (L_Lo)
4883 and then
4884 Expr_Value (L_Lo) /= Expr_Value (Lo_Val (First (Stat)))
4885 then
4886 Append_To (Alts,
4887 Make_Case_Statement_Alternative (Loc,
4888 Statements => New_List (Make_Exit_Statement (Loc)),
4889 Discrete_Choices => New_List (L_Lo)));
4890 end if;
4892 else
4893 -- Initial value is smallest value in predicate
4895 if Is_Itype (Ltype) then
4896 D :=
4897 Make_Object_Declaration (Loc,
4898 Defining_Identifier => Loop_Id,
4899 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4900 Expression => L_Lo);
4901 else
4902 D :=
4903 Make_Object_Declaration (Loc,
4904 Defining_Identifier => Loop_Id,
4905 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4906 Expression => Lo_Val (First (Stat)));
4907 end if;
4909 P := First (Stat);
4910 while Present (P) loop
4911 if No (Next (P)) then
4912 S := Make_Exit_Statement (Loc);
4913 else
4914 S :=
4915 Make_Assignment_Statement (Loc,
4916 Name => New_Occurrence_Of (Loop_Id, Loc),
4917 Expression => Lo_Val (Next (P)));
4918 Set_Suppress_Assignment_Checks (S);
4919 end if;
4921 Append_To (Alts,
4922 Make_Case_Statement_Alternative (Loc,
4923 Statements => New_List (S),
4924 Discrete_Choices => New_List (Hi_Val (P))));
4926 Next (P);
4927 end loop;
4929 if Is_Itype (Ltype)
4930 and then Is_OK_Static_Expression (L_Hi)
4931 and then
4932 Expr_Value (L_Hi) /= Expr_Value (Lo_Val (Last (Stat)))
4933 then
4934 Append_To (Alts,
4935 Make_Case_Statement_Alternative (Loc,
4936 Statements => New_List (Make_Exit_Statement (Loc)),
4937 Discrete_Choices => New_List (L_Hi)));
4938 end if;
4939 end if;
4941 -- Add others choice
4943 declare
4944 Name_Next : Name_Id;
4946 begin
4947 if Reverse_Present (LPS) then
4948 Name_Next := Name_Pred;
4949 else
4950 Name_Next := Name_Succ;
4951 end if;
4953 S :=
4954 Make_Assignment_Statement (Loc,
4955 Name => New_Occurrence_Of (Loop_Id, Loc),
4956 Expression =>
4957 Make_Attribute_Reference (Loc,
4958 Prefix => New_Occurrence_Of (Ltype, Loc),
4959 Attribute_Name => Name_Next,
4960 Expressions => New_List (
4961 New_Occurrence_Of (Loop_Id, Loc))));
4962 Set_Suppress_Assignment_Checks (S);
4963 end;
4965 Append_To (Alts,
4966 Make_Case_Statement_Alternative (Loc,
4967 Discrete_Choices => New_List (Make_Others_Choice (Loc)),
4968 Statements => New_List (S)));
4970 -- Construct case statement and append to body statements
4972 Cstm :=
4973 Make_Case_Statement (Loc,
4974 Expression => New_Occurrence_Of (Loop_Id, Loc),
4975 Alternatives => Alts);
4976 Append_To (Stmts, Cstm);
4978 -- Rewrite the loop
4980 Set_Suppress_Assignment_Checks (D);
4982 Rewrite (N,
4983 Make_Block_Statement (Loc,
4984 Declarations => New_List (D),
4985 Handled_Statement_Sequence =>
4986 Make_Handled_Sequence_Of_Statements (Loc,
4987 Statements => New_List (
4988 Make_Loop_Statement (Loc,
4989 Statements => Stmts,
4990 End_Label => Empty)))));
4992 Analyze (N);
4993 end Static_Predicate;
4994 end if;
4995 end Expand_Predicated_Loop;
4997 ------------------------------
4998 -- Make_Tag_Ctrl_Assignment --
4999 ------------------------------
5001 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
5002 Asn : constant Node_Id := Relocate_Node (N);
5003 L : constant Node_Id := Name (N);
5004 Loc : constant Source_Ptr := Sloc (N);
5005 Res : constant List_Id := New_List;
5006 T : constant Entity_Id := Underlying_Type (Etype (L));
5008 Comp_Asn : constant Boolean := Is_Fully_Repped_Tagged_Type (T);
5009 Ctrl_Act : constant Boolean := Needs_Finalization (T)
5010 and then not No_Ctrl_Actions (N);
5011 Save_Tag : constant Boolean := Is_Tagged_Type (T)
5012 and then not Comp_Asn
5013 and then not No_Ctrl_Actions (N)
5014 and then Tagged_Type_Expansion;
5015 Adj_Call : Node_Id;
5016 Fin_Call : Node_Id;
5017 Tag_Id : Entity_Id;
5019 begin
5020 -- Finalize the target of the assignment when controlled
5022 -- We have two exceptions here:
5024 -- 1. If we are in an init proc since it is an initialization more
5025 -- than an assignment.
5027 -- 2. If the left-hand side is a temporary that was not initialized
5028 -- (or the parent part of a temporary since it is the case in
5029 -- extension aggregates). Such a temporary does not come from
5030 -- source. We must examine the original node for the prefix, because
5031 -- it may be a component of an entry formal, in which case it has
5032 -- been rewritten and does not appear to come from source either.
5034 -- Case of init proc
5036 if not Ctrl_Act then
5037 null;
5039 -- The left-hand side is an uninitialized temporary object
5041 elsif Nkind (L) = N_Type_Conversion
5042 and then Is_Entity_Name (Expression (L))
5043 and then Nkind (Parent (Entity (Expression (L)))) =
5044 N_Object_Declaration
5045 and then No_Initialization (Parent (Entity (Expression (L))))
5046 then
5047 null;
5049 else
5050 Fin_Call :=
5051 Make_Final_Call
5052 (Obj_Ref => Duplicate_Subexpr_No_Checks (L),
5053 Typ => Etype (L));
5055 if Present (Fin_Call) then
5056 Append_To (Res, Fin_Call);
5057 end if;
5058 end if;
5060 -- Save the Tag in a local variable Tag_Id
5062 if Save_Tag then
5063 Tag_Id := Make_Temporary (Loc, 'A');
5065 Append_To (Res,
5066 Make_Object_Declaration (Loc,
5067 Defining_Identifier => Tag_Id,
5068 Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc),
5069 Expression =>
5070 Make_Selected_Component (Loc,
5071 Prefix => Duplicate_Subexpr_No_Checks (L),
5072 Selector_Name =>
5073 New_Occurrence_Of (First_Tag_Component (T), Loc))));
5075 -- Otherwise Tag_Id is not used
5077 else
5078 Tag_Id := Empty;
5079 end if;
5081 -- If the tagged type has a full rep clause, expand the assignment into
5082 -- component-wise assignments. Mark the node as unanalyzed in order to
5083 -- generate the proper code and propagate this scenario by setting a
5084 -- flag to avoid infinite recursion.
5086 if Comp_Asn then
5087 Set_Analyzed (Asn, False);
5088 Set_Componentwise_Assignment (Asn, True);
5089 end if;
5091 Append_To (Res, Asn);
5093 -- Restore the tag
5095 if Save_Tag then
5096 Append_To (Res,
5097 Make_Assignment_Statement (Loc,
5098 Name =>
5099 Make_Selected_Component (Loc,
5100 Prefix => Duplicate_Subexpr_No_Checks (L),
5101 Selector_Name =>
5102 New_Occurrence_Of (First_Tag_Component (T), Loc)),
5103 Expression => New_Occurrence_Of (Tag_Id, Loc)));
5104 end if;
5106 -- Adjust the target after the assignment when controlled (not in the
5107 -- init proc since it is an initialization more than an assignment).
5109 if Ctrl_Act then
5110 Adj_Call :=
5111 Make_Adjust_Call
5112 (Obj_Ref => Duplicate_Subexpr_Move_Checks (L),
5113 Typ => Etype (L));
5115 if Present (Adj_Call) then
5116 Append_To (Res, Adj_Call);
5117 end if;
5118 end if;
5120 return Res;
5122 exception
5124 -- Could use comment here ???
5126 when RE_Not_Available =>
5127 return Empty_List;
5128 end Make_Tag_Ctrl_Assignment;
5130 end Exp_Ch5;