i386: Update INCOMING_FRAME_SP_OFFSET for exception handler
[official-gcc.git] / gcc / ada / exp_ch5.adb
blob5267024bc6e8d8050ed2fd11da62e5bec46b4b48
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-2016, 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 Change_Of_Representation (N : Node_Id) return Boolean;
78 -- Determine if the right-hand side of assignment N is a type conversion
79 -- which requires a change of representation. Called only for the array
80 -- and record cases.
82 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id);
83 -- N is an assignment which assigns an array value. This routine process
84 -- the various special cases and checks required for such assignments,
85 -- including change of representation. Rhs is normally simply the right-
86 -- hand side of the assignment, except that if the right-hand side is a
87 -- type conversion or a qualified expression, then the RHS is the actual
88 -- expression inside any such type conversions or qualifications.
90 function Expand_Assign_Array_Loop
91 (N : Node_Id;
92 Larray : Entity_Id;
93 Rarray : Entity_Id;
94 L_Type : Entity_Id;
95 R_Type : Entity_Id;
96 Ndim : Pos;
97 Rev : Boolean) return Node_Id;
98 -- N is an assignment statement which assigns an array value. This routine
99 -- expands the assignment into a loop (or nested loops for the case of a
100 -- multi-dimensional array) to do the assignment component by component.
101 -- Larray and Rarray are the entities of the actual arrays on the left-hand
102 -- and right-hand sides. L_Type and R_Type are the types of these arrays
103 -- (which may not be the same, due to either sliding, or to a change of
104 -- representation case). Ndim is the number of dimensions and the parameter
105 -- Rev indicates if the loops run normally (Rev = False), or reversed
106 -- (Rev = True). The value returned is the constructed loop statement.
107 -- Auxiliary declarations are inserted before node N using the standard
108 -- Insert_Actions mechanism.
110 procedure Expand_Assign_Record (N : Node_Id);
111 -- N is an assignment of an untagged record value. This routine handles
112 -- the case where the assignment must be made component by component,
113 -- either because the target is not byte aligned, or there is a change
114 -- of representation, or when we have a tagged type with a representation
115 -- clause (this last case is required because holes in the tagged type
116 -- might be filled with components from child types).
118 procedure Expand_Assign_With_Target_Names (N : Node_Id);
119 -- (AI12-0125): N is an assignment statement whose RHS contains occurrences
120 -- of @ that designate the value of the LHS of the assignment. If the LHS
121 -- is side-effect free the target names can be replaced with a copy of the
122 -- LHS; otherwise the semantics of the assignment is described in terms of
123 -- a procedure with an in-out parameter, and expanded as such.
125 procedure Expand_Formal_Container_Loop (N : Node_Id);
126 -- Use the primitives specified in an Iterable aspect to expand a loop
127 -- over a so-called formal container, primarily for SPARK usage.
129 procedure Expand_Formal_Container_Element_Loop (N : Node_Id);
130 -- Same, for an iterator of the form " For E of C". In this case the
131 -- iterator provides the name of the element, and the cursor is generated
132 -- internally.
134 procedure Expand_Iterator_Loop (N : Node_Id);
135 -- Expand loop over arrays and containers that uses the form "for X of C"
136 -- with an optional subtype mark, or "for Y in C".
138 procedure Expand_Iterator_Loop_Over_Container
139 (N : Node_Id;
140 Isc : Node_Id;
141 I_Spec : Node_Id;
142 Container : Node_Id;
143 Container_Typ : Entity_Id);
144 -- Expand loop over containers that uses the form "for X of C" with an
145 -- optional subtype mark, or "for Y in C". Isc is the iteration scheme.
146 -- I_Spec is the iterator specification and Container is either the
147 -- Container (for OF) or the iterator (for IN).
149 procedure Expand_Predicated_Loop (N : Node_Id);
150 -- Expand for loop over predicated subtype
152 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id;
153 -- Generate the necessary code for controlled and tagged assignment, that
154 -- is to say, finalization of the target before, adjustment of the target
155 -- after and save and restore of the tag and finalization pointers which
156 -- are not 'part of the value' and must not be changed upon assignment. N
157 -- is the original Assignment node.
159 --------------------------------------
160 -- Build_Formal_Container_iteration --
161 --------------------------------------
163 procedure Build_Formal_Container_Iteration
164 (N : Node_Id;
165 Container : Entity_Id;
166 Cursor : Entity_Id;
167 Init : out Node_Id;
168 Advance : out Node_Id;
169 New_Loop : out Node_Id)
171 Loc : constant Source_Ptr := Sloc (N);
172 Stats : constant List_Id := Statements (N);
173 Typ : constant Entity_Id := Base_Type (Etype (Container));
174 First_Op : constant Entity_Id :=
175 Get_Iterable_Type_Primitive (Typ, Name_First);
176 Next_Op : constant Entity_Id :=
177 Get_Iterable_Type_Primitive (Typ, Name_Next);
179 Has_Element_Op : constant Entity_Id :=
180 Get_Iterable_Type_Primitive (Typ, Name_Has_Element);
181 begin
182 -- Declaration for Cursor
184 Init :=
185 Make_Object_Declaration (Loc,
186 Defining_Identifier => Cursor,
187 Object_Definition => New_Occurrence_Of (Etype (First_Op), Loc),
188 Expression =>
189 Make_Function_Call (Loc,
190 Name => New_Occurrence_Of (First_Op, Loc),
191 Parameter_Associations => New_List (
192 New_Occurrence_Of (Container, Loc))));
194 -- Statement that advances cursor in loop
196 Advance :=
197 Make_Assignment_Statement (Loc,
198 Name => New_Occurrence_Of (Cursor, Loc),
199 Expression =>
200 Make_Function_Call (Loc,
201 Name => New_Occurrence_Of (Next_Op, Loc),
202 Parameter_Associations => New_List (
203 New_Occurrence_Of (Container, Loc),
204 New_Occurrence_Of (Cursor, Loc))));
206 -- Iterator is rewritten as a while_loop
208 New_Loop :=
209 Make_Loop_Statement (Loc,
210 Iteration_Scheme =>
211 Make_Iteration_Scheme (Loc,
212 Condition =>
213 Make_Function_Call (Loc,
214 Name => New_Occurrence_Of (Has_Element_Op, Loc),
215 Parameter_Associations => New_List (
216 New_Occurrence_Of (Container, Loc),
217 New_Occurrence_Of (Cursor, Loc)))),
218 Statements => Stats,
219 End_Label => Empty);
220 end Build_Formal_Container_Iteration;
222 ------------------------------
223 -- Change_Of_Representation --
224 ------------------------------
226 function Change_Of_Representation (N : Node_Id) return Boolean is
227 Rhs : constant Node_Id := Expression (N);
228 begin
229 return
230 Nkind (Rhs) = N_Type_Conversion
231 and then
232 not Same_Representation (Etype (Rhs), Etype (Expression (Rhs)));
233 end Change_Of_Representation;
235 -------------------------
236 -- Expand_Assign_Array --
237 -------------------------
239 -- There are two issues here. First, do we let Gigi do a block move, or
240 -- do we expand out into a loop? Second, we need to set the two flags
241 -- Forwards_OK and Backwards_OK which show whether the block move (or
242 -- corresponding loops) can be legitimately done in a forwards (low to
243 -- high) or backwards (high to low) manner.
245 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id) is
246 Loc : constant Source_Ptr := Sloc (N);
248 Lhs : constant Node_Id := Name (N);
250 Act_Lhs : constant Node_Id := Get_Referenced_Object (Lhs);
251 Act_Rhs : Node_Id := Get_Referenced_Object (Rhs);
253 L_Type : constant Entity_Id :=
254 Underlying_Type (Get_Actual_Subtype (Act_Lhs));
255 R_Type : Entity_Id :=
256 Underlying_Type (Get_Actual_Subtype (Act_Rhs));
258 L_Slice : constant Boolean := Nkind (Act_Lhs) = N_Slice;
259 R_Slice : constant Boolean := Nkind (Act_Rhs) = N_Slice;
261 Crep : constant Boolean := Change_Of_Representation (N);
263 Larray : Node_Id;
264 Rarray : Node_Id;
266 Ndim : constant Pos := Number_Dimensions (L_Type);
268 Loop_Required : Boolean := False;
269 -- This switch is set to True if the array move must be done using
270 -- an explicit front end generated loop.
272 procedure Apply_Dereference (Arg : Node_Id);
273 -- If the argument is an access to an array, and the assignment is
274 -- converted into a procedure call, apply explicit dereference.
276 function Has_Address_Clause (Exp : Node_Id) return Boolean;
277 -- Test if Exp is a reference to an array whose declaration has
278 -- an address clause, or it is a slice of such an array.
280 function Is_Formal_Array (Exp : Node_Id) return Boolean;
281 -- Test if Exp is a reference to an array which is either a formal
282 -- parameter or a slice of a formal parameter. These are the cases
283 -- where hidden aliasing can occur.
285 function Is_Non_Local_Array (Exp : Node_Id) return Boolean;
286 -- Determine if Exp is a reference to an array variable which is other
287 -- than an object defined in the current scope, or a component or a
288 -- slice of such an object. Such objects can be aliased to parameters
289 -- (unlike local array references).
291 -----------------------
292 -- Apply_Dereference --
293 -----------------------
295 procedure Apply_Dereference (Arg : Node_Id) is
296 Typ : constant Entity_Id := Etype (Arg);
297 begin
298 if Is_Access_Type (Typ) then
299 Rewrite (Arg, Make_Explicit_Dereference (Loc,
300 Prefix => Relocate_Node (Arg)));
301 Analyze_And_Resolve (Arg, Designated_Type (Typ));
302 end if;
303 end Apply_Dereference;
305 ------------------------
306 -- Has_Address_Clause --
307 ------------------------
309 function Has_Address_Clause (Exp : Node_Id) return Boolean is
310 begin
311 return
312 (Is_Entity_Name (Exp) and then
313 Present (Address_Clause (Entity (Exp))))
314 or else
315 (Nkind (Exp) = N_Slice and then Has_Address_Clause (Prefix (Exp)));
316 end Has_Address_Clause;
318 ---------------------
319 -- Is_Formal_Array --
320 ---------------------
322 function Is_Formal_Array (Exp : Node_Id) return Boolean is
323 begin
324 return
325 (Is_Entity_Name (Exp) and then Is_Formal (Entity (Exp)))
326 or else
327 (Nkind (Exp) = N_Slice and then Is_Formal_Array (Prefix (Exp)));
328 end Is_Formal_Array;
330 ------------------------
331 -- Is_Non_Local_Array --
332 ------------------------
334 function Is_Non_Local_Array (Exp : Node_Id) return Boolean is
335 begin
336 case Nkind (Exp) is
337 when N_Indexed_Component
338 | N_Selected_Component
339 | N_Slice
341 return Is_Non_Local_Array (Prefix (Exp));
343 when others =>
344 return
345 not (Is_Entity_Name (Exp)
346 and then Scope (Entity (Exp)) = Current_Scope);
347 end case;
348 end Is_Non_Local_Array;
350 -- Determine if Lhs, Rhs are formal arrays or nonlocal arrays
352 Lhs_Formal : constant Boolean := Is_Formal_Array (Act_Lhs);
353 Rhs_Formal : constant Boolean := Is_Formal_Array (Act_Rhs);
355 Lhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Lhs);
356 Rhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Rhs);
358 -- Start of processing for Expand_Assign_Array
360 begin
361 -- Deal with length check. Note that the length check is done with
362 -- respect to the right-hand side as given, not a possible underlying
363 -- renamed object, since this would generate incorrect extra checks.
365 Apply_Length_Check (Rhs, L_Type);
367 -- We start by assuming that the move can be done in either direction,
368 -- i.e. that the two sides are completely disjoint.
370 Set_Forwards_OK (N, True);
371 Set_Backwards_OK (N, True);
373 -- Normally it is only the slice case that can lead to overlap, and
374 -- explicit checks for slices are made below. But there is one case
375 -- where the slice can be implicit and invisible to us: when we have a
376 -- one dimensional array, and either both operands are parameters, or
377 -- one is a parameter (which can be a slice passed by reference) and the
378 -- other is a non-local variable. In this case the parameter could be a
379 -- slice that overlaps with the other operand.
381 -- However, if the array subtype is a constrained first subtype in the
382 -- parameter case, then we don't have to worry about overlap, since
383 -- slice assignments aren't possible (other than for a slice denoting
384 -- the whole array).
386 -- Note: No overlap is possible if there is a change of representation,
387 -- so we can exclude this case.
389 if Ndim = 1
390 and then not Crep
391 and then
392 ((Lhs_Formal and Rhs_Formal)
393 or else
394 (Lhs_Formal and Rhs_Non_Local_Var)
395 or else
396 (Rhs_Formal and Lhs_Non_Local_Var))
397 and then
398 (not Is_Constrained (Etype (Lhs))
399 or else not Is_First_Subtype (Etype (Lhs)))
400 then
401 Set_Forwards_OK (N, False);
402 Set_Backwards_OK (N, False);
404 -- Note: the bit-packed case is not worrisome here, since if we have
405 -- a slice passed as a parameter, it is always aligned on a byte
406 -- boundary, and if there are no explicit slices, the assignment
407 -- can be performed directly.
408 end if;
410 -- If either operand has an address clause clear Backwards_OK and
411 -- Forwards_OK, since we cannot tell if the operands overlap. We
412 -- exclude this treatment when Rhs is an aggregate, since we know
413 -- that overlap can't occur.
415 if (Has_Address_Clause (Lhs) and then Nkind (Rhs) /= N_Aggregate)
416 or else Has_Address_Clause (Rhs)
417 then
418 Set_Forwards_OK (N, False);
419 Set_Backwards_OK (N, False);
420 end if;
422 -- We certainly must use a loop for change of representation and also
423 -- we use the operand of the conversion on the right-hand side as the
424 -- effective right-hand side (the component types must match in this
425 -- situation).
427 if Crep then
428 Act_Rhs := Get_Referenced_Object (Rhs);
429 R_Type := Get_Actual_Subtype (Act_Rhs);
430 Loop_Required := True;
432 -- We require a loop if the left side is possibly bit unaligned
434 elsif Possible_Bit_Aligned_Component (Lhs)
435 or else
436 Possible_Bit_Aligned_Component (Rhs)
437 then
438 Loop_Required := True;
440 -- Arrays with controlled components are expanded into a loop to force
441 -- calls to Adjust at the component level.
443 elsif Has_Controlled_Component (L_Type) then
444 Loop_Required := True;
446 -- If object is atomic/VFA, we cannot tolerate a loop
448 elsif Is_Atomic_Or_VFA_Object (Act_Lhs)
449 or else
450 Is_Atomic_Or_VFA_Object (Act_Rhs)
451 then
452 return;
454 -- Loop is required if we have atomic components since we have to
455 -- be sure to do any accesses on an element by element basis.
457 elsif Has_Atomic_Components (L_Type)
458 or else Has_Atomic_Components (R_Type)
459 or else Is_Atomic_Or_VFA (Component_Type (L_Type))
460 or else Is_Atomic_Or_VFA (Component_Type (R_Type))
461 then
462 Loop_Required := True;
464 -- Case where no slice is involved
466 elsif not L_Slice and not R_Slice then
468 -- The following code deals with the case of unconstrained bit packed
469 -- arrays. The problem is that the template for such arrays contains
470 -- the bounds of the actual source level array, but the copy of an
471 -- entire array requires the bounds of the underlying array. It would
472 -- be nice if the back end could take care of this, but right now it
473 -- does not know how, so if we have such a type, then we expand out
474 -- into a loop, which is inefficient but works correctly. If we don't
475 -- do this, we get the wrong length computed for the array to be
476 -- moved. The two cases we need to worry about are:
478 -- Explicit dereference of an unconstrained packed array type as in
479 -- the following example:
481 -- procedure C52 is
482 -- type BITS is array(INTEGER range <>) of BOOLEAN;
483 -- pragma PACK(BITS);
484 -- type A is access BITS;
485 -- P1,P2 : A;
486 -- begin
487 -- P1 := new BITS (1 .. 65_535);
488 -- P2 := new BITS (1 .. 65_535);
489 -- P2.ALL := P1.ALL;
490 -- end C52;
492 -- A formal parameter reference with an unconstrained bit array type
493 -- is the other case we need to worry about (here we assume the same
494 -- BITS type declared above):
496 -- procedure Write_All (File : out BITS; Contents : BITS);
497 -- begin
498 -- File.Storage := Contents;
499 -- end Write_All;
501 -- We expand to a loop in either of these two cases
503 -- Question for future thought. Another potentially more efficient
504 -- approach would be to create the actual subtype, and then do an
505 -- unchecked conversion to this actual subtype ???
507 Check_Unconstrained_Bit_Packed_Array : declare
509 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean;
510 -- Function to perform required test for the first case, above
511 -- (dereference of an unconstrained bit packed array).
513 -----------------------
514 -- Is_UBPA_Reference --
515 -----------------------
517 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean is
518 Typ : constant Entity_Id := Underlying_Type (Etype (Opnd));
519 P_Type : Entity_Id;
520 Des_Type : Entity_Id;
522 begin
523 if Present (Packed_Array_Impl_Type (Typ))
524 and then Is_Array_Type (Packed_Array_Impl_Type (Typ))
525 and then not Is_Constrained (Packed_Array_Impl_Type (Typ))
526 then
527 return True;
529 elsif Nkind (Opnd) = N_Explicit_Dereference then
530 P_Type := Underlying_Type (Etype (Prefix (Opnd)));
532 if not Is_Access_Type (P_Type) then
533 return False;
535 else
536 Des_Type := Designated_Type (P_Type);
537 return
538 Is_Bit_Packed_Array (Des_Type)
539 and then not Is_Constrained (Des_Type);
540 end if;
542 else
543 return False;
544 end if;
545 end Is_UBPA_Reference;
547 -- Start of processing for Check_Unconstrained_Bit_Packed_Array
549 begin
550 if Is_UBPA_Reference (Lhs)
551 or else
552 Is_UBPA_Reference (Rhs)
553 then
554 Loop_Required := True;
556 -- Here if we do not have the case of a reference to a bit packed
557 -- unconstrained array case. In this case gigi can most certainly
558 -- handle the assignment if a forwards move is allowed.
560 -- (could it handle the backwards case also???)
562 elsif Forwards_OK (N) then
563 return;
564 end if;
565 end Check_Unconstrained_Bit_Packed_Array;
567 -- The back end can always handle the assignment if the right side is a
568 -- string literal (note that overlap is definitely impossible in this
569 -- case). If the type is packed, a string literal is always converted
570 -- into an aggregate, except in the case of a null slice, for which no
571 -- aggregate can be written. In that case, rewrite the assignment as a
572 -- null statement, a length check has already been emitted to verify
573 -- that the range of the left-hand side is empty.
575 -- Note that this code is not executed if we have an assignment of a
576 -- string literal to a non-bit aligned component of a record, a case
577 -- which cannot be handled by the backend.
579 elsif Nkind (Rhs) = N_String_Literal then
580 if String_Length (Strval (Rhs)) = 0
581 and then Is_Bit_Packed_Array (L_Type)
582 then
583 Rewrite (N, Make_Null_Statement (Loc));
584 Analyze (N);
585 end if;
587 return;
589 -- If either operand is bit packed, then we need a loop, since we can't
590 -- be sure that the slice is byte aligned. Similarly, if either operand
591 -- is a possibly unaligned slice, then we need a loop (since the back
592 -- end cannot handle unaligned slices).
594 elsif Is_Bit_Packed_Array (L_Type)
595 or else Is_Bit_Packed_Array (R_Type)
596 or else Is_Possibly_Unaligned_Slice (Lhs)
597 or else Is_Possibly_Unaligned_Slice (Rhs)
598 then
599 Loop_Required := True;
601 -- If we are not bit-packed, and we have only one slice, then no overlap
602 -- is possible except in the parameter case, so we can let the back end
603 -- handle things.
605 elsif not (L_Slice and R_Slice) then
606 if Forwards_OK (N) then
607 return;
608 end if;
609 end if;
611 -- If the right-hand side is a string literal, introduce a temporary for
612 -- it, for use in the generated loop that will follow.
614 if Nkind (Rhs) = N_String_Literal then
615 declare
616 Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Rhs);
617 Decl : Node_Id;
619 begin
620 Decl :=
621 Make_Object_Declaration (Loc,
622 Defining_Identifier => Temp,
623 Object_Definition => New_Occurrence_Of (L_Type, Loc),
624 Expression => Relocate_Node (Rhs));
626 Insert_Action (N, Decl);
627 Rewrite (Rhs, New_Occurrence_Of (Temp, Loc));
628 R_Type := Etype (Temp);
629 end;
630 end if;
632 -- Come here to complete the analysis
634 -- Loop_Required: Set to True if we know that a loop is required
635 -- regardless of overlap considerations.
637 -- Forwards_OK: Set to False if we already know that a forwards
638 -- move is not safe, else set to True.
640 -- Backwards_OK: Set to False if we already know that a backwards
641 -- move is not safe, else set to True
643 -- Our task at this stage is to complete the overlap analysis, which can
644 -- result in possibly setting Forwards_OK or Backwards_OK to False, and
645 -- then generating the final code, either by deciding that it is OK
646 -- after all to let Gigi handle it, or by generating appropriate code
647 -- in the front end.
649 declare
650 L_Index_Typ : constant Node_Id := Etype (First_Index (L_Type));
651 R_Index_Typ : constant Node_Id := Etype (First_Index (R_Type));
653 Left_Lo : constant Node_Id := Type_Low_Bound (L_Index_Typ);
654 Left_Hi : constant Node_Id := Type_High_Bound (L_Index_Typ);
655 Right_Lo : constant Node_Id := Type_Low_Bound (R_Index_Typ);
656 Right_Hi : constant Node_Id := Type_High_Bound (R_Index_Typ);
658 Act_L_Array : Node_Id;
659 Act_R_Array : Node_Id;
661 Cleft_Lo : Node_Id;
662 Cright_Lo : Node_Id;
663 Condition : Node_Id;
665 Cresult : Compare_Result;
667 begin
668 -- Get the expressions for the arrays. If we are dealing with a
669 -- private type, then convert to the underlying type. We can do
670 -- direct assignments to an array that is a private type, but we
671 -- cannot assign to elements of the array without this extra
672 -- unchecked conversion.
674 -- Note: We propagate Parent to the conversion nodes to generate
675 -- a well-formed subtree.
677 if Nkind (Act_Lhs) = N_Slice then
678 Larray := Prefix (Act_Lhs);
679 else
680 Larray := Act_Lhs;
682 if Is_Private_Type (Etype (Larray)) then
683 declare
684 Par : constant Node_Id := Parent (Larray);
685 begin
686 Larray :=
687 Unchecked_Convert_To
688 (Underlying_Type (Etype (Larray)), Larray);
689 Set_Parent (Larray, Par);
690 end;
691 end if;
692 end if;
694 if Nkind (Act_Rhs) = N_Slice then
695 Rarray := Prefix (Act_Rhs);
696 else
697 Rarray := Act_Rhs;
699 if Is_Private_Type (Etype (Rarray)) then
700 declare
701 Par : constant Node_Id := Parent (Rarray);
702 begin
703 Rarray :=
704 Unchecked_Convert_To
705 (Underlying_Type (Etype (Rarray)), Rarray);
706 Set_Parent (Rarray, Par);
707 end;
708 end if;
709 end if;
711 -- If both sides are slices, we must figure out whether it is safe
712 -- to do the move in one direction or the other. It is always safe
713 -- if there is a change of representation since obviously two arrays
714 -- with different representations cannot possibly overlap.
716 if (not Crep) and L_Slice and R_Slice then
717 Act_L_Array := Get_Referenced_Object (Prefix (Act_Lhs));
718 Act_R_Array := Get_Referenced_Object (Prefix (Act_Rhs));
720 -- If both left- and right-hand arrays are entity names, and refer
721 -- to different entities, then we know that the move is safe (the
722 -- two storage areas are completely disjoint).
724 if Is_Entity_Name (Act_L_Array)
725 and then Is_Entity_Name (Act_R_Array)
726 and then Entity (Act_L_Array) /= Entity (Act_R_Array)
727 then
728 null;
730 -- Otherwise, we assume the worst, which is that the two arrays
731 -- are the same array. There is no need to check if we know that
732 -- is the case, because if we don't know it, we still have to
733 -- assume it.
735 -- Generally if the same array is involved, then we have an
736 -- overlapping case. We will have to really assume the worst (i.e.
737 -- set neither of the OK flags) unless we can determine the lower
738 -- or upper bounds at compile time and compare them.
740 else
741 Cresult :=
742 Compile_Time_Compare
743 (Left_Lo, Right_Lo, Assume_Valid => True);
745 if Cresult = Unknown then
746 Cresult :=
747 Compile_Time_Compare
748 (Left_Hi, Right_Hi, Assume_Valid => True);
749 end if;
751 case Cresult is
752 when EQ | LE | LT =>
753 Set_Backwards_OK (N, False);
755 when GE | GT =>
756 Set_Forwards_OK (N, False);
758 when NE | Unknown =>
759 Set_Backwards_OK (N, False);
760 Set_Forwards_OK (N, False);
761 end case;
762 end if;
763 end if;
765 -- If after that analysis Loop_Required is False, meaning that we
766 -- have not discovered some non-overlap reason for requiring a loop,
767 -- then the outcome depends on the capabilities of the back end.
769 if not Loop_Required then
770 -- Assume the back end can deal with all cases of overlap by
771 -- falling back to memmove if it cannot use a more efficient
772 -- approach.
774 return;
775 end if;
777 -- At this stage we have to generate an explicit loop, and we have
778 -- the following cases:
780 -- Forwards_OK = True
782 -- Rnn : right_index := right_index'First;
783 -- for Lnn in left-index loop
784 -- left (Lnn) := right (Rnn);
785 -- Rnn := right_index'Succ (Rnn);
786 -- end loop;
788 -- Note: the above code MUST be analyzed with checks off, because
789 -- otherwise the Succ could overflow. But in any case this is more
790 -- efficient.
792 -- Forwards_OK = False, Backwards_OK = True
794 -- Rnn : right_index := right_index'Last;
795 -- for Lnn in reverse left-index loop
796 -- left (Lnn) := right (Rnn);
797 -- Rnn := right_index'Pred (Rnn);
798 -- end loop;
800 -- Note: the above code MUST be analyzed with checks off, because
801 -- otherwise the Pred could overflow. But in any case this is more
802 -- efficient.
804 -- Forwards_OK = Backwards_OK = False
806 -- This only happens if we have the same array on each side. It is
807 -- possible to create situations using overlays that violate this,
808 -- but we simply do not promise to get this "right" in this case.
810 -- There are two possible subcases. If the No_Implicit_Conditionals
811 -- restriction is set, then we generate the following code:
813 -- declare
814 -- T : constant <operand-type> := rhs;
815 -- begin
816 -- lhs := T;
817 -- end;
819 -- If implicit conditionals are permitted, then we generate:
821 -- if Left_Lo <= Right_Lo then
822 -- <code for Forwards_OK = True above>
823 -- else
824 -- <code for Backwards_OK = True above>
825 -- end if;
827 -- In order to detect possible aliasing, we examine the renamed
828 -- expression when the source or target is a renaming. However,
829 -- the renaming may be intended to capture an address that may be
830 -- affected by subsequent code, and therefore we must recover
831 -- the actual entity for the expansion that follows, not the
832 -- object it renames. In particular, if source or target designate
833 -- a portion of a dynamically allocated object, the pointer to it
834 -- may be reassigned but the renaming preserves the proper location.
836 if Is_Entity_Name (Rhs)
837 and then
838 Nkind (Parent (Entity (Rhs))) = N_Object_Renaming_Declaration
839 and then Nkind (Act_Rhs) = N_Slice
840 then
841 Rarray := Rhs;
842 end if;
844 if Is_Entity_Name (Lhs)
845 and then
846 Nkind (Parent (Entity (Lhs))) = N_Object_Renaming_Declaration
847 and then Nkind (Act_Lhs) = N_Slice
848 then
849 Larray := Lhs;
850 end if;
852 -- Cases where either Forwards_OK or Backwards_OK is true
854 if Forwards_OK (N) or else Backwards_OK (N) then
855 if Needs_Finalization (Component_Type (L_Type))
856 and then Base_Type (L_Type) = Base_Type (R_Type)
857 and then Ndim = 1
858 and then not No_Ctrl_Actions (N)
859 then
860 declare
861 Proc : constant Entity_Id :=
862 TSS (Base_Type (L_Type), TSS_Slice_Assign);
863 Actuals : List_Id;
865 begin
866 Apply_Dereference (Larray);
867 Apply_Dereference (Rarray);
868 Actuals := New_List (
869 Duplicate_Subexpr (Larray, Name_Req => True),
870 Duplicate_Subexpr (Rarray, Name_Req => True),
871 Duplicate_Subexpr (Left_Lo, Name_Req => True),
872 Duplicate_Subexpr (Left_Hi, Name_Req => True),
873 Duplicate_Subexpr (Right_Lo, Name_Req => True),
874 Duplicate_Subexpr (Right_Hi, Name_Req => True));
876 Append_To (Actuals,
877 New_Occurrence_Of (
878 Boolean_Literals (not Forwards_OK (N)), Loc));
880 Rewrite (N,
881 Make_Procedure_Call_Statement (Loc,
882 Name => New_Occurrence_Of (Proc, Loc),
883 Parameter_Associations => Actuals));
884 end;
886 else
887 Rewrite (N,
888 Expand_Assign_Array_Loop
889 (N, Larray, Rarray, L_Type, R_Type, Ndim,
890 Rev => not Forwards_OK (N)));
891 end if;
893 -- Case of both are false with No_Implicit_Conditionals
895 elsif Restriction_Active (No_Implicit_Conditionals) then
896 declare
897 T : constant Entity_Id :=
898 Make_Defining_Identifier (Loc, Chars => Name_T);
900 begin
901 Rewrite (N,
902 Make_Block_Statement (Loc,
903 Declarations => New_List (
904 Make_Object_Declaration (Loc,
905 Defining_Identifier => T,
906 Constant_Present => True,
907 Object_Definition =>
908 New_Occurrence_Of (Etype (Rhs), Loc),
909 Expression => Relocate_Node (Rhs))),
911 Handled_Statement_Sequence =>
912 Make_Handled_Sequence_Of_Statements (Loc,
913 Statements => New_List (
914 Make_Assignment_Statement (Loc,
915 Name => Relocate_Node (Lhs),
916 Expression => New_Occurrence_Of (T, Loc))))));
917 end;
919 -- Case of both are false with implicit conditionals allowed
921 else
922 -- Before we generate this code, we must ensure that the left and
923 -- right side array types are defined. They may be itypes, and we
924 -- cannot let them be defined inside the if, since the first use
925 -- in the then may not be executed.
927 Ensure_Defined (L_Type, N);
928 Ensure_Defined (R_Type, N);
930 -- We normally compare addresses to find out which way round to
931 -- do the loop, since this is reliable, and handles the cases of
932 -- parameters, conversions etc. But we can't do that in the bit
933 -- packed case, because addresses don't work there.
935 if not Is_Bit_Packed_Array (L_Type) then
936 Condition :=
937 Make_Op_Le (Loc,
938 Left_Opnd =>
939 Unchecked_Convert_To (RTE (RE_Integer_Address),
940 Make_Attribute_Reference (Loc,
941 Prefix =>
942 Make_Indexed_Component (Loc,
943 Prefix =>
944 Duplicate_Subexpr_Move_Checks (Larray, True),
945 Expressions => New_List (
946 Make_Attribute_Reference (Loc,
947 Prefix =>
948 New_Occurrence_Of
949 (L_Index_Typ, Loc),
950 Attribute_Name => Name_First))),
951 Attribute_Name => Name_Address)),
953 Right_Opnd =>
954 Unchecked_Convert_To (RTE (RE_Integer_Address),
955 Make_Attribute_Reference (Loc,
956 Prefix =>
957 Make_Indexed_Component (Loc,
958 Prefix =>
959 Duplicate_Subexpr_Move_Checks (Rarray, True),
960 Expressions => New_List (
961 Make_Attribute_Reference (Loc,
962 Prefix =>
963 New_Occurrence_Of
964 (R_Index_Typ, Loc),
965 Attribute_Name => Name_First))),
966 Attribute_Name => Name_Address)));
968 -- For the bit packed and VM cases we use the bounds. That's OK,
969 -- because we don't have to worry about parameters, since they
970 -- cannot cause overlap. Perhaps we should worry about weird slice
971 -- conversions ???
973 else
974 -- Copy the bounds
976 Cleft_Lo := New_Copy_Tree (Left_Lo);
977 Cright_Lo := New_Copy_Tree (Right_Lo);
979 -- If the types do not match we add an implicit conversion
980 -- here to ensure proper match
982 if Etype (Left_Lo) /= Etype (Right_Lo) then
983 Cright_Lo :=
984 Unchecked_Convert_To (Etype (Left_Lo), Cright_Lo);
985 end if;
987 -- Reset the Analyzed flag, because the bounds of the index
988 -- type itself may be universal, and must must be reanalyzed
989 -- to acquire the proper type for the back end.
991 Set_Analyzed (Cleft_Lo, False);
992 Set_Analyzed (Cright_Lo, False);
994 Condition :=
995 Make_Op_Le (Loc,
996 Left_Opnd => Cleft_Lo,
997 Right_Opnd => Cright_Lo);
998 end if;
1000 if Needs_Finalization (Component_Type (L_Type))
1001 and then Base_Type (L_Type) = Base_Type (R_Type)
1002 and then Ndim = 1
1003 and then not No_Ctrl_Actions (N)
1004 then
1006 -- Call TSS procedure for array assignment, passing the
1007 -- explicit bounds of right- and left-hand sides.
1009 declare
1010 Proc : constant Entity_Id :=
1011 TSS (Base_Type (L_Type), TSS_Slice_Assign);
1012 Actuals : List_Id;
1014 begin
1015 Apply_Dereference (Larray);
1016 Apply_Dereference (Rarray);
1017 Actuals := New_List (
1018 Duplicate_Subexpr (Larray, Name_Req => True),
1019 Duplicate_Subexpr (Rarray, Name_Req => True),
1020 Duplicate_Subexpr (Left_Lo, Name_Req => True),
1021 Duplicate_Subexpr (Left_Hi, Name_Req => True),
1022 Duplicate_Subexpr (Right_Lo, Name_Req => True),
1023 Duplicate_Subexpr (Right_Hi, Name_Req => True));
1025 Append_To (Actuals,
1026 Make_Op_Not (Loc,
1027 Right_Opnd => Condition));
1029 Rewrite (N,
1030 Make_Procedure_Call_Statement (Loc,
1031 Name => New_Occurrence_Of (Proc, Loc),
1032 Parameter_Associations => Actuals));
1033 end;
1035 else
1036 Rewrite (N,
1037 Make_Implicit_If_Statement (N,
1038 Condition => Condition,
1040 Then_Statements => New_List (
1041 Expand_Assign_Array_Loop
1042 (N, Larray, Rarray, L_Type, R_Type, Ndim,
1043 Rev => False)),
1045 Else_Statements => New_List (
1046 Expand_Assign_Array_Loop
1047 (N, Larray, Rarray, L_Type, R_Type, Ndim,
1048 Rev => True))));
1049 end if;
1050 end if;
1052 Analyze (N, Suppress => All_Checks);
1053 end;
1055 exception
1056 when RE_Not_Available =>
1057 return;
1058 end Expand_Assign_Array;
1060 ------------------------------
1061 -- Expand_Assign_Array_Loop --
1062 ------------------------------
1064 -- The following is an example of the loop generated for the case of a
1065 -- two-dimensional array:
1067 -- declare
1068 -- R2b : Tm1X1 := 1;
1069 -- begin
1070 -- for L1b in 1 .. 100 loop
1071 -- declare
1072 -- R4b : Tm1X2 := 1;
1073 -- begin
1074 -- for L3b in 1 .. 100 loop
1075 -- vm1 (L1b, L3b) := vm2 (R2b, R4b);
1076 -- R4b := Tm1X2'succ(R4b);
1077 -- end loop;
1078 -- end;
1079 -- R2b := Tm1X1'succ(R2b);
1080 -- end loop;
1081 -- end;
1083 -- Here Rev is False, and Tm1Xn are the subscript types for the right-hand
1084 -- side. The declarations of R2b and R4b are inserted before the original
1085 -- assignment statement.
1087 function Expand_Assign_Array_Loop
1088 (N : Node_Id;
1089 Larray : Entity_Id;
1090 Rarray : Entity_Id;
1091 L_Type : Entity_Id;
1092 R_Type : Entity_Id;
1093 Ndim : Pos;
1094 Rev : Boolean) return Node_Id
1096 Loc : constant Source_Ptr := Sloc (N);
1098 Lnn : array (1 .. Ndim) of Entity_Id;
1099 Rnn : array (1 .. Ndim) of Entity_Id;
1100 -- Entities used as subscripts on left and right sides
1102 L_Index_Type : array (1 .. Ndim) of Entity_Id;
1103 R_Index_Type : array (1 .. Ndim) of Entity_Id;
1104 -- Left and right index types
1106 Assign : Node_Id;
1108 F_Or_L : Name_Id;
1109 S_Or_P : Name_Id;
1111 function Build_Step (J : Nat) return Node_Id;
1112 -- The increment step for the index of the right-hand side is written
1113 -- as an attribute reference (Succ or Pred). This function returns
1114 -- the corresponding node, which is placed at the end of the loop body.
1116 ----------------
1117 -- Build_Step --
1118 ----------------
1120 function Build_Step (J : Nat) return Node_Id is
1121 Step : Node_Id;
1122 Lim : Name_Id;
1124 begin
1125 if Rev then
1126 Lim := Name_First;
1127 else
1128 Lim := Name_Last;
1129 end if;
1131 Step :=
1132 Make_Assignment_Statement (Loc,
1133 Name => New_Occurrence_Of (Rnn (J), Loc),
1134 Expression =>
1135 Make_Attribute_Reference (Loc,
1136 Prefix =>
1137 New_Occurrence_Of (R_Index_Type (J), Loc),
1138 Attribute_Name => S_Or_P,
1139 Expressions => New_List (
1140 New_Occurrence_Of (Rnn (J), Loc))));
1142 -- Note that on the last iteration of the loop, the index is increased
1143 -- (or decreased) past the corresponding bound. This is consistent with
1144 -- the C semantics of the back-end, where such an off-by-one value on a
1145 -- dead index variable is OK. However, in CodePeer mode this leads to
1146 -- spurious warnings, and thus we place a guard around the attribute
1147 -- reference. For obvious reasons we only do this for CodePeer.
1149 if CodePeer_Mode then
1150 Step :=
1151 Make_If_Statement (Loc,
1152 Condition =>
1153 Make_Op_Ne (Loc,
1154 Left_Opnd => New_Occurrence_Of (Lnn (J), Loc),
1155 Right_Opnd =>
1156 Make_Attribute_Reference (Loc,
1157 Prefix => New_Occurrence_Of (L_Index_Type (J), Loc),
1158 Attribute_Name => Lim)),
1159 Then_Statements => New_List (Step));
1160 end if;
1162 return Step;
1163 end Build_Step;
1165 -- Start of processing for Expand_Assign_Array_Loop
1167 begin
1168 if Rev then
1169 F_Or_L := Name_Last;
1170 S_Or_P := Name_Pred;
1171 else
1172 F_Or_L := Name_First;
1173 S_Or_P := Name_Succ;
1174 end if;
1176 -- Setup index types and subscript entities
1178 declare
1179 L_Index : Node_Id;
1180 R_Index : Node_Id;
1182 begin
1183 L_Index := First_Index (L_Type);
1184 R_Index := First_Index (R_Type);
1186 for J in 1 .. Ndim loop
1187 Lnn (J) := Make_Temporary (Loc, 'L');
1188 Rnn (J) := Make_Temporary (Loc, 'R');
1190 L_Index_Type (J) := Etype (L_Index);
1191 R_Index_Type (J) := Etype (R_Index);
1193 Next_Index (L_Index);
1194 Next_Index (R_Index);
1195 end loop;
1196 end;
1198 -- Now construct the assignment statement
1200 declare
1201 ExprL : constant List_Id := New_List;
1202 ExprR : constant List_Id := New_List;
1204 begin
1205 for J in 1 .. Ndim loop
1206 Append_To (ExprL, New_Occurrence_Of (Lnn (J), Loc));
1207 Append_To (ExprR, New_Occurrence_Of (Rnn (J), Loc));
1208 end loop;
1210 Assign :=
1211 Make_Assignment_Statement (Loc,
1212 Name =>
1213 Make_Indexed_Component (Loc,
1214 Prefix => Duplicate_Subexpr (Larray, Name_Req => True),
1215 Expressions => ExprL),
1216 Expression =>
1217 Make_Indexed_Component (Loc,
1218 Prefix => Duplicate_Subexpr (Rarray, Name_Req => True),
1219 Expressions => ExprR));
1221 -- We set assignment OK, since there are some cases, e.g. in object
1222 -- declarations, where we are actually assigning into a constant.
1223 -- If there really is an illegality, it was caught long before now,
1224 -- and was flagged when the original assignment was analyzed.
1226 Set_Assignment_OK (Name (Assign));
1228 -- Propagate the No_Ctrl_Actions flag to individual assignments
1230 Set_No_Ctrl_Actions (Assign, No_Ctrl_Actions (N));
1231 end;
1233 -- Now construct the loop from the inside out, with the last subscript
1234 -- varying most rapidly. Note that Assign is first the raw assignment
1235 -- statement, and then subsequently the loop that wraps it up.
1237 for J in reverse 1 .. Ndim loop
1238 Assign :=
1239 Make_Block_Statement (Loc,
1240 Declarations => New_List (
1241 Make_Object_Declaration (Loc,
1242 Defining_Identifier => Rnn (J),
1243 Object_Definition =>
1244 New_Occurrence_Of (R_Index_Type (J), Loc),
1245 Expression =>
1246 Make_Attribute_Reference (Loc,
1247 Prefix => New_Occurrence_Of (R_Index_Type (J), Loc),
1248 Attribute_Name => F_Or_L))),
1250 Handled_Statement_Sequence =>
1251 Make_Handled_Sequence_Of_Statements (Loc,
1252 Statements => New_List (
1253 Make_Implicit_Loop_Statement (N,
1254 Iteration_Scheme =>
1255 Make_Iteration_Scheme (Loc,
1256 Loop_Parameter_Specification =>
1257 Make_Loop_Parameter_Specification (Loc,
1258 Defining_Identifier => Lnn (J),
1259 Reverse_Present => Rev,
1260 Discrete_Subtype_Definition =>
1261 New_Occurrence_Of (L_Index_Type (J), Loc))),
1263 Statements => New_List (Assign, Build_Step (J))))));
1264 end loop;
1266 return Assign;
1267 end Expand_Assign_Array_Loop;
1269 --------------------------
1270 -- Expand_Assign_Record --
1271 --------------------------
1273 procedure Expand_Assign_Record (N : Node_Id) is
1274 Lhs : constant Node_Id := Name (N);
1275 Rhs : Node_Id := Expression (N);
1276 L_Typ : constant Entity_Id := Base_Type (Etype (Lhs));
1278 begin
1279 -- If change of representation, then extract the real right-hand side
1280 -- from the type conversion, and proceed with component-wise assignment,
1281 -- since the two types are not the same as far as the back end is
1282 -- concerned.
1284 if Change_Of_Representation (N) then
1285 Rhs := Expression (Rhs);
1287 -- If this may be a case of a large bit aligned component, then proceed
1288 -- with component-wise assignment, to avoid possible clobbering of other
1289 -- components sharing bits in the first or last byte of the component to
1290 -- be assigned.
1292 elsif Possible_Bit_Aligned_Component (Lhs)
1294 Possible_Bit_Aligned_Component (Rhs)
1295 then
1296 null;
1298 -- If we have a tagged type that has a complete record representation
1299 -- clause, we must do we must do component-wise assignments, since child
1300 -- types may have used gaps for their components, and we might be
1301 -- dealing with a view conversion.
1303 elsif Is_Fully_Repped_Tagged_Type (L_Typ) then
1304 null;
1306 -- If neither condition met, then nothing special to do, the back end
1307 -- can handle assignment of the entire component as a single entity.
1309 else
1310 return;
1311 end if;
1313 -- At this stage we know that we must do a component wise assignment
1315 declare
1316 Loc : constant Source_Ptr := Sloc (N);
1317 R_Typ : constant Entity_Id := Base_Type (Etype (Rhs));
1318 Decl : constant Node_Id := Declaration_Node (R_Typ);
1319 RDef : Node_Id;
1320 F : Entity_Id;
1322 function Find_Component
1323 (Typ : Entity_Id;
1324 Comp : Entity_Id) return Entity_Id;
1325 -- Find the component with the given name in the underlying record
1326 -- declaration for Typ. We need to use the actual entity because the
1327 -- type may be private and resolution by identifier alone would fail.
1329 function Make_Component_List_Assign
1330 (CL : Node_Id;
1331 U_U : Boolean := False) return List_Id;
1332 -- Returns a sequence of statements to assign the components that
1333 -- are referenced in the given component list. The flag U_U is
1334 -- used to force the usage of the inferred value of the variant
1335 -- part expression as the switch for the generated case statement.
1337 function Make_Field_Assign
1338 (C : Entity_Id;
1339 U_U : Boolean := False) return Node_Id;
1340 -- Given C, the entity for a discriminant or component, build an
1341 -- assignment for the corresponding field values. The flag U_U
1342 -- signals the presence of an Unchecked_Union and forces the usage
1343 -- of the inferred discriminant value of C as the right-hand side
1344 -- of the assignment.
1346 function Make_Field_Assigns (CI : List_Id) return List_Id;
1347 -- Given CI, a component items list, construct series of statements
1348 -- for fieldwise assignment of the corresponding components.
1350 --------------------
1351 -- Find_Component --
1352 --------------------
1354 function Find_Component
1355 (Typ : Entity_Id;
1356 Comp : Entity_Id) return Entity_Id
1358 Utyp : constant Entity_Id := Underlying_Type (Typ);
1359 C : Entity_Id;
1361 begin
1362 C := First_Entity (Utyp);
1363 while Present (C) loop
1364 if Chars (C) = Chars (Comp) then
1365 return C;
1366 end if;
1368 Next_Entity (C);
1369 end loop;
1371 raise Program_Error;
1372 end Find_Component;
1374 --------------------------------
1375 -- Make_Component_List_Assign --
1376 --------------------------------
1378 function Make_Component_List_Assign
1379 (CL : Node_Id;
1380 U_U : Boolean := False) return List_Id
1382 CI : constant List_Id := Component_Items (CL);
1383 VP : constant Node_Id := Variant_Part (CL);
1385 Alts : List_Id;
1386 DC : Node_Id;
1387 DCH : List_Id;
1388 Expr : Node_Id;
1389 Result : List_Id;
1390 V : Node_Id;
1392 begin
1393 Result := Make_Field_Assigns (CI);
1395 if Present (VP) then
1396 V := First_Non_Pragma (Variants (VP));
1397 Alts := New_List;
1398 while Present (V) loop
1399 DCH := New_List;
1400 DC := First (Discrete_Choices (V));
1401 while Present (DC) loop
1402 Append_To (DCH, New_Copy_Tree (DC));
1403 Next (DC);
1404 end loop;
1406 Append_To (Alts,
1407 Make_Case_Statement_Alternative (Loc,
1408 Discrete_Choices => DCH,
1409 Statements =>
1410 Make_Component_List_Assign (Component_List (V))));
1411 Next_Non_Pragma (V);
1412 end loop;
1414 -- If we have an Unchecked_Union, use the value of the inferred
1415 -- discriminant of the variant part expression as the switch
1416 -- for the case statement. The case statement may later be
1417 -- folded.
1419 if U_U then
1420 Expr :=
1421 New_Copy (Get_Discriminant_Value (
1422 Entity (Name (VP)),
1423 Etype (Rhs),
1424 Discriminant_Constraint (Etype (Rhs))));
1425 else
1426 Expr :=
1427 Make_Selected_Component (Loc,
1428 Prefix => Duplicate_Subexpr (Rhs),
1429 Selector_Name =>
1430 Make_Identifier (Loc, Chars (Name (VP))));
1431 end if;
1433 Append_To (Result,
1434 Make_Case_Statement (Loc,
1435 Expression => Expr,
1436 Alternatives => Alts));
1437 end if;
1439 return Result;
1440 end Make_Component_List_Assign;
1442 -----------------------
1443 -- Make_Field_Assign --
1444 -----------------------
1446 function Make_Field_Assign
1447 (C : Entity_Id;
1448 U_U : Boolean := False) return Node_Id
1450 A : Node_Id;
1451 Expr : Node_Id;
1453 begin
1454 -- In the case of an Unchecked_Union, use the discriminant
1455 -- constraint value as on the right-hand side of the assignment.
1457 if U_U then
1458 Expr :=
1459 New_Copy (Get_Discriminant_Value (C,
1460 Etype (Rhs),
1461 Discriminant_Constraint (Etype (Rhs))));
1462 else
1463 Expr :=
1464 Make_Selected_Component (Loc,
1465 Prefix => Duplicate_Subexpr (Rhs),
1466 Selector_Name => New_Occurrence_Of (C, Loc));
1467 end if;
1469 A :=
1470 Make_Assignment_Statement (Loc,
1471 Name =>
1472 Make_Selected_Component (Loc,
1473 Prefix => Duplicate_Subexpr (Lhs),
1474 Selector_Name =>
1475 New_Occurrence_Of (Find_Component (L_Typ, C), Loc)),
1476 Expression => Expr);
1478 -- Set Assignment_OK, so discriminants can be assigned
1480 Set_Assignment_OK (Name (A), True);
1482 if Componentwise_Assignment (N)
1483 and then Nkind (Name (A)) = N_Selected_Component
1484 and then Chars (Selector_Name (Name (A))) = Name_uParent
1485 then
1486 Set_Componentwise_Assignment (A);
1487 end if;
1489 return A;
1490 end Make_Field_Assign;
1492 ------------------------
1493 -- Make_Field_Assigns --
1494 ------------------------
1496 function Make_Field_Assigns (CI : List_Id) return List_Id is
1497 Item : Node_Id;
1498 Result : List_Id;
1500 begin
1501 Item := First (CI);
1502 Result := New_List;
1504 while Present (Item) loop
1506 -- Look for components, but exclude _tag field assignment if
1507 -- the special Componentwise_Assignment flag is set.
1509 if Nkind (Item) = N_Component_Declaration
1510 and then not (Is_Tag (Defining_Identifier (Item))
1511 and then Componentwise_Assignment (N))
1512 then
1513 Append_To
1514 (Result, Make_Field_Assign (Defining_Identifier (Item)));
1515 end if;
1517 Next (Item);
1518 end loop;
1520 return Result;
1521 end Make_Field_Assigns;
1523 -- Start of processing for Expand_Assign_Record
1525 begin
1526 -- Note that we use the base types for this processing. This results
1527 -- in some extra work in the constrained case, but the change of
1528 -- representation case is so unusual that it is not worth the effort.
1530 -- First copy the discriminants. This is done unconditionally. It
1531 -- is required in the unconstrained left side case, and also in the
1532 -- case where this assignment was constructed during the expansion
1533 -- of a type conversion (since initialization of discriminants is
1534 -- suppressed in this case). It is unnecessary but harmless in
1535 -- other cases.
1537 if Has_Discriminants (L_Typ) then
1538 F := First_Discriminant (R_Typ);
1539 while Present (F) loop
1541 -- If we are expanding the initialization of a derived record
1542 -- that constrains or renames discriminants of the parent, we
1543 -- must use the corresponding discriminant in the parent.
1545 declare
1546 CF : Entity_Id;
1548 begin
1549 if Inside_Init_Proc
1550 and then Present (Corresponding_Discriminant (F))
1551 then
1552 CF := Corresponding_Discriminant (F);
1553 else
1554 CF := F;
1555 end if;
1557 if Is_Unchecked_Union (Base_Type (R_Typ)) then
1559 -- Within an initialization procedure this is the
1560 -- assignment to an unchecked union component, in which
1561 -- case there is no discriminant to initialize.
1563 if Inside_Init_Proc then
1564 null;
1566 else
1567 -- The assignment is part of a conversion from a
1568 -- derived unchecked union type with an inferable
1569 -- discriminant, to a parent type.
1571 Insert_Action (N, Make_Field_Assign (CF, True));
1572 end if;
1574 else
1575 Insert_Action (N, Make_Field_Assign (CF));
1576 end if;
1578 Next_Discriminant (F);
1579 end;
1580 end loop;
1581 end if;
1583 -- We know the underlying type is a record, but its current view
1584 -- may be private. We must retrieve the usable record declaration.
1586 if Nkind_In (Decl, N_Private_Type_Declaration,
1587 N_Private_Extension_Declaration)
1588 and then Present (Full_View (R_Typ))
1589 then
1590 RDef := Type_Definition (Declaration_Node (Full_View (R_Typ)));
1591 else
1592 RDef := Type_Definition (Decl);
1593 end if;
1595 if Nkind (RDef) = N_Derived_Type_Definition then
1596 RDef := Record_Extension_Part (RDef);
1597 end if;
1599 if Nkind (RDef) = N_Record_Definition
1600 and then Present (Component_List (RDef))
1601 then
1602 if Is_Unchecked_Union (R_Typ) then
1603 Insert_Actions (N,
1604 Make_Component_List_Assign (Component_List (RDef), True));
1605 else
1606 Insert_Actions
1607 (N, Make_Component_List_Assign (Component_List (RDef)));
1608 end if;
1610 Rewrite (N, Make_Null_Statement (Loc));
1611 end if;
1612 end;
1613 end Expand_Assign_Record;
1615 -------------------------------------
1616 -- Expand_Assign_With_Target_Names --
1617 -------------------------------------
1619 procedure Expand_Assign_With_Target_Names (N : Node_Id) is
1620 LHS : constant Node_Id := Name (N);
1621 LHS_Typ : constant Entity_Id := Etype (LHS);
1622 Loc : constant Source_Ptr := Sloc (N);
1623 RHS : constant Node_Id := Expression (N);
1625 Ent : Entity_Id;
1626 -- The entity of the left-hand side
1628 function Replace_Target (N : Node_Id) return Traverse_Result;
1629 -- Replace occurrences of the target name by the proper entity: either
1630 -- the entity of the LHS in simple cases, or the formal of the
1631 -- constructed procedure otherwise.
1633 --------------------
1634 -- Replace_Target --
1635 --------------------
1637 function Replace_Target (N : Node_Id) return Traverse_Result is
1638 begin
1639 if Nkind (N) = N_Target_Name then
1640 Rewrite (N, New_Occurrence_Of (Ent, Sloc (N)));
1642 -- The expression will be reanalyzed when the enclosing assignment
1643 -- is reanalyzed, so reset the entity, which may be a temporary
1644 -- created during analysis, e.g. a loop variable for an iterated
1645 -- component association. However, if entity is callable then
1646 -- resolution has established its proper identity (including in
1647 -- rewritten prefixed calls) so we must preserve it.
1649 elsif Is_Entity_Name (N) then
1650 if Present (Entity (N))
1651 and then not Is_Overloadable (Entity (N))
1652 then
1653 Set_Entity (N, Empty);
1654 end if;
1655 end if;
1657 Set_Analyzed (N, False);
1658 return OK;
1659 end Replace_Target;
1661 procedure Replace_Target_Name is new Traverse_Proc (Replace_Target);
1663 -- Local variables
1665 New_RHS : Node_Id;
1666 Proc_Id : Entity_Id;
1668 -- Start of processing for Expand_Assign_With_Target_Names
1670 begin
1671 New_RHS := New_Copy_Tree (RHS);
1673 -- The left-hand side is a direct name
1675 if Is_Entity_Name (LHS)
1676 and then not Is_Renaming_Of_Object (Entity (LHS))
1677 then
1678 Ent := Entity (LHS);
1679 Replace_Target_Name (New_RHS);
1681 -- Generate:
1682 -- LHS := ... LHS ...;
1684 Rewrite (N,
1685 Make_Assignment_Statement (Loc,
1686 Name => Relocate_Node (LHS),
1687 Expression => New_RHS));
1689 -- The left-hand side is not a direct name, but is side-effect free.
1690 -- Capture its value in a temporary to avoid multiple evaluations.
1692 elsif Side_Effect_Free (LHS) then
1693 Ent := Make_Temporary (Loc, 'T');
1694 Replace_Target_Name (New_RHS);
1696 -- Generate:
1697 -- T : LHS_Typ := LHS;
1699 Insert_Before_And_Analyze (N,
1700 Make_Object_Declaration (Loc,
1701 Defining_Identifier => Ent,
1702 Object_Definition => New_Occurrence_Of (LHS_Typ, Loc),
1703 Expression => New_Copy_Tree (LHS)));
1705 -- Generate:
1706 -- LHS := ... T ...;
1708 Rewrite (N,
1709 Make_Assignment_Statement (Loc,
1710 Name => Relocate_Node (LHS),
1711 Expression => New_RHS));
1713 -- Otherwise wrap the whole assignment statement in a procedure with an
1714 -- IN OUT parameter. The original assignment then becomes a call to the
1715 -- procedure with the left-hand side as an actual.
1717 else
1718 Ent := Make_Temporary (Loc, 'T');
1719 Replace_Target_Name (New_RHS);
1721 -- Generate:
1722 -- procedure P (T : in out LHS_Typ) is
1723 -- begin
1724 -- T := ... T ...;
1725 -- end P;
1727 Proc_Id := Make_Temporary (Loc, 'P');
1729 Insert_Before_And_Analyze (N,
1730 Make_Subprogram_Body (Loc,
1731 Specification =>
1732 Make_Procedure_Specification (Loc,
1733 Defining_Unit_Name => Proc_Id,
1734 Parameter_Specifications => New_List (
1735 Make_Parameter_Specification (Loc,
1736 Defining_Identifier => Ent,
1737 In_Present => True,
1738 Out_Present => True,
1739 Parameter_Type =>
1740 New_Occurrence_Of (LHS_Typ, Loc)))),
1742 Declarations => Empty_List,
1744 Handled_Statement_Sequence =>
1745 Make_Handled_Sequence_Of_Statements (Loc,
1746 Statements => New_List (
1747 Make_Assignment_Statement (Loc,
1748 Name => New_Occurrence_Of (Ent, Loc),
1749 Expression => New_RHS)))));
1751 -- Generate:
1752 -- P (LHS);
1754 Rewrite (N,
1755 Make_Procedure_Call_Statement (Loc,
1756 Name => New_Occurrence_Of (Proc_Id, Loc),
1757 Parameter_Associations => New_List (Relocate_Node (LHS))));
1758 end if;
1760 -- Analyze rewritten node, either as assignment or procedure call
1762 Analyze (N);
1763 end Expand_Assign_With_Target_Names;
1765 -----------------------------------
1766 -- Expand_N_Assignment_Statement --
1767 -----------------------------------
1769 -- This procedure implements various cases where an assignment statement
1770 -- cannot just be passed on to the back end in untransformed state.
1772 procedure Expand_N_Assignment_Statement (N : Node_Id) is
1773 Crep : constant Boolean := Change_Of_Representation (N);
1774 Lhs : constant Node_Id := Name (N);
1775 Loc : constant Source_Ptr := Sloc (N);
1776 Rhs : constant Node_Id := Expression (N);
1777 Typ : constant Entity_Id := Underlying_Type (Etype (Lhs));
1778 Exp : Node_Id;
1780 begin
1781 -- Special case to check right away, if the Componentwise_Assignment
1782 -- flag is set, this is a reanalysis from the expansion of the primitive
1783 -- assignment procedure for a tagged type, and all we need to do is to
1784 -- expand to assignment of components, because otherwise, we would get
1785 -- infinite recursion (since this looks like a tagged assignment which
1786 -- would normally try to *call* the primitive assignment procedure).
1788 if Componentwise_Assignment (N) then
1789 Expand_Assign_Record (N);
1790 return;
1791 end if;
1793 -- Defend against invalid subscripts on left side if we are in standard
1794 -- validity checking mode. No need to do this if we are checking all
1795 -- subscripts.
1797 -- Note that we do this right away, because there are some early return
1798 -- paths in this procedure, and this is required on all paths.
1800 if Validity_Checks_On
1801 and then Validity_Check_Default
1802 and then not Validity_Check_Subscripts
1803 then
1804 Check_Valid_Lvalue_Subscripts (Lhs);
1805 end if;
1807 -- Separate expansion if RHS contain target names. Note that assignment
1808 -- may already have been expanded if RHS is aggregate.
1810 if Nkind (N) = N_Assignment_Statement and then Has_Target_Names (N) then
1811 Expand_Assign_With_Target_Names (N);
1812 return;
1813 end if;
1815 -- Ada 2005 (AI-327): Handle assignment to priority of protected object
1817 -- Rewrite an assignment to X'Priority into a run-time call
1819 -- For example: X'Priority := New_Prio_Expr;
1820 -- ...is expanded into Set_Ceiling (X._Object, New_Prio_Expr);
1822 -- Note that although X'Priority is notionally an object, it is quite
1823 -- deliberately not defined as an aliased object in the RM. This means
1824 -- that it works fine to rewrite it as a call, without having to worry
1825 -- about complications that would other arise from X'Priority'Access,
1826 -- which is illegal, because of the lack of aliasing.
1828 if Ada_Version >= Ada_2005 then
1829 declare
1830 Call : Node_Id;
1831 Conctyp : Entity_Id;
1832 Ent : Entity_Id;
1833 Subprg : Entity_Id;
1834 RT_Subprg_Name : Node_Id;
1836 begin
1837 -- Handle chains of renamings
1839 Ent := Name (N);
1840 while Nkind (Ent) in N_Has_Entity
1841 and then Present (Entity (Ent))
1842 and then Present (Renamed_Object (Entity (Ent)))
1843 loop
1844 Ent := Renamed_Object (Entity (Ent));
1845 end loop;
1847 -- The attribute Priority applied to protected objects has been
1848 -- previously expanded into a call to the Get_Ceiling run-time
1849 -- subprogram. In restricted profiles this is not available.
1851 if Is_Expanded_Priority_Attribute (Ent) then
1853 -- Look for the enclosing concurrent type
1855 Conctyp := Current_Scope;
1856 while not Is_Concurrent_Type (Conctyp) loop
1857 Conctyp := Scope (Conctyp);
1858 end loop;
1860 pragma Assert (Is_Protected_Type (Conctyp));
1862 -- Generate the first actual of the call
1864 Subprg := Current_Scope;
1865 while not Present (Protected_Body_Subprogram (Subprg)) loop
1866 Subprg := Scope (Subprg);
1867 end loop;
1869 -- Select the appropriate run-time call
1871 if Number_Entries (Conctyp) = 0 then
1872 RT_Subprg_Name :=
1873 New_Occurrence_Of (RTE (RE_Set_Ceiling), Loc);
1874 else
1875 RT_Subprg_Name :=
1876 New_Occurrence_Of (RTE (RO_PE_Set_Ceiling), Loc);
1877 end if;
1879 Call :=
1880 Make_Procedure_Call_Statement (Loc,
1881 Name => RT_Subprg_Name,
1882 Parameter_Associations => New_List (
1883 New_Copy_Tree (First (Parameter_Associations (Ent))),
1884 Relocate_Node (Expression (N))));
1886 Rewrite (N, Call);
1887 Analyze (N);
1889 return;
1890 end if;
1891 end;
1892 end if;
1894 -- Deal with assignment checks unless suppressed
1896 if not Suppress_Assignment_Checks (N) then
1898 -- First deal with generation of range check if required
1900 if Do_Range_Check (Rhs) then
1901 Generate_Range_Check (Rhs, Typ, CE_Range_Check_Failed);
1902 end if;
1904 -- Then generate predicate check if required
1906 Apply_Predicate_Check (Rhs, Typ);
1907 end if;
1909 -- Check for a special case where a high level transformation is
1910 -- required. If we have either of:
1912 -- P.field := rhs;
1913 -- P (sub) := rhs;
1915 -- where P is a reference to a bit packed array, then we have to unwind
1916 -- the assignment. The exact meaning of being a reference to a bit
1917 -- packed array is as follows:
1919 -- An indexed component whose prefix is a bit packed array is a
1920 -- reference to a bit packed array.
1922 -- An indexed component or selected component whose prefix is a
1923 -- reference to a bit packed array is itself a reference ot a
1924 -- bit packed array.
1926 -- The required transformation is
1928 -- Tnn : prefix_type := P;
1929 -- Tnn.field := rhs;
1930 -- P := Tnn;
1932 -- or
1934 -- Tnn : prefix_type := P;
1935 -- Tnn (subscr) := rhs;
1936 -- P := Tnn;
1938 -- Since P is going to be evaluated more than once, any subscripts
1939 -- in P must have their evaluation forced.
1941 if Nkind_In (Lhs, N_Indexed_Component, N_Selected_Component)
1942 and then Is_Ref_To_Bit_Packed_Array (Prefix (Lhs))
1943 then
1944 declare
1945 BPAR_Expr : constant Node_Id := Relocate_Node (Prefix (Lhs));
1946 BPAR_Typ : constant Entity_Id := Etype (BPAR_Expr);
1947 Tnn : constant Entity_Id :=
1948 Make_Temporary (Loc, 'T', BPAR_Expr);
1950 begin
1951 -- Insert the post assignment first, because we want to copy the
1952 -- BPAR_Expr tree before it gets analyzed in the context of the
1953 -- pre assignment. Note that we do not analyze the post assignment
1954 -- yet (we cannot till we have completed the analysis of the pre
1955 -- assignment). As usual, the analysis of this post assignment
1956 -- will happen on its own when we "run into" it after finishing
1957 -- the current assignment.
1959 Insert_After (N,
1960 Make_Assignment_Statement (Loc,
1961 Name => New_Copy_Tree (BPAR_Expr),
1962 Expression => New_Occurrence_Of (Tnn, Loc)));
1964 -- At this stage BPAR_Expr is a reference to a bit packed array
1965 -- where the reference was not expanded in the original tree,
1966 -- since it was on the left side of an assignment. But in the
1967 -- pre-assignment statement (the object definition), BPAR_Expr
1968 -- will end up on the right-hand side, and must be reexpanded. To
1969 -- achieve this, we reset the analyzed flag of all selected and
1970 -- indexed components down to the actual indexed component for
1971 -- the packed array.
1973 Exp := BPAR_Expr;
1974 loop
1975 Set_Analyzed (Exp, False);
1977 if Nkind_In (Exp, N_Indexed_Component,
1978 N_Selected_Component)
1979 then
1980 Exp := Prefix (Exp);
1981 else
1982 exit;
1983 end if;
1984 end loop;
1986 -- Now we can insert and analyze the pre-assignment
1988 -- If the right-hand side requires a transient scope, it has
1989 -- already been placed on the stack. However, the declaration is
1990 -- inserted in the tree outside of this scope, and must reflect
1991 -- the proper scope for its variable. This awkward bit is forced
1992 -- by the stricter scope discipline imposed by GCC 2.97.
1994 declare
1995 Uses_Transient_Scope : constant Boolean :=
1996 Scope_Is_Transient
1997 and then N = Node_To_Be_Wrapped;
1999 begin
2000 if Uses_Transient_Scope then
2001 Push_Scope (Scope (Current_Scope));
2002 end if;
2004 Insert_Before_And_Analyze (N,
2005 Make_Object_Declaration (Loc,
2006 Defining_Identifier => Tnn,
2007 Object_Definition => New_Occurrence_Of (BPAR_Typ, Loc),
2008 Expression => BPAR_Expr));
2010 if Uses_Transient_Scope then
2011 Pop_Scope;
2012 end if;
2013 end;
2015 -- Now fix up the original assignment and continue processing
2017 Rewrite (Prefix (Lhs),
2018 New_Occurrence_Of (Tnn, Loc));
2020 -- We do not need to reanalyze that assignment, and we do not need
2021 -- to worry about references to the temporary, but we do need to
2022 -- make sure that the temporary is not marked as a true constant
2023 -- since we now have a generated assignment to it.
2025 Set_Is_True_Constant (Tnn, False);
2026 end;
2027 end if;
2029 -- When we have the appropriate type of aggregate in the expression (it
2030 -- has been determined during analysis of the aggregate by setting the
2031 -- delay flag), let's perform in place assignment and thus avoid
2032 -- creating a temporary.
2034 if Is_Delayed_Aggregate (Rhs) then
2035 Convert_Aggr_In_Assignment (N);
2036 Rewrite (N, Make_Null_Statement (Loc));
2037 Analyze (N);
2039 return;
2040 end if;
2042 -- Apply discriminant check if required. If Lhs is an access type to a
2043 -- designated type with discriminants, we must always check. If the
2044 -- type has unknown discriminants, more elaborate processing below.
2046 if Has_Discriminants (Etype (Lhs))
2047 and then not Has_Unknown_Discriminants (Etype (Lhs))
2048 then
2049 -- Skip discriminant check if change of representation. Will be
2050 -- done when the change of representation is expanded out.
2052 if not Crep then
2053 Apply_Discriminant_Check (Rhs, Etype (Lhs), Lhs);
2054 end if;
2056 -- If the type is private without discriminants, and the full type
2057 -- has discriminants (necessarily with defaults) a check may still be
2058 -- necessary if the Lhs is aliased. The private discriminants must be
2059 -- visible to build the discriminant constraints.
2061 -- Only an explicit dereference that comes from source indicates
2062 -- aliasing. Access to formals of protected operations and entries
2063 -- create dereferences but are not semantic aliasings.
2065 elsif Is_Private_Type (Etype (Lhs))
2066 and then Has_Discriminants (Typ)
2067 and then Nkind (Lhs) = N_Explicit_Dereference
2068 and then Comes_From_Source (Lhs)
2069 then
2070 declare
2071 Lt : constant Entity_Id := Etype (Lhs);
2072 Ubt : Entity_Id := Base_Type (Typ);
2074 begin
2075 -- In the case of an expander-generated record subtype whose base
2076 -- type still appears private, Typ will have been set to that
2077 -- private type rather than the underlying record type (because
2078 -- Underlying type will have returned the record subtype), so it's
2079 -- necessary to apply Underlying_Type again to the base type to
2080 -- get the record type we need for the discriminant check. Such
2081 -- subtypes can be created for assignments in certain cases, such
2082 -- as within an instantiation passed this kind of private type.
2083 -- It would be good to avoid this special test, but making changes
2084 -- to prevent this odd form of record subtype seems difficult. ???
2086 if Is_Private_Type (Ubt) then
2087 Ubt := Underlying_Type (Ubt);
2088 end if;
2090 Set_Etype (Lhs, Ubt);
2091 Rewrite (Rhs, OK_Convert_To (Base_Type (Ubt), Rhs));
2092 Apply_Discriminant_Check (Rhs, Ubt, Lhs);
2093 Set_Etype (Lhs, Lt);
2094 end;
2096 -- If the Lhs has a private type with unknown discriminants, it may
2097 -- have a full view with discriminants, but those are nameable only
2098 -- in the underlying type, so convert the Rhs to it before potential
2099 -- checking. Convert Lhs as well, otherwise the actual subtype might
2100 -- not be constructible. If the discriminants have defaults the type
2101 -- is unconstrained and there is nothing to check.
2103 elsif Has_Unknown_Discriminants (Base_Type (Etype (Lhs)))
2104 and then Has_Discriminants (Typ)
2105 and then not Has_Defaulted_Discriminants (Typ)
2106 then
2107 Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
2108 Rewrite (Lhs, OK_Convert_To (Base_Type (Typ), Lhs));
2109 Apply_Discriminant_Check (Rhs, Typ, Lhs);
2111 -- In the access type case, we need the same discriminant check, and
2112 -- also range checks if we have an access to constrained array.
2114 elsif Is_Access_Type (Etype (Lhs))
2115 and then Is_Constrained (Designated_Type (Etype (Lhs)))
2116 then
2117 if Has_Discriminants (Designated_Type (Etype (Lhs))) then
2119 -- Skip discriminant check if change of representation. Will be
2120 -- done when the change of representation is expanded out.
2122 if not Crep then
2123 Apply_Discriminant_Check (Rhs, Etype (Lhs));
2124 end if;
2126 elsif Is_Array_Type (Designated_Type (Etype (Lhs))) then
2127 Apply_Range_Check (Rhs, Etype (Lhs));
2129 if Is_Constrained (Etype (Lhs)) then
2130 Apply_Length_Check (Rhs, Etype (Lhs));
2131 end if;
2133 if Nkind (Rhs) = N_Allocator then
2134 declare
2135 Target_Typ : constant Entity_Id := Etype (Expression (Rhs));
2136 C_Es : Check_Result;
2138 begin
2139 C_Es :=
2140 Get_Range_Checks
2141 (Lhs,
2142 Target_Typ,
2143 Etype (Designated_Type (Etype (Lhs))));
2145 Insert_Range_Checks
2146 (C_Es,
2148 Target_Typ,
2149 Sloc (Lhs),
2150 Lhs);
2151 end;
2152 end if;
2153 end if;
2155 -- Apply range check for access type case
2157 elsif Is_Access_Type (Etype (Lhs))
2158 and then Nkind (Rhs) = N_Allocator
2159 and then Nkind (Expression (Rhs)) = N_Qualified_Expression
2160 then
2161 Analyze_And_Resolve (Expression (Rhs));
2162 Apply_Range_Check
2163 (Expression (Rhs), Designated_Type (Etype (Lhs)));
2164 end if;
2166 -- Ada 2005 (AI-231): Generate the run-time check
2168 if Is_Access_Type (Typ)
2169 and then Can_Never_Be_Null (Etype (Lhs))
2170 and then not Can_Never_Be_Null (Etype (Rhs))
2172 -- If an actual is an out parameter of a null-excluding access
2173 -- type, there is access check on entry, so we set the flag
2174 -- Suppress_Assignment_Checks on the generated statement to
2175 -- assign the actual to the parameter block, and we do not want
2176 -- to generate an additional check at this point.
2178 and then not Suppress_Assignment_Checks (N)
2179 then
2180 Apply_Constraint_Check (Rhs, Etype (Lhs));
2181 end if;
2183 -- Ada 2012 (AI05-148): Update current accessibility level if Rhs is a
2184 -- stand-alone obj of an anonymous access type. Do not install the check
2185 -- when the Lhs denotes a container cursor and the Next function employs
2186 -- an access type, because this can never result in a dangling pointer.
2188 if Is_Access_Type (Typ)
2189 and then Is_Entity_Name (Lhs)
2190 and then Ekind (Entity (Lhs)) /= E_Loop_Parameter
2191 and then Present (Effective_Extra_Accessibility (Entity (Lhs)))
2192 then
2193 declare
2194 function Lhs_Entity return Entity_Id;
2195 -- Look through renames to find the underlying entity.
2196 -- For assignment to a rename, we don't care about the
2197 -- Enclosing_Dynamic_Scope of the rename declaration.
2199 ----------------
2200 -- Lhs_Entity --
2201 ----------------
2203 function Lhs_Entity return Entity_Id is
2204 Result : Entity_Id := Entity (Lhs);
2206 begin
2207 while Present (Renamed_Object (Result)) loop
2209 -- Renamed_Object must return an Entity_Name here
2210 -- because of preceding "Present (E_E_A (...))" test.
2212 Result := Entity (Renamed_Object (Result));
2213 end loop;
2215 return Result;
2216 end Lhs_Entity;
2218 -- Local Declarations
2220 Access_Check : constant Node_Id :=
2221 Make_Raise_Program_Error (Loc,
2222 Condition =>
2223 Make_Op_Gt (Loc,
2224 Left_Opnd =>
2225 Dynamic_Accessibility_Level (Rhs),
2226 Right_Opnd =>
2227 Make_Integer_Literal (Loc,
2228 Intval =>
2229 Scope_Depth
2230 (Enclosing_Dynamic_Scope
2231 (Lhs_Entity)))),
2232 Reason => PE_Accessibility_Check_Failed);
2234 Access_Level_Update : constant Node_Id :=
2235 Make_Assignment_Statement (Loc,
2236 Name =>
2237 New_Occurrence_Of
2238 (Effective_Extra_Accessibility
2239 (Entity (Lhs)), Loc),
2240 Expression =>
2241 Dynamic_Accessibility_Level (Rhs));
2243 begin
2244 if not Accessibility_Checks_Suppressed (Entity (Lhs)) then
2245 Insert_Action (N, Access_Check);
2246 end if;
2248 Insert_Action (N, Access_Level_Update);
2249 end;
2250 end if;
2252 -- Case of assignment to a bit packed array element. If there is a
2253 -- change of representation this must be expanded into components,
2254 -- otherwise this is a bit-field assignment.
2256 if Nkind (Lhs) = N_Indexed_Component
2257 and then Is_Bit_Packed_Array (Etype (Prefix (Lhs)))
2258 then
2259 -- Normal case, no change of representation
2261 if not Crep then
2262 Expand_Bit_Packed_Element_Set (N);
2263 return;
2265 -- Change of representation case
2267 else
2268 -- Generate the following, to force component-by-component
2269 -- assignments in an efficient way. Otherwise each component
2270 -- will require a temporary and two bit-field manipulations.
2272 -- T1 : Elmt_Type;
2273 -- T1 := RhS;
2274 -- Lhs := T1;
2276 declare
2277 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T');
2278 Stats : List_Id;
2280 begin
2281 Stats :=
2282 New_List (
2283 Make_Object_Declaration (Loc,
2284 Defining_Identifier => Tnn,
2285 Object_Definition =>
2286 New_Occurrence_Of (Etype (Lhs), Loc)),
2287 Make_Assignment_Statement (Loc,
2288 Name => New_Occurrence_Of (Tnn, Loc),
2289 Expression => Relocate_Node (Rhs)),
2290 Make_Assignment_Statement (Loc,
2291 Name => Relocate_Node (Lhs),
2292 Expression => New_Occurrence_Of (Tnn, Loc)));
2294 Insert_Actions (N, Stats);
2295 Rewrite (N, Make_Null_Statement (Loc));
2296 Analyze (N);
2297 end;
2298 end if;
2300 -- Build-in-place function call case. Note that we're not yet doing
2301 -- build-in-place for user-written assignment statements (the assignment
2302 -- here came from an aggregate.)
2304 elsif Ada_Version >= Ada_2005
2305 and then Is_Build_In_Place_Function_Call (Rhs)
2306 then
2307 Make_Build_In_Place_Call_In_Assignment (N, Rhs);
2309 elsif Is_Tagged_Type (Typ)
2310 or else (Needs_Finalization (Typ) and then not Is_Array_Type (Typ))
2311 then
2312 Tagged_Case : declare
2313 L : List_Id := No_List;
2314 Expand_Ctrl_Actions : constant Boolean := not No_Ctrl_Actions (N);
2316 begin
2317 -- In the controlled case, we ensure that function calls are
2318 -- evaluated before finalizing the target. In all cases, it makes
2319 -- the expansion easier if the side effects are removed first.
2321 Remove_Side_Effects (Lhs);
2322 Remove_Side_Effects (Rhs);
2324 -- Avoid recursion in the mechanism
2326 Set_Analyzed (N);
2328 -- If dispatching assignment, we need to dispatch to _assign
2330 if Is_Class_Wide_Type (Typ)
2332 -- If the type is tagged, we may as well use the predefined
2333 -- primitive assignment. This avoids inlining a lot of code
2334 -- and in the class-wide case, the assignment is replaced
2335 -- by a dispatching call to _assign. It is suppressed in the
2336 -- case of assignments created by the expander that correspond
2337 -- to initializations, where we do want to copy the tag
2338 -- (Expand_Ctrl_Actions flag is set False in this case). It is
2339 -- also suppressed if restriction No_Dispatching_Calls is in
2340 -- force because in that case predefined primitives are not
2341 -- generated.
2343 or else (Is_Tagged_Type (Typ)
2344 and then Chars (Current_Scope) /= Name_uAssign
2345 and then Expand_Ctrl_Actions
2346 and then
2347 not Restriction_Active (No_Dispatching_Calls))
2348 then
2349 if Is_Limited_Type (Typ) then
2351 -- This can happen in an instance when the formal is an
2352 -- extension of a limited interface, and the actual is
2353 -- limited. This is an error according to AI05-0087, but
2354 -- is not caught at the point of instantiation in earlier
2355 -- versions.
2357 -- This is wrong, error messages cannot be issued during
2358 -- expansion, since they would be missed in -gnatc mode ???
2360 Error_Msg_N ("assignment not available on limited type", N);
2361 return;
2362 end if;
2364 -- Fetch the primitive op _assign and proper type to call it.
2365 -- Because of possible conflicts between private and full view,
2366 -- fetch the proper type directly from the operation profile.
2368 declare
2369 Op : constant Entity_Id :=
2370 Find_Prim_Op (Typ, Name_uAssign);
2371 F_Typ : Entity_Id := Etype (First_Formal (Op));
2373 begin
2374 -- If the assignment is dispatching, make sure to use the
2375 -- proper type.
2377 if Is_Class_Wide_Type (Typ) then
2378 F_Typ := Class_Wide_Type (F_Typ);
2379 end if;
2381 L := New_List;
2383 -- In case of assignment to a class-wide tagged type, before
2384 -- the assignment we generate run-time check to ensure that
2385 -- the tags of source and target match.
2387 if not Tag_Checks_Suppressed (Typ)
2388 and then Is_Class_Wide_Type (Typ)
2389 and then Is_Tagged_Type (Typ)
2390 and then Is_Tagged_Type (Underlying_Type (Etype (Rhs)))
2391 then
2392 declare
2393 Lhs_Tag : Node_Id;
2394 Rhs_Tag : Node_Id;
2396 begin
2397 if not Is_Interface (Typ) then
2398 Lhs_Tag :=
2399 Make_Selected_Component (Loc,
2400 Prefix => Duplicate_Subexpr (Lhs),
2401 Selector_Name =>
2402 Make_Identifier (Loc, Name_uTag));
2403 Rhs_Tag :=
2404 Make_Selected_Component (Loc,
2405 Prefix => Duplicate_Subexpr (Rhs),
2406 Selector_Name =>
2407 Make_Identifier (Loc, Name_uTag));
2408 else
2409 -- Displace the pointer to the base of the objects
2410 -- applying 'Address, which is later expanded into
2411 -- a call to RE_Base_Address.
2413 Lhs_Tag :=
2414 Make_Explicit_Dereference (Loc,
2415 Prefix =>
2416 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
2417 Make_Attribute_Reference (Loc,
2418 Prefix => Duplicate_Subexpr (Lhs),
2419 Attribute_Name => Name_Address)));
2420 Rhs_Tag :=
2421 Make_Explicit_Dereference (Loc,
2422 Prefix =>
2423 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
2424 Make_Attribute_Reference (Loc,
2425 Prefix => Duplicate_Subexpr (Rhs),
2426 Attribute_Name => Name_Address)));
2427 end if;
2429 Append_To (L,
2430 Make_Raise_Constraint_Error (Loc,
2431 Condition =>
2432 Make_Op_Ne (Loc,
2433 Left_Opnd => Lhs_Tag,
2434 Right_Opnd => Rhs_Tag),
2435 Reason => CE_Tag_Check_Failed));
2436 end;
2437 end if;
2439 declare
2440 Left_N : Node_Id := Duplicate_Subexpr (Lhs);
2441 Right_N : Node_Id := Duplicate_Subexpr (Rhs);
2443 begin
2444 -- In order to dispatch the call to _assign the type of
2445 -- the actuals must match. Add conversion (if required).
2447 if Etype (Lhs) /= F_Typ then
2448 Left_N := Unchecked_Convert_To (F_Typ, Left_N);
2449 end if;
2451 if Etype (Rhs) /= F_Typ then
2452 Right_N := Unchecked_Convert_To (F_Typ, Right_N);
2453 end if;
2455 Append_To (L,
2456 Make_Procedure_Call_Statement (Loc,
2457 Name => New_Occurrence_Of (Op, Loc),
2458 Parameter_Associations => New_List (
2459 Node1 => Left_N,
2460 Node2 => Right_N)));
2461 end;
2462 end;
2464 else
2465 L := Make_Tag_Ctrl_Assignment (N);
2467 -- We can't afford to have destructive Finalization Actions in
2468 -- the Self assignment case, so if the target and the source
2469 -- are not obviously different, code is generated to avoid the
2470 -- self assignment case:
2472 -- if lhs'address /= rhs'address then
2473 -- <code for controlled and/or tagged assignment>
2474 -- end if;
2476 -- Skip this if Restriction (No_Finalization) is active
2478 if not Statically_Different (Lhs, Rhs)
2479 and then Expand_Ctrl_Actions
2480 and then not Restriction_Active (No_Finalization)
2481 then
2482 L := New_List (
2483 Make_Implicit_If_Statement (N,
2484 Condition =>
2485 Make_Op_Ne (Loc,
2486 Left_Opnd =>
2487 Make_Attribute_Reference (Loc,
2488 Prefix => Duplicate_Subexpr (Lhs),
2489 Attribute_Name => Name_Address),
2491 Right_Opnd =>
2492 Make_Attribute_Reference (Loc,
2493 Prefix => Duplicate_Subexpr (Rhs),
2494 Attribute_Name => Name_Address)),
2496 Then_Statements => L));
2497 end if;
2499 -- We need to set up an exception handler for implementing
2500 -- 7.6.1(18). The remaining adjustments are tackled by the
2501 -- implementation of adjust for record_controllers (see
2502 -- s-finimp.adb).
2504 -- This is skipped if we have no finalization
2506 if Expand_Ctrl_Actions
2507 and then not Restriction_Active (No_Finalization)
2508 then
2509 L := New_List (
2510 Make_Block_Statement (Loc,
2511 Handled_Statement_Sequence =>
2512 Make_Handled_Sequence_Of_Statements (Loc,
2513 Statements => L,
2514 Exception_Handlers => New_List (
2515 Make_Handler_For_Ctrl_Operation (Loc)))));
2516 end if;
2517 end if;
2519 Rewrite (N,
2520 Make_Block_Statement (Loc,
2521 Handled_Statement_Sequence =>
2522 Make_Handled_Sequence_Of_Statements (Loc, Statements => L)));
2524 -- If no restrictions on aborts, protect the whole assignment
2525 -- for controlled objects as per 9.8(11).
2527 if Needs_Finalization (Typ)
2528 and then Expand_Ctrl_Actions
2529 and then Abort_Allowed
2530 then
2531 declare
2532 Blk : constant Entity_Id :=
2533 New_Internal_Entity
2534 (E_Block, Current_Scope, Sloc (N), 'B');
2535 AUD : constant Entity_Id := RTE (RE_Abort_Undefer_Direct);
2537 begin
2538 Set_Is_Abort_Block (N);
2540 Set_Scope (Blk, Current_Scope);
2541 Set_Etype (Blk, Standard_Void_Type);
2542 Set_Identifier (N, New_Occurrence_Of (Blk, Sloc (N)));
2544 Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
2545 Set_At_End_Proc (Handled_Statement_Sequence (N),
2546 New_Occurrence_Of (AUD, Loc));
2548 -- Present the Abort_Undefer_Direct function to the backend
2549 -- so that it can inline the call to the function.
2551 Add_Inlined_Body (AUD, N);
2553 Expand_At_End_Handler
2554 (Handled_Statement_Sequence (N), Blk);
2555 end;
2556 end if;
2558 -- N has been rewritten to a block statement for which it is
2559 -- known by construction that no checks are necessary: analyze
2560 -- it with all checks suppressed.
2562 Analyze (N, Suppress => All_Checks);
2563 return;
2564 end Tagged_Case;
2566 -- Array types
2568 elsif Is_Array_Type (Typ) then
2569 declare
2570 Actual_Rhs : Node_Id := Rhs;
2572 begin
2573 while Nkind_In (Actual_Rhs, N_Type_Conversion,
2574 N_Qualified_Expression)
2575 loop
2576 Actual_Rhs := Expression (Actual_Rhs);
2577 end loop;
2579 Expand_Assign_Array (N, Actual_Rhs);
2580 return;
2581 end;
2583 -- Record types
2585 elsif Is_Record_Type (Typ) then
2586 Expand_Assign_Record (N);
2587 return;
2589 -- Scalar types. This is where we perform the processing related to the
2590 -- requirements of (RM 13.9.1(9-11)) concerning the handling of invalid
2591 -- scalar values.
2593 elsif Is_Scalar_Type (Typ) then
2595 -- Case where right side is known valid
2597 if Expr_Known_Valid (Rhs) then
2599 -- Here the right side is valid, so it is fine. The case to deal
2600 -- with is when the left side is a local variable reference whose
2601 -- value is not currently known to be valid. If this is the case,
2602 -- and the assignment appears in an unconditional context, then
2603 -- we can mark the left side as now being valid if one of these
2604 -- conditions holds:
2606 -- The expression of the right side has Do_Range_Check set so
2607 -- that we know a range check will be performed. Note that it
2608 -- can be the case that a range check is omitted because we
2609 -- make the assumption that we can assume validity for operands
2610 -- appearing in the right side in determining whether a range
2611 -- check is required
2613 -- The subtype of the right side matches the subtype of the
2614 -- left side. In this case, even though we have not checked
2615 -- the range of the right side, we know it is in range of its
2616 -- subtype if the expression is valid.
2618 if Is_Local_Variable_Reference (Lhs)
2619 and then not Is_Known_Valid (Entity (Lhs))
2620 and then In_Unconditional_Context (N)
2621 then
2622 if Do_Range_Check (Rhs)
2623 or else Etype (Lhs) = Etype (Rhs)
2624 then
2625 Set_Is_Known_Valid (Entity (Lhs), True);
2626 end if;
2627 end if;
2629 -- Case where right side may be invalid in the sense of the RM
2630 -- reference above. The RM does not require that we check for the
2631 -- validity on an assignment, but it does require that the assignment
2632 -- of an invalid value not cause erroneous behavior.
2634 -- The general approach in GNAT is to use the Is_Known_Valid flag
2635 -- to avoid the need for validity checking on assignments. However
2636 -- in some cases, we have to do validity checking in order to make
2637 -- sure that the setting of this flag is correct.
2639 else
2640 -- Validate right side if we are validating copies
2642 if Validity_Checks_On
2643 and then Validity_Check_Copies
2644 then
2645 -- Skip this if left-hand side is an array or record component
2646 -- and elementary component validity checks are suppressed.
2648 if Nkind_In (Lhs, N_Selected_Component, N_Indexed_Component)
2649 and then not Validity_Check_Components
2650 then
2651 null;
2652 else
2653 Ensure_Valid (Rhs);
2654 end if;
2656 -- We can propagate this to the left side where appropriate
2658 if Is_Local_Variable_Reference (Lhs)
2659 and then not Is_Known_Valid (Entity (Lhs))
2660 and then In_Unconditional_Context (N)
2661 then
2662 Set_Is_Known_Valid (Entity (Lhs), True);
2663 end if;
2665 -- Otherwise check to see what should be done
2667 -- If left side is a local variable, then we just set its flag to
2668 -- indicate that its value may no longer be valid, since we are
2669 -- copying a potentially invalid value.
2671 elsif Is_Local_Variable_Reference (Lhs) then
2672 Set_Is_Known_Valid (Entity (Lhs), False);
2674 -- Check for case of a nonlocal variable on the left side which
2675 -- is currently known to be valid. In this case, we simply ensure
2676 -- that the right side is valid. We only play the game of copying
2677 -- validity status for local variables, since we are doing this
2678 -- statically, not by tracing the full flow graph.
2680 elsif Is_Entity_Name (Lhs)
2681 and then Is_Known_Valid (Entity (Lhs))
2682 then
2683 -- Note: If Validity_Checking mode is set to none, we ignore
2684 -- the Ensure_Valid call so don't worry about that case here.
2686 Ensure_Valid (Rhs);
2688 -- In all other cases, we can safely copy an invalid value without
2689 -- worrying about the status of the left side. Since it is not a
2690 -- variable reference it will not be considered
2691 -- as being known to be valid in any case.
2693 else
2694 null;
2695 end if;
2696 end if;
2697 end if;
2699 exception
2700 when RE_Not_Available =>
2701 return;
2702 end Expand_N_Assignment_Statement;
2704 ------------------------------
2705 -- Expand_N_Block_Statement --
2706 ------------------------------
2708 -- Encode entity names defined in block statement
2710 procedure Expand_N_Block_Statement (N : Node_Id) is
2711 begin
2712 Qualify_Entity_Names (N);
2713 end Expand_N_Block_Statement;
2715 -----------------------------
2716 -- Expand_N_Case_Statement --
2717 -----------------------------
2719 procedure Expand_N_Case_Statement (N : Node_Id) is
2720 Loc : constant Source_Ptr := Sloc (N);
2721 Expr : constant Node_Id := Expression (N);
2722 Alt : Node_Id;
2723 Len : Nat;
2724 Cond : Node_Id;
2725 Choice : Node_Id;
2726 Chlist : List_Id;
2728 begin
2729 -- Check for the situation where we know at compile time which branch
2730 -- will be taken.
2732 -- If the value is static but its subtype is predicated and the value
2733 -- does not obey the predicate, the value is marked non-static, and
2734 -- there can be no corresponding static alternative. In that case we
2735 -- replace the case statement with an exception, regardless of whether
2736 -- assertions are enabled or not, unless predicates are ignored.
2738 if Compile_Time_Known_Value (Expr)
2739 and then Has_Predicates (Etype (Expr))
2740 and then not Predicates_Ignored (Etype (Expr))
2741 and then not Is_OK_Static_Expression (Expr)
2742 then
2743 Rewrite (N,
2744 Make_Raise_Constraint_Error (Loc, Reason => CE_Invalid_Data));
2745 Analyze (N);
2746 return;
2748 elsif Compile_Time_Known_Value (Expr)
2749 and then (not Has_Predicates (Etype (Expr))
2750 or else Is_Static_Expression (Expr))
2751 then
2752 Alt := Find_Static_Alternative (N);
2754 -- Do not consider controlled objects found in a case statement which
2755 -- actually models a case expression because their early finalization
2756 -- will affect the result of the expression.
2758 if not From_Conditional_Expression (N) then
2759 Process_Statements_For_Controlled_Objects (Alt);
2760 end if;
2762 -- Move statements from this alternative after the case statement.
2763 -- They are already analyzed, so will be skipped by the analyzer.
2765 Insert_List_After (N, Statements (Alt));
2767 -- That leaves the case statement as a shell. So now we can kill all
2768 -- other alternatives in the case statement.
2770 Kill_Dead_Code (Expression (N));
2772 declare
2773 Dead_Alt : Node_Id;
2775 begin
2776 -- Loop through case alternatives, skipping pragmas, and skipping
2777 -- the one alternative that we select (and therefore retain).
2779 Dead_Alt := First (Alternatives (N));
2780 while Present (Dead_Alt) loop
2781 if Dead_Alt /= Alt
2782 and then Nkind (Dead_Alt) = N_Case_Statement_Alternative
2783 then
2784 Kill_Dead_Code (Statements (Dead_Alt), Warn_On_Deleted_Code);
2785 end if;
2787 Next (Dead_Alt);
2788 end loop;
2789 end;
2791 Rewrite (N, Make_Null_Statement (Loc));
2792 return;
2793 end if;
2795 -- Here if the choice is not determined at compile time
2797 declare
2798 Last_Alt : constant Node_Id := Last (Alternatives (N));
2800 Others_Present : Boolean;
2801 Others_Node : Node_Id;
2803 Then_Stms : List_Id;
2804 Else_Stms : List_Id;
2806 begin
2807 if Nkind (First (Discrete_Choices (Last_Alt))) = N_Others_Choice then
2808 Others_Present := True;
2809 Others_Node := Last_Alt;
2810 else
2811 Others_Present := False;
2812 end if;
2814 -- First step is to worry about possible invalid argument. The RM
2815 -- requires (RM 5.4(13)) that if the result is invalid (e.g. it is
2816 -- outside the base range), then Constraint_Error must be raised.
2818 -- Case of validity check required (validity checks are on, the
2819 -- expression is not known to be valid, and the case statement
2820 -- comes from source -- no need to validity check internally
2821 -- generated case statements).
2823 if Validity_Check_Default
2824 and then not Predicates_Ignored (Etype (Expr))
2825 then
2826 Ensure_Valid (Expr);
2827 end if;
2829 -- If there is only a single alternative, just replace it with the
2830 -- sequence of statements since obviously that is what is going to
2831 -- be executed in all cases.
2833 Len := List_Length (Alternatives (N));
2835 if Len = 1 then
2837 -- We still need to evaluate the expression if it has any side
2838 -- effects.
2840 Remove_Side_Effects (Expression (N));
2841 Alt := First (Alternatives (N));
2843 -- Do not consider controlled objects found in a case statement
2844 -- which actually models a case expression because their early
2845 -- finalization will affect the result of the expression.
2847 if not From_Conditional_Expression (N) then
2848 Process_Statements_For_Controlled_Objects (Alt);
2849 end if;
2851 Insert_List_After (N, Statements (Alt));
2853 -- That leaves the case statement as a shell. The alternative that
2854 -- will be executed is reset to a null list. So now we can kill
2855 -- the entire case statement.
2857 Kill_Dead_Code (Expression (N));
2858 Rewrite (N, Make_Null_Statement (Loc));
2859 return;
2861 -- An optimization. If there are only two alternatives, and only
2862 -- a single choice, then rewrite the whole case statement as an
2863 -- if statement, since this can result in subsequent optimizations.
2864 -- This helps not only with case statements in the source of a
2865 -- simple form, but also with generated code (discriminant check
2866 -- functions in particular).
2868 -- Note: it is OK to do this before expanding out choices for any
2869 -- static predicates, since the if statement processing will handle
2870 -- the static predicate case fine.
2872 elsif Len = 2 then
2873 Chlist := Discrete_Choices (First (Alternatives (N)));
2875 if List_Length (Chlist) = 1 then
2876 Choice := First (Chlist);
2878 Then_Stms := Statements (First (Alternatives (N)));
2879 Else_Stms := Statements (Last (Alternatives (N)));
2881 -- For TRUE, generate "expression", not expression = true
2883 if Nkind (Choice) = N_Identifier
2884 and then Entity (Choice) = Standard_True
2885 then
2886 Cond := Expression (N);
2888 -- For FALSE, generate "expression" and switch then/else
2890 elsif Nkind (Choice) = N_Identifier
2891 and then Entity (Choice) = Standard_False
2892 then
2893 Cond := Expression (N);
2894 Else_Stms := Statements (First (Alternatives (N)));
2895 Then_Stms := Statements (Last (Alternatives (N)));
2897 -- For a range, generate "expression in range"
2899 elsif Nkind (Choice) = N_Range
2900 or else (Nkind (Choice) = N_Attribute_Reference
2901 and then Attribute_Name (Choice) = Name_Range)
2902 or else (Is_Entity_Name (Choice)
2903 and then Is_Type (Entity (Choice)))
2904 then
2905 Cond :=
2906 Make_In (Loc,
2907 Left_Opnd => Expression (N),
2908 Right_Opnd => Relocate_Node (Choice));
2910 -- A subtype indication is not a legal operator in a membership
2911 -- test, so retrieve its range.
2913 elsif Nkind (Choice) = N_Subtype_Indication then
2914 Cond :=
2915 Make_In (Loc,
2916 Left_Opnd => Expression (N),
2917 Right_Opnd =>
2918 Relocate_Node
2919 (Range_Expression (Constraint (Choice))));
2921 -- For any other subexpression "expression = value"
2923 else
2924 Cond :=
2925 Make_Op_Eq (Loc,
2926 Left_Opnd => Expression (N),
2927 Right_Opnd => Relocate_Node (Choice));
2928 end if;
2930 -- Now rewrite the case as an IF
2932 Rewrite (N,
2933 Make_If_Statement (Loc,
2934 Condition => Cond,
2935 Then_Statements => Then_Stms,
2936 Else_Statements => Else_Stms));
2937 Analyze (N);
2938 return;
2939 end if;
2940 end if;
2942 -- If the last alternative is not an Others choice, replace it with
2943 -- an N_Others_Choice. Note that we do not bother to call Analyze on
2944 -- the modified case statement, since it's only effect would be to
2945 -- compute the contents of the Others_Discrete_Choices which is not
2946 -- needed by the back end anyway.
2948 -- The reason for this is that the back end always needs some default
2949 -- for a switch, so if we have not supplied one in the processing
2950 -- above for validity checking, then we need to supply one here.
2952 if not Others_Present then
2953 Others_Node := Make_Others_Choice (Sloc (Last_Alt));
2955 -- If Predicates_Ignored is true the value does not satisfy the
2956 -- predicate, and there is no Others choice, Constraint_Error
2957 -- must be raised (4.5.7 (21/3)).
2959 if Predicates_Ignored (Etype (Expr)) then
2960 declare
2961 Except : constant Node_Id :=
2962 Make_Raise_Constraint_Error (Loc,
2963 Reason => CE_Invalid_Data);
2964 New_Alt : constant Node_Id :=
2965 Make_Case_Statement_Alternative (Loc,
2966 Discrete_Choices => New_List (
2967 Make_Others_Choice (Loc)),
2968 Statements => New_List (Except));
2970 begin
2971 Append (New_Alt, Alternatives (N));
2972 Analyze_And_Resolve (Except);
2973 end;
2975 else
2976 Set_Others_Discrete_Choices
2977 (Others_Node, Discrete_Choices (Last_Alt));
2978 Set_Discrete_Choices (Last_Alt, New_List (Others_Node));
2979 end if;
2981 end if;
2983 -- Deal with possible declarations of controlled objects, and also
2984 -- with rewriting choice sequences for static predicate references.
2986 Alt := First_Non_Pragma (Alternatives (N));
2987 while Present (Alt) loop
2989 -- Do not consider controlled objects found in a case statement
2990 -- which actually models a case expression because their early
2991 -- finalization will affect the result of the expression.
2993 if not From_Conditional_Expression (N) then
2994 Process_Statements_For_Controlled_Objects (Alt);
2995 end if;
2997 if Has_SP_Choice (Alt) then
2998 Expand_Static_Predicates_In_Choices (Alt);
2999 end if;
3001 Next_Non_Pragma (Alt);
3002 end loop;
3003 end;
3004 end Expand_N_Case_Statement;
3006 -----------------------------
3007 -- Expand_N_Exit_Statement --
3008 -----------------------------
3010 -- The only processing required is to deal with a possible C/Fortran
3011 -- boolean value used as the condition for the exit statement.
3013 procedure Expand_N_Exit_Statement (N : Node_Id) is
3014 begin
3015 Adjust_Condition (Condition (N));
3016 end Expand_N_Exit_Statement;
3018 ----------------------------------
3019 -- Expand_Formal_Container_Loop --
3020 ----------------------------------
3022 procedure Expand_Formal_Container_Loop (N : Node_Id) is
3023 Loc : constant Source_Ptr := Sloc (N);
3024 Isc : constant Node_Id := Iteration_Scheme (N);
3025 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3026 Cursor : constant Entity_Id := Defining_Identifier (I_Spec);
3027 Container : constant Node_Id := Entity (Name (I_Spec));
3028 Stats : constant List_Id := Statements (N);
3030 Advance : Node_Id;
3031 Blk_Nod : Node_Id;
3032 Init : Node_Id;
3033 New_Loop : Node_Id;
3035 begin
3036 -- The expansion resembles the one for Ada containers, but the
3037 -- primitives mention the domain of iteration explicitly, and
3038 -- function First applied to the container yields a cursor directly.
3040 -- Cursor : Cursor_type := First (Container);
3041 -- while Has_Element (Cursor, Container) loop
3042 -- <original loop statements>
3043 -- Cursor := Next (Container, Cursor);
3044 -- end loop;
3046 Build_Formal_Container_Iteration
3047 (N, Container, Cursor, Init, Advance, New_Loop);
3049 Set_Ekind (Cursor, E_Variable);
3050 Append_To (Stats, Advance);
3052 -- Build block to capture declaration of cursor entity.
3054 Blk_Nod :=
3055 Make_Block_Statement (Loc,
3056 Declarations => New_List (Init),
3057 Handled_Statement_Sequence =>
3058 Make_Handled_Sequence_Of_Statements (Loc,
3059 Statements => New_List (New_Loop)));
3061 Rewrite (N, Blk_Nod);
3062 Analyze (N);
3063 end Expand_Formal_Container_Loop;
3065 ------------------------------------------
3066 -- Expand_Formal_Container_Element_Loop --
3067 ------------------------------------------
3069 procedure Expand_Formal_Container_Element_Loop (N : Node_Id) is
3070 Loc : constant Source_Ptr := Sloc (N);
3071 Isc : constant Node_Id := Iteration_Scheme (N);
3072 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3073 Element : constant Entity_Id := Defining_Identifier (I_Spec);
3074 Container : constant Node_Id := Entity (Name (I_Spec));
3075 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
3076 Stats : constant List_Id := Statements (N);
3078 Cursor : constant Entity_Id :=
3079 Make_Defining_Identifier (Loc,
3080 Chars => New_External_Name (Chars (Element), 'C'));
3081 Elmt_Decl : Node_Id;
3082 Elmt_Ref : Node_Id;
3084 Element_Op : constant Entity_Id :=
3085 Get_Iterable_Type_Primitive (Container_Typ, Name_Element);
3087 Advance : Node_Id;
3088 Init : Node_Id;
3089 New_Loop : Node_Id;
3091 begin
3092 -- For an element iterator, the Element aspect must be present,
3093 -- (this is checked during analysis) and the expansion takes the form:
3095 -- Cursor : Cursor_Type := First (Container);
3096 -- Elmt : Element_Type;
3097 -- while Has_Element (Cursor, Container) loop
3098 -- Elmt := Element (Container, Cursor);
3099 -- <original loop statements>
3100 -- Cursor := Next (Container, Cursor);
3101 -- end loop;
3103 -- However this expansion is not legal if the element is indefinite.
3104 -- In that case we create a block to hold a variable declaration
3105 -- initialized with a call to Element, and generate:
3107 -- Cursor : Cursor_Type := First (Container);
3108 -- while Has_Element (Cursor, Container) loop
3109 -- declare
3110 -- Elmt : Element_Type := Element (Container, Cursor);
3111 -- begin
3112 -- <original loop statements>
3113 -- Cursor := Next (Container, Cursor);
3114 -- end;
3115 -- end loop;
3117 Build_Formal_Container_Iteration
3118 (N, Container, Cursor, Init, Advance, New_Loop);
3119 Append_To (Stats, Advance);
3121 Set_Ekind (Cursor, E_Variable);
3122 Insert_Action (N, Init);
3124 -- Declaration for Element
3126 Elmt_Decl :=
3127 Make_Object_Declaration (Loc,
3128 Defining_Identifier => Element,
3129 Object_Definition => New_Occurrence_Of (Etype (Element_Op), Loc));
3131 if not Is_Constrained (Etype (Element_Op)) then
3132 Set_Expression (Elmt_Decl,
3133 Make_Function_Call (Loc,
3134 Name => New_Occurrence_Of (Element_Op, Loc),
3135 Parameter_Associations => New_List (
3136 New_Occurrence_Of (Container, Loc),
3137 New_Occurrence_Of (Cursor, Loc))));
3139 Set_Statements (New_Loop,
3140 New_List
3141 (Make_Block_Statement (Loc,
3142 Declarations => New_List (Elmt_Decl),
3143 Handled_Statement_Sequence =>
3144 Make_Handled_Sequence_Of_Statements (Loc,
3145 Statements => Stats))));
3147 else
3148 Elmt_Ref :=
3149 Make_Assignment_Statement (Loc,
3150 Name => New_Occurrence_Of (Element, Loc),
3151 Expression =>
3152 Make_Function_Call (Loc,
3153 Name => New_Occurrence_Of (Element_Op, Loc),
3154 Parameter_Associations => New_List (
3155 New_Occurrence_Of (Container, Loc),
3156 New_Occurrence_Of (Cursor, Loc))));
3158 Prepend (Elmt_Ref, Stats);
3160 -- The element is assignable in the expanded code
3162 Set_Assignment_OK (Name (Elmt_Ref));
3164 -- The loop is rewritten as a block, to hold the element declaration
3166 New_Loop :=
3167 Make_Block_Statement (Loc,
3168 Declarations => New_List (Elmt_Decl),
3169 Handled_Statement_Sequence =>
3170 Make_Handled_Sequence_Of_Statements (Loc,
3171 Statements => New_List (New_Loop)));
3172 end if;
3174 -- The element is only modified in expanded code, so it appears as
3175 -- unassigned to the warning machinery. We must suppress this spurious
3176 -- warning explicitly.
3178 Set_Warnings_Off (Element);
3180 Rewrite (N, New_Loop);
3182 -- The loop parameter is declared by an object declaration, but within
3183 -- the loop we must prevent user assignments to it, so we analyze the
3184 -- declaration and reset the entity kind, before analyzing the rest of
3185 -- the loop;
3187 Analyze (Elmt_Decl);
3188 Set_Ekind (Defining_Identifier (Elmt_Decl), E_Loop_Parameter);
3190 Analyze (N);
3191 end Expand_Formal_Container_Element_Loop;
3193 -----------------------------
3194 -- Expand_N_Goto_Statement --
3195 -----------------------------
3197 -- Add poll before goto if polling active
3199 procedure Expand_N_Goto_Statement (N : Node_Id) is
3200 begin
3201 Generate_Poll_Call (N);
3202 end Expand_N_Goto_Statement;
3204 ---------------------------
3205 -- Expand_N_If_Statement --
3206 ---------------------------
3208 -- First we deal with the case of C and Fortran convention boolean values,
3209 -- with zero/non-zero semantics.
3211 -- Second, we deal with the obvious rewriting for the cases where the
3212 -- condition of the IF is known at compile time to be True or False.
3214 -- Third, we remove elsif parts which have non-empty Condition_Actions and
3215 -- rewrite as independent if statements. For example:
3217 -- if x then xs
3218 -- elsif y then ys
3219 -- ...
3220 -- end if;
3222 -- becomes
3224 -- if x then xs
3225 -- else
3226 -- <<condition actions of y>>
3227 -- if y then ys
3228 -- ...
3229 -- end if;
3230 -- end if;
3232 -- This rewriting is needed if at least one elsif part has a non-empty
3233 -- Condition_Actions list. We also do the same processing if there is a
3234 -- constant condition in an elsif part (in conjunction with the first
3235 -- processing step mentioned above, for the recursive call made to deal
3236 -- with the created inner if, this deals with properly optimizing the
3237 -- cases of constant elsif conditions).
3239 procedure Expand_N_If_Statement (N : Node_Id) is
3240 Loc : constant Source_Ptr := Sloc (N);
3241 Hed : Node_Id;
3242 E : Node_Id;
3243 New_If : Node_Id;
3245 Warn_If_Deleted : constant Boolean :=
3246 Warn_On_Deleted_Code and then Comes_From_Source (N);
3247 -- Indicates whether we want warnings when we delete branches of the
3248 -- if statement based on constant condition analysis. We never want
3249 -- these warnings for expander generated code.
3251 begin
3252 -- Do not consider controlled objects found in an if statement which
3253 -- actually models an if expression because their early finalization
3254 -- will affect the result of the expression.
3256 if not From_Conditional_Expression (N) then
3257 Process_Statements_For_Controlled_Objects (N);
3258 end if;
3260 Adjust_Condition (Condition (N));
3262 -- The following loop deals with constant conditions for the IF. We
3263 -- need a loop because as we eliminate False conditions, we grab the
3264 -- first elsif condition and use it as the primary condition.
3266 while Compile_Time_Known_Value (Condition (N)) loop
3268 -- If condition is True, we can simply rewrite the if statement now
3269 -- by replacing it by the series of then statements.
3271 if Is_True (Expr_Value (Condition (N))) then
3273 -- All the else parts can be killed
3275 Kill_Dead_Code (Elsif_Parts (N), Warn_If_Deleted);
3276 Kill_Dead_Code (Else_Statements (N), Warn_If_Deleted);
3278 Hed := Remove_Head (Then_Statements (N));
3279 Insert_List_After (N, Then_Statements (N));
3280 Rewrite (N, Hed);
3281 return;
3283 -- If condition is False, then we can delete the condition and
3284 -- the Then statements
3286 else
3287 -- We do not delete the condition if constant condition warnings
3288 -- are enabled, since otherwise we end up deleting the desired
3289 -- warning. Of course the backend will get rid of this True/False
3290 -- test anyway, so nothing is lost here.
3292 if not Constant_Condition_Warnings then
3293 Kill_Dead_Code (Condition (N));
3294 end if;
3296 Kill_Dead_Code (Then_Statements (N), Warn_If_Deleted);
3298 -- If there are no elsif statements, then we simply replace the
3299 -- entire if statement by the sequence of else statements.
3301 if No (Elsif_Parts (N)) then
3302 if No (Else_Statements (N))
3303 or else Is_Empty_List (Else_Statements (N))
3304 then
3305 Rewrite (N,
3306 Make_Null_Statement (Sloc (N)));
3307 else
3308 Hed := Remove_Head (Else_Statements (N));
3309 Insert_List_After (N, Else_Statements (N));
3310 Rewrite (N, Hed);
3311 end if;
3313 return;
3315 -- If there are elsif statements, the first of them becomes the
3316 -- if/then section of the rebuilt if statement This is the case
3317 -- where we loop to reprocess this copied condition.
3319 else
3320 Hed := Remove_Head (Elsif_Parts (N));
3321 Insert_Actions (N, Condition_Actions (Hed));
3322 Set_Condition (N, Condition (Hed));
3323 Set_Then_Statements (N, Then_Statements (Hed));
3325 -- Hed might have been captured as the condition determining
3326 -- the current value for an entity. Now it is detached from
3327 -- the tree, so a Current_Value pointer in the condition might
3328 -- need to be updated.
3330 Set_Current_Value_Condition (N);
3332 if Is_Empty_List (Elsif_Parts (N)) then
3333 Set_Elsif_Parts (N, No_List);
3334 end if;
3335 end if;
3336 end if;
3337 end loop;
3339 -- Loop through elsif parts, dealing with constant conditions and
3340 -- possible condition actions that are present.
3342 if Present (Elsif_Parts (N)) then
3343 E := First (Elsif_Parts (N));
3344 while Present (E) loop
3346 -- Do not consider controlled objects found in an if statement
3347 -- which actually models an if expression because their early
3348 -- finalization will affect the result of the expression.
3350 if not From_Conditional_Expression (N) then
3351 Process_Statements_For_Controlled_Objects (E);
3352 end if;
3354 Adjust_Condition (Condition (E));
3356 -- If there are condition actions, then rewrite the if statement
3357 -- as indicated above. We also do the same rewrite for a True or
3358 -- False condition. The further processing of this constant
3359 -- condition is then done by the recursive call to expand the
3360 -- newly created if statement
3362 if Present (Condition_Actions (E))
3363 or else Compile_Time_Known_Value (Condition (E))
3364 then
3365 New_If :=
3366 Make_If_Statement (Sloc (E),
3367 Condition => Condition (E),
3368 Then_Statements => Then_Statements (E),
3369 Elsif_Parts => No_List,
3370 Else_Statements => Else_Statements (N));
3372 -- Elsif parts for new if come from remaining elsif's of parent
3374 while Present (Next (E)) loop
3375 if No (Elsif_Parts (New_If)) then
3376 Set_Elsif_Parts (New_If, New_List);
3377 end if;
3379 Append (Remove_Next (E), Elsif_Parts (New_If));
3380 end loop;
3382 Set_Else_Statements (N, New_List (New_If));
3384 if Present (Condition_Actions (E)) then
3385 Insert_List_Before (New_If, Condition_Actions (E));
3386 end if;
3388 Remove (E);
3390 if Is_Empty_List (Elsif_Parts (N)) then
3391 Set_Elsif_Parts (N, No_List);
3392 end if;
3394 Analyze (New_If);
3396 -- Note this is not an implicit if statement, since it is part
3397 -- of an explicit if statement in the source (or of an implicit
3398 -- if statement that has already been tested). We set the flag
3399 -- after calling Analyze to avoid generating extra warnings
3400 -- specific to pure if statements, however (see
3401 -- Sem_Ch5.Analyze_If_Statement).
3403 Set_Comes_From_Source (New_If, Comes_From_Source (N));
3404 return;
3406 -- No special processing for that elsif part, move to next
3408 else
3409 Next (E);
3410 end if;
3411 end loop;
3412 end if;
3414 -- Some more optimizations applicable if we still have an IF statement
3416 if Nkind (N) /= N_If_Statement then
3417 return;
3418 end if;
3420 -- Another optimization, special cases that can be simplified
3422 -- if expression then
3423 -- return true;
3424 -- else
3425 -- return false;
3426 -- end if;
3428 -- can be changed to:
3430 -- return expression;
3432 -- and
3434 -- if expression then
3435 -- return false;
3436 -- else
3437 -- return true;
3438 -- end if;
3440 -- can be changed to:
3442 -- return not (expression);
3444 -- Only do these optimizations if we are at least at -O1 level and
3445 -- do not do them if control flow optimizations are suppressed.
3447 if Optimization_Level > 0
3448 and then not Opt.Suppress_Control_Flow_Optimizations
3449 then
3450 if Nkind (N) = N_If_Statement
3451 and then No (Elsif_Parts (N))
3452 and then Present (Else_Statements (N))
3453 and then List_Length (Then_Statements (N)) = 1
3454 and then List_Length (Else_Statements (N)) = 1
3455 then
3456 declare
3457 Then_Stm : constant Node_Id := First (Then_Statements (N));
3458 Else_Stm : constant Node_Id := First (Else_Statements (N));
3460 begin
3461 if Nkind (Then_Stm) = N_Simple_Return_Statement
3462 and then
3463 Nkind (Else_Stm) = N_Simple_Return_Statement
3464 then
3465 declare
3466 Then_Expr : constant Node_Id := Expression (Then_Stm);
3467 Else_Expr : constant Node_Id := Expression (Else_Stm);
3469 begin
3470 if Nkind (Then_Expr) = N_Identifier
3471 and then
3472 Nkind (Else_Expr) = N_Identifier
3473 then
3474 if Entity (Then_Expr) = Standard_True
3475 and then Entity (Else_Expr) = Standard_False
3476 then
3477 Rewrite (N,
3478 Make_Simple_Return_Statement (Loc,
3479 Expression => Relocate_Node (Condition (N))));
3480 Analyze (N);
3481 return;
3483 elsif Entity (Then_Expr) = Standard_False
3484 and then Entity (Else_Expr) = Standard_True
3485 then
3486 Rewrite (N,
3487 Make_Simple_Return_Statement (Loc,
3488 Expression =>
3489 Make_Op_Not (Loc,
3490 Right_Opnd =>
3491 Relocate_Node (Condition (N)))));
3492 Analyze (N);
3493 return;
3494 end if;
3495 end if;
3496 end;
3497 end if;
3498 end;
3499 end if;
3500 end if;
3501 end Expand_N_If_Statement;
3503 --------------------------
3504 -- Expand_Iterator_Loop --
3505 --------------------------
3507 procedure Expand_Iterator_Loop (N : Node_Id) is
3508 Isc : constant Node_Id := Iteration_Scheme (N);
3509 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3511 Container : constant Node_Id := Name (I_Spec);
3512 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
3514 begin
3515 -- Processing for arrays
3517 if Is_Array_Type (Container_Typ) then
3518 pragma Assert (Of_Present (I_Spec));
3519 Expand_Iterator_Loop_Over_Array (N);
3521 elsif Has_Aspect (Container_Typ, Aspect_Iterable) then
3522 if Of_Present (I_Spec) then
3523 Expand_Formal_Container_Element_Loop (N);
3524 else
3525 Expand_Formal_Container_Loop (N);
3526 end if;
3528 -- Processing for containers
3530 else
3531 Expand_Iterator_Loop_Over_Container
3532 (N, Isc, I_Spec, Container, Container_Typ);
3533 end if;
3534 end Expand_Iterator_Loop;
3536 -------------------------------------
3537 -- Expand_Iterator_Loop_Over_Array --
3538 -------------------------------------
3540 procedure Expand_Iterator_Loop_Over_Array (N : Node_Id) is
3541 Isc : constant Node_Id := Iteration_Scheme (N);
3542 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3543 Array_Node : constant Node_Id := Name (I_Spec);
3544 Array_Typ : constant Entity_Id := Base_Type (Etype (Array_Node));
3545 Array_Dim : constant Pos := Number_Dimensions (Array_Typ);
3546 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3547 Loc : constant Source_Ptr := Sloc (N);
3548 Stats : constant List_Id := Statements (N);
3549 Core_Loop : Node_Id;
3550 Dim1 : Int;
3551 Ind_Comp : Node_Id;
3552 Iterator : Entity_Id;
3554 -- Start of processing for Expand_Iterator_Loop_Over_Array
3556 begin
3557 -- for Element of Array loop
3559 -- It requires an internally generated cursor to iterate over the array
3561 pragma Assert (Of_Present (I_Spec));
3563 Iterator := Make_Temporary (Loc, 'C');
3565 -- Generate:
3566 -- Element : Component_Type renames Array (Iterator);
3567 -- Iterator is the index value, or a list of index values
3568 -- in the case of a multidimensional array.
3570 Ind_Comp :=
3571 Make_Indexed_Component (Loc,
3572 Prefix => Relocate_Node (Array_Node),
3573 Expressions => New_List (New_Occurrence_Of (Iterator, Loc)));
3575 Prepend_To (Stats,
3576 Make_Object_Renaming_Declaration (Loc,
3577 Defining_Identifier => Id,
3578 Subtype_Mark =>
3579 New_Occurrence_Of (Component_Type (Array_Typ), Loc),
3580 Name => Ind_Comp));
3582 -- Mark the loop variable as needing debug info, so that expansion
3583 -- of the renaming will result in Materialize_Entity getting set via
3584 -- Debug_Renaming_Declaration. (This setting is needed here because
3585 -- the setting in Freeze_Entity comes after the expansion, which is
3586 -- too late. ???)
3588 Set_Debug_Info_Needed (Id);
3590 -- Generate:
3592 -- for Iterator in [reverse] Array'Range (Array_Dim) loop
3593 -- Element : Component_Type renames Array (Iterator);
3594 -- <original loop statements>
3595 -- end loop;
3597 -- If this is an iteration over a multidimensional array, the
3598 -- innermost loop is over the last dimension in Ada, and over
3599 -- the first dimension in Fortran.
3601 if Convention (Array_Typ) = Convention_Fortran then
3602 Dim1 := 1;
3603 else
3604 Dim1 := Array_Dim;
3605 end if;
3607 Core_Loop :=
3608 Make_Loop_Statement (Loc,
3609 Iteration_Scheme =>
3610 Make_Iteration_Scheme (Loc,
3611 Loop_Parameter_Specification =>
3612 Make_Loop_Parameter_Specification (Loc,
3613 Defining_Identifier => Iterator,
3614 Discrete_Subtype_Definition =>
3615 Make_Attribute_Reference (Loc,
3616 Prefix => Relocate_Node (Array_Node),
3617 Attribute_Name => Name_Range,
3618 Expressions => New_List (
3619 Make_Integer_Literal (Loc, Dim1))),
3620 Reverse_Present => Reverse_Present (I_Spec))),
3621 Statements => Stats,
3622 End_Label => Empty);
3624 -- Processing for multidimensional array. The body of each loop is
3625 -- a loop over a previous dimension, going in decreasing order in Ada
3626 -- and in increasing order in Fortran.
3628 if Array_Dim > 1 then
3629 for Dim in 1 .. Array_Dim - 1 loop
3630 if Convention (Array_Typ) = Convention_Fortran then
3631 Dim1 := Dim + 1;
3632 else
3633 Dim1 := Array_Dim - Dim;
3634 end if;
3636 Iterator := Make_Temporary (Loc, 'C');
3638 -- Generate the dimension loops starting from the innermost one
3640 -- for Iterator in [reverse] Array'Range (Array_Dim - Dim) loop
3641 -- <core loop>
3642 -- end loop;
3644 Core_Loop :=
3645 Make_Loop_Statement (Loc,
3646 Iteration_Scheme =>
3647 Make_Iteration_Scheme (Loc,
3648 Loop_Parameter_Specification =>
3649 Make_Loop_Parameter_Specification (Loc,
3650 Defining_Identifier => Iterator,
3651 Discrete_Subtype_Definition =>
3652 Make_Attribute_Reference (Loc,
3653 Prefix => Relocate_Node (Array_Node),
3654 Attribute_Name => Name_Range,
3655 Expressions => New_List (
3656 Make_Integer_Literal (Loc, Dim1))),
3657 Reverse_Present => Reverse_Present (I_Spec))),
3658 Statements => New_List (Core_Loop),
3659 End_Label => Empty);
3661 -- Update the previously created object renaming declaration with
3662 -- the new iterator, by adding the index of the next loop to the
3663 -- indexed component, in the order that corresponds to the
3664 -- convention.
3666 if Convention (Array_Typ) = Convention_Fortran then
3667 Append_To (Expressions (Ind_Comp),
3668 New_Occurrence_Of (Iterator, Loc));
3669 else
3670 Prepend_To (Expressions (Ind_Comp),
3671 New_Occurrence_Of (Iterator, Loc));
3672 end if;
3673 end loop;
3674 end if;
3676 -- Inherit the loop identifier from the original loop. This ensures that
3677 -- the scope stack is consistent after the rewriting.
3679 if Present (Identifier (N)) then
3680 Set_Identifier (Core_Loop, Relocate_Node (Identifier (N)));
3681 end if;
3683 Rewrite (N, Core_Loop);
3684 Analyze (N);
3685 end Expand_Iterator_Loop_Over_Array;
3687 -----------------------------------------
3688 -- Expand_Iterator_Loop_Over_Container --
3689 -----------------------------------------
3691 -- For a 'for ... in' loop, such as:
3693 -- for Cursor in Iterator_Function (...) loop
3694 -- ...
3695 -- end loop;
3697 -- we generate:
3699 -- Iter : Iterator_Type := Iterator_Function (...);
3700 -- Cursor : Cursor_type := First (Iter); -- or Last for "reverse"
3701 -- while Has_Element (Cursor) loop
3702 -- ...
3704 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
3705 -- end loop;
3707 -- For a 'for ... of' loop, such as:
3709 -- for X of Container loop
3710 -- ...
3711 -- end loop;
3713 -- the RM implies the generation of:
3715 -- Iter : Iterator_Type := Container.Iterate; -- the Default_Iterator
3716 -- Cursor : Cursor_Type := First (Iter); -- or Last for "reverse"
3717 -- while Has_Element (Cursor) loop
3718 -- declare
3719 -- X : Element_Type renames Element (Cursor).Element.all;
3720 -- -- or Constant_Element
3721 -- begin
3722 -- ...
3723 -- end;
3724 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
3725 -- end loop;
3727 -- In the general case, we do what the RM says. However, the operations
3728 -- Element and Iter.Next are slow, which is bad inside a loop, because they
3729 -- involve dispatching via interfaces, secondary stack manipulation,
3730 -- Busy/Lock incr/decr, and adjust/finalization/at-end handling. So for the
3731 -- predefined containers, we use an equivalent but optimized expansion.
3733 -- In the optimized case, we make use of these:
3735 -- procedure Next (Position : in out Cursor); -- instead of Iter.Next
3737 -- function Pseudo_Reference
3738 -- (Container : aliased Vector'Class) return Reference_Control_Type;
3740 -- type Element_Access is access all Element_Type;
3742 -- function Get_Element_Access
3743 -- (Position : Cursor) return not null Element_Access;
3745 -- Next is declared in the visible part of the container packages.
3746 -- The other three are added in the private part. (We're not supposed to
3747 -- pollute the namespace for clients. The compiler has no trouble breaking
3748 -- privacy to call things in the private part of an instance.)
3750 -- Source:
3752 -- for X of My_Vector loop
3753 -- X.Count := X.Count + 1;
3754 -- ...
3755 -- end loop;
3757 -- The compiler will generate:
3759 -- Iter : Reversible_Iterator'Class := Iterate (My_Vector);
3760 -- -- Reversible_Iterator is an interface. Iterate is the
3761 -- -- Default_Iterator aspect of Vector. This increments Lock,
3762 -- -- disallowing tampering with cursors. Unfortunately, it does not
3763 -- -- increment Busy. The result of Iterate is Limited_Controlled;
3764 -- -- finalization will decrement Lock. This is a build-in-place
3765 -- -- dispatching call to Iterate.
3767 -- Cur : Cursor := First (Iter); -- or Last
3768 -- -- Dispatching call via interface.
3770 -- Control : Reference_Control_Type := Pseudo_Reference (My_Vector);
3771 -- -- Pseudo_Reference increments Busy, to detect tampering with
3772 -- -- elements, as required by RM. Also redundantly increment
3773 -- -- Lock. Finalization of Control will decrement both Busy and
3774 -- -- Lock. Pseudo_Reference returns a record containing a pointer to
3775 -- -- My_Vector, used by Finalize.
3776 -- --
3777 -- -- Control is not used below, except to finalize it -- it's purely
3778 -- -- an RAII thing. This is needed because we are eliminating the
3779 -- -- call to Reference within the loop.
3781 -- while Has_Element (Cur) loop
3782 -- declare
3783 -- X : My_Element renames Get_Element_Access (Cur).all;
3784 -- -- Get_Element_Access returns a pointer to the element
3785 -- -- designated by Cur. No dispatching here, and no horsing
3786 -- -- around with access discriminants. This is instead of the
3787 -- -- existing
3788 -- --
3789 -- -- X : My_Element renames Reference (Cur).Element.all;
3790 -- --
3791 -- -- which creates a controlled object.
3792 -- begin
3793 -- -- Any attempt to tamper with My_Vector here in the loop
3794 -- -- will correctly raise Program_Error, because of the
3795 -- -- Control.
3797 -- X.Count := X.Count + 1;
3798 -- ...
3800 -- Next (Cur); -- or Prev
3801 -- -- This is instead of "Cur := Next (Iter, Cur);"
3802 -- end;
3803 -- -- No finalization here
3804 -- end loop;
3805 -- Finalize Iter and Control here, decrementing Lock twice and Busy
3806 -- once.
3808 -- This optimization makes "for ... of" loops over 30 times faster in cases
3809 -- measured.
3811 procedure Expand_Iterator_Loop_Over_Container
3812 (N : Node_Id;
3813 Isc : Node_Id;
3814 I_Spec : Node_Id;
3815 Container : Node_Id;
3816 Container_Typ : Entity_Id)
3818 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3819 Elem_Typ : constant Entity_Id := Etype (Id);
3820 Id_Kind : constant Entity_Kind := Ekind (Id);
3821 Loc : constant Source_Ptr := Sloc (N);
3822 Stats : constant List_Id := Statements (N);
3824 Cursor : Entity_Id;
3825 Decl : Node_Id;
3826 Iter_Type : Entity_Id;
3827 Iterator : Entity_Id;
3828 Name_Init : Name_Id;
3829 Name_Step : Name_Id;
3830 New_Loop : Node_Id;
3832 Fast_Element_Access_Op : Entity_Id := Empty;
3833 Fast_Step_Op : Entity_Id := Empty;
3834 -- Only for optimized version of "for ... of"
3836 Iter_Pack : Entity_Id;
3837 -- The package in which the iterator interface is instantiated. This is
3838 -- typically an instance within the container package.
3840 Pack : Entity_Id;
3841 -- The package in which the container type is declared
3843 begin
3844 -- Determine the advancement and initialization steps for the cursor.
3845 -- Analysis of the expanded loop will verify that the container has a
3846 -- reverse iterator.
3848 if Reverse_Present (I_Spec) then
3849 Name_Init := Name_Last;
3850 Name_Step := Name_Previous;
3851 else
3852 Name_Init := Name_First;
3853 Name_Step := Name_Next;
3854 end if;
3856 -- The type of the iterator is the return type of the Iterate function
3857 -- used. For the "of" form this is the default iterator for the type,
3858 -- otherwise it is the type of the explicit function used in the
3859 -- iterator specification. The most common case will be an Iterate
3860 -- function in the container package.
3862 -- The Iterator type is declared in an instance within the container
3863 -- package itself, for example:
3865 -- package Vector_Iterator_Interfaces is new
3866 -- Ada.Iterator_Interfaces (Cursor, Has_Element);
3868 -- If the container type is a derived type, the cursor type is found in
3869 -- the package of the ultimate ancestor type.
3871 if Is_Derived_Type (Container_Typ) then
3872 Pack := Scope (Root_Type (Container_Typ));
3873 else
3874 Pack := Scope (Container_Typ);
3875 end if;
3877 if Of_Present (I_Spec) then
3878 Handle_Of : declare
3879 Container_Arg : Node_Id;
3881 function Get_Default_Iterator
3882 (T : Entity_Id) return Entity_Id;
3883 -- If the container is a derived type, the aspect holds the parent
3884 -- operation. The required one is a primitive of the derived type
3885 -- and is either inherited or overridden. Also sets Container_Arg.
3887 --------------------------
3888 -- Get_Default_Iterator --
3889 --------------------------
3891 function Get_Default_Iterator
3892 (T : Entity_Id) return Entity_Id
3894 Iter : constant Entity_Id :=
3895 Entity (Find_Value_Of_Aspect (T, Aspect_Default_Iterator));
3896 Prim : Elmt_Id;
3897 Op : Entity_Id;
3899 begin
3900 Container_Arg := New_Copy_Tree (Container);
3902 -- A previous version of GNAT allowed indexing aspects to
3903 -- be redefined on derived container types, while the
3904 -- default iterator was inherited from the parent type.
3905 -- This non-standard extension is preserved temporarily for
3906 -- use by the modelling project under debug flag d.X.
3908 if Debug_Flag_Dot_XX then
3909 if Base_Type (Etype (Container)) /=
3910 Base_Type (Etype (First_Formal (Iter)))
3911 then
3912 Container_Arg :=
3913 Make_Type_Conversion (Loc,
3914 Subtype_Mark =>
3915 New_Occurrence_Of
3916 (Etype (First_Formal (Iter)), Loc),
3917 Expression => Container_Arg);
3918 end if;
3920 return Iter;
3922 elsif Is_Derived_Type (T) then
3924 -- The default iterator must be a primitive operation of the
3925 -- type, at the same dispatch slot position. The DT position
3926 -- may not be established if type is not frozen yet.
3928 Prim := First_Elmt (Primitive_Operations (T));
3929 while Present (Prim) loop
3930 Op := Node (Prim);
3932 if Alias (Op) = Iter
3933 or else
3934 (Chars (Op) = Chars (Iter)
3935 and then Present (DTC_Entity (Op))
3936 and then DT_Position (Op) = DT_Position (Iter))
3937 then
3938 return Op;
3939 end if;
3941 Next_Elmt (Prim);
3942 end loop;
3944 -- Default iterator must exist
3946 pragma Assert (False);
3948 -- Otherwise not a derived type
3950 else
3951 return Iter;
3952 end if;
3953 end Get_Default_Iterator;
3955 -- Local variables
3957 Default_Iter : Entity_Id;
3958 Ent : Entity_Id;
3960 Reference_Control_Type : Entity_Id := Empty;
3961 Pseudo_Reference : Entity_Id := Empty;
3963 -- Start of processing for Handle_Of
3965 begin
3966 if Is_Class_Wide_Type (Container_Typ) then
3967 Default_Iter :=
3968 Get_Default_Iterator (Etype (Base_Type (Container_Typ)));
3969 else
3970 Default_Iter := Get_Default_Iterator (Etype (Container));
3971 end if;
3973 Cursor := Make_Temporary (Loc, 'C');
3975 -- For a container element iterator, the iterator type is obtained
3976 -- from the corresponding aspect, whose return type is descended
3977 -- from the corresponding interface type in some instance of
3978 -- Ada.Iterator_Interfaces. The actuals of that instantiation
3979 -- are Cursor and Has_Element.
3981 Iter_Type := Etype (Default_Iter);
3983 -- The iterator type, which is a class-wide type, may itself be
3984 -- derived locally, so the desired instantiation is the scope of
3985 -- the root type of the iterator type.
3987 Iter_Pack := Scope (Root_Type (Etype (Iter_Type)));
3989 -- Find declarations needed for "for ... of" optimization
3991 Ent := First_Entity (Pack);
3992 while Present (Ent) loop
3993 if Chars (Ent) = Name_Get_Element_Access then
3994 Fast_Element_Access_Op := Ent;
3996 elsif Chars (Ent) = Name_Step
3997 and then Ekind (Ent) = E_Procedure
3998 then
3999 Fast_Step_Op := Ent;
4001 elsif Chars (Ent) = Name_Reference_Control_Type then
4002 Reference_Control_Type := Ent;
4004 elsif Chars (Ent) = Name_Pseudo_Reference then
4005 Pseudo_Reference := Ent;
4006 end if;
4008 Next_Entity (Ent);
4009 end loop;
4011 if Present (Reference_Control_Type)
4012 and then Present (Pseudo_Reference)
4013 then
4014 Insert_Action (N,
4015 Make_Object_Declaration (Loc,
4016 Defining_Identifier => Make_Temporary (Loc, 'D'),
4017 Object_Definition =>
4018 New_Occurrence_Of (Reference_Control_Type, Loc),
4019 Expression =>
4020 Make_Function_Call (Loc,
4021 Name =>
4022 New_Occurrence_Of (Pseudo_Reference, Loc),
4023 Parameter_Associations =>
4024 New_List (New_Copy_Tree (Container_Arg)))));
4025 end if;
4027 -- Rewrite domain of iteration as a call to the default iterator
4028 -- for the container type. The formal may be an access parameter
4029 -- in which case we must build a reference to the container.
4031 declare
4032 Arg : Node_Id;
4033 begin
4034 if Is_Access_Type (Etype (First_Entity (Default_Iter))) then
4035 Arg :=
4036 Make_Attribute_Reference (Loc,
4037 Prefix => Container_Arg,
4038 Attribute_Name => Name_Unrestricted_Access);
4039 else
4040 Arg := Container_Arg;
4041 end if;
4043 Rewrite (Name (I_Spec),
4044 Make_Function_Call (Loc,
4045 Name =>
4046 New_Occurrence_Of (Default_Iter, Loc),
4047 Parameter_Associations => New_List (Arg)));
4048 end;
4050 Analyze_And_Resolve (Name (I_Spec));
4052 -- Find cursor type in proper iterator package, which is an
4053 -- instantiation of Iterator_Interfaces.
4055 Ent := First_Entity (Iter_Pack);
4056 while Present (Ent) loop
4057 if Chars (Ent) = Name_Cursor then
4058 Set_Etype (Cursor, Etype (Ent));
4059 exit;
4060 end if;
4062 Next_Entity (Ent);
4063 end loop;
4065 if Present (Fast_Element_Access_Op) then
4066 Decl :=
4067 Make_Object_Renaming_Declaration (Loc,
4068 Defining_Identifier => Id,
4069 Subtype_Mark =>
4070 New_Occurrence_Of (Elem_Typ, Loc),
4071 Name =>
4072 Make_Explicit_Dereference (Loc,
4073 Prefix =>
4074 Make_Function_Call (Loc,
4075 Name =>
4076 New_Occurrence_Of (Fast_Element_Access_Op, Loc),
4077 Parameter_Associations =>
4078 New_List (New_Occurrence_Of (Cursor, Loc)))));
4080 else
4081 Decl :=
4082 Make_Object_Renaming_Declaration (Loc,
4083 Defining_Identifier => Id,
4084 Subtype_Mark =>
4085 New_Occurrence_Of (Elem_Typ, Loc),
4086 Name =>
4087 Make_Indexed_Component (Loc,
4088 Prefix => Relocate_Node (Container_Arg),
4089 Expressions =>
4090 New_List (New_Occurrence_Of (Cursor, Loc))));
4091 end if;
4093 -- The defining identifier in the iterator is user-visible and
4094 -- must be visible in the debugger.
4096 Set_Debug_Info_Needed (Id);
4098 -- If the container does not have a variable indexing aspect,
4099 -- the element is a constant in the loop. The container itself
4100 -- may be constant, in which case the element is a constant as
4101 -- well. The container has been rewritten as a call to Iterate,
4102 -- so examine original node.
4104 if No (Find_Value_Of_Aspect
4105 (Container_Typ, Aspect_Variable_Indexing))
4106 or else not Is_Variable (Original_Node (Container))
4107 then
4108 Set_Ekind (Id, E_Constant);
4109 end if;
4111 Prepend_To (Stats, Decl);
4112 end Handle_Of;
4114 -- X in Iterate (S) : type of iterator is type of explicitly given
4115 -- Iterate function, and the loop variable is the cursor. It will be
4116 -- assigned in the loop and must be a variable.
4118 else
4119 Iter_Type := Etype (Name (I_Spec));
4121 -- The iterator type, which is a class-wide type, may itself be
4122 -- derived locally, so the desired instantiation is the scope of
4123 -- the root type of the iterator type, as in the "of" case.
4125 Iter_Pack := Scope (Root_Type (Etype (Iter_Type)));
4126 Cursor := Id;
4127 end if;
4129 Iterator := Make_Temporary (Loc, 'I');
4131 -- For both iterator forms, add a call to the step operation to advance
4132 -- the cursor. Generate:
4134 -- Cursor := Iterator.Next (Cursor);
4136 -- or else
4138 -- Cursor := Next (Cursor);
4140 if Present (Fast_Element_Access_Op) and then Present (Fast_Step_Op) then
4141 declare
4142 Curs_Name : constant Node_Id := New_Occurrence_Of (Cursor, Loc);
4143 Step_Call : Node_Id;
4145 begin
4146 Step_Call :=
4147 Make_Procedure_Call_Statement (Loc,
4148 Name =>
4149 New_Occurrence_Of (Fast_Step_Op, Loc),
4150 Parameter_Associations => New_List (Curs_Name));
4152 Append_To (Stats, Step_Call);
4153 Set_Assignment_OK (Curs_Name);
4154 end;
4156 else
4157 declare
4158 Rhs : Node_Id;
4160 begin
4161 Rhs :=
4162 Make_Function_Call (Loc,
4163 Name =>
4164 Make_Selected_Component (Loc,
4165 Prefix => New_Occurrence_Of (Iterator, Loc),
4166 Selector_Name => Make_Identifier (Loc, Name_Step)),
4167 Parameter_Associations => New_List (
4168 New_Occurrence_Of (Cursor, Loc)));
4170 Append_To (Stats,
4171 Make_Assignment_Statement (Loc,
4172 Name => New_Occurrence_Of (Cursor, Loc),
4173 Expression => Rhs));
4174 Set_Assignment_OK (Name (Last (Stats)));
4175 end;
4176 end if;
4178 -- Generate:
4179 -- while Has_Element (Cursor) loop
4180 -- <Stats>
4181 -- end loop;
4183 -- Has_Element is the second actual in the iterator package
4185 New_Loop :=
4186 Make_Loop_Statement (Loc,
4187 Iteration_Scheme =>
4188 Make_Iteration_Scheme (Loc,
4189 Condition =>
4190 Make_Function_Call (Loc,
4191 Name =>
4192 New_Occurrence_Of
4193 (Next_Entity (First_Entity (Iter_Pack)), Loc),
4194 Parameter_Associations => New_List (
4195 New_Occurrence_Of (Cursor, Loc)))),
4197 Statements => Stats,
4198 End_Label => Empty);
4200 -- If present, preserve identifier of loop, which can be used in an exit
4201 -- statement in the body.
4203 if Present (Identifier (N)) then
4204 Set_Identifier (New_Loop, Relocate_Node (Identifier (N)));
4205 end if;
4207 -- Create the declarations for Iterator and cursor and insert them
4208 -- before the source loop. Given that the domain of iteration is already
4209 -- an entity, the iterator is just a renaming of that entity. Possible
4210 -- optimization ???
4212 Insert_Action (N,
4213 Make_Object_Renaming_Declaration (Loc,
4214 Defining_Identifier => Iterator,
4215 Subtype_Mark => New_Occurrence_Of (Iter_Type, Loc),
4216 Name => Relocate_Node (Name (I_Spec))));
4218 -- Create declaration for cursor
4220 declare
4221 Cursor_Decl : constant Node_Id :=
4222 Make_Object_Declaration (Loc,
4223 Defining_Identifier => Cursor,
4224 Object_Definition =>
4225 New_Occurrence_Of (Etype (Cursor), Loc),
4226 Expression =>
4227 Make_Selected_Component (Loc,
4228 Prefix =>
4229 New_Occurrence_Of (Iterator, Loc),
4230 Selector_Name =>
4231 Make_Identifier (Loc, Name_Init)));
4233 begin
4234 -- The cursor is only modified in expanded code, so it appears
4235 -- as unassigned to the warning machinery. We must suppress this
4236 -- spurious warning explicitly. The cursor's kind is that of the
4237 -- original loop parameter (it is a constant if the domain of
4238 -- iteration is constant).
4240 Set_Warnings_Off (Cursor);
4241 Set_Assignment_OK (Cursor_Decl);
4243 Insert_Action (N, Cursor_Decl);
4244 Set_Ekind (Cursor, Id_Kind);
4245 end;
4247 -- If the range of iteration is given by a function call that returns
4248 -- a container, the finalization actions have been saved in the
4249 -- Condition_Actions of the iterator. Insert them now at the head of
4250 -- the loop.
4252 if Present (Condition_Actions (Isc)) then
4253 Insert_List_Before (N, Condition_Actions (Isc));
4254 end if;
4256 Rewrite (N, New_Loop);
4257 Analyze (N);
4258 end Expand_Iterator_Loop_Over_Container;
4260 -----------------------------
4261 -- Expand_N_Loop_Statement --
4262 -----------------------------
4264 -- 1. Remove null loop entirely
4265 -- 2. Deal with while condition for C/Fortran boolean
4266 -- 3. Deal with loops with a non-standard enumeration type range
4267 -- 4. Deal with while loops where Condition_Actions is set
4268 -- 5. Deal with loops over predicated subtypes
4269 -- 6. Deal with loops with iterators over arrays and containers
4270 -- 7. Insert polling call if required
4272 procedure Expand_N_Loop_Statement (N : Node_Id) is
4273 Loc : constant Source_Ptr := Sloc (N);
4274 Scheme : constant Node_Id := Iteration_Scheme (N);
4275 Stmt : Node_Id;
4277 begin
4278 -- Delete null loop
4280 if Is_Null_Loop (N) then
4281 Rewrite (N, Make_Null_Statement (Loc));
4282 return;
4283 end if;
4285 -- Deal with condition for C/Fortran Boolean
4287 if Present (Scheme) then
4288 Adjust_Condition (Condition (Scheme));
4289 end if;
4291 -- Generate polling call
4293 if Is_Non_Empty_List (Statements (N)) then
4294 Generate_Poll_Call (First (Statements (N)));
4295 end if;
4297 -- Nothing more to do for plain loop with no iteration scheme
4299 if No (Scheme) then
4300 null;
4302 -- Case of for loop (Loop_Parameter_Specification present)
4304 -- Note: we do not have to worry about validity checking of the for loop
4305 -- range bounds here, since they were frozen with constant declarations
4306 -- and it is during that process that the validity checking is done.
4308 elsif Present (Loop_Parameter_Specification (Scheme)) then
4309 declare
4310 LPS : constant Node_Id :=
4311 Loop_Parameter_Specification (Scheme);
4312 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4313 Ltype : constant Entity_Id := Etype (Loop_Id);
4314 Btype : constant Entity_Id := Base_Type (Ltype);
4315 Expr : Node_Id;
4316 Decls : List_Id;
4317 New_Id : Entity_Id;
4319 begin
4320 -- Deal with loop over predicates
4322 if Is_Discrete_Type (Ltype)
4323 and then Present (Predicate_Function (Ltype))
4324 then
4325 Expand_Predicated_Loop (N);
4327 -- Handle the case where we have a for loop with the range type
4328 -- being an enumeration type with non-standard representation.
4329 -- In this case we expand:
4331 -- for x in [reverse] a .. b loop
4332 -- ...
4333 -- end loop;
4335 -- to
4337 -- for xP in [reverse] integer
4338 -- range etype'Pos (a) .. etype'Pos (b)
4339 -- loop
4340 -- declare
4341 -- x : constant etype := Pos_To_Rep (xP);
4342 -- begin
4343 -- ...
4344 -- end;
4345 -- end loop;
4347 elsif Is_Enumeration_Type (Btype)
4348 and then Present (Enum_Pos_To_Rep (Btype))
4349 then
4350 New_Id :=
4351 Make_Defining_Identifier (Loc,
4352 Chars => New_External_Name (Chars (Loop_Id), 'P'));
4354 -- If the type has a contiguous representation, successive
4355 -- values can be generated as offsets from the first literal.
4357 if Has_Contiguous_Rep (Btype) then
4358 Expr :=
4359 Unchecked_Convert_To (Btype,
4360 Make_Op_Add (Loc,
4361 Left_Opnd =>
4362 Make_Integer_Literal (Loc,
4363 Enumeration_Rep (First_Literal (Btype))),
4364 Right_Opnd => New_Occurrence_Of (New_Id, Loc)));
4365 else
4366 -- Use the constructed array Enum_Pos_To_Rep
4368 Expr :=
4369 Make_Indexed_Component (Loc,
4370 Prefix =>
4371 New_Occurrence_Of (Enum_Pos_To_Rep (Btype), Loc),
4372 Expressions =>
4373 New_List (New_Occurrence_Of (New_Id, Loc)));
4374 end if;
4376 -- Build declaration for loop identifier
4378 Decls :=
4379 New_List (
4380 Make_Object_Declaration (Loc,
4381 Defining_Identifier => Loop_Id,
4382 Constant_Present => True,
4383 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4384 Expression => Expr));
4386 Rewrite (N,
4387 Make_Loop_Statement (Loc,
4388 Identifier => Identifier (N),
4390 Iteration_Scheme =>
4391 Make_Iteration_Scheme (Loc,
4392 Loop_Parameter_Specification =>
4393 Make_Loop_Parameter_Specification (Loc,
4394 Defining_Identifier => New_Id,
4395 Reverse_Present => Reverse_Present (LPS),
4397 Discrete_Subtype_Definition =>
4398 Make_Subtype_Indication (Loc,
4400 Subtype_Mark =>
4401 New_Occurrence_Of (Standard_Natural, Loc),
4403 Constraint =>
4404 Make_Range_Constraint (Loc,
4405 Range_Expression =>
4406 Make_Range (Loc,
4408 Low_Bound =>
4409 Make_Attribute_Reference (Loc,
4410 Prefix =>
4411 New_Occurrence_Of (Btype, Loc),
4413 Attribute_Name => Name_Pos,
4415 Expressions => New_List (
4416 Relocate_Node
4417 (Type_Low_Bound (Ltype)))),
4419 High_Bound =>
4420 Make_Attribute_Reference (Loc,
4421 Prefix =>
4422 New_Occurrence_Of (Btype, Loc),
4424 Attribute_Name => Name_Pos,
4426 Expressions => New_List (
4427 Relocate_Node
4428 (Type_High_Bound
4429 (Ltype))))))))),
4431 Statements => New_List (
4432 Make_Block_Statement (Loc,
4433 Declarations => Decls,
4434 Handled_Statement_Sequence =>
4435 Make_Handled_Sequence_Of_Statements (Loc,
4436 Statements => Statements (N)))),
4438 End_Label => End_Label (N)));
4440 -- The loop parameter's entity must be removed from the loop
4441 -- scope's entity list and rendered invisible, since it will
4442 -- now be located in the new block scope. Any other entities
4443 -- already associated with the loop scope, such as the loop
4444 -- parameter's subtype, will remain there.
4446 -- In an element loop, the loop will contain a declaration for
4447 -- a cursor variable; otherwise the loop id is the first entity
4448 -- in the scope constructed for the loop.
4450 if Comes_From_Source (Loop_Id) then
4451 pragma Assert (First_Entity (Scope (Loop_Id)) = Loop_Id);
4452 null;
4453 end if;
4455 Set_First_Entity (Scope (Loop_Id), Next_Entity (Loop_Id));
4456 Remove_Homonym (Loop_Id);
4458 if Last_Entity (Scope (Loop_Id)) = Loop_Id then
4459 Set_Last_Entity (Scope (Loop_Id), Empty);
4460 end if;
4462 Analyze (N);
4464 -- Nothing to do with other cases of for loops
4466 else
4467 null;
4468 end if;
4469 end;
4471 -- Second case, if we have a while loop with Condition_Actions set, then
4472 -- we change it into a plain loop:
4474 -- while C loop
4475 -- ...
4476 -- end loop;
4478 -- changed to:
4480 -- loop
4481 -- <<condition actions>>
4482 -- exit when not C;
4483 -- ...
4484 -- end loop
4486 elsif Present (Scheme)
4487 and then Present (Condition_Actions (Scheme))
4488 and then Present (Condition (Scheme))
4489 then
4490 declare
4491 ES : Node_Id;
4493 begin
4494 ES :=
4495 Make_Exit_Statement (Sloc (Condition (Scheme)),
4496 Condition =>
4497 Make_Op_Not (Sloc (Condition (Scheme)),
4498 Right_Opnd => Condition (Scheme)));
4500 Prepend (ES, Statements (N));
4501 Insert_List_Before (ES, Condition_Actions (Scheme));
4503 -- This is not an implicit loop, since it is generated in response
4504 -- to the loop statement being processed. If this is itself
4505 -- implicit, the restriction has already been checked. If not,
4506 -- it is an explicit loop.
4508 Rewrite (N,
4509 Make_Loop_Statement (Sloc (N),
4510 Identifier => Identifier (N),
4511 Statements => Statements (N),
4512 End_Label => End_Label (N)));
4514 Analyze (N);
4515 end;
4517 -- Here to deal with iterator case
4519 elsif Present (Scheme)
4520 and then Present (Iterator_Specification (Scheme))
4521 then
4522 Expand_Iterator_Loop (N);
4524 -- An iterator loop may generate renaming declarations for elements
4525 -- that require debug information. This is the case in particular
4526 -- with element iterators, where debug information must be generated
4527 -- for the temporary that holds the element value. These temporaries
4528 -- are created within a transient block whose local declarations are
4529 -- transferred to the loop, which now has nontrivial local objects.
4531 if Nkind (N) = N_Loop_Statement
4532 and then Present (Identifier (N))
4533 then
4534 Qualify_Entity_Names (N);
4535 end if;
4536 end if;
4538 -- When the iteration scheme mentiones attribute 'Loop_Entry, the loop
4539 -- is transformed into a conditional block where the original loop is
4540 -- the sole statement. Inspect the statements of the nested loop for
4541 -- controlled objects.
4543 Stmt := N;
4545 if Subject_To_Loop_Entry_Attributes (Stmt) then
4546 Stmt := Find_Loop_In_Conditional_Block (Stmt);
4547 end if;
4549 Process_Statements_For_Controlled_Objects (Stmt);
4550 end Expand_N_Loop_Statement;
4552 ----------------------------
4553 -- Expand_Predicated_Loop --
4554 ----------------------------
4556 -- Note: the expander can handle generation of loops over predicated
4557 -- subtypes for both the dynamic and static cases. Depending on what
4558 -- we decide is allowed in Ada 2012 mode and/or extensions allowed
4559 -- mode, the semantic analyzer may disallow one or both forms.
4561 procedure Expand_Predicated_Loop (N : Node_Id) is
4562 Loc : constant Source_Ptr := Sloc (N);
4563 Isc : constant Node_Id := Iteration_Scheme (N);
4564 LPS : constant Node_Id := Loop_Parameter_Specification (Isc);
4565 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4566 Ltype : constant Entity_Id := Etype (Loop_Id);
4567 Stat : constant List_Id := Static_Discrete_Predicate (Ltype);
4568 Stmts : constant List_Id := Statements (N);
4570 begin
4571 -- Case of iteration over non-static predicate, should not be possible
4572 -- since this is not allowed by the semantics and should have been
4573 -- caught during analysis of the loop statement.
4575 if No (Stat) then
4576 raise Program_Error;
4578 -- If the predicate list is empty, that corresponds to a predicate of
4579 -- False, in which case the loop won't run at all, and we rewrite the
4580 -- entire loop as a null statement.
4582 elsif Is_Empty_List (Stat) then
4583 Rewrite (N, Make_Null_Statement (Loc));
4584 Analyze (N);
4586 -- For expansion over a static predicate we generate the following
4588 -- declare
4589 -- J : Ltype := min-val;
4590 -- begin
4591 -- loop
4592 -- body
4593 -- case J is
4594 -- when endpoint => J := startpoint;
4595 -- when endpoint => J := startpoint;
4596 -- ...
4597 -- when max-val => exit;
4598 -- when others => J := Lval'Succ (J);
4599 -- end case;
4600 -- end loop;
4601 -- end;
4603 -- with min-val replaced by max-val and Succ replaced by Pred if the
4604 -- loop parameter specification carries a Reverse indicator.
4606 -- To make this a little clearer, let's take a specific example:
4608 -- type Int is range 1 .. 10;
4609 -- subtype StaticP is Int with
4610 -- predicate => StaticP in 3 | 10 | 5 .. 7;
4611 -- ...
4612 -- for L in StaticP loop
4613 -- Put_Line ("static:" & J'Img);
4614 -- end loop;
4616 -- In this case, the loop is transformed into
4618 -- begin
4619 -- J : L := 3;
4620 -- loop
4621 -- body
4622 -- case J is
4623 -- when 3 => J := 5;
4624 -- when 7 => J := 10;
4625 -- when 10 => exit;
4626 -- when others => J := L'Succ (J);
4627 -- end case;
4628 -- end loop;
4629 -- end;
4631 else
4632 Static_Predicate : declare
4633 S : Node_Id;
4634 D : Node_Id;
4635 P : Node_Id;
4636 Alts : List_Id;
4637 Cstm : Node_Id;
4639 function Lo_Val (N : Node_Id) return Node_Id;
4640 -- Given static expression or static range, returns an identifier
4641 -- whose value is the low bound of the expression value or range.
4643 function Hi_Val (N : Node_Id) return Node_Id;
4644 -- Given static expression or static range, returns an identifier
4645 -- whose value is the high bound of the expression value or range.
4647 ------------
4648 -- Hi_Val --
4649 ------------
4651 function Hi_Val (N : Node_Id) return Node_Id is
4652 begin
4653 if Is_OK_Static_Expression (N) then
4654 return New_Copy (N);
4655 else
4656 pragma Assert (Nkind (N) = N_Range);
4657 return New_Copy (High_Bound (N));
4658 end if;
4659 end Hi_Val;
4661 ------------
4662 -- Lo_Val --
4663 ------------
4665 function Lo_Val (N : Node_Id) return Node_Id is
4666 begin
4667 if Is_OK_Static_Expression (N) then
4668 return New_Copy (N);
4669 else
4670 pragma Assert (Nkind (N) = N_Range);
4671 return New_Copy (Low_Bound (N));
4672 end if;
4673 end Lo_Val;
4675 -- Start of processing for Static_Predicate
4677 begin
4678 -- Convert loop identifier to normal variable and reanalyze it so
4679 -- that this conversion works. We have to use the same defining
4680 -- identifier, since there may be references in the loop body.
4682 Set_Analyzed (Loop_Id, False);
4683 Set_Ekind (Loop_Id, E_Variable);
4685 -- In most loops the loop variable is assigned in various
4686 -- alternatives in the body. However, in the rare case when
4687 -- the range specifies a single element, the loop variable
4688 -- may trigger a spurious warning that is could be constant.
4689 -- This warning might as well be suppressed.
4691 Set_Warnings_Off (Loop_Id);
4693 -- Loop to create branches of case statement
4695 Alts := New_List;
4697 if Reverse_Present (LPS) then
4699 -- Initial value is largest value in predicate.
4701 D :=
4702 Make_Object_Declaration (Loc,
4703 Defining_Identifier => Loop_Id,
4704 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4705 Expression => Hi_Val (Last (Stat)));
4707 P := Last (Stat);
4708 while Present (P) loop
4709 if No (Prev (P)) then
4710 S := Make_Exit_Statement (Loc);
4711 else
4712 S :=
4713 Make_Assignment_Statement (Loc,
4714 Name => New_Occurrence_Of (Loop_Id, Loc),
4715 Expression => Hi_Val (Prev (P)));
4716 Set_Suppress_Assignment_Checks (S);
4717 end if;
4719 Append_To (Alts,
4720 Make_Case_Statement_Alternative (Loc,
4721 Statements => New_List (S),
4722 Discrete_Choices => New_List (Lo_Val (P))));
4724 Prev (P);
4725 end loop;
4727 else
4729 -- Initial value is smallest value in predicate.
4731 D :=
4732 Make_Object_Declaration (Loc,
4733 Defining_Identifier => Loop_Id,
4734 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4735 Expression => Lo_Val (First (Stat)));
4737 P := First (Stat);
4738 while Present (P) loop
4739 if No (Next (P)) then
4740 S := Make_Exit_Statement (Loc);
4741 else
4742 S :=
4743 Make_Assignment_Statement (Loc,
4744 Name => New_Occurrence_Of (Loop_Id, Loc),
4745 Expression => Lo_Val (Next (P)));
4746 Set_Suppress_Assignment_Checks (S);
4747 end if;
4749 Append_To (Alts,
4750 Make_Case_Statement_Alternative (Loc,
4751 Statements => New_List (S),
4752 Discrete_Choices => New_List (Hi_Val (P))));
4754 Next (P);
4755 end loop;
4756 end if;
4758 -- Add others choice
4760 declare
4761 Name_Next : Name_Id;
4763 begin
4764 if Reverse_Present (LPS) then
4765 Name_Next := Name_Pred;
4766 else
4767 Name_Next := Name_Succ;
4768 end if;
4770 S :=
4771 Make_Assignment_Statement (Loc,
4772 Name => New_Occurrence_Of (Loop_Id, Loc),
4773 Expression =>
4774 Make_Attribute_Reference (Loc,
4775 Prefix => New_Occurrence_Of (Ltype, Loc),
4776 Attribute_Name => Name_Next,
4777 Expressions => New_List (
4778 New_Occurrence_Of (Loop_Id, Loc))));
4779 Set_Suppress_Assignment_Checks (S);
4780 end;
4782 Append_To (Alts,
4783 Make_Case_Statement_Alternative (Loc,
4784 Discrete_Choices => New_List (Make_Others_Choice (Loc)),
4785 Statements => New_List (S)));
4787 -- Construct case statement and append to body statements
4789 Cstm :=
4790 Make_Case_Statement (Loc,
4791 Expression => New_Occurrence_Of (Loop_Id, Loc),
4792 Alternatives => Alts);
4793 Append_To (Stmts, Cstm);
4795 -- Rewrite the loop
4797 Set_Suppress_Assignment_Checks (D);
4799 Rewrite (N,
4800 Make_Block_Statement (Loc,
4801 Declarations => New_List (D),
4802 Handled_Statement_Sequence =>
4803 Make_Handled_Sequence_Of_Statements (Loc,
4804 Statements => New_List (
4805 Make_Loop_Statement (Loc,
4806 Statements => Stmts,
4807 End_Label => Empty)))));
4809 Analyze (N);
4810 end Static_Predicate;
4811 end if;
4812 end Expand_Predicated_Loop;
4814 ------------------------------
4815 -- Make_Tag_Ctrl_Assignment --
4816 ------------------------------
4818 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
4819 Asn : constant Node_Id := Relocate_Node (N);
4820 L : constant Node_Id := Name (N);
4821 Loc : constant Source_Ptr := Sloc (N);
4822 Res : constant List_Id := New_List;
4823 T : constant Entity_Id := Underlying_Type (Etype (L));
4825 Comp_Asn : constant Boolean := Is_Fully_Repped_Tagged_Type (T);
4826 Ctrl_Act : constant Boolean := Needs_Finalization (T)
4827 and then not No_Ctrl_Actions (N);
4828 Save_Tag : constant Boolean := Is_Tagged_Type (T)
4829 and then not Comp_Asn
4830 and then not No_Ctrl_Actions (N)
4831 and then Tagged_Type_Expansion;
4832 Adj_Call : Node_Id;
4833 Fin_Call : Node_Id;
4834 Tag_Id : Entity_Id;
4836 begin
4837 -- Finalize the target of the assignment when controlled
4839 -- We have two exceptions here:
4841 -- 1. If we are in an init proc since it is an initialization more
4842 -- than an assignment.
4844 -- 2. If the left-hand side is a temporary that was not initialized
4845 -- (or the parent part of a temporary since it is the case in
4846 -- extension aggregates). Such a temporary does not come from
4847 -- source. We must examine the original node for the prefix, because
4848 -- it may be a component of an entry formal, in which case it has
4849 -- been rewritten and does not appear to come from source either.
4851 -- Case of init proc
4853 if not Ctrl_Act then
4854 null;
4856 -- The left-hand side is an uninitialized temporary object
4858 elsif Nkind (L) = N_Type_Conversion
4859 and then Is_Entity_Name (Expression (L))
4860 and then Nkind (Parent (Entity (Expression (L)))) =
4861 N_Object_Declaration
4862 and then No_Initialization (Parent (Entity (Expression (L))))
4863 then
4864 null;
4866 else
4867 Fin_Call :=
4868 Make_Final_Call
4869 (Obj_Ref => Duplicate_Subexpr_No_Checks (L),
4870 Typ => Etype (L));
4872 if Present (Fin_Call) then
4873 Append_To (Res, Fin_Call);
4874 end if;
4875 end if;
4877 -- Save the Tag in a local variable Tag_Id
4879 if Save_Tag then
4880 Tag_Id := Make_Temporary (Loc, 'A');
4882 Append_To (Res,
4883 Make_Object_Declaration (Loc,
4884 Defining_Identifier => Tag_Id,
4885 Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc),
4886 Expression =>
4887 Make_Selected_Component (Loc,
4888 Prefix => Duplicate_Subexpr_No_Checks (L),
4889 Selector_Name =>
4890 New_Occurrence_Of (First_Tag_Component (T), Loc))));
4892 -- Otherwise Tag_Id is not used
4894 else
4895 Tag_Id := Empty;
4896 end if;
4898 -- If the tagged type has a full rep clause, expand the assignment into
4899 -- component-wise assignments. Mark the node as unanalyzed in order to
4900 -- generate the proper code and propagate this scenario by setting a
4901 -- flag to avoid infinite recursion.
4903 if Comp_Asn then
4904 Set_Analyzed (Asn, False);
4905 Set_Componentwise_Assignment (Asn, True);
4906 end if;
4908 Append_To (Res, Asn);
4910 -- Restore the tag
4912 if Save_Tag then
4913 Append_To (Res,
4914 Make_Assignment_Statement (Loc,
4915 Name =>
4916 Make_Selected_Component (Loc,
4917 Prefix => Duplicate_Subexpr_No_Checks (L),
4918 Selector_Name =>
4919 New_Occurrence_Of (First_Tag_Component (T), Loc)),
4920 Expression => New_Occurrence_Of (Tag_Id, Loc)));
4921 end if;
4923 -- Adjust the target after the assignment when controlled (not in the
4924 -- init proc since it is an initialization more than an assignment).
4926 if Ctrl_Act then
4927 Adj_Call :=
4928 Make_Adjust_Call
4929 (Obj_Ref => Duplicate_Subexpr_Move_Checks (L),
4930 Typ => Etype (L));
4932 if Present (Adj_Call) then
4933 Append_To (Res, Adj_Call);
4934 end if;
4935 end if;
4937 return Res;
4939 exception
4941 -- Could use comment here ???
4943 when RE_Not_Available =>
4944 return Empty_List;
4945 end Make_Tag_Ctrl_Assignment;
4947 end Exp_Ch5;