* tree-vect-loop-manip.c (vect_do_peeling): Do not use
[official-gcc.git] / gcc / ada / exp_ch5.adb
blobd98e725d85ff260c4bae85ad16f5b9e26edf767d
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-2017, 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 New_Loop : Node_Id;
3140 begin
3141 -- The expansion of a formal container loop resembles the one for Ada
3142 -- containers. The only difference is that the primitives mention the
3143 -- domain of iteration explicitly, and function First applied to the
3144 -- container yields a cursor directly.
3146 -- Cursor : Cursor_type := First (Container);
3147 -- while Has_Element (Cursor, Container) loop
3148 -- <original loop statements>
3149 -- Cursor := Next (Container, Cursor);
3150 -- end loop;
3152 Build_Formal_Container_Iteration
3153 (N, Container, Cursor, Init_Decl, Advance, New_Loop);
3155 Append_To (Stats, Advance);
3157 -- Build a block to capture declaration of the cursor
3159 Rewrite (N,
3160 Make_Block_Statement (Loc,
3161 Declarations => New_List (Init_Decl),
3162 Handled_Statement_Sequence =>
3163 Make_Handled_Sequence_Of_Statements (Loc,
3164 Statements => New_List (New_Loop))));
3166 -- The loop parameter is declared by an object declaration, but within
3167 -- the loop we must prevent user assignments to it, so we analyze the
3168 -- declaration and reset the entity kind, before analyzing the rest of
3169 -- the loop.
3171 Analyze (Init_Decl);
3172 Set_Ekind (Defining_Identifier (Init_Decl), E_Loop_Parameter);
3174 -- The cursor was marked as a loop parameter to prevent user assignments
3175 -- to it, however this renders the advancement step illegal as it is not
3176 -- possible to change the value of a constant. Flag the advancement step
3177 -- as a legal form of assignment to remedy this side effect.
3179 Set_Assignment_OK (Name (Advance));
3180 Analyze (N);
3182 -- Because we have to analyze the initial declaration of the loop
3183 -- parameter multiple times its scope is incorrectly set at this point
3184 -- to the one surrounding the block statement - so set the scope
3185 -- manually to be the actual block statement.
3187 Set_Scope (Defining_Identifier (Init_Decl), Entity (Identifier (N)));
3188 end Expand_Formal_Container_Loop;
3190 ------------------------------------------
3191 -- Expand_Formal_Container_Element_Loop --
3192 ------------------------------------------
3194 procedure Expand_Formal_Container_Element_Loop (N : Node_Id) is
3195 Loc : constant Source_Ptr := Sloc (N);
3196 Isc : constant Node_Id := Iteration_Scheme (N);
3197 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3198 Element : constant Entity_Id := Defining_Identifier (I_Spec);
3199 Container : constant Node_Id := Entity (Name (I_Spec));
3200 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
3201 Stats : constant List_Id := Statements (N);
3203 Cursor : constant Entity_Id :=
3204 Make_Defining_Identifier (Loc,
3205 Chars => New_External_Name (Chars (Element), 'C'));
3206 Elmt_Decl : Node_Id;
3207 Elmt_Ref : Node_Id;
3209 Element_Op : constant Entity_Id :=
3210 Get_Iterable_Type_Primitive (Container_Typ, Name_Element);
3212 Advance : Node_Id;
3213 Init : Node_Id;
3214 New_Loop : Node_Id;
3216 begin
3217 -- For an element iterator, the Element aspect must be present,
3218 -- (this is checked during analysis) and the expansion takes the form:
3220 -- Cursor : Cursor_Type := First (Container);
3221 -- Elmt : Element_Type;
3222 -- while Has_Element (Cursor, Container) loop
3223 -- Elmt := Element (Container, Cursor);
3224 -- <original loop statements>
3225 -- Cursor := Next (Container, Cursor);
3226 -- end loop;
3228 -- However this expansion is not legal if the element is indefinite.
3229 -- In that case we create a block to hold a variable declaration
3230 -- initialized with a call to Element, and generate:
3232 -- Cursor : Cursor_Type := First (Container);
3233 -- while Has_Element (Cursor, Container) loop
3234 -- declare
3235 -- Elmt : Element_Type := Element (Container, Cursor);
3236 -- begin
3237 -- <original loop statements>
3238 -- Cursor := Next (Container, Cursor);
3239 -- end;
3240 -- end loop;
3242 Build_Formal_Container_Iteration
3243 (N, Container, Cursor, Init, Advance, New_Loop);
3244 Append_To (Stats, Advance);
3246 Set_Ekind (Cursor, E_Variable);
3247 Insert_Action (N, Init);
3249 -- Declaration for Element
3251 Elmt_Decl :=
3252 Make_Object_Declaration (Loc,
3253 Defining_Identifier => Element,
3254 Object_Definition => New_Occurrence_Of (Etype (Element_Op), Loc));
3256 if not Is_Constrained (Etype (Element_Op)) then
3257 Set_Expression (Elmt_Decl,
3258 Make_Function_Call (Loc,
3259 Name => New_Occurrence_Of (Element_Op, Loc),
3260 Parameter_Associations => New_List (
3261 Convert_To_Iterable_Type (Container, Loc),
3262 New_Occurrence_Of (Cursor, Loc))));
3264 Set_Statements (New_Loop,
3265 New_List
3266 (Make_Block_Statement (Loc,
3267 Declarations => New_List (Elmt_Decl),
3268 Handled_Statement_Sequence =>
3269 Make_Handled_Sequence_Of_Statements (Loc,
3270 Statements => Stats))));
3272 else
3273 Elmt_Ref :=
3274 Make_Assignment_Statement (Loc,
3275 Name => New_Occurrence_Of (Element, Loc),
3276 Expression =>
3277 Make_Function_Call (Loc,
3278 Name => New_Occurrence_Of (Element_Op, Loc),
3279 Parameter_Associations => New_List (
3280 Convert_To_Iterable_Type (Container, Loc),
3281 New_Occurrence_Of (Cursor, Loc))));
3283 Prepend (Elmt_Ref, Stats);
3285 -- The element is assignable in the expanded code
3287 Set_Assignment_OK (Name (Elmt_Ref));
3289 -- The loop is rewritten as a block, to hold the element declaration
3291 New_Loop :=
3292 Make_Block_Statement (Loc,
3293 Declarations => New_List (Elmt_Decl),
3294 Handled_Statement_Sequence =>
3295 Make_Handled_Sequence_Of_Statements (Loc,
3296 Statements => New_List (New_Loop)));
3297 end if;
3299 -- The element is only modified in expanded code, so it appears as
3300 -- unassigned to the warning machinery. We must suppress this spurious
3301 -- warning explicitly.
3303 Set_Warnings_Off (Element);
3305 Rewrite (N, New_Loop);
3307 -- The loop parameter is declared by an object declaration, but within
3308 -- the loop we must prevent user assignments to it, so we analyze the
3309 -- declaration and reset the entity kind, before analyzing the rest of
3310 -- the loop.
3312 Analyze (Elmt_Decl);
3313 Set_Ekind (Defining_Identifier (Elmt_Decl), E_Loop_Parameter);
3315 Analyze (N);
3316 end Expand_Formal_Container_Element_Loop;
3318 -----------------------------
3319 -- Expand_N_Goto_Statement --
3320 -----------------------------
3322 -- Add poll before goto if polling active
3324 procedure Expand_N_Goto_Statement (N : Node_Id) is
3325 begin
3326 Generate_Poll_Call (N);
3327 end Expand_N_Goto_Statement;
3329 ---------------------------
3330 -- Expand_N_If_Statement --
3331 ---------------------------
3333 -- First we deal with the case of C and Fortran convention boolean values,
3334 -- with zero/non-zero semantics.
3336 -- Second, we deal with the obvious rewriting for the cases where the
3337 -- condition of the IF is known at compile time to be True or False.
3339 -- Third, we remove elsif parts which have non-empty Condition_Actions and
3340 -- rewrite as independent if statements. For example:
3342 -- if x then xs
3343 -- elsif y then ys
3344 -- ...
3345 -- end if;
3347 -- becomes
3349 -- if x then xs
3350 -- else
3351 -- <<condition actions of y>>
3352 -- if y then ys
3353 -- ...
3354 -- end if;
3355 -- end if;
3357 -- This rewriting is needed if at least one elsif part has a non-empty
3358 -- Condition_Actions list. We also do the same processing if there is a
3359 -- constant condition in an elsif part (in conjunction with the first
3360 -- processing step mentioned above, for the recursive call made to deal
3361 -- with the created inner if, this deals with properly optimizing the
3362 -- cases of constant elsif conditions).
3364 procedure Expand_N_If_Statement (N : Node_Id) is
3365 Loc : constant Source_Ptr := Sloc (N);
3366 Hed : Node_Id;
3367 E : Node_Id;
3368 New_If : Node_Id;
3370 Warn_If_Deleted : constant Boolean :=
3371 Warn_On_Deleted_Code and then Comes_From_Source (N);
3372 -- Indicates whether we want warnings when we delete branches of the
3373 -- if statement based on constant condition analysis. We never want
3374 -- these warnings for expander generated code.
3376 begin
3377 -- Do not consider controlled objects found in an if statement which
3378 -- actually models an if expression because their early finalization
3379 -- will affect the result of the expression.
3381 if not From_Conditional_Expression (N) then
3382 Process_Statements_For_Controlled_Objects (N);
3383 end if;
3385 Adjust_Condition (Condition (N));
3387 -- The following loop deals with constant conditions for the IF. We
3388 -- need a loop because as we eliminate False conditions, we grab the
3389 -- first elsif condition and use it as the primary condition.
3391 while Compile_Time_Known_Value (Condition (N)) loop
3393 -- If condition is True, we can simply rewrite the if statement now
3394 -- by replacing it by the series of then statements.
3396 if Is_True (Expr_Value (Condition (N))) then
3398 -- All the else parts can be killed
3400 Kill_Dead_Code (Elsif_Parts (N), Warn_If_Deleted);
3401 Kill_Dead_Code (Else_Statements (N), Warn_If_Deleted);
3403 Hed := Remove_Head (Then_Statements (N));
3404 Insert_List_After (N, Then_Statements (N));
3405 Rewrite (N, Hed);
3406 return;
3408 -- If condition is False, then we can delete the condition and
3409 -- the Then statements
3411 else
3412 -- We do not delete the condition if constant condition warnings
3413 -- are enabled, since otherwise we end up deleting the desired
3414 -- warning. Of course the backend will get rid of this True/False
3415 -- test anyway, so nothing is lost here.
3417 if not Constant_Condition_Warnings then
3418 Kill_Dead_Code (Condition (N));
3419 end if;
3421 Kill_Dead_Code (Then_Statements (N), Warn_If_Deleted);
3423 -- If there are no elsif statements, then we simply replace the
3424 -- entire if statement by the sequence of else statements.
3426 if No (Elsif_Parts (N)) then
3427 if No (Else_Statements (N))
3428 or else Is_Empty_List (Else_Statements (N))
3429 then
3430 Rewrite (N,
3431 Make_Null_Statement (Sloc (N)));
3432 else
3433 Hed := Remove_Head (Else_Statements (N));
3434 Insert_List_After (N, Else_Statements (N));
3435 Rewrite (N, Hed);
3436 end if;
3438 return;
3440 -- If there are elsif statements, the first of them becomes the
3441 -- if/then section of the rebuilt if statement This is the case
3442 -- where we loop to reprocess this copied condition.
3444 else
3445 Hed := Remove_Head (Elsif_Parts (N));
3446 Insert_Actions (N, Condition_Actions (Hed));
3447 Set_Condition (N, Condition (Hed));
3448 Set_Then_Statements (N, Then_Statements (Hed));
3450 -- Hed might have been captured as the condition determining
3451 -- the current value for an entity. Now it is detached from
3452 -- the tree, so a Current_Value pointer in the condition might
3453 -- need to be updated.
3455 Set_Current_Value_Condition (N);
3457 if Is_Empty_List (Elsif_Parts (N)) then
3458 Set_Elsif_Parts (N, No_List);
3459 end if;
3460 end if;
3461 end if;
3462 end loop;
3464 -- Loop through elsif parts, dealing with constant conditions and
3465 -- possible condition actions that are present.
3467 if Present (Elsif_Parts (N)) then
3468 E := First (Elsif_Parts (N));
3469 while Present (E) loop
3471 -- Do not consider controlled objects found in an if statement
3472 -- which actually models an if expression because their early
3473 -- finalization will affect the result of the expression.
3475 if not From_Conditional_Expression (N) then
3476 Process_Statements_For_Controlled_Objects (E);
3477 end if;
3479 Adjust_Condition (Condition (E));
3481 -- If there are condition actions, then rewrite the if statement
3482 -- as indicated above. We also do the same rewrite for a True or
3483 -- False condition. The further processing of this constant
3484 -- condition is then done by the recursive call to expand the
3485 -- newly created if statement
3487 if Present (Condition_Actions (E))
3488 or else Compile_Time_Known_Value (Condition (E))
3489 then
3490 New_If :=
3491 Make_If_Statement (Sloc (E),
3492 Condition => Condition (E),
3493 Then_Statements => Then_Statements (E),
3494 Elsif_Parts => No_List,
3495 Else_Statements => Else_Statements (N));
3497 -- Elsif parts for new if come from remaining elsif's of parent
3499 while Present (Next (E)) loop
3500 if No (Elsif_Parts (New_If)) then
3501 Set_Elsif_Parts (New_If, New_List);
3502 end if;
3504 Append (Remove_Next (E), Elsif_Parts (New_If));
3505 end loop;
3507 Set_Else_Statements (N, New_List (New_If));
3509 if Present (Condition_Actions (E)) then
3510 Insert_List_Before (New_If, Condition_Actions (E));
3511 end if;
3513 Remove (E);
3515 if Is_Empty_List (Elsif_Parts (N)) then
3516 Set_Elsif_Parts (N, No_List);
3517 end if;
3519 Analyze (New_If);
3521 -- Note this is not an implicit if statement, since it is part
3522 -- of an explicit if statement in the source (or of an implicit
3523 -- if statement that has already been tested). We set the flag
3524 -- after calling Analyze to avoid generating extra warnings
3525 -- specific to pure if statements, however (see
3526 -- Sem_Ch5.Analyze_If_Statement).
3528 Set_Comes_From_Source (New_If, Comes_From_Source (N));
3529 return;
3531 -- No special processing for that elsif part, move to next
3533 else
3534 Next (E);
3535 end if;
3536 end loop;
3537 end if;
3539 -- Some more optimizations applicable if we still have an IF statement
3541 if Nkind (N) /= N_If_Statement then
3542 return;
3543 end if;
3545 -- Another optimization, special cases that can be simplified
3547 -- if expression then
3548 -- return true;
3549 -- else
3550 -- return false;
3551 -- end if;
3553 -- can be changed to:
3555 -- return expression;
3557 -- and
3559 -- if expression then
3560 -- return false;
3561 -- else
3562 -- return true;
3563 -- end if;
3565 -- can be changed to:
3567 -- return not (expression);
3569 -- Only do these optimizations if we are at least at -O1 level and
3570 -- do not do them if control flow optimizations are suppressed.
3572 if Optimization_Level > 0
3573 and then not Opt.Suppress_Control_Flow_Optimizations
3574 then
3575 if Nkind (N) = N_If_Statement
3576 and then No (Elsif_Parts (N))
3577 and then Present (Else_Statements (N))
3578 and then List_Length (Then_Statements (N)) = 1
3579 and then List_Length (Else_Statements (N)) = 1
3580 then
3581 declare
3582 Then_Stm : constant Node_Id := First (Then_Statements (N));
3583 Else_Stm : constant Node_Id := First (Else_Statements (N));
3585 begin
3586 if Nkind (Then_Stm) = N_Simple_Return_Statement
3587 and then
3588 Nkind (Else_Stm) = N_Simple_Return_Statement
3589 then
3590 declare
3591 Then_Expr : constant Node_Id := Expression (Then_Stm);
3592 Else_Expr : constant Node_Id := Expression (Else_Stm);
3594 begin
3595 if Nkind (Then_Expr) = N_Identifier
3596 and then
3597 Nkind (Else_Expr) = N_Identifier
3598 then
3599 if Entity (Then_Expr) = Standard_True
3600 and then Entity (Else_Expr) = Standard_False
3601 then
3602 Rewrite (N,
3603 Make_Simple_Return_Statement (Loc,
3604 Expression => Relocate_Node (Condition (N))));
3605 Analyze (N);
3606 return;
3608 elsif Entity (Then_Expr) = Standard_False
3609 and then Entity (Else_Expr) = Standard_True
3610 then
3611 Rewrite (N,
3612 Make_Simple_Return_Statement (Loc,
3613 Expression =>
3614 Make_Op_Not (Loc,
3615 Right_Opnd =>
3616 Relocate_Node (Condition (N)))));
3617 Analyze (N);
3618 return;
3619 end if;
3620 end if;
3621 end;
3622 end if;
3623 end;
3624 end if;
3625 end if;
3626 end Expand_N_If_Statement;
3628 --------------------------
3629 -- Expand_Iterator_Loop --
3630 --------------------------
3632 procedure Expand_Iterator_Loop (N : Node_Id) is
3633 Isc : constant Node_Id := Iteration_Scheme (N);
3634 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3636 Container : constant Node_Id := Name (I_Spec);
3637 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
3639 begin
3640 -- Processing for arrays
3642 if Is_Array_Type (Container_Typ) then
3643 pragma Assert (Of_Present (I_Spec));
3644 Expand_Iterator_Loop_Over_Array (N);
3646 elsif Has_Aspect (Container_Typ, Aspect_Iterable) then
3647 if Of_Present (I_Spec) then
3648 Expand_Formal_Container_Element_Loop (N);
3649 else
3650 Expand_Formal_Container_Loop (N);
3651 end if;
3653 -- Processing for containers
3655 else
3656 Expand_Iterator_Loop_Over_Container
3657 (N, Isc, I_Spec, Container, Container_Typ);
3658 end if;
3659 end Expand_Iterator_Loop;
3661 -------------------------------------
3662 -- Expand_Iterator_Loop_Over_Array --
3663 -------------------------------------
3665 procedure Expand_Iterator_Loop_Over_Array (N : Node_Id) is
3666 Isc : constant Node_Id := Iteration_Scheme (N);
3667 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3668 Array_Node : constant Node_Id := Name (I_Spec);
3669 Array_Typ : constant Entity_Id := Base_Type (Etype (Array_Node));
3670 Array_Dim : constant Pos := Number_Dimensions (Array_Typ);
3671 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3672 Loc : constant Source_Ptr := Sloc (N);
3673 Stats : constant List_Id := Statements (N);
3674 Core_Loop : Node_Id;
3675 Dim1 : Int;
3676 Ind_Comp : Node_Id;
3677 Iterator : Entity_Id;
3679 -- Start of processing for Expand_Iterator_Loop_Over_Array
3681 begin
3682 -- for Element of Array loop
3684 -- It requires an internally generated cursor to iterate over the array
3686 pragma Assert (Of_Present (I_Spec));
3688 Iterator := Make_Temporary (Loc, 'C');
3690 -- Generate:
3691 -- Element : Component_Type renames Array (Iterator);
3692 -- Iterator is the index value, or a list of index values
3693 -- in the case of a multidimensional array.
3695 Ind_Comp :=
3696 Make_Indexed_Component (Loc,
3697 Prefix => Relocate_Node (Array_Node),
3698 Expressions => New_List (New_Occurrence_Of (Iterator, Loc)));
3700 Prepend_To (Stats,
3701 Make_Object_Renaming_Declaration (Loc,
3702 Defining_Identifier => Id,
3703 Subtype_Mark =>
3704 New_Occurrence_Of (Component_Type (Array_Typ), Loc),
3705 Name => Ind_Comp));
3707 -- Mark the loop variable as needing debug info, so that expansion
3708 -- of the renaming will result in Materialize_Entity getting set via
3709 -- Debug_Renaming_Declaration. (This setting is needed here because
3710 -- the setting in Freeze_Entity comes after the expansion, which is
3711 -- too late. ???)
3713 Set_Debug_Info_Needed (Id);
3715 -- Generate:
3717 -- for Iterator in [reverse] Array'Range (Array_Dim) loop
3718 -- Element : Component_Type renames Array (Iterator);
3719 -- <original loop statements>
3720 -- end loop;
3722 -- If this is an iteration over a multidimensional array, the
3723 -- innermost loop is over the last dimension in Ada, and over
3724 -- the first dimension in Fortran.
3726 if Convention (Array_Typ) = Convention_Fortran then
3727 Dim1 := 1;
3728 else
3729 Dim1 := Array_Dim;
3730 end if;
3732 Core_Loop :=
3733 Make_Loop_Statement (Loc,
3734 Iteration_Scheme =>
3735 Make_Iteration_Scheme (Loc,
3736 Loop_Parameter_Specification =>
3737 Make_Loop_Parameter_Specification (Loc,
3738 Defining_Identifier => Iterator,
3739 Discrete_Subtype_Definition =>
3740 Make_Attribute_Reference (Loc,
3741 Prefix => Relocate_Node (Array_Node),
3742 Attribute_Name => Name_Range,
3743 Expressions => New_List (
3744 Make_Integer_Literal (Loc, Dim1))),
3745 Reverse_Present => Reverse_Present (I_Spec))),
3746 Statements => Stats,
3747 End_Label => Empty);
3749 -- Processing for multidimensional array. The body of each loop is
3750 -- a loop over a previous dimension, going in decreasing order in Ada
3751 -- and in increasing order in Fortran.
3753 if Array_Dim > 1 then
3754 for Dim in 1 .. Array_Dim - 1 loop
3755 if Convention (Array_Typ) = Convention_Fortran then
3756 Dim1 := Dim + 1;
3757 else
3758 Dim1 := Array_Dim - Dim;
3759 end if;
3761 Iterator := Make_Temporary (Loc, 'C');
3763 -- Generate the dimension loops starting from the innermost one
3765 -- for Iterator in [reverse] Array'Range (Array_Dim - Dim) loop
3766 -- <core loop>
3767 -- end loop;
3769 Core_Loop :=
3770 Make_Loop_Statement (Loc,
3771 Iteration_Scheme =>
3772 Make_Iteration_Scheme (Loc,
3773 Loop_Parameter_Specification =>
3774 Make_Loop_Parameter_Specification (Loc,
3775 Defining_Identifier => Iterator,
3776 Discrete_Subtype_Definition =>
3777 Make_Attribute_Reference (Loc,
3778 Prefix => Relocate_Node (Array_Node),
3779 Attribute_Name => Name_Range,
3780 Expressions => New_List (
3781 Make_Integer_Literal (Loc, Dim1))),
3782 Reverse_Present => Reverse_Present (I_Spec))),
3783 Statements => New_List (Core_Loop),
3784 End_Label => Empty);
3786 -- Update the previously created object renaming declaration with
3787 -- the new iterator, by adding the index of the next loop to the
3788 -- indexed component, in the order that corresponds to the
3789 -- convention.
3791 if Convention (Array_Typ) = Convention_Fortran then
3792 Append_To (Expressions (Ind_Comp),
3793 New_Occurrence_Of (Iterator, Loc));
3794 else
3795 Prepend_To (Expressions (Ind_Comp),
3796 New_Occurrence_Of (Iterator, Loc));
3797 end if;
3798 end loop;
3799 end if;
3801 -- Inherit the loop identifier from the original loop. This ensures that
3802 -- the scope stack is consistent after the rewriting.
3804 if Present (Identifier (N)) then
3805 Set_Identifier (Core_Loop, Relocate_Node (Identifier (N)));
3806 end if;
3808 Rewrite (N, Core_Loop);
3809 Analyze (N);
3810 end Expand_Iterator_Loop_Over_Array;
3812 -----------------------------------------
3813 -- Expand_Iterator_Loop_Over_Container --
3814 -----------------------------------------
3816 -- For a 'for ... in' loop, such as:
3818 -- for Cursor in Iterator_Function (...) loop
3819 -- ...
3820 -- end loop;
3822 -- we generate:
3824 -- Iter : Iterator_Type := Iterator_Function (...);
3825 -- Cursor : Cursor_type := First (Iter); -- or Last for "reverse"
3826 -- while Has_Element (Cursor) loop
3827 -- ...
3829 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
3830 -- end loop;
3832 -- For a 'for ... of' loop, such as:
3834 -- for X of Container loop
3835 -- ...
3836 -- end loop;
3838 -- the RM implies the generation of:
3840 -- Iter : Iterator_Type := Container.Iterate; -- the Default_Iterator
3841 -- Cursor : Cursor_Type := First (Iter); -- or Last for "reverse"
3842 -- while Has_Element (Cursor) loop
3843 -- declare
3844 -- X : Element_Type renames Element (Cursor).Element.all;
3845 -- -- or Constant_Element
3846 -- begin
3847 -- ...
3848 -- end;
3849 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
3850 -- end loop;
3852 -- In the general case, we do what the RM says. However, the operations
3853 -- Element and Iter.Next are slow, which is bad inside a loop, because they
3854 -- involve dispatching via interfaces, secondary stack manipulation,
3855 -- Busy/Lock incr/decr, and adjust/finalization/at-end handling. So for the
3856 -- predefined containers, we use an equivalent but optimized expansion.
3858 -- In the optimized case, we make use of these:
3860 -- procedure Next (Position : in out Cursor); -- instead of Iter.Next
3862 -- function Pseudo_Reference
3863 -- (Container : aliased Vector'Class) return Reference_Control_Type;
3865 -- type Element_Access is access all Element_Type;
3867 -- function Get_Element_Access
3868 -- (Position : Cursor) return not null Element_Access;
3870 -- Next is declared in the visible part of the container packages.
3871 -- The other three are added in the private part. (We're not supposed to
3872 -- pollute the namespace for clients. The compiler has no trouble breaking
3873 -- privacy to call things in the private part of an instance.)
3875 -- Source:
3877 -- for X of My_Vector loop
3878 -- X.Count := X.Count + 1;
3879 -- ...
3880 -- end loop;
3882 -- The compiler will generate:
3884 -- Iter : Reversible_Iterator'Class := Iterate (My_Vector);
3885 -- -- Reversible_Iterator is an interface. Iterate is the
3886 -- -- Default_Iterator aspect of Vector. This increments Lock,
3887 -- -- disallowing tampering with cursors. Unfortunately, it does not
3888 -- -- increment Busy. The result of Iterate is Limited_Controlled;
3889 -- -- finalization will decrement Lock. This is a build-in-place
3890 -- -- dispatching call to Iterate.
3892 -- Cur : Cursor := First (Iter); -- or Last
3893 -- -- Dispatching call via interface.
3895 -- Control : Reference_Control_Type := Pseudo_Reference (My_Vector);
3896 -- -- Pseudo_Reference increments Busy, to detect tampering with
3897 -- -- elements, as required by RM. Also redundantly increment
3898 -- -- Lock. Finalization of Control will decrement both Busy and
3899 -- -- Lock. Pseudo_Reference returns a record containing a pointer to
3900 -- -- My_Vector, used by Finalize.
3901 -- --
3902 -- -- Control is not used below, except to finalize it -- it's purely
3903 -- -- an RAII thing. This is needed because we are eliminating the
3904 -- -- call to Reference within the loop.
3906 -- while Has_Element (Cur) loop
3907 -- declare
3908 -- X : My_Element renames Get_Element_Access (Cur).all;
3909 -- -- Get_Element_Access returns a pointer to the element
3910 -- -- designated by Cur. No dispatching here, and no horsing
3911 -- -- around with access discriminants. This is instead of the
3912 -- -- existing
3913 -- --
3914 -- -- X : My_Element renames Reference (Cur).Element.all;
3915 -- --
3916 -- -- which creates a controlled object.
3917 -- begin
3918 -- -- Any attempt to tamper with My_Vector here in the loop
3919 -- -- will correctly raise Program_Error, because of the
3920 -- -- Control.
3922 -- X.Count := X.Count + 1;
3923 -- ...
3925 -- Next (Cur); -- or Prev
3926 -- -- This is instead of "Cur := Next (Iter, Cur);"
3927 -- end;
3928 -- -- No finalization here
3929 -- end loop;
3930 -- Finalize Iter and Control here, decrementing Lock twice and Busy
3931 -- once.
3933 -- This optimization makes "for ... of" loops over 30 times faster in cases
3934 -- measured.
3936 procedure Expand_Iterator_Loop_Over_Container
3937 (N : Node_Id;
3938 Isc : Node_Id;
3939 I_Spec : Node_Id;
3940 Container : Node_Id;
3941 Container_Typ : Entity_Id)
3943 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3944 Elem_Typ : constant Entity_Id := Etype (Id);
3945 Id_Kind : constant Entity_Kind := Ekind (Id);
3946 Loc : constant Source_Ptr := Sloc (N);
3947 Stats : constant List_Id := Statements (N);
3949 Cursor : Entity_Id;
3950 Decl : Node_Id;
3951 Iter_Type : Entity_Id;
3952 Iterator : Entity_Id;
3953 Name_Init : Name_Id;
3954 Name_Step : Name_Id;
3955 New_Loop : Node_Id;
3957 Fast_Element_Access_Op : Entity_Id := Empty;
3958 Fast_Step_Op : Entity_Id := Empty;
3959 -- Only for optimized version of "for ... of"
3961 Iter_Pack : Entity_Id;
3962 -- The package in which the iterator interface is instantiated. This is
3963 -- typically an instance within the container package.
3965 Pack : Entity_Id;
3966 -- The package in which the container type is declared
3968 begin
3969 -- Determine the advancement and initialization steps for the cursor.
3970 -- Analysis of the expanded loop will verify that the container has a
3971 -- reverse iterator.
3973 if Reverse_Present (I_Spec) then
3974 Name_Init := Name_Last;
3975 Name_Step := Name_Previous;
3976 else
3977 Name_Init := Name_First;
3978 Name_Step := Name_Next;
3979 end if;
3981 -- The type of the iterator is the return type of the Iterate function
3982 -- used. For the "of" form this is the default iterator for the type,
3983 -- otherwise it is the type of the explicit function used in the
3984 -- iterator specification. The most common case will be an Iterate
3985 -- function in the container package.
3987 -- The Iterator type is declared in an instance within the container
3988 -- package itself, for example:
3990 -- package Vector_Iterator_Interfaces is new
3991 -- Ada.Iterator_Interfaces (Cursor, Has_Element);
3993 -- If the container type is a derived type, the cursor type is found in
3994 -- the package of the ultimate ancestor type.
3996 if Is_Derived_Type (Container_Typ) then
3997 Pack := Scope (Root_Type (Container_Typ));
3998 else
3999 Pack := Scope (Container_Typ);
4000 end if;
4002 if Of_Present (I_Spec) then
4003 Handle_Of : declare
4004 Container_Arg : Node_Id;
4006 function Get_Default_Iterator
4007 (T : Entity_Id) return Entity_Id;
4008 -- Return the default iterator for a specific type. If the type is
4009 -- derived, we return the inherited or overridden one if
4010 -- appropriate.
4012 --------------------------
4013 -- Get_Default_Iterator --
4014 --------------------------
4016 function Get_Default_Iterator
4017 (T : Entity_Id) return Entity_Id
4019 Iter : constant Entity_Id :=
4020 Entity (Find_Value_Of_Aspect (T, Aspect_Default_Iterator));
4021 Prim : Elmt_Id;
4022 Op : Entity_Id;
4024 begin
4025 Container_Arg := New_Copy_Tree (Container);
4027 -- A previous version of GNAT allowed indexing aspects to be
4028 -- redefined on derived container types, while the default
4029 -- iterator was inherited from the parent type. This
4030 -- nonstandard extension is preserved for use by the
4031 -- modeling project under debug flag -gnatd.X.
4033 if Debug_Flag_Dot_XX then
4034 if Base_Type (Etype (Container)) /=
4035 Base_Type (Etype (First_Formal (Iter)))
4036 then
4037 Container_Arg :=
4038 Make_Type_Conversion (Loc,
4039 Subtype_Mark =>
4040 New_Occurrence_Of
4041 (Etype (First_Formal (Iter)), Loc),
4042 Expression => Container_Arg);
4043 end if;
4045 return Iter;
4047 elsif Is_Derived_Type (T) then
4049 -- The default iterator must be a primitive operation of the
4050 -- type, at the same dispatch slot position. The DT position
4051 -- may not be established if type is not frozen yet.
4053 Prim := First_Elmt (Primitive_Operations (T));
4054 while Present (Prim) loop
4055 Op := Node (Prim);
4057 if Alias (Op) = Iter
4058 or else
4059 (Chars (Op) = Chars (Iter)
4060 and then Present (DTC_Entity (Op))
4061 and then DT_Position (Op) = DT_Position (Iter))
4062 then
4063 return Op;
4064 end if;
4066 Next_Elmt (Prim);
4067 end loop;
4069 -- If we didn't find it, then our parent type is not
4070 -- iterable, so we return the Default_Iterator aspect of
4071 -- this type.
4073 return Iter;
4075 -- Otherwise not a derived type
4077 else
4078 return Iter;
4079 end if;
4080 end Get_Default_Iterator;
4082 -- Local variables
4084 Default_Iter : Entity_Id;
4085 Ent : Entity_Id;
4087 Reference_Control_Type : Entity_Id := Empty;
4088 Pseudo_Reference : Entity_Id := Empty;
4090 -- Start of processing for Handle_Of
4092 begin
4093 if Is_Class_Wide_Type (Container_Typ) then
4094 Default_Iter :=
4095 Get_Default_Iterator (Etype (Base_Type (Container_Typ)));
4096 else
4097 Default_Iter := Get_Default_Iterator (Etype (Container));
4098 end if;
4100 Cursor := Make_Temporary (Loc, 'C');
4102 -- For a container element iterator, the iterator type is obtained
4103 -- from the corresponding aspect, whose return type is descended
4104 -- from the corresponding interface type in some instance of
4105 -- Ada.Iterator_Interfaces. The actuals of that instantiation
4106 -- are Cursor and Has_Element.
4108 Iter_Type := Etype (Default_Iter);
4110 -- The iterator type, which is a class-wide type, may itself be
4111 -- derived locally, so the desired instantiation is the scope of
4112 -- the root type of the iterator type.
4114 Iter_Pack := Scope (Root_Type (Etype (Iter_Type)));
4116 -- Find declarations needed for "for ... of" optimization
4118 Ent := First_Entity (Pack);
4119 while Present (Ent) loop
4120 if Chars (Ent) = Name_Get_Element_Access then
4121 Fast_Element_Access_Op := Ent;
4123 elsif Chars (Ent) = Name_Step
4124 and then Ekind (Ent) = E_Procedure
4125 then
4126 Fast_Step_Op := Ent;
4128 elsif Chars (Ent) = Name_Reference_Control_Type then
4129 Reference_Control_Type := Ent;
4131 elsif Chars (Ent) = Name_Pseudo_Reference then
4132 Pseudo_Reference := Ent;
4133 end if;
4135 Next_Entity (Ent);
4136 end loop;
4138 if Present (Reference_Control_Type)
4139 and then Present (Pseudo_Reference)
4140 then
4141 Insert_Action (N,
4142 Make_Object_Declaration (Loc,
4143 Defining_Identifier => Make_Temporary (Loc, 'D'),
4144 Object_Definition =>
4145 New_Occurrence_Of (Reference_Control_Type, Loc),
4146 Expression =>
4147 Make_Function_Call (Loc,
4148 Name =>
4149 New_Occurrence_Of (Pseudo_Reference, Loc),
4150 Parameter_Associations =>
4151 New_List (New_Copy_Tree (Container_Arg)))));
4152 end if;
4154 -- Rewrite domain of iteration as a call to the default iterator
4155 -- for the container type. The formal may be an access parameter
4156 -- in which case we must build a reference to the container.
4158 declare
4159 Arg : Node_Id;
4160 begin
4161 if Is_Access_Type (Etype (First_Entity (Default_Iter))) then
4162 Arg :=
4163 Make_Attribute_Reference (Loc,
4164 Prefix => Container_Arg,
4165 Attribute_Name => Name_Unrestricted_Access);
4166 else
4167 Arg := Container_Arg;
4168 end if;
4170 Rewrite (Name (I_Spec),
4171 Make_Function_Call (Loc,
4172 Name =>
4173 New_Occurrence_Of (Default_Iter, Loc),
4174 Parameter_Associations => New_List (Arg)));
4175 end;
4177 Analyze_And_Resolve (Name (I_Spec));
4179 -- Find cursor type in proper iterator package, which is an
4180 -- instantiation of Iterator_Interfaces.
4182 Ent := First_Entity (Iter_Pack);
4183 while Present (Ent) loop
4184 if Chars (Ent) = Name_Cursor then
4185 Set_Etype (Cursor, Etype (Ent));
4186 exit;
4187 end if;
4189 Next_Entity (Ent);
4190 end loop;
4192 if Present (Fast_Element_Access_Op) then
4193 Decl :=
4194 Make_Object_Renaming_Declaration (Loc,
4195 Defining_Identifier => Id,
4196 Subtype_Mark =>
4197 New_Occurrence_Of (Elem_Typ, Loc),
4198 Name =>
4199 Make_Explicit_Dereference (Loc,
4200 Prefix =>
4201 Make_Function_Call (Loc,
4202 Name =>
4203 New_Occurrence_Of (Fast_Element_Access_Op, Loc),
4204 Parameter_Associations =>
4205 New_List (New_Occurrence_Of (Cursor, Loc)))));
4207 else
4208 Decl :=
4209 Make_Object_Renaming_Declaration (Loc,
4210 Defining_Identifier => Id,
4211 Subtype_Mark =>
4212 New_Occurrence_Of (Elem_Typ, Loc),
4213 Name =>
4214 Make_Indexed_Component (Loc,
4215 Prefix => Relocate_Node (Container_Arg),
4216 Expressions =>
4217 New_List (New_Occurrence_Of (Cursor, Loc))));
4218 end if;
4220 -- The defining identifier in the iterator is user-visible and
4221 -- must be visible in the debugger.
4223 Set_Debug_Info_Needed (Id);
4225 -- If the container does not have a variable indexing aspect,
4226 -- the element is a constant in the loop. The container itself
4227 -- may be constant, in which case the element is a constant as
4228 -- well. The container has been rewritten as a call to Iterate,
4229 -- so examine original node.
4231 if No (Find_Value_Of_Aspect
4232 (Container_Typ, Aspect_Variable_Indexing))
4233 or else not Is_Variable (Original_Node (Container))
4234 then
4235 Set_Ekind (Id, E_Constant);
4236 end if;
4238 Prepend_To (Stats, Decl);
4239 end Handle_Of;
4241 -- X in Iterate (S) : type of iterator is type of explicitly given
4242 -- Iterate function, and the loop variable is the cursor. It will be
4243 -- assigned in the loop and must be a variable.
4245 else
4246 Iter_Type := Etype (Name (I_Spec));
4248 -- The iterator type, which is a class-wide type, may itself be
4249 -- derived locally, so the desired instantiation is the scope of
4250 -- the root type of the iterator type, as in the "of" case.
4252 Iter_Pack := Scope (Root_Type (Etype (Iter_Type)));
4253 Cursor := Id;
4254 end if;
4256 Iterator := Make_Temporary (Loc, 'I');
4258 -- For both iterator forms, add a call to the step operation to advance
4259 -- the cursor. Generate:
4261 -- Cursor := Iterator.Next (Cursor);
4263 -- or else
4265 -- Cursor := Next (Cursor);
4267 if Present (Fast_Element_Access_Op) and then Present (Fast_Step_Op) then
4268 declare
4269 Curs_Name : constant Node_Id := New_Occurrence_Of (Cursor, Loc);
4270 Step_Call : Node_Id;
4272 begin
4273 Step_Call :=
4274 Make_Procedure_Call_Statement (Loc,
4275 Name =>
4276 New_Occurrence_Of (Fast_Step_Op, Loc),
4277 Parameter_Associations => New_List (Curs_Name));
4279 Append_To (Stats, Step_Call);
4280 Set_Assignment_OK (Curs_Name);
4281 end;
4283 else
4284 declare
4285 Rhs : Node_Id;
4287 begin
4288 Rhs :=
4289 Make_Function_Call (Loc,
4290 Name =>
4291 Make_Selected_Component (Loc,
4292 Prefix => New_Occurrence_Of (Iterator, Loc),
4293 Selector_Name => Make_Identifier (Loc, Name_Step)),
4294 Parameter_Associations => New_List (
4295 New_Occurrence_Of (Cursor, Loc)));
4297 Append_To (Stats,
4298 Make_Assignment_Statement (Loc,
4299 Name => New_Occurrence_Of (Cursor, Loc),
4300 Expression => Rhs));
4301 Set_Assignment_OK (Name (Last (Stats)));
4302 end;
4303 end if;
4305 -- Generate:
4306 -- while Has_Element (Cursor) loop
4307 -- <Stats>
4308 -- end loop;
4310 -- Has_Element is the second actual in the iterator package
4312 New_Loop :=
4313 Make_Loop_Statement (Loc,
4314 Iteration_Scheme =>
4315 Make_Iteration_Scheme (Loc,
4316 Condition =>
4317 Make_Function_Call (Loc,
4318 Name =>
4319 New_Occurrence_Of
4320 (Next_Entity (First_Entity (Iter_Pack)), Loc),
4321 Parameter_Associations => New_List (
4322 New_Occurrence_Of (Cursor, Loc)))),
4324 Statements => Stats,
4325 End_Label => Empty);
4327 -- If present, preserve identifier of loop, which can be used in an exit
4328 -- statement in the body.
4330 if Present (Identifier (N)) then
4331 Set_Identifier (New_Loop, Relocate_Node (Identifier (N)));
4332 end if;
4334 -- Create the declarations for Iterator and cursor and insert them
4335 -- before the source loop. Given that the domain of iteration is already
4336 -- an entity, the iterator is just a renaming of that entity. Possible
4337 -- optimization ???
4339 Insert_Action (N,
4340 Make_Object_Renaming_Declaration (Loc,
4341 Defining_Identifier => Iterator,
4342 Subtype_Mark => New_Occurrence_Of (Iter_Type, Loc),
4343 Name => Relocate_Node (Name (I_Spec))));
4345 -- Create declaration for cursor
4347 declare
4348 Cursor_Decl : constant Node_Id :=
4349 Make_Object_Declaration (Loc,
4350 Defining_Identifier => Cursor,
4351 Object_Definition =>
4352 New_Occurrence_Of (Etype (Cursor), Loc),
4353 Expression =>
4354 Make_Selected_Component (Loc,
4355 Prefix =>
4356 New_Occurrence_Of (Iterator, Loc),
4357 Selector_Name =>
4358 Make_Identifier (Loc, Name_Init)));
4360 begin
4361 -- The cursor is only modified in expanded code, so it appears
4362 -- as unassigned to the warning machinery. We must suppress this
4363 -- spurious warning explicitly. The cursor's kind is that of the
4364 -- original loop parameter (it is a constant if the domain of
4365 -- iteration is constant).
4367 Set_Warnings_Off (Cursor);
4368 Set_Assignment_OK (Cursor_Decl);
4370 Insert_Action (N, Cursor_Decl);
4371 Set_Ekind (Cursor, Id_Kind);
4372 end;
4374 -- If the range of iteration is given by a function call that returns
4375 -- a container, the finalization actions have been saved in the
4376 -- Condition_Actions of the iterator. Insert them now at the head of
4377 -- the loop.
4379 if Present (Condition_Actions (Isc)) then
4380 Insert_List_Before (N, Condition_Actions (Isc));
4381 end if;
4383 Rewrite (N, New_Loop);
4384 Analyze (N);
4385 end Expand_Iterator_Loop_Over_Container;
4387 -----------------------------
4388 -- Expand_N_Loop_Statement --
4389 -----------------------------
4391 -- 1. Remove null loop entirely
4392 -- 2. Deal with while condition for C/Fortran boolean
4393 -- 3. Deal with loops with a non-standard enumeration type range
4394 -- 4. Deal with while loops where Condition_Actions is set
4395 -- 5. Deal with loops over predicated subtypes
4396 -- 6. Deal with loops with iterators over arrays and containers
4397 -- 7. Insert polling call if required
4399 procedure Expand_N_Loop_Statement (N : Node_Id) is
4400 Loc : constant Source_Ptr := Sloc (N);
4401 Scheme : constant Node_Id := Iteration_Scheme (N);
4402 Stmt : Node_Id;
4404 begin
4405 -- Delete null loop
4407 if Is_Null_Loop (N) then
4408 Rewrite (N, Make_Null_Statement (Loc));
4409 return;
4410 end if;
4412 -- Deal with condition for C/Fortran Boolean
4414 if Present (Scheme) then
4415 Adjust_Condition (Condition (Scheme));
4416 end if;
4418 -- Generate polling call
4420 if Is_Non_Empty_List (Statements (N)) then
4421 Generate_Poll_Call (First (Statements (N)));
4422 end if;
4424 -- Nothing more to do for plain loop with no iteration scheme
4426 if No (Scheme) then
4427 null;
4429 -- Case of for loop (Loop_Parameter_Specification present)
4431 -- Note: we do not have to worry about validity checking of the for loop
4432 -- range bounds here, since they were frozen with constant declarations
4433 -- and it is during that process that the validity checking is done.
4435 elsif Present (Loop_Parameter_Specification (Scheme)) then
4436 declare
4437 LPS : constant Node_Id :=
4438 Loop_Parameter_Specification (Scheme);
4439 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4440 Ltype : constant Entity_Id := Etype (Loop_Id);
4441 Btype : constant Entity_Id := Base_Type (Ltype);
4442 Expr : Node_Id;
4443 Decls : List_Id;
4444 New_Id : Entity_Id;
4446 begin
4447 -- Deal with loop over predicates
4449 if Is_Discrete_Type (Ltype)
4450 and then Present (Predicate_Function (Ltype))
4451 then
4452 Expand_Predicated_Loop (N);
4454 -- Handle the case where we have a for loop with the range type
4455 -- being an enumeration type with non-standard representation.
4456 -- In this case we expand:
4458 -- for x in [reverse] a .. b loop
4459 -- ...
4460 -- end loop;
4462 -- to
4464 -- for xP in [reverse] integer
4465 -- range etype'Pos (a) .. etype'Pos (b)
4466 -- loop
4467 -- declare
4468 -- x : constant etype := Pos_To_Rep (xP);
4469 -- begin
4470 -- ...
4471 -- end;
4472 -- end loop;
4474 elsif Is_Enumeration_Type (Btype)
4475 and then Present (Enum_Pos_To_Rep (Btype))
4476 then
4477 New_Id :=
4478 Make_Defining_Identifier (Loc,
4479 Chars => New_External_Name (Chars (Loop_Id), 'P'));
4481 -- If the type has a contiguous representation, successive
4482 -- values can be generated as offsets from the first literal.
4484 if Has_Contiguous_Rep (Btype) then
4485 Expr :=
4486 Unchecked_Convert_To (Btype,
4487 Make_Op_Add (Loc,
4488 Left_Opnd =>
4489 Make_Integer_Literal (Loc,
4490 Enumeration_Rep (First_Literal (Btype))),
4491 Right_Opnd => New_Occurrence_Of (New_Id, Loc)));
4492 else
4493 -- Use the constructed array Enum_Pos_To_Rep
4495 Expr :=
4496 Make_Indexed_Component (Loc,
4497 Prefix =>
4498 New_Occurrence_Of (Enum_Pos_To_Rep (Btype), Loc),
4499 Expressions =>
4500 New_List (New_Occurrence_Of (New_Id, Loc)));
4501 end if;
4503 -- Build declaration for loop identifier
4505 Decls :=
4506 New_List (
4507 Make_Object_Declaration (Loc,
4508 Defining_Identifier => Loop_Id,
4509 Constant_Present => True,
4510 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4511 Expression => Expr));
4513 Rewrite (N,
4514 Make_Loop_Statement (Loc,
4515 Identifier => Identifier (N),
4517 Iteration_Scheme =>
4518 Make_Iteration_Scheme (Loc,
4519 Loop_Parameter_Specification =>
4520 Make_Loop_Parameter_Specification (Loc,
4521 Defining_Identifier => New_Id,
4522 Reverse_Present => Reverse_Present (LPS),
4524 Discrete_Subtype_Definition =>
4525 Make_Subtype_Indication (Loc,
4527 Subtype_Mark =>
4528 New_Occurrence_Of (Standard_Natural, Loc),
4530 Constraint =>
4531 Make_Range_Constraint (Loc,
4532 Range_Expression =>
4533 Make_Range (Loc,
4535 Low_Bound =>
4536 Make_Attribute_Reference (Loc,
4537 Prefix =>
4538 New_Occurrence_Of (Btype, Loc),
4540 Attribute_Name => Name_Pos,
4542 Expressions => New_List (
4543 Relocate_Node
4544 (Type_Low_Bound (Ltype)))),
4546 High_Bound =>
4547 Make_Attribute_Reference (Loc,
4548 Prefix =>
4549 New_Occurrence_Of (Btype, Loc),
4551 Attribute_Name => Name_Pos,
4553 Expressions => New_List (
4554 Relocate_Node
4555 (Type_High_Bound
4556 (Ltype))))))))),
4558 Statements => New_List (
4559 Make_Block_Statement (Loc,
4560 Declarations => Decls,
4561 Handled_Statement_Sequence =>
4562 Make_Handled_Sequence_Of_Statements (Loc,
4563 Statements => Statements (N)))),
4565 End_Label => End_Label (N)));
4567 -- The loop parameter's entity must be removed from the loop
4568 -- scope's entity list and rendered invisible, since it will
4569 -- now be located in the new block scope. Any other entities
4570 -- already associated with the loop scope, such as the loop
4571 -- parameter's subtype, will remain there.
4573 -- In an element loop, the loop will contain a declaration for
4574 -- a cursor variable; otherwise the loop id is the first entity
4575 -- in the scope constructed for the loop.
4577 if Comes_From_Source (Loop_Id) then
4578 pragma Assert (First_Entity (Scope (Loop_Id)) = Loop_Id);
4579 null;
4580 end if;
4582 Set_First_Entity (Scope (Loop_Id), Next_Entity (Loop_Id));
4583 Remove_Homonym (Loop_Id);
4585 if Last_Entity (Scope (Loop_Id)) = Loop_Id then
4586 Set_Last_Entity (Scope (Loop_Id), Empty);
4587 end if;
4589 Analyze (N);
4591 -- Nothing to do with other cases of for loops
4593 else
4594 null;
4595 end if;
4596 end;
4598 -- Second case, if we have a while loop with Condition_Actions set, then
4599 -- we change it into a plain loop:
4601 -- while C loop
4602 -- ...
4603 -- end loop;
4605 -- changed to:
4607 -- loop
4608 -- <<condition actions>>
4609 -- exit when not C;
4610 -- ...
4611 -- end loop
4613 elsif Present (Scheme)
4614 and then Present (Condition_Actions (Scheme))
4615 and then Present (Condition (Scheme))
4616 then
4617 declare
4618 ES : Node_Id;
4620 begin
4621 ES :=
4622 Make_Exit_Statement (Sloc (Condition (Scheme)),
4623 Condition =>
4624 Make_Op_Not (Sloc (Condition (Scheme)),
4625 Right_Opnd => Condition (Scheme)));
4627 Prepend (ES, Statements (N));
4628 Insert_List_Before (ES, Condition_Actions (Scheme));
4630 -- This is not an implicit loop, since it is generated in response
4631 -- to the loop statement being processed. If this is itself
4632 -- implicit, the restriction has already been checked. If not,
4633 -- it is an explicit loop.
4635 Rewrite (N,
4636 Make_Loop_Statement (Sloc (N),
4637 Identifier => Identifier (N),
4638 Statements => Statements (N),
4639 End_Label => End_Label (N)));
4641 Analyze (N);
4642 end;
4644 -- Here to deal with iterator case
4646 elsif Present (Scheme)
4647 and then Present (Iterator_Specification (Scheme))
4648 then
4649 Expand_Iterator_Loop (N);
4651 -- An iterator loop may generate renaming declarations for elements
4652 -- that require debug information. This is the case in particular
4653 -- with element iterators, where debug information must be generated
4654 -- for the temporary that holds the element value. These temporaries
4655 -- are created within a transient block whose local declarations are
4656 -- transferred to the loop, which now has nontrivial local objects.
4658 if Nkind (N) = N_Loop_Statement
4659 and then Present (Identifier (N))
4660 then
4661 Qualify_Entity_Names (N);
4662 end if;
4663 end if;
4665 -- When the iteration scheme mentiones attribute 'Loop_Entry, the loop
4666 -- is transformed into a conditional block where the original loop is
4667 -- the sole statement. Inspect the statements of the nested loop for
4668 -- controlled objects.
4670 Stmt := N;
4672 if Subject_To_Loop_Entry_Attributes (Stmt) then
4673 Stmt := Find_Loop_In_Conditional_Block (Stmt);
4674 end if;
4676 Process_Statements_For_Controlled_Objects (Stmt);
4677 end Expand_N_Loop_Statement;
4679 ----------------------------
4680 -- Expand_Predicated_Loop --
4681 ----------------------------
4683 -- Note: the expander can handle generation of loops over predicated
4684 -- subtypes for both the dynamic and static cases. Depending on what
4685 -- we decide is allowed in Ada 2012 mode and/or extensions allowed
4686 -- mode, the semantic analyzer may disallow one or both forms.
4688 procedure Expand_Predicated_Loop (N : Node_Id) is
4689 Loc : constant Source_Ptr := Sloc (N);
4690 Isc : constant Node_Id := Iteration_Scheme (N);
4691 LPS : constant Node_Id := Loop_Parameter_Specification (Isc);
4692 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4693 Ltype : constant Entity_Id := Etype (Loop_Id);
4694 Stat : constant List_Id := Static_Discrete_Predicate (Ltype);
4695 Stmts : constant List_Id := Statements (N);
4697 begin
4698 -- Case of iteration over non-static predicate, should not be possible
4699 -- since this is not allowed by the semantics and should have been
4700 -- caught during analysis of the loop statement.
4702 if No (Stat) then
4703 raise Program_Error;
4705 -- If the predicate list is empty, that corresponds to a predicate of
4706 -- False, in which case the loop won't run at all, and we rewrite the
4707 -- entire loop as a null statement.
4709 elsif Is_Empty_List (Stat) then
4710 Rewrite (N, Make_Null_Statement (Loc));
4711 Analyze (N);
4713 -- For expansion over a static predicate we generate the following
4715 -- declare
4716 -- J : Ltype := min-val;
4717 -- begin
4718 -- loop
4719 -- body
4720 -- case J is
4721 -- when endpoint => J := startpoint;
4722 -- when endpoint => J := startpoint;
4723 -- ...
4724 -- when max-val => exit;
4725 -- when others => J := Lval'Succ (J);
4726 -- end case;
4727 -- end loop;
4728 -- end;
4730 -- with min-val replaced by max-val and Succ replaced by Pred if the
4731 -- loop parameter specification carries a Reverse indicator.
4733 -- To make this a little clearer, let's take a specific example:
4735 -- type Int is range 1 .. 10;
4736 -- subtype StaticP is Int with
4737 -- predicate => StaticP in 3 | 10 | 5 .. 7;
4738 -- ...
4739 -- for L in StaticP loop
4740 -- Put_Line ("static:" & J'Img);
4741 -- end loop;
4743 -- In this case, the loop is transformed into
4745 -- begin
4746 -- J : L := 3;
4747 -- loop
4748 -- body
4749 -- case J is
4750 -- when 3 => J := 5;
4751 -- when 7 => J := 10;
4752 -- when 10 => exit;
4753 -- when others => J := L'Succ (J);
4754 -- end case;
4755 -- end loop;
4756 -- end;
4758 -- In addition, if the loop specification is given by a subtype
4759 -- indication that constrains a predicated type, the bounds of
4760 -- iteration are given by those of the subtype indication.
4762 else
4763 Static_Predicate : declare
4764 S : Node_Id;
4765 D : Node_Id;
4766 P : Node_Id;
4767 Alts : List_Id;
4768 Cstm : Node_Id;
4770 -- If the domain is an itype, note the bounds of its range.
4772 L_Hi : Node_Id := Empty;
4773 L_Lo : Node_Id := Empty;
4775 function Lo_Val (N : Node_Id) return Node_Id;
4776 -- Given static expression or static range, returns an identifier
4777 -- whose value is the low bound of the expression value or range.
4779 function Hi_Val (N : Node_Id) return Node_Id;
4780 -- Given static expression or static range, returns an identifier
4781 -- whose value is the high bound of the expression value or range.
4783 ------------
4784 -- Hi_Val --
4785 ------------
4787 function Hi_Val (N : Node_Id) return Node_Id is
4788 begin
4789 if Is_OK_Static_Expression (N) then
4790 return New_Copy (N);
4791 else
4792 pragma Assert (Nkind (N) = N_Range);
4793 return New_Copy (High_Bound (N));
4794 end if;
4795 end Hi_Val;
4797 ------------
4798 -- Lo_Val --
4799 ------------
4801 function Lo_Val (N : Node_Id) return Node_Id is
4802 begin
4803 if Is_OK_Static_Expression (N) then
4804 return New_Copy (N);
4805 else
4806 pragma Assert (Nkind (N) = N_Range);
4807 return New_Copy (Low_Bound (N));
4808 end if;
4809 end Lo_Val;
4811 -- Start of processing for Static_Predicate
4813 begin
4814 -- Convert loop identifier to normal variable and reanalyze it so
4815 -- that this conversion works. We have to use the same defining
4816 -- identifier, since there may be references in the loop body.
4818 Set_Analyzed (Loop_Id, False);
4819 Set_Ekind (Loop_Id, E_Variable);
4821 -- In most loops the loop variable is assigned in various
4822 -- alternatives in the body. However, in the rare case when
4823 -- the range specifies a single element, the loop variable
4824 -- may trigger a spurious warning that is could be constant.
4825 -- This warning might as well be suppressed.
4827 Set_Warnings_Off (Loop_Id);
4829 if Is_Itype (Ltype) then
4830 L_Hi := High_Bound (Scalar_Range (Ltype));
4831 L_Lo := Low_Bound (Scalar_Range (Ltype));
4832 end if;
4834 -- Loop to create branches of case statement
4836 Alts := New_List;
4838 if Reverse_Present (LPS) then
4840 -- Initial value is largest value in predicate.
4842 if Is_Itype (Ltype) then
4843 D :=
4844 Make_Object_Declaration (Loc,
4845 Defining_Identifier => Loop_Id,
4846 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4847 Expression => L_Hi);
4849 else
4850 D :=
4851 Make_Object_Declaration (Loc,
4852 Defining_Identifier => Loop_Id,
4853 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4854 Expression => Hi_Val (Last (Stat)));
4855 end if;
4857 P := Last (Stat);
4858 while Present (P) loop
4859 if No (Prev (P)) then
4860 S := Make_Exit_Statement (Loc);
4861 else
4862 S :=
4863 Make_Assignment_Statement (Loc,
4864 Name => New_Occurrence_Of (Loop_Id, Loc),
4865 Expression => Hi_Val (Prev (P)));
4866 Set_Suppress_Assignment_Checks (S);
4867 end if;
4869 Append_To (Alts,
4870 Make_Case_Statement_Alternative (Loc,
4871 Statements => New_List (S),
4872 Discrete_Choices => New_List (Lo_Val (P))));
4874 Prev (P);
4875 end loop;
4877 if Is_Itype (Ltype)
4878 and then Is_OK_Static_Expression (L_Lo)
4879 and then
4880 Expr_Value (L_Lo) /= Expr_Value (Lo_Val (First (Stat)))
4881 then
4882 Append_To (Alts,
4883 Make_Case_Statement_Alternative (Loc,
4884 Statements => New_List (Make_Exit_Statement (Loc)),
4885 Discrete_Choices => New_List (L_Lo)));
4886 end if;
4888 else
4889 -- Initial value is smallest value in predicate
4891 if Is_Itype (Ltype) then
4892 D :=
4893 Make_Object_Declaration (Loc,
4894 Defining_Identifier => Loop_Id,
4895 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4896 Expression => L_Lo);
4897 else
4898 D :=
4899 Make_Object_Declaration (Loc,
4900 Defining_Identifier => Loop_Id,
4901 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4902 Expression => Lo_Val (First (Stat)));
4903 end if;
4905 P := First (Stat);
4906 while Present (P) loop
4907 if No (Next (P)) then
4908 S := Make_Exit_Statement (Loc);
4909 else
4910 S :=
4911 Make_Assignment_Statement (Loc,
4912 Name => New_Occurrence_Of (Loop_Id, Loc),
4913 Expression => Lo_Val (Next (P)));
4914 Set_Suppress_Assignment_Checks (S);
4915 end if;
4917 Append_To (Alts,
4918 Make_Case_Statement_Alternative (Loc,
4919 Statements => New_List (S),
4920 Discrete_Choices => New_List (Hi_Val (P))));
4922 Next (P);
4923 end loop;
4925 if Is_Itype (Ltype)
4926 and then Is_OK_Static_Expression (L_Hi)
4927 and then
4928 Expr_Value (L_Hi) /= Expr_Value (Lo_Val (Last (Stat)))
4929 then
4930 Append_To (Alts,
4931 Make_Case_Statement_Alternative (Loc,
4932 Statements => New_List (Make_Exit_Statement (Loc)),
4933 Discrete_Choices => New_List (L_Hi)));
4934 end if;
4935 end if;
4937 -- Add others choice
4939 declare
4940 Name_Next : Name_Id;
4942 begin
4943 if Reverse_Present (LPS) then
4944 Name_Next := Name_Pred;
4945 else
4946 Name_Next := Name_Succ;
4947 end if;
4949 S :=
4950 Make_Assignment_Statement (Loc,
4951 Name => New_Occurrence_Of (Loop_Id, Loc),
4952 Expression =>
4953 Make_Attribute_Reference (Loc,
4954 Prefix => New_Occurrence_Of (Ltype, Loc),
4955 Attribute_Name => Name_Next,
4956 Expressions => New_List (
4957 New_Occurrence_Of (Loop_Id, Loc))));
4958 Set_Suppress_Assignment_Checks (S);
4959 end;
4961 Append_To (Alts,
4962 Make_Case_Statement_Alternative (Loc,
4963 Discrete_Choices => New_List (Make_Others_Choice (Loc)),
4964 Statements => New_List (S)));
4966 -- Construct case statement and append to body statements
4968 Cstm :=
4969 Make_Case_Statement (Loc,
4970 Expression => New_Occurrence_Of (Loop_Id, Loc),
4971 Alternatives => Alts);
4972 Append_To (Stmts, Cstm);
4974 -- Rewrite the loop
4976 Set_Suppress_Assignment_Checks (D);
4978 Rewrite (N,
4979 Make_Block_Statement (Loc,
4980 Declarations => New_List (D),
4981 Handled_Statement_Sequence =>
4982 Make_Handled_Sequence_Of_Statements (Loc,
4983 Statements => New_List (
4984 Make_Loop_Statement (Loc,
4985 Statements => Stmts,
4986 End_Label => Empty)))));
4988 Analyze (N);
4989 end Static_Predicate;
4990 end if;
4991 end Expand_Predicated_Loop;
4993 ------------------------------
4994 -- Make_Tag_Ctrl_Assignment --
4995 ------------------------------
4997 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
4998 Asn : constant Node_Id := Relocate_Node (N);
4999 L : constant Node_Id := Name (N);
5000 Loc : constant Source_Ptr := Sloc (N);
5001 Res : constant List_Id := New_List;
5002 T : constant Entity_Id := Underlying_Type (Etype (L));
5004 Comp_Asn : constant Boolean := Is_Fully_Repped_Tagged_Type (T);
5005 Ctrl_Act : constant Boolean := Needs_Finalization (T)
5006 and then not No_Ctrl_Actions (N);
5007 Save_Tag : constant Boolean := Is_Tagged_Type (T)
5008 and then not Comp_Asn
5009 and then not No_Ctrl_Actions (N)
5010 and then Tagged_Type_Expansion;
5011 Adj_Call : Node_Id;
5012 Fin_Call : Node_Id;
5013 Tag_Id : Entity_Id;
5015 begin
5016 -- Finalize the target of the assignment when controlled
5018 -- We have two exceptions here:
5020 -- 1. If we are in an init proc since it is an initialization more
5021 -- than an assignment.
5023 -- 2. If the left-hand side is a temporary that was not initialized
5024 -- (or the parent part of a temporary since it is the case in
5025 -- extension aggregates). Such a temporary does not come from
5026 -- source. We must examine the original node for the prefix, because
5027 -- it may be a component of an entry formal, in which case it has
5028 -- been rewritten and does not appear to come from source either.
5030 -- Case of init proc
5032 if not Ctrl_Act then
5033 null;
5035 -- The left-hand side is an uninitialized temporary object
5037 elsif Nkind (L) = N_Type_Conversion
5038 and then Is_Entity_Name (Expression (L))
5039 and then Nkind (Parent (Entity (Expression (L)))) =
5040 N_Object_Declaration
5041 and then No_Initialization (Parent (Entity (Expression (L))))
5042 then
5043 null;
5045 else
5046 Fin_Call :=
5047 Make_Final_Call
5048 (Obj_Ref => Duplicate_Subexpr_No_Checks (L),
5049 Typ => Etype (L));
5051 if Present (Fin_Call) then
5052 Append_To (Res, Fin_Call);
5053 end if;
5054 end if;
5056 -- Save the Tag in a local variable Tag_Id
5058 if Save_Tag then
5059 Tag_Id := Make_Temporary (Loc, 'A');
5061 Append_To (Res,
5062 Make_Object_Declaration (Loc,
5063 Defining_Identifier => Tag_Id,
5064 Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc),
5065 Expression =>
5066 Make_Selected_Component (Loc,
5067 Prefix => Duplicate_Subexpr_No_Checks (L),
5068 Selector_Name =>
5069 New_Occurrence_Of (First_Tag_Component (T), Loc))));
5071 -- Otherwise Tag_Id is not used
5073 else
5074 Tag_Id := Empty;
5075 end if;
5077 -- If the tagged type has a full rep clause, expand the assignment into
5078 -- component-wise assignments. Mark the node as unanalyzed in order to
5079 -- generate the proper code and propagate this scenario by setting a
5080 -- flag to avoid infinite recursion.
5082 if Comp_Asn then
5083 Set_Analyzed (Asn, False);
5084 Set_Componentwise_Assignment (Asn, True);
5085 end if;
5087 Append_To (Res, Asn);
5089 -- Restore the tag
5091 if Save_Tag then
5092 Append_To (Res,
5093 Make_Assignment_Statement (Loc,
5094 Name =>
5095 Make_Selected_Component (Loc,
5096 Prefix => Duplicate_Subexpr_No_Checks (L),
5097 Selector_Name =>
5098 New_Occurrence_Of (First_Tag_Component (T), Loc)),
5099 Expression => New_Occurrence_Of (Tag_Id, Loc)));
5100 end if;
5102 -- Adjust the target after the assignment when controlled (not in the
5103 -- init proc since it is an initialization more than an assignment).
5105 if Ctrl_Act then
5106 Adj_Call :=
5107 Make_Adjust_Call
5108 (Obj_Ref => Duplicate_Subexpr_Move_Checks (L),
5109 Typ => Etype (L));
5111 if Present (Adj_Call) then
5112 Append_To (Res, Adj_Call);
5113 end if;
5114 end if;
5116 return Res;
5118 exception
5120 -- Could use comment here ???
5122 when RE_Not_Available =>
5123 return Empty_List;
5124 end Make_Tag_Ctrl_Assignment;
5126 end Exp_Ch5;