PR rtl-optimization/79386
[official-gcc.git] / gcc / ada / exp_ch5.adb
blob6a808a35a30eb567a9902c8e2b3da5590bf05882
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)));
1641 end if;
1643 Set_Analyzed (N, False);
1644 return OK;
1645 end Replace_Target;
1647 procedure Replace_Target_Name is new Traverse_Proc (Replace_Target);
1649 -- Local variables
1651 New_RHS : Node_Id;
1652 Proc_Id : Entity_Id;
1654 -- Start of processing for Expand_Assign_With_Target_Names
1656 begin
1657 New_RHS := New_Copy_Tree (RHS);
1659 -- The left-hand side is a direct name
1661 if Is_Entity_Name (LHS)
1662 and then not Is_Renaming_Of_Object (Entity (LHS))
1663 then
1664 Ent := Entity (LHS);
1665 Replace_Target_Name (New_RHS);
1667 -- Generate:
1668 -- LHS := ... LHS ...;
1670 Rewrite (N,
1671 Make_Assignment_Statement (Loc,
1672 Name => Relocate_Node (LHS),
1673 Expression => New_RHS));
1675 -- The left-hand side is not a direct name, but is side-effect free.
1676 -- Capture its value in a temporary to avoid multiple evaluations.
1678 elsif Side_Effect_Free (LHS) then
1679 Ent := Make_Temporary (Loc, 'T');
1680 Replace_Target_Name (New_RHS);
1682 -- Generate:
1683 -- T : LHS_Typ := LHS;
1685 Insert_Before_And_Analyze (N,
1686 Make_Object_Declaration (Loc,
1687 Defining_Identifier => Ent,
1688 Object_Definition => New_Occurrence_Of (LHS_Typ, Loc),
1689 Expression => New_Copy_Tree (LHS)));
1691 -- Generate:
1692 -- LHS := ... T ...;
1694 Rewrite (N,
1695 Make_Assignment_Statement (Loc,
1696 Name => Relocate_Node (LHS),
1697 Expression => New_RHS));
1699 -- Otherwise wrap the whole assignment statement in a procedure with an
1700 -- IN OUT parameter. The original assignment then becomes a call to the
1701 -- procedure with the left-hand side as an actual.
1703 else
1704 Ent := Make_Temporary (Loc, 'T');
1705 Replace_Target_Name (New_RHS);
1707 -- Generate:
1708 -- procedure P (T : in out LHS_Typ) is
1709 -- begin
1710 -- T := ... T ...;
1711 -- end P;
1713 Proc_Id := Make_Temporary (Loc, 'P');
1715 Insert_Before_And_Analyze (N,
1716 Make_Subprogram_Body (Loc,
1717 Specification =>
1718 Make_Procedure_Specification (Loc,
1719 Defining_Unit_Name => Proc_Id,
1720 Parameter_Specifications => New_List (
1721 Make_Parameter_Specification (Loc,
1722 Defining_Identifier => Ent,
1723 In_Present => True,
1724 Out_Present => True,
1725 Parameter_Type =>
1726 New_Occurrence_Of (LHS_Typ, Loc)))),
1728 Declarations => Empty_List,
1730 Handled_Statement_Sequence =>
1731 Make_Handled_Sequence_Of_Statements (Loc,
1732 Statements => New_List (
1733 Make_Assignment_Statement (Loc,
1734 Name => New_Occurrence_Of (Ent, Loc),
1735 Expression => New_RHS)))));
1737 -- Generate:
1738 -- P (LHS);
1740 Rewrite (N,
1741 Make_Procedure_Call_Statement (Loc,
1742 Name => New_Occurrence_Of (Proc_Id, Loc),
1743 Parameter_Associations => New_List (Relocate_Node (LHS))));
1744 end if;
1746 -- Analyze rewritten node, either as assignment or procedure call
1748 Analyze (N);
1749 end Expand_Assign_With_Target_Names;
1751 -----------------------------------
1752 -- Expand_N_Assignment_Statement --
1753 -----------------------------------
1755 -- This procedure implements various cases where an assignment statement
1756 -- cannot just be passed on to the back end in untransformed state.
1758 procedure Expand_N_Assignment_Statement (N : Node_Id) is
1759 Crep : constant Boolean := Change_Of_Representation (N);
1760 Lhs : constant Node_Id := Name (N);
1761 Loc : constant Source_Ptr := Sloc (N);
1762 Rhs : constant Node_Id := Expression (N);
1763 Typ : constant Entity_Id := Underlying_Type (Etype (Lhs));
1764 Exp : Node_Id;
1766 begin
1767 -- Special case to check right away, if the Componentwise_Assignment
1768 -- flag is set, this is a reanalysis from the expansion of the primitive
1769 -- assignment procedure for a tagged type, and all we need to do is to
1770 -- expand to assignment of components, because otherwise, we would get
1771 -- infinite recursion (since this looks like a tagged assignment which
1772 -- would normally try to *call* the primitive assignment procedure).
1774 if Componentwise_Assignment (N) then
1775 Expand_Assign_Record (N);
1776 return;
1777 end if;
1779 -- Defend against invalid subscripts on left side if we are in standard
1780 -- validity checking mode. No need to do this if we are checking all
1781 -- subscripts.
1783 -- Note that we do this right away, because there are some early return
1784 -- paths in this procedure, and this is required on all paths.
1786 if Validity_Checks_On
1787 and then Validity_Check_Default
1788 and then not Validity_Check_Subscripts
1789 then
1790 Check_Valid_Lvalue_Subscripts (Lhs);
1791 end if;
1793 -- Separate expansion if RHS contain target names. Note that assignment
1794 -- may already have been expanded if RHS is aggregate.
1796 if Nkind (N) = N_Assignment_Statement and then Has_Target_Names (N) then
1797 Expand_Assign_With_Target_Names (N);
1798 return;
1799 end if;
1801 -- Ada 2005 (AI-327): Handle assignment to priority of protected object
1803 -- Rewrite an assignment to X'Priority into a run-time call
1805 -- For example: X'Priority := New_Prio_Expr;
1806 -- ...is expanded into Set_Ceiling (X._Object, New_Prio_Expr);
1808 -- Note that although X'Priority is notionally an object, it is quite
1809 -- deliberately not defined as an aliased object in the RM. This means
1810 -- that it works fine to rewrite it as a call, without having to worry
1811 -- about complications that would other arise from X'Priority'Access,
1812 -- which is illegal, because of the lack of aliasing.
1814 if Ada_Version >= Ada_2005 then
1815 declare
1816 Call : Node_Id;
1817 Conctyp : Entity_Id;
1818 Ent : Entity_Id;
1819 Subprg : Entity_Id;
1820 RT_Subprg_Name : Node_Id;
1822 begin
1823 -- Handle chains of renamings
1825 Ent := Name (N);
1826 while Nkind (Ent) in N_Has_Entity
1827 and then Present (Entity (Ent))
1828 and then Present (Renamed_Object (Entity (Ent)))
1829 loop
1830 Ent := Renamed_Object (Entity (Ent));
1831 end loop;
1833 -- The attribute Priority applied to protected objects has been
1834 -- previously expanded into a call to the Get_Ceiling run-time
1835 -- subprogram. In restricted profiles this is not available.
1837 if Is_Expanded_Priority_Attribute (Ent) then
1839 -- Look for the enclosing concurrent type
1841 Conctyp := Current_Scope;
1842 while not Is_Concurrent_Type (Conctyp) loop
1843 Conctyp := Scope (Conctyp);
1844 end loop;
1846 pragma Assert (Is_Protected_Type (Conctyp));
1848 -- Generate the first actual of the call
1850 Subprg := Current_Scope;
1851 while not Present (Protected_Body_Subprogram (Subprg)) loop
1852 Subprg := Scope (Subprg);
1853 end loop;
1855 -- Select the appropriate run-time call
1857 if Number_Entries (Conctyp) = 0 then
1858 RT_Subprg_Name :=
1859 New_Occurrence_Of (RTE (RE_Set_Ceiling), Loc);
1860 else
1861 RT_Subprg_Name :=
1862 New_Occurrence_Of (RTE (RO_PE_Set_Ceiling), Loc);
1863 end if;
1865 Call :=
1866 Make_Procedure_Call_Statement (Loc,
1867 Name => RT_Subprg_Name,
1868 Parameter_Associations => New_List (
1869 New_Copy_Tree (First (Parameter_Associations (Ent))),
1870 Relocate_Node (Expression (N))));
1872 Rewrite (N, Call);
1873 Analyze (N);
1875 return;
1876 end if;
1877 end;
1878 end if;
1880 -- Deal with assignment checks unless suppressed
1882 if not Suppress_Assignment_Checks (N) then
1884 -- First deal with generation of range check if required
1886 if Do_Range_Check (Rhs) then
1887 Generate_Range_Check (Rhs, Typ, CE_Range_Check_Failed);
1888 end if;
1890 -- Then generate predicate check if required
1892 Apply_Predicate_Check (Rhs, Typ);
1893 end if;
1895 -- Check for a special case where a high level transformation is
1896 -- required. If we have either of:
1898 -- P.field := rhs;
1899 -- P (sub) := rhs;
1901 -- where P is a reference to a bit packed array, then we have to unwind
1902 -- the assignment. The exact meaning of being a reference to a bit
1903 -- packed array is as follows:
1905 -- An indexed component whose prefix is a bit packed array is a
1906 -- reference to a bit packed array.
1908 -- An indexed component or selected component whose prefix is a
1909 -- reference to a bit packed array is itself a reference ot a
1910 -- bit packed array.
1912 -- The required transformation is
1914 -- Tnn : prefix_type := P;
1915 -- Tnn.field := rhs;
1916 -- P := Tnn;
1918 -- or
1920 -- Tnn : prefix_type := P;
1921 -- Tnn (subscr) := rhs;
1922 -- P := Tnn;
1924 -- Since P is going to be evaluated more than once, any subscripts
1925 -- in P must have their evaluation forced.
1927 if Nkind_In (Lhs, N_Indexed_Component, N_Selected_Component)
1928 and then Is_Ref_To_Bit_Packed_Array (Prefix (Lhs))
1929 then
1930 declare
1931 BPAR_Expr : constant Node_Id := Relocate_Node (Prefix (Lhs));
1932 BPAR_Typ : constant Entity_Id := Etype (BPAR_Expr);
1933 Tnn : constant Entity_Id :=
1934 Make_Temporary (Loc, 'T', BPAR_Expr);
1936 begin
1937 -- Insert the post assignment first, because we want to copy the
1938 -- BPAR_Expr tree before it gets analyzed in the context of the
1939 -- pre assignment. Note that we do not analyze the post assignment
1940 -- yet (we cannot till we have completed the analysis of the pre
1941 -- assignment). As usual, the analysis of this post assignment
1942 -- will happen on its own when we "run into" it after finishing
1943 -- the current assignment.
1945 Insert_After (N,
1946 Make_Assignment_Statement (Loc,
1947 Name => New_Copy_Tree (BPAR_Expr),
1948 Expression => New_Occurrence_Of (Tnn, Loc)));
1950 -- At this stage BPAR_Expr is a reference to a bit packed array
1951 -- where the reference was not expanded in the original tree,
1952 -- since it was on the left side of an assignment. But in the
1953 -- pre-assignment statement (the object definition), BPAR_Expr
1954 -- will end up on the right-hand side, and must be reexpanded. To
1955 -- achieve this, we reset the analyzed flag of all selected and
1956 -- indexed components down to the actual indexed component for
1957 -- the packed array.
1959 Exp := BPAR_Expr;
1960 loop
1961 Set_Analyzed (Exp, False);
1963 if Nkind_In (Exp, N_Indexed_Component,
1964 N_Selected_Component)
1965 then
1966 Exp := Prefix (Exp);
1967 else
1968 exit;
1969 end if;
1970 end loop;
1972 -- Now we can insert and analyze the pre-assignment
1974 -- If the right-hand side requires a transient scope, it has
1975 -- already been placed on the stack. However, the declaration is
1976 -- inserted in the tree outside of this scope, and must reflect
1977 -- the proper scope for its variable. This awkward bit is forced
1978 -- by the stricter scope discipline imposed by GCC 2.97.
1980 declare
1981 Uses_Transient_Scope : constant Boolean :=
1982 Scope_Is_Transient
1983 and then N = Node_To_Be_Wrapped;
1985 begin
1986 if Uses_Transient_Scope then
1987 Push_Scope (Scope (Current_Scope));
1988 end if;
1990 Insert_Before_And_Analyze (N,
1991 Make_Object_Declaration (Loc,
1992 Defining_Identifier => Tnn,
1993 Object_Definition => New_Occurrence_Of (BPAR_Typ, Loc),
1994 Expression => BPAR_Expr));
1996 if Uses_Transient_Scope then
1997 Pop_Scope;
1998 end if;
1999 end;
2001 -- Now fix up the original assignment and continue processing
2003 Rewrite (Prefix (Lhs),
2004 New_Occurrence_Of (Tnn, Loc));
2006 -- We do not need to reanalyze that assignment, and we do not need
2007 -- to worry about references to the temporary, but we do need to
2008 -- make sure that the temporary is not marked as a true constant
2009 -- since we now have a generated assignment to it.
2011 Set_Is_True_Constant (Tnn, False);
2012 end;
2013 end if;
2015 -- When we have the appropriate type of aggregate in the expression (it
2016 -- has been determined during analysis of the aggregate by setting the
2017 -- delay flag), let's perform in place assignment and thus avoid
2018 -- creating a temporary.
2020 if Is_Delayed_Aggregate (Rhs) then
2021 Convert_Aggr_In_Assignment (N);
2022 Rewrite (N, Make_Null_Statement (Loc));
2023 Analyze (N);
2025 return;
2026 end if;
2028 -- Apply discriminant check if required. If Lhs is an access type to a
2029 -- designated type with discriminants, we must always check. If the
2030 -- type has unknown discriminants, more elaborate processing below.
2032 if Has_Discriminants (Etype (Lhs))
2033 and then not Has_Unknown_Discriminants (Etype (Lhs))
2034 then
2035 -- Skip discriminant check if change of representation. Will be
2036 -- done when the change of representation is expanded out.
2038 if not Crep then
2039 Apply_Discriminant_Check (Rhs, Etype (Lhs), Lhs);
2040 end if;
2042 -- If the type is private without discriminants, and the full type
2043 -- has discriminants (necessarily with defaults) a check may still be
2044 -- necessary if the Lhs is aliased. The private discriminants must be
2045 -- visible to build the discriminant constraints.
2047 -- Only an explicit dereference that comes from source indicates
2048 -- aliasing. Access to formals of protected operations and entries
2049 -- create dereferences but are not semantic aliasings.
2051 elsif Is_Private_Type (Etype (Lhs))
2052 and then Has_Discriminants (Typ)
2053 and then Nkind (Lhs) = N_Explicit_Dereference
2054 and then Comes_From_Source (Lhs)
2055 then
2056 declare
2057 Lt : constant Entity_Id := Etype (Lhs);
2058 Ubt : Entity_Id := Base_Type (Typ);
2060 begin
2061 -- In the case of an expander-generated record subtype whose base
2062 -- type still appears private, Typ will have been set to that
2063 -- private type rather than the underlying record type (because
2064 -- Underlying type will have returned the record subtype), so it's
2065 -- necessary to apply Underlying_Type again to the base type to
2066 -- get the record type we need for the discriminant check. Such
2067 -- subtypes can be created for assignments in certain cases, such
2068 -- as within an instantiation passed this kind of private type.
2069 -- It would be good to avoid this special test, but making changes
2070 -- to prevent this odd form of record subtype seems difficult. ???
2072 if Is_Private_Type (Ubt) then
2073 Ubt := Underlying_Type (Ubt);
2074 end if;
2076 Set_Etype (Lhs, Ubt);
2077 Rewrite (Rhs, OK_Convert_To (Base_Type (Ubt), Rhs));
2078 Apply_Discriminant_Check (Rhs, Ubt, Lhs);
2079 Set_Etype (Lhs, Lt);
2080 end;
2082 -- If the Lhs has a private type with unknown discriminants, it may
2083 -- have a full view with discriminants, but those are nameable only
2084 -- in the underlying type, so convert the Rhs to it before potential
2085 -- checking. Convert Lhs as well, otherwise the actual subtype might
2086 -- not be constructible. If the discriminants have defaults the type
2087 -- is unconstrained and there is nothing to check.
2089 elsif Has_Unknown_Discriminants (Base_Type (Etype (Lhs)))
2090 and then Has_Discriminants (Typ)
2091 and then not Has_Defaulted_Discriminants (Typ)
2092 then
2093 Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
2094 Rewrite (Lhs, OK_Convert_To (Base_Type (Typ), Lhs));
2095 Apply_Discriminant_Check (Rhs, Typ, Lhs);
2097 -- In the access type case, we need the same discriminant check, and
2098 -- also range checks if we have an access to constrained array.
2100 elsif Is_Access_Type (Etype (Lhs))
2101 and then Is_Constrained (Designated_Type (Etype (Lhs)))
2102 then
2103 if Has_Discriminants (Designated_Type (Etype (Lhs))) then
2105 -- Skip discriminant check if change of representation. Will be
2106 -- done when the change of representation is expanded out.
2108 if not Crep then
2109 Apply_Discriminant_Check (Rhs, Etype (Lhs));
2110 end if;
2112 elsif Is_Array_Type (Designated_Type (Etype (Lhs))) then
2113 Apply_Range_Check (Rhs, Etype (Lhs));
2115 if Is_Constrained (Etype (Lhs)) then
2116 Apply_Length_Check (Rhs, Etype (Lhs));
2117 end if;
2119 if Nkind (Rhs) = N_Allocator then
2120 declare
2121 Target_Typ : constant Entity_Id := Etype (Expression (Rhs));
2122 C_Es : Check_Result;
2124 begin
2125 C_Es :=
2126 Get_Range_Checks
2127 (Lhs,
2128 Target_Typ,
2129 Etype (Designated_Type (Etype (Lhs))));
2131 Insert_Range_Checks
2132 (C_Es,
2134 Target_Typ,
2135 Sloc (Lhs),
2136 Lhs);
2137 end;
2138 end if;
2139 end if;
2141 -- Apply range check for access type case
2143 elsif Is_Access_Type (Etype (Lhs))
2144 and then Nkind (Rhs) = N_Allocator
2145 and then Nkind (Expression (Rhs)) = N_Qualified_Expression
2146 then
2147 Analyze_And_Resolve (Expression (Rhs));
2148 Apply_Range_Check
2149 (Expression (Rhs), Designated_Type (Etype (Lhs)));
2150 end if;
2152 -- Ada 2005 (AI-231): Generate the run-time check
2154 if Is_Access_Type (Typ)
2155 and then Can_Never_Be_Null (Etype (Lhs))
2156 and then not Can_Never_Be_Null (Etype (Rhs))
2158 -- If an actual is an out parameter of a null-excluding access
2159 -- type, there is access check on entry, so we set the flag
2160 -- Suppress_Assignment_Checks on the generated statement to
2161 -- assign the actual to the parameter block, and we do not want
2162 -- to generate an additional check at this point.
2164 and then not Suppress_Assignment_Checks (N)
2165 then
2166 Apply_Constraint_Check (Rhs, Etype (Lhs));
2167 end if;
2169 -- Ada 2012 (AI05-148): Update current accessibility level if Rhs is a
2170 -- stand-alone obj of an anonymous access type. Do not install the check
2171 -- when the Lhs denotes a container cursor and the Next function employs
2172 -- an access type, because this can never result in a dangling pointer.
2174 if Is_Access_Type (Typ)
2175 and then Is_Entity_Name (Lhs)
2176 and then Ekind (Entity (Lhs)) /= E_Loop_Parameter
2177 and then Present (Effective_Extra_Accessibility (Entity (Lhs)))
2178 then
2179 declare
2180 function Lhs_Entity return Entity_Id;
2181 -- Look through renames to find the underlying entity.
2182 -- For assignment to a rename, we don't care about the
2183 -- Enclosing_Dynamic_Scope of the rename declaration.
2185 ----------------
2186 -- Lhs_Entity --
2187 ----------------
2189 function Lhs_Entity return Entity_Id is
2190 Result : Entity_Id := Entity (Lhs);
2192 begin
2193 while Present (Renamed_Object (Result)) loop
2195 -- Renamed_Object must return an Entity_Name here
2196 -- because of preceding "Present (E_E_A (...))" test.
2198 Result := Entity (Renamed_Object (Result));
2199 end loop;
2201 return Result;
2202 end Lhs_Entity;
2204 -- Local Declarations
2206 Access_Check : constant Node_Id :=
2207 Make_Raise_Program_Error (Loc,
2208 Condition =>
2209 Make_Op_Gt (Loc,
2210 Left_Opnd =>
2211 Dynamic_Accessibility_Level (Rhs),
2212 Right_Opnd =>
2213 Make_Integer_Literal (Loc,
2214 Intval =>
2215 Scope_Depth
2216 (Enclosing_Dynamic_Scope
2217 (Lhs_Entity)))),
2218 Reason => PE_Accessibility_Check_Failed);
2220 Access_Level_Update : constant Node_Id :=
2221 Make_Assignment_Statement (Loc,
2222 Name =>
2223 New_Occurrence_Of
2224 (Effective_Extra_Accessibility
2225 (Entity (Lhs)), Loc),
2226 Expression =>
2227 Dynamic_Accessibility_Level (Rhs));
2229 begin
2230 if not Accessibility_Checks_Suppressed (Entity (Lhs)) then
2231 Insert_Action (N, Access_Check);
2232 end if;
2234 Insert_Action (N, Access_Level_Update);
2235 end;
2236 end if;
2238 -- Case of assignment to a bit packed array element. If there is a
2239 -- change of representation this must be expanded into components,
2240 -- otherwise this is a bit-field assignment.
2242 if Nkind (Lhs) = N_Indexed_Component
2243 and then Is_Bit_Packed_Array (Etype (Prefix (Lhs)))
2244 then
2245 -- Normal case, no change of representation
2247 if not Crep then
2248 Expand_Bit_Packed_Element_Set (N);
2249 return;
2251 -- Change of representation case
2253 else
2254 -- Generate the following, to force component-by-component
2255 -- assignments in an efficient way. Otherwise each component
2256 -- will require a temporary and two bit-field manipulations.
2258 -- T1 : Elmt_Type;
2259 -- T1 := RhS;
2260 -- Lhs := T1;
2262 declare
2263 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T');
2264 Stats : List_Id;
2266 begin
2267 Stats :=
2268 New_List (
2269 Make_Object_Declaration (Loc,
2270 Defining_Identifier => Tnn,
2271 Object_Definition =>
2272 New_Occurrence_Of (Etype (Lhs), Loc)),
2273 Make_Assignment_Statement (Loc,
2274 Name => New_Occurrence_Of (Tnn, Loc),
2275 Expression => Relocate_Node (Rhs)),
2276 Make_Assignment_Statement (Loc,
2277 Name => Relocate_Node (Lhs),
2278 Expression => New_Occurrence_Of (Tnn, Loc)));
2280 Insert_Actions (N, Stats);
2281 Rewrite (N, Make_Null_Statement (Loc));
2282 Analyze (N);
2283 end;
2284 end if;
2286 -- Build-in-place function call case. Note that we're not yet doing
2287 -- build-in-place for user-written assignment statements (the assignment
2288 -- here came from an aggregate.)
2290 elsif Ada_Version >= Ada_2005
2291 and then Is_Build_In_Place_Function_Call (Rhs)
2292 then
2293 Make_Build_In_Place_Call_In_Assignment (N, Rhs);
2295 elsif Is_Tagged_Type (Typ)
2296 or else (Needs_Finalization (Typ) and then not Is_Array_Type (Typ))
2297 then
2298 Tagged_Case : declare
2299 L : List_Id := No_List;
2300 Expand_Ctrl_Actions : constant Boolean := not No_Ctrl_Actions (N);
2302 begin
2303 -- In the controlled case, we ensure that function calls are
2304 -- evaluated before finalizing the target. In all cases, it makes
2305 -- the expansion easier if the side effects are removed first.
2307 Remove_Side_Effects (Lhs);
2308 Remove_Side_Effects (Rhs);
2310 -- Avoid recursion in the mechanism
2312 Set_Analyzed (N);
2314 -- If dispatching assignment, we need to dispatch to _assign
2316 if Is_Class_Wide_Type (Typ)
2318 -- If the type is tagged, we may as well use the predefined
2319 -- primitive assignment. This avoids inlining a lot of code
2320 -- and in the class-wide case, the assignment is replaced
2321 -- by a dispatching call to _assign. It is suppressed in the
2322 -- case of assignments created by the expander that correspond
2323 -- to initializations, where we do want to copy the tag
2324 -- (Expand_Ctrl_Actions flag is set False in this case). It is
2325 -- also suppressed if restriction No_Dispatching_Calls is in
2326 -- force because in that case predefined primitives are not
2327 -- generated.
2329 or else (Is_Tagged_Type (Typ)
2330 and then Chars (Current_Scope) /= Name_uAssign
2331 and then Expand_Ctrl_Actions
2332 and then
2333 not Restriction_Active (No_Dispatching_Calls))
2334 then
2335 if Is_Limited_Type (Typ) then
2337 -- This can happen in an instance when the formal is an
2338 -- extension of a limited interface, and the actual is
2339 -- limited. This is an error according to AI05-0087, but
2340 -- is not caught at the point of instantiation in earlier
2341 -- versions.
2343 -- This is wrong, error messages cannot be issued during
2344 -- expansion, since they would be missed in -gnatc mode ???
2346 Error_Msg_N ("assignment not available on limited type", N);
2347 return;
2348 end if;
2350 -- Fetch the primitive op _assign and proper type to call it.
2351 -- Because of possible conflicts between private and full view,
2352 -- fetch the proper type directly from the operation profile.
2354 declare
2355 Op : constant Entity_Id :=
2356 Find_Prim_Op (Typ, Name_uAssign);
2357 F_Typ : Entity_Id := Etype (First_Formal (Op));
2359 begin
2360 -- If the assignment is dispatching, make sure to use the
2361 -- proper type.
2363 if Is_Class_Wide_Type (Typ) then
2364 F_Typ := Class_Wide_Type (F_Typ);
2365 end if;
2367 L := New_List;
2369 -- In case of assignment to a class-wide tagged type, before
2370 -- the assignment we generate run-time check to ensure that
2371 -- the tags of source and target match.
2373 if not Tag_Checks_Suppressed (Typ)
2374 and then Is_Class_Wide_Type (Typ)
2375 and then Is_Tagged_Type (Typ)
2376 and then Is_Tagged_Type (Underlying_Type (Etype (Rhs)))
2377 then
2378 declare
2379 Lhs_Tag : Node_Id;
2380 Rhs_Tag : Node_Id;
2382 begin
2383 if not Is_Interface (Typ) then
2384 Lhs_Tag :=
2385 Make_Selected_Component (Loc,
2386 Prefix => Duplicate_Subexpr (Lhs),
2387 Selector_Name =>
2388 Make_Identifier (Loc, Name_uTag));
2389 Rhs_Tag :=
2390 Make_Selected_Component (Loc,
2391 Prefix => Duplicate_Subexpr (Rhs),
2392 Selector_Name =>
2393 Make_Identifier (Loc, Name_uTag));
2394 else
2395 -- Displace the pointer to the base of the objects
2396 -- applying 'Address, which is later expanded into
2397 -- a call to RE_Base_Address.
2399 Lhs_Tag :=
2400 Make_Explicit_Dereference (Loc,
2401 Prefix =>
2402 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
2403 Make_Attribute_Reference (Loc,
2404 Prefix => Duplicate_Subexpr (Lhs),
2405 Attribute_Name => Name_Address)));
2406 Rhs_Tag :=
2407 Make_Explicit_Dereference (Loc,
2408 Prefix =>
2409 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
2410 Make_Attribute_Reference (Loc,
2411 Prefix => Duplicate_Subexpr (Rhs),
2412 Attribute_Name => Name_Address)));
2413 end if;
2415 Append_To (L,
2416 Make_Raise_Constraint_Error (Loc,
2417 Condition =>
2418 Make_Op_Ne (Loc,
2419 Left_Opnd => Lhs_Tag,
2420 Right_Opnd => Rhs_Tag),
2421 Reason => CE_Tag_Check_Failed));
2422 end;
2423 end if;
2425 declare
2426 Left_N : Node_Id := Duplicate_Subexpr (Lhs);
2427 Right_N : Node_Id := Duplicate_Subexpr (Rhs);
2429 begin
2430 -- In order to dispatch the call to _assign the type of
2431 -- the actuals must match. Add conversion (if required).
2433 if Etype (Lhs) /= F_Typ then
2434 Left_N := Unchecked_Convert_To (F_Typ, Left_N);
2435 end if;
2437 if Etype (Rhs) /= F_Typ then
2438 Right_N := Unchecked_Convert_To (F_Typ, Right_N);
2439 end if;
2441 Append_To (L,
2442 Make_Procedure_Call_Statement (Loc,
2443 Name => New_Occurrence_Of (Op, Loc),
2444 Parameter_Associations => New_List (
2445 Node1 => Left_N,
2446 Node2 => Right_N)));
2447 end;
2448 end;
2450 else
2451 L := Make_Tag_Ctrl_Assignment (N);
2453 -- We can't afford to have destructive Finalization Actions in
2454 -- the Self assignment case, so if the target and the source
2455 -- are not obviously different, code is generated to avoid the
2456 -- self assignment case:
2458 -- if lhs'address /= rhs'address then
2459 -- <code for controlled and/or tagged assignment>
2460 -- end if;
2462 -- Skip this if Restriction (No_Finalization) is active
2464 if not Statically_Different (Lhs, Rhs)
2465 and then Expand_Ctrl_Actions
2466 and then not Restriction_Active (No_Finalization)
2467 then
2468 L := New_List (
2469 Make_Implicit_If_Statement (N,
2470 Condition =>
2471 Make_Op_Ne (Loc,
2472 Left_Opnd =>
2473 Make_Attribute_Reference (Loc,
2474 Prefix => Duplicate_Subexpr (Lhs),
2475 Attribute_Name => Name_Address),
2477 Right_Opnd =>
2478 Make_Attribute_Reference (Loc,
2479 Prefix => Duplicate_Subexpr (Rhs),
2480 Attribute_Name => Name_Address)),
2482 Then_Statements => L));
2483 end if;
2485 -- We need to set up an exception handler for implementing
2486 -- 7.6.1(18). The remaining adjustments are tackled by the
2487 -- implementation of adjust for record_controllers (see
2488 -- s-finimp.adb).
2490 -- This is skipped if we have no finalization
2492 if Expand_Ctrl_Actions
2493 and then not Restriction_Active (No_Finalization)
2494 then
2495 L := New_List (
2496 Make_Block_Statement (Loc,
2497 Handled_Statement_Sequence =>
2498 Make_Handled_Sequence_Of_Statements (Loc,
2499 Statements => L,
2500 Exception_Handlers => New_List (
2501 Make_Handler_For_Ctrl_Operation (Loc)))));
2502 end if;
2503 end if;
2505 Rewrite (N,
2506 Make_Block_Statement (Loc,
2507 Handled_Statement_Sequence =>
2508 Make_Handled_Sequence_Of_Statements (Loc, Statements => L)));
2510 -- If no restrictions on aborts, protect the whole assignment
2511 -- for controlled objects as per 9.8(11).
2513 if Needs_Finalization (Typ)
2514 and then Expand_Ctrl_Actions
2515 and then Abort_Allowed
2516 then
2517 declare
2518 Blk : constant Entity_Id :=
2519 New_Internal_Entity
2520 (E_Block, Current_Scope, Sloc (N), 'B');
2521 AUD : constant Entity_Id := RTE (RE_Abort_Undefer_Direct);
2523 begin
2524 Set_Is_Abort_Block (N);
2526 Set_Scope (Blk, Current_Scope);
2527 Set_Etype (Blk, Standard_Void_Type);
2528 Set_Identifier (N, New_Occurrence_Of (Blk, Sloc (N)));
2530 Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
2531 Set_At_End_Proc (Handled_Statement_Sequence (N),
2532 New_Occurrence_Of (AUD, Loc));
2534 -- Present the Abort_Undefer_Direct function to the backend
2535 -- so that it can inline the call to the function.
2537 Add_Inlined_Body (AUD, N);
2539 Expand_At_End_Handler
2540 (Handled_Statement_Sequence (N), Blk);
2541 end;
2542 end if;
2544 -- N has been rewritten to a block statement for which it is
2545 -- known by construction that no checks are necessary: analyze
2546 -- it with all checks suppressed.
2548 Analyze (N, Suppress => All_Checks);
2549 return;
2550 end Tagged_Case;
2552 -- Array types
2554 elsif Is_Array_Type (Typ) then
2555 declare
2556 Actual_Rhs : Node_Id := Rhs;
2558 begin
2559 while Nkind_In (Actual_Rhs, N_Type_Conversion,
2560 N_Qualified_Expression)
2561 loop
2562 Actual_Rhs := Expression (Actual_Rhs);
2563 end loop;
2565 Expand_Assign_Array (N, Actual_Rhs);
2566 return;
2567 end;
2569 -- Record types
2571 elsif Is_Record_Type (Typ) then
2572 Expand_Assign_Record (N);
2573 return;
2575 -- Scalar types. This is where we perform the processing related to the
2576 -- requirements of (RM 13.9.1(9-11)) concerning the handling of invalid
2577 -- scalar values.
2579 elsif Is_Scalar_Type (Typ) then
2581 -- Case where right side is known valid
2583 if Expr_Known_Valid (Rhs) then
2585 -- Here the right side is valid, so it is fine. The case to deal
2586 -- with is when the left side is a local variable reference whose
2587 -- value is not currently known to be valid. If this is the case,
2588 -- and the assignment appears in an unconditional context, then
2589 -- we can mark the left side as now being valid if one of these
2590 -- conditions holds:
2592 -- The expression of the right side has Do_Range_Check set so
2593 -- that we know a range check will be performed. Note that it
2594 -- can be the case that a range check is omitted because we
2595 -- make the assumption that we can assume validity for operands
2596 -- appearing in the right side in determining whether a range
2597 -- check is required
2599 -- The subtype of the right side matches the subtype of the
2600 -- left side. In this case, even though we have not checked
2601 -- the range of the right side, we know it is in range of its
2602 -- subtype if the expression is valid.
2604 if Is_Local_Variable_Reference (Lhs)
2605 and then not Is_Known_Valid (Entity (Lhs))
2606 and then In_Unconditional_Context (N)
2607 then
2608 if Do_Range_Check (Rhs)
2609 or else Etype (Lhs) = Etype (Rhs)
2610 then
2611 Set_Is_Known_Valid (Entity (Lhs), True);
2612 end if;
2613 end if;
2615 -- Case where right side may be invalid in the sense of the RM
2616 -- reference above. The RM does not require that we check for the
2617 -- validity on an assignment, but it does require that the assignment
2618 -- of an invalid value not cause erroneous behavior.
2620 -- The general approach in GNAT is to use the Is_Known_Valid flag
2621 -- to avoid the need for validity checking on assignments. However
2622 -- in some cases, we have to do validity checking in order to make
2623 -- sure that the setting of this flag is correct.
2625 else
2626 -- Validate right side if we are validating copies
2628 if Validity_Checks_On
2629 and then Validity_Check_Copies
2630 then
2631 -- Skip this if left-hand side is an array or record component
2632 -- and elementary component validity checks are suppressed.
2634 if Nkind_In (Lhs, N_Selected_Component, N_Indexed_Component)
2635 and then not Validity_Check_Components
2636 then
2637 null;
2638 else
2639 Ensure_Valid (Rhs);
2640 end if;
2642 -- We can propagate this to the left side where appropriate
2644 if Is_Local_Variable_Reference (Lhs)
2645 and then not Is_Known_Valid (Entity (Lhs))
2646 and then In_Unconditional_Context (N)
2647 then
2648 Set_Is_Known_Valid (Entity (Lhs), True);
2649 end if;
2651 -- Otherwise check to see what should be done
2653 -- If left side is a local variable, then we just set its flag to
2654 -- indicate that its value may no longer be valid, since we are
2655 -- copying a potentially invalid value.
2657 elsif Is_Local_Variable_Reference (Lhs) then
2658 Set_Is_Known_Valid (Entity (Lhs), False);
2660 -- Check for case of a nonlocal variable on the left side which
2661 -- is currently known to be valid. In this case, we simply ensure
2662 -- that the right side is valid. We only play the game of copying
2663 -- validity status for local variables, since we are doing this
2664 -- statically, not by tracing the full flow graph.
2666 elsif Is_Entity_Name (Lhs)
2667 and then Is_Known_Valid (Entity (Lhs))
2668 then
2669 -- Note: If Validity_Checking mode is set to none, we ignore
2670 -- the Ensure_Valid call so don't worry about that case here.
2672 Ensure_Valid (Rhs);
2674 -- In all other cases, we can safely copy an invalid value without
2675 -- worrying about the status of the left side. Since it is not a
2676 -- variable reference it will not be considered
2677 -- as being known to be valid in any case.
2679 else
2680 null;
2681 end if;
2682 end if;
2683 end if;
2685 exception
2686 when RE_Not_Available =>
2687 return;
2688 end Expand_N_Assignment_Statement;
2690 ------------------------------
2691 -- Expand_N_Block_Statement --
2692 ------------------------------
2694 -- Encode entity names defined in block statement
2696 procedure Expand_N_Block_Statement (N : Node_Id) is
2697 begin
2698 Qualify_Entity_Names (N);
2699 end Expand_N_Block_Statement;
2701 -----------------------------
2702 -- Expand_N_Case_Statement --
2703 -----------------------------
2705 procedure Expand_N_Case_Statement (N : Node_Id) is
2706 Loc : constant Source_Ptr := Sloc (N);
2707 Expr : constant Node_Id := Expression (N);
2708 Alt : Node_Id;
2709 Len : Nat;
2710 Cond : Node_Id;
2711 Choice : Node_Id;
2712 Chlist : List_Id;
2714 begin
2715 -- Check for the situation where we know at compile time which branch
2716 -- will be taken.
2718 -- If the value is static but its subtype is predicated and the value
2719 -- does not obey the predicate, the value is marked non-static, and
2720 -- there can be no corresponding static alternative. In that case we
2721 -- replace the case statement with an exception, regardless of whether
2722 -- assertions are enabled or not, unless predicates are ignored.
2724 if Compile_Time_Known_Value (Expr)
2725 and then Has_Predicates (Etype (Expr))
2726 and then not Predicates_Ignored (Etype (Expr))
2727 and then not Is_OK_Static_Expression (Expr)
2728 then
2729 Rewrite (N,
2730 Make_Raise_Constraint_Error (Loc, Reason => CE_Invalid_Data));
2731 Analyze (N);
2732 return;
2734 elsif Compile_Time_Known_Value (Expr)
2735 and then (not Has_Predicates (Etype (Expr))
2736 or else Is_Static_Expression (Expr))
2737 then
2738 Alt := Find_Static_Alternative (N);
2740 -- Do not consider controlled objects found in a case statement which
2741 -- actually models a case expression because their early finalization
2742 -- will affect the result of the expression.
2744 if not From_Conditional_Expression (N) then
2745 Process_Statements_For_Controlled_Objects (Alt);
2746 end if;
2748 -- Move statements from this alternative after the case statement.
2749 -- They are already analyzed, so will be skipped by the analyzer.
2751 Insert_List_After (N, Statements (Alt));
2753 -- That leaves the case statement as a shell. So now we can kill all
2754 -- other alternatives in the case statement.
2756 Kill_Dead_Code (Expression (N));
2758 declare
2759 Dead_Alt : Node_Id;
2761 begin
2762 -- Loop through case alternatives, skipping pragmas, and skipping
2763 -- the one alternative that we select (and therefore retain).
2765 Dead_Alt := First (Alternatives (N));
2766 while Present (Dead_Alt) loop
2767 if Dead_Alt /= Alt
2768 and then Nkind (Dead_Alt) = N_Case_Statement_Alternative
2769 then
2770 Kill_Dead_Code (Statements (Dead_Alt), Warn_On_Deleted_Code);
2771 end if;
2773 Next (Dead_Alt);
2774 end loop;
2775 end;
2777 Rewrite (N, Make_Null_Statement (Loc));
2778 return;
2779 end if;
2781 -- Here if the choice is not determined at compile time
2783 declare
2784 Last_Alt : constant Node_Id := Last (Alternatives (N));
2786 Others_Present : Boolean;
2787 Others_Node : Node_Id;
2789 Then_Stms : List_Id;
2790 Else_Stms : List_Id;
2792 begin
2793 if Nkind (First (Discrete_Choices (Last_Alt))) = N_Others_Choice then
2794 Others_Present := True;
2795 Others_Node := Last_Alt;
2796 else
2797 Others_Present := False;
2798 end if;
2800 -- First step is to worry about possible invalid argument. The RM
2801 -- requires (RM 5.4(13)) that if the result is invalid (e.g. it is
2802 -- outside the base range), then Constraint_Error must be raised.
2804 -- Case of validity check required (validity checks are on, the
2805 -- expression is not known to be valid, and the case statement
2806 -- comes from source -- no need to validity check internally
2807 -- generated case statements).
2809 if Validity_Check_Default
2810 and then not Predicates_Ignored (Etype (Expr))
2811 then
2812 Ensure_Valid (Expr);
2813 end if;
2815 -- If there is only a single alternative, just replace it with the
2816 -- sequence of statements since obviously that is what is going to
2817 -- be executed in all cases.
2819 Len := List_Length (Alternatives (N));
2821 if Len = 1 then
2823 -- We still need to evaluate the expression if it has any side
2824 -- effects.
2826 Remove_Side_Effects (Expression (N));
2827 Alt := First (Alternatives (N));
2829 -- Do not consider controlled objects found in a case statement
2830 -- which actually models a case expression because their early
2831 -- finalization will affect the result of the expression.
2833 if not From_Conditional_Expression (N) then
2834 Process_Statements_For_Controlled_Objects (Alt);
2835 end if;
2837 Insert_List_After (N, Statements (Alt));
2839 -- That leaves the case statement as a shell. The alternative that
2840 -- will be executed is reset to a null list. So now we can kill
2841 -- the entire case statement.
2843 Kill_Dead_Code (Expression (N));
2844 Rewrite (N, Make_Null_Statement (Loc));
2845 return;
2847 -- An optimization. If there are only two alternatives, and only
2848 -- a single choice, then rewrite the whole case statement as an
2849 -- if statement, since this can result in subsequent optimizations.
2850 -- This helps not only with case statements in the source of a
2851 -- simple form, but also with generated code (discriminant check
2852 -- functions in particular).
2854 -- Note: it is OK to do this before expanding out choices for any
2855 -- static predicates, since the if statement processing will handle
2856 -- the static predicate case fine.
2858 elsif Len = 2 then
2859 Chlist := Discrete_Choices (First (Alternatives (N)));
2861 if List_Length (Chlist) = 1 then
2862 Choice := First (Chlist);
2864 Then_Stms := Statements (First (Alternatives (N)));
2865 Else_Stms := Statements (Last (Alternatives (N)));
2867 -- For TRUE, generate "expression", not expression = true
2869 if Nkind (Choice) = N_Identifier
2870 and then Entity (Choice) = Standard_True
2871 then
2872 Cond := Expression (N);
2874 -- For FALSE, generate "expression" and switch then/else
2876 elsif Nkind (Choice) = N_Identifier
2877 and then Entity (Choice) = Standard_False
2878 then
2879 Cond := Expression (N);
2880 Else_Stms := Statements (First (Alternatives (N)));
2881 Then_Stms := Statements (Last (Alternatives (N)));
2883 -- For a range, generate "expression in range"
2885 elsif Nkind (Choice) = N_Range
2886 or else (Nkind (Choice) = N_Attribute_Reference
2887 and then Attribute_Name (Choice) = Name_Range)
2888 or else (Is_Entity_Name (Choice)
2889 and then Is_Type (Entity (Choice)))
2890 then
2891 Cond :=
2892 Make_In (Loc,
2893 Left_Opnd => Expression (N),
2894 Right_Opnd => Relocate_Node (Choice));
2896 -- A subtype indication is not a legal operator in a membership
2897 -- test, so retrieve its range.
2899 elsif Nkind (Choice) = N_Subtype_Indication then
2900 Cond :=
2901 Make_In (Loc,
2902 Left_Opnd => Expression (N),
2903 Right_Opnd =>
2904 Relocate_Node
2905 (Range_Expression (Constraint (Choice))));
2907 -- For any other subexpression "expression = value"
2909 else
2910 Cond :=
2911 Make_Op_Eq (Loc,
2912 Left_Opnd => Expression (N),
2913 Right_Opnd => Relocate_Node (Choice));
2914 end if;
2916 -- Now rewrite the case as an IF
2918 Rewrite (N,
2919 Make_If_Statement (Loc,
2920 Condition => Cond,
2921 Then_Statements => Then_Stms,
2922 Else_Statements => Else_Stms));
2923 Analyze (N);
2924 return;
2925 end if;
2926 end if;
2928 -- If the last alternative is not an Others choice, replace it with
2929 -- an N_Others_Choice. Note that we do not bother to call Analyze on
2930 -- the modified case statement, since it's only effect would be to
2931 -- compute the contents of the Others_Discrete_Choices which is not
2932 -- needed by the back end anyway.
2934 -- The reason for this is that the back end always needs some default
2935 -- for a switch, so if we have not supplied one in the processing
2936 -- above for validity checking, then we need to supply one here.
2938 if not Others_Present then
2939 Others_Node := Make_Others_Choice (Sloc (Last_Alt));
2941 -- If Predicates_Ignored is true the value does not satisfy the
2942 -- predicate, and there is no Others choice, Constraint_Error
2943 -- must be raised (4.5.7 (21/3)).
2945 if Predicates_Ignored (Etype (Expr)) then
2946 declare
2947 Except : constant Node_Id :=
2948 Make_Raise_Constraint_Error (Loc,
2949 Reason => CE_Invalid_Data);
2950 New_Alt : constant Node_Id :=
2951 Make_Case_Statement_Alternative (Loc,
2952 Discrete_Choices => New_List (
2953 Make_Others_Choice (Loc)),
2954 Statements => New_List (Except));
2956 begin
2957 Append (New_Alt, Alternatives (N));
2958 Analyze_And_Resolve (Except);
2959 end;
2961 else
2962 Set_Others_Discrete_Choices
2963 (Others_Node, Discrete_Choices (Last_Alt));
2964 Set_Discrete_Choices (Last_Alt, New_List (Others_Node));
2965 end if;
2967 end if;
2969 -- Deal with possible declarations of controlled objects, and also
2970 -- with rewriting choice sequences for static predicate references.
2972 Alt := First_Non_Pragma (Alternatives (N));
2973 while Present (Alt) loop
2975 -- Do not consider controlled objects found in a case statement
2976 -- which actually models a case expression because their early
2977 -- finalization will affect the result of the expression.
2979 if not From_Conditional_Expression (N) then
2980 Process_Statements_For_Controlled_Objects (Alt);
2981 end if;
2983 if Has_SP_Choice (Alt) then
2984 Expand_Static_Predicates_In_Choices (Alt);
2985 end if;
2987 Next_Non_Pragma (Alt);
2988 end loop;
2989 end;
2990 end Expand_N_Case_Statement;
2992 -----------------------------
2993 -- Expand_N_Exit_Statement --
2994 -----------------------------
2996 -- The only processing required is to deal with a possible C/Fortran
2997 -- boolean value used as the condition for the exit statement.
2999 procedure Expand_N_Exit_Statement (N : Node_Id) is
3000 begin
3001 Adjust_Condition (Condition (N));
3002 end Expand_N_Exit_Statement;
3004 ----------------------------------
3005 -- Expand_Formal_Container_Loop --
3006 ----------------------------------
3008 procedure Expand_Formal_Container_Loop (N : Node_Id) is
3009 Loc : constant Source_Ptr := Sloc (N);
3010 Isc : constant Node_Id := Iteration_Scheme (N);
3011 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3012 Cursor : constant Entity_Id := Defining_Identifier (I_Spec);
3013 Container : constant Node_Id := Entity (Name (I_Spec));
3014 Stats : constant List_Id := Statements (N);
3016 Advance : Node_Id;
3017 Blk_Nod : Node_Id;
3018 Init : Node_Id;
3019 New_Loop : Node_Id;
3021 begin
3022 -- The expansion resembles the one for Ada containers, but the
3023 -- primitives mention the domain of iteration explicitly, and
3024 -- function First applied to the container yields a cursor directly.
3026 -- Cursor : Cursor_type := First (Container);
3027 -- while Has_Element (Cursor, Container) loop
3028 -- <original loop statements>
3029 -- Cursor := Next (Container, Cursor);
3030 -- end loop;
3032 Build_Formal_Container_Iteration
3033 (N, Container, Cursor, Init, Advance, New_Loop);
3035 Set_Ekind (Cursor, E_Variable);
3036 Append_To (Stats, Advance);
3038 -- Build block to capture declaration of cursor entity.
3040 Blk_Nod :=
3041 Make_Block_Statement (Loc,
3042 Declarations => New_List (Init),
3043 Handled_Statement_Sequence =>
3044 Make_Handled_Sequence_Of_Statements (Loc,
3045 Statements => New_List (New_Loop)));
3047 Rewrite (N, Blk_Nod);
3048 Analyze (N);
3049 end Expand_Formal_Container_Loop;
3051 ------------------------------------------
3052 -- Expand_Formal_Container_Element_Loop --
3053 ------------------------------------------
3055 procedure Expand_Formal_Container_Element_Loop (N : Node_Id) is
3056 Loc : constant Source_Ptr := Sloc (N);
3057 Isc : constant Node_Id := Iteration_Scheme (N);
3058 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3059 Element : constant Entity_Id := Defining_Identifier (I_Spec);
3060 Container : constant Node_Id := Entity (Name (I_Spec));
3061 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
3062 Stats : constant List_Id := Statements (N);
3064 Cursor : constant Entity_Id :=
3065 Make_Defining_Identifier (Loc,
3066 Chars => New_External_Name (Chars (Element), 'C'));
3067 Elmt_Decl : Node_Id;
3068 Elmt_Ref : Node_Id;
3070 Element_Op : constant Entity_Id :=
3071 Get_Iterable_Type_Primitive (Container_Typ, Name_Element);
3073 Advance : Node_Id;
3074 Init : Node_Id;
3075 New_Loop : Node_Id;
3077 begin
3078 -- For an element iterator, the Element aspect must be present,
3079 -- (this is checked during analysis) and the expansion takes the form:
3081 -- Cursor : Cursor_Type := First (Container);
3082 -- Elmt : Element_Type;
3083 -- while Has_Element (Cursor, Container) loop
3084 -- Elmt := Element (Container, Cursor);
3085 -- <original loop statements>
3086 -- Cursor := Next (Container, Cursor);
3087 -- end loop;
3089 -- However this expansion is not legal if the element is indefinite.
3090 -- In that case we create a block to hold a variable declaration
3091 -- initialized with a call to Element, and generate:
3093 -- Cursor : Cursor_Type := First (Container);
3094 -- while Has_Element (Cursor, Container) loop
3095 -- declare
3096 -- Elmt : Element_Type := Element (Container, Cursor);
3097 -- begin
3098 -- <original loop statements>
3099 -- Cursor := Next (Container, Cursor);
3100 -- end;
3101 -- end loop;
3103 Build_Formal_Container_Iteration
3104 (N, Container, Cursor, Init, Advance, New_Loop);
3105 Append_To (Stats, Advance);
3107 Set_Ekind (Cursor, E_Variable);
3108 Insert_Action (N, Init);
3110 -- Declaration for Element
3112 Elmt_Decl :=
3113 Make_Object_Declaration (Loc,
3114 Defining_Identifier => Element,
3115 Object_Definition => New_Occurrence_Of (Etype (Element_Op), Loc));
3117 if not Is_Constrained (Etype (Element_Op)) then
3118 Set_Expression (Elmt_Decl,
3119 Make_Function_Call (Loc,
3120 Name => New_Occurrence_Of (Element_Op, Loc),
3121 Parameter_Associations => New_List (
3122 New_Occurrence_Of (Container, Loc),
3123 New_Occurrence_Of (Cursor, Loc))));
3125 Set_Statements (New_Loop,
3126 New_List
3127 (Make_Block_Statement (Loc,
3128 Declarations => New_List (Elmt_Decl),
3129 Handled_Statement_Sequence =>
3130 Make_Handled_Sequence_Of_Statements (Loc,
3131 Statements => Stats))));
3133 else
3134 Elmt_Ref :=
3135 Make_Assignment_Statement (Loc,
3136 Name => New_Occurrence_Of (Element, Loc),
3137 Expression =>
3138 Make_Function_Call (Loc,
3139 Name => New_Occurrence_Of (Element_Op, Loc),
3140 Parameter_Associations => New_List (
3141 New_Occurrence_Of (Container, Loc),
3142 New_Occurrence_Of (Cursor, Loc))));
3144 Prepend (Elmt_Ref, Stats);
3146 -- The element is assignable in the expanded code
3148 Set_Assignment_OK (Name (Elmt_Ref));
3150 -- The loop is rewritten as a block, to hold the element declaration
3152 New_Loop :=
3153 Make_Block_Statement (Loc,
3154 Declarations => New_List (Elmt_Decl),
3155 Handled_Statement_Sequence =>
3156 Make_Handled_Sequence_Of_Statements (Loc,
3157 Statements => New_List (New_Loop)));
3158 end if;
3160 -- The element is only modified in expanded code, so it appears as
3161 -- unassigned to the warning machinery. We must suppress this spurious
3162 -- warning explicitly.
3164 Set_Warnings_Off (Element);
3166 Rewrite (N, New_Loop);
3168 -- The loop parameter is declared by an object declaration, but within
3169 -- the loop we must prevent user assignments to it, so we analyze the
3170 -- declaration and reset the entity kind, before analyzing the rest of
3171 -- the loop;
3173 Analyze (Elmt_Decl);
3174 Set_Ekind (Defining_Identifier (Elmt_Decl), E_Loop_Parameter);
3176 Analyze (N);
3177 end Expand_Formal_Container_Element_Loop;
3179 -----------------------------
3180 -- Expand_N_Goto_Statement --
3181 -----------------------------
3183 -- Add poll before goto if polling active
3185 procedure Expand_N_Goto_Statement (N : Node_Id) is
3186 begin
3187 Generate_Poll_Call (N);
3188 end Expand_N_Goto_Statement;
3190 ---------------------------
3191 -- Expand_N_If_Statement --
3192 ---------------------------
3194 -- First we deal with the case of C and Fortran convention boolean values,
3195 -- with zero/non-zero semantics.
3197 -- Second, we deal with the obvious rewriting for the cases where the
3198 -- condition of the IF is known at compile time to be True or False.
3200 -- Third, we remove elsif parts which have non-empty Condition_Actions and
3201 -- rewrite as independent if statements. For example:
3203 -- if x then xs
3204 -- elsif y then ys
3205 -- ...
3206 -- end if;
3208 -- becomes
3210 -- if x then xs
3211 -- else
3212 -- <<condition actions of y>>
3213 -- if y then ys
3214 -- ...
3215 -- end if;
3216 -- end if;
3218 -- This rewriting is needed if at least one elsif part has a non-empty
3219 -- Condition_Actions list. We also do the same processing if there is a
3220 -- constant condition in an elsif part (in conjunction with the first
3221 -- processing step mentioned above, for the recursive call made to deal
3222 -- with the created inner if, this deals with properly optimizing the
3223 -- cases of constant elsif conditions).
3225 procedure Expand_N_If_Statement (N : Node_Id) is
3226 Loc : constant Source_Ptr := Sloc (N);
3227 Hed : Node_Id;
3228 E : Node_Id;
3229 New_If : Node_Id;
3231 Warn_If_Deleted : constant Boolean :=
3232 Warn_On_Deleted_Code and then Comes_From_Source (N);
3233 -- Indicates whether we want warnings when we delete branches of the
3234 -- if statement based on constant condition analysis. We never want
3235 -- these warnings for expander generated code.
3237 begin
3238 -- Do not consider controlled objects found in an if statement which
3239 -- actually models an if expression because their early finalization
3240 -- will affect the result of the expression.
3242 if not From_Conditional_Expression (N) then
3243 Process_Statements_For_Controlled_Objects (N);
3244 end if;
3246 Adjust_Condition (Condition (N));
3248 -- The following loop deals with constant conditions for the IF. We
3249 -- need a loop because as we eliminate False conditions, we grab the
3250 -- first elsif condition and use it as the primary condition.
3252 while Compile_Time_Known_Value (Condition (N)) loop
3254 -- If condition is True, we can simply rewrite the if statement now
3255 -- by replacing it by the series of then statements.
3257 if Is_True (Expr_Value (Condition (N))) then
3259 -- All the else parts can be killed
3261 Kill_Dead_Code (Elsif_Parts (N), Warn_If_Deleted);
3262 Kill_Dead_Code (Else_Statements (N), Warn_If_Deleted);
3264 Hed := Remove_Head (Then_Statements (N));
3265 Insert_List_After (N, Then_Statements (N));
3266 Rewrite (N, Hed);
3267 return;
3269 -- If condition is False, then we can delete the condition and
3270 -- the Then statements
3272 else
3273 -- We do not delete the condition if constant condition warnings
3274 -- are enabled, since otherwise we end up deleting the desired
3275 -- warning. Of course the backend will get rid of this True/False
3276 -- test anyway, so nothing is lost here.
3278 if not Constant_Condition_Warnings then
3279 Kill_Dead_Code (Condition (N));
3280 end if;
3282 Kill_Dead_Code (Then_Statements (N), Warn_If_Deleted);
3284 -- If there are no elsif statements, then we simply replace the
3285 -- entire if statement by the sequence of else statements.
3287 if No (Elsif_Parts (N)) then
3288 if No (Else_Statements (N))
3289 or else Is_Empty_List (Else_Statements (N))
3290 then
3291 Rewrite (N,
3292 Make_Null_Statement (Sloc (N)));
3293 else
3294 Hed := Remove_Head (Else_Statements (N));
3295 Insert_List_After (N, Else_Statements (N));
3296 Rewrite (N, Hed);
3297 end if;
3299 return;
3301 -- If there are elsif statements, the first of them becomes the
3302 -- if/then section of the rebuilt if statement This is the case
3303 -- where we loop to reprocess this copied condition.
3305 else
3306 Hed := Remove_Head (Elsif_Parts (N));
3307 Insert_Actions (N, Condition_Actions (Hed));
3308 Set_Condition (N, Condition (Hed));
3309 Set_Then_Statements (N, Then_Statements (Hed));
3311 -- Hed might have been captured as the condition determining
3312 -- the current value for an entity. Now it is detached from
3313 -- the tree, so a Current_Value pointer in the condition might
3314 -- need to be updated.
3316 Set_Current_Value_Condition (N);
3318 if Is_Empty_List (Elsif_Parts (N)) then
3319 Set_Elsif_Parts (N, No_List);
3320 end if;
3321 end if;
3322 end if;
3323 end loop;
3325 -- Loop through elsif parts, dealing with constant conditions and
3326 -- possible condition actions that are present.
3328 if Present (Elsif_Parts (N)) then
3329 E := First (Elsif_Parts (N));
3330 while Present (E) loop
3332 -- Do not consider controlled objects found in an if statement
3333 -- which actually models an if expression because their early
3334 -- finalization will affect the result of the expression.
3336 if not From_Conditional_Expression (N) then
3337 Process_Statements_For_Controlled_Objects (E);
3338 end if;
3340 Adjust_Condition (Condition (E));
3342 -- If there are condition actions, then rewrite the if statement
3343 -- as indicated above. We also do the same rewrite for a True or
3344 -- False condition. The further processing of this constant
3345 -- condition is then done by the recursive call to expand the
3346 -- newly created if statement
3348 if Present (Condition_Actions (E))
3349 or else Compile_Time_Known_Value (Condition (E))
3350 then
3351 New_If :=
3352 Make_If_Statement (Sloc (E),
3353 Condition => Condition (E),
3354 Then_Statements => Then_Statements (E),
3355 Elsif_Parts => No_List,
3356 Else_Statements => Else_Statements (N));
3358 -- Elsif parts for new if come from remaining elsif's of parent
3360 while Present (Next (E)) loop
3361 if No (Elsif_Parts (New_If)) then
3362 Set_Elsif_Parts (New_If, New_List);
3363 end if;
3365 Append (Remove_Next (E), Elsif_Parts (New_If));
3366 end loop;
3368 Set_Else_Statements (N, New_List (New_If));
3370 if Present (Condition_Actions (E)) then
3371 Insert_List_Before (New_If, Condition_Actions (E));
3372 end if;
3374 Remove (E);
3376 if Is_Empty_List (Elsif_Parts (N)) then
3377 Set_Elsif_Parts (N, No_List);
3378 end if;
3380 Analyze (New_If);
3382 -- Note this is not an implicit if statement, since it is part
3383 -- of an explicit if statement in the source (or of an implicit
3384 -- if statement that has already been tested). We set the flag
3385 -- after calling Analyze to avoid generating extra warnings
3386 -- specific to pure if statements, however (see
3387 -- Sem_Ch5.Analyze_If_Statement).
3389 Set_Comes_From_Source (New_If, Comes_From_Source (N));
3390 return;
3392 -- No special processing for that elsif part, move to next
3394 else
3395 Next (E);
3396 end if;
3397 end loop;
3398 end if;
3400 -- Some more optimizations applicable if we still have an IF statement
3402 if Nkind (N) /= N_If_Statement then
3403 return;
3404 end if;
3406 -- Another optimization, special cases that can be simplified
3408 -- if expression then
3409 -- return true;
3410 -- else
3411 -- return false;
3412 -- end if;
3414 -- can be changed to:
3416 -- return expression;
3418 -- and
3420 -- if expression then
3421 -- return false;
3422 -- else
3423 -- return true;
3424 -- end if;
3426 -- can be changed to:
3428 -- return not (expression);
3430 -- Only do these optimizations if we are at least at -O1 level and
3431 -- do not do them if control flow optimizations are suppressed.
3433 if Optimization_Level > 0
3434 and then not Opt.Suppress_Control_Flow_Optimizations
3435 then
3436 if Nkind (N) = N_If_Statement
3437 and then No (Elsif_Parts (N))
3438 and then Present (Else_Statements (N))
3439 and then List_Length (Then_Statements (N)) = 1
3440 and then List_Length (Else_Statements (N)) = 1
3441 then
3442 declare
3443 Then_Stm : constant Node_Id := First (Then_Statements (N));
3444 Else_Stm : constant Node_Id := First (Else_Statements (N));
3446 begin
3447 if Nkind (Then_Stm) = N_Simple_Return_Statement
3448 and then
3449 Nkind (Else_Stm) = N_Simple_Return_Statement
3450 then
3451 declare
3452 Then_Expr : constant Node_Id := Expression (Then_Stm);
3453 Else_Expr : constant Node_Id := Expression (Else_Stm);
3455 begin
3456 if Nkind (Then_Expr) = N_Identifier
3457 and then
3458 Nkind (Else_Expr) = N_Identifier
3459 then
3460 if Entity (Then_Expr) = Standard_True
3461 and then Entity (Else_Expr) = Standard_False
3462 then
3463 Rewrite (N,
3464 Make_Simple_Return_Statement (Loc,
3465 Expression => Relocate_Node (Condition (N))));
3466 Analyze (N);
3467 return;
3469 elsif Entity (Then_Expr) = Standard_False
3470 and then Entity (Else_Expr) = Standard_True
3471 then
3472 Rewrite (N,
3473 Make_Simple_Return_Statement (Loc,
3474 Expression =>
3475 Make_Op_Not (Loc,
3476 Right_Opnd =>
3477 Relocate_Node (Condition (N)))));
3478 Analyze (N);
3479 return;
3480 end if;
3481 end if;
3482 end;
3483 end if;
3484 end;
3485 end if;
3486 end if;
3487 end Expand_N_If_Statement;
3489 --------------------------
3490 -- Expand_Iterator_Loop --
3491 --------------------------
3493 procedure Expand_Iterator_Loop (N : Node_Id) is
3494 Isc : constant Node_Id := Iteration_Scheme (N);
3495 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3497 Container : constant Node_Id := Name (I_Spec);
3498 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
3500 begin
3501 -- Processing for arrays
3503 if Is_Array_Type (Container_Typ) then
3504 pragma Assert (Of_Present (I_Spec));
3505 Expand_Iterator_Loop_Over_Array (N);
3507 elsif Has_Aspect (Container_Typ, Aspect_Iterable) then
3508 if Of_Present (I_Spec) then
3509 Expand_Formal_Container_Element_Loop (N);
3510 else
3511 Expand_Formal_Container_Loop (N);
3512 end if;
3514 -- Processing for containers
3516 else
3517 Expand_Iterator_Loop_Over_Container
3518 (N, Isc, I_Spec, Container, Container_Typ);
3519 end if;
3520 end Expand_Iterator_Loop;
3522 -------------------------------------
3523 -- Expand_Iterator_Loop_Over_Array --
3524 -------------------------------------
3526 procedure Expand_Iterator_Loop_Over_Array (N : Node_Id) is
3527 Isc : constant Node_Id := Iteration_Scheme (N);
3528 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3529 Array_Node : constant Node_Id := Name (I_Spec);
3530 Array_Typ : constant Entity_Id := Base_Type (Etype (Array_Node));
3531 Array_Dim : constant Pos := Number_Dimensions (Array_Typ);
3532 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3533 Loc : constant Source_Ptr := Sloc (N);
3534 Stats : constant List_Id := Statements (N);
3535 Core_Loop : Node_Id;
3536 Dim1 : Int;
3537 Ind_Comp : Node_Id;
3538 Iterator : Entity_Id;
3540 -- Start of processing for Expand_Iterator_Loop_Over_Array
3542 begin
3543 -- for Element of Array loop
3545 -- It requires an internally generated cursor to iterate over the array
3547 pragma Assert (Of_Present (I_Spec));
3549 Iterator := Make_Temporary (Loc, 'C');
3551 -- Generate:
3552 -- Element : Component_Type renames Array (Iterator);
3553 -- Iterator is the index value, or a list of index values
3554 -- in the case of a multidimensional array.
3556 Ind_Comp :=
3557 Make_Indexed_Component (Loc,
3558 Prefix => Relocate_Node (Array_Node),
3559 Expressions => New_List (New_Occurrence_Of (Iterator, Loc)));
3561 Prepend_To (Stats,
3562 Make_Object_Renaming_Declaration (Loc,
3563 Defining_Identifier => Id,
3564 Subtype_Mark =>
3565 New_Occurrence_Of (Component_Type (Array_Typ), Loc),
3566 Name => Ind_Comp));
3568 -- Mark the loop variable as needing debug info, so that expansion
3569 -- of the renaming will result in Materialize_Entity getting set via
3570 -- Debug_Renaming_Declaration. (This setting is needed here because
3571 -- the setting in Freeze_Entity comes after the expansion, which is
3572 -- too late. ???)
3574 Set_Debug_Info_Needed (Id);
3576 -- Generate:
3578 -- for Iterator in [reverse] Array'Range (Array_Dim) loop
3579 -- Element : Component_Type renames Array (Iterator);
3580 -- <original loop statements>
3581 -- end loop;
3583 -- If this is an iteration over a multidimensional array, the
3584 -- innermost loop is over the last dimension in Ada, and over
3585 -- the first dimension in Fortran.
3587 if Convention (Array_Typ) = Convention_Fortran then
3588 Dim1 := 1;
3589 else
3590 Dim1 := Array_Dim;
3591 end if;
3593 Core_Loop :=
3594 Make_Loop_Statement (Loc,
3595 Iteration_Scheme =>
3596 Make_Iteration_Scheme (Loc,
3597 Loop_Parameter_Specification =>
3598 Make_Loop_Parameter_Specification (Loc,
3599 Defining_Identifier => Iterator,
3600 Discrete_Subtype_Definition =>
3601 Make_Attribute_Reference (Loc,
3602 Prefix => Relocate_Node (Array_Node),
3603 Attribute_Name => Name_Range,
3604 Expressions => New_List (
3605 Make_Integer_Literal (Loc, Dim1))),
3606 Reverse_Present => Reverse_Present (I_Spec))),
3607 Statements => Stats,
3608 End_Label => Empty);
3610 -- Processing for multidimensional array. The body of each loop is
3611 -- a loop over a previous dimension, going in decreasing order in Ada
3612 -- and in increasing order in Fortran.
3614 if Array_Dim > 1 then
3615 for Dim in 1 .. Array_Dim - 1 loop
3616 if Convention (Array_Typ) = Convention_Fortran then
3617 Dim1 := Dim + 1;
3618 else
3619 Dim1 := Array_Dim - Dim;
3620 end if;
3622 Iterator := Make_Temporary (Loc, 'C');
3624 -- Generate the dimension loops starting from the innermost one
3626 -- for Iterator in [reverse] Array'Range (Array_Dim - Dim) loop
3627 -- <core loop>
3628 -- end loop;
3630 Core_Loop :=
3631 Make_Loop_Statement (Loc,
3632 Iteration_Scheme =>
3633 Make_Iteration_Scheme (Loc,
3634 Loop_Parameter_Specification =>
3635 Make_Loop_Parameter_Specification (Loc,
3636 Defining_Identifier => Iterator,
3637 Discrete_Subtype_Definition =>
3638 Make_Attribute_Reference (Loc,
3639 Prefix => Relocate_Node (Array_Node),
3640 Attribute_Name => Name_Range,
3641 Expressions => New_List (
3642 Make_Integer_Literal (Loc, Dim1))),
3643 Reverse_Present => Reverse_Present (I_Spec))),
3644 Statements => New_List (Core_Loop),
3645 End_Label => Empty);
3647 -- Update the previously created object renaming declaration with
3648 -- the new iterator, by adding the index of the next loop to the
3649 -- indexed component, in the order that corresponds to the
3650 -- convention.
3652 if Convention (Array_Typ) = Convention_Fortran then
3653 Append_To (Expressions (Ind_Comp),
3654 New_Occurrence_Of (Iterator, Loc));
3655 else
3656 Prepend_To (Expressions (Ind_Comp),
3657 New_Occurrence_Of (Iterator, Loc));
3658 end if;
3659 end loop;
3660 end if;
3662 -- Inherit the loop identifier from the original loop. This ensures that
3663 -- the scope stack is consistent after the rewriting.
3665 if Present (Identifier (N)) then
3666 Set_Identifier (Core_Loop, Relocate_Node (Identifier (N)));
3667 end if;
3669 Rewrite (N, Core_Loop);
3670 Analyze (N);
3671 end Expand_Iterator_Loop_Over_Array;
3673 -----------------------------------------
3674 -- Expand_Iterator_Loop_Over_Container --
3675 -----------------------------------------
3677 -- For a 'for ... in' loop, such as:
3679 -- for Cursor in Iterator_Function (...) loop
3680 -- ...
3681 -- end loop;
3683 -- we generate:
3685 -- Iter : Iterator_Type := Iterator_Function (...);
3686 -- Cursor : Cursor_type := First (Iter); -- or Last for "reverse"
3687 -- while Has_Element (Cursor) loop
3688 -- ...
3690 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
3691 -- end loop;
3693 -- For a 'for ... of' loop, such as:
3695 -- for X of Container loop
3696 -- ...
3697 -- end loop;
3699 -- the RM implies the generation of:
3701 -- Iter : Iterator_Type := Container.Iterate; -- the Default_Iterator
3702 -- Cursor : Cursor_Type := First (Iter); -- or Last for "reverse"
3703 -- while Has_Element (Cursor) loop
3704 -- declare
3705 -- X : Element_Type renames Element (Cursor).Element.all;
3706 -- -- or Constant_Element
3707 -- begin
3708 -- ...
3709 -- end;
3710 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
3711 -- end loop;
3713 -- In the general case, we do what the RM says. However, the operations
3714 -- Element and Iter.Next are slow, which is bad inside a loop, because they
3715 -- involve dispatching via interfaces, secondary stack manipulation,
3716 -- Busy/Lock incr/decr, and adjust/finalization/at-end handling. So for the
3717 -- predefined containers, we use an equivalent but optimized expansion.
3719 -- In the optimized case, we make use of these:
3721 -- procedure Next (Position : in out Cursor); -- instead of Iter.Next
3723 -- function Pseudo_Reference
3724 -- (Container : aliased Vector'Class) return Reference_Control_Type;
3726 -- type Element_Access is access all Element_Type;
3728 -- function Get_Element_Access
3729 -- (Position : Cursor) return not null Element_Access;
3731 -- Next is declared in the visible part of the container packages.
3732 -- The other three are added in the private part. (We're not supposed to
3733 -- pollute the namespace for clients. The compiler has no trouble breaking
3734 -- privacy to call things in the private part of an instance.)
3736 -- Source:
3738 -- for X of My_Vector loop
3739 -- X.Count := X.Count + 1;
3740 -- ...
3741 -- end loop;
3743 -- The compiler will generate:
3745 -- Iter : Reversible_Iterator'Class := Iterate (My_Vector);
3746 -- -- Reversible_Iterator is an interface. Iterate is the
3747 -- -- Default_Iterator aspect of Vector. This increments Lock,
3748 -- -- disallowing tampering with cursors. Unfortunately, it does not
3749 -- -- increment Busy. The result of Iterate is Limited_Controlled;
3750 -- -- finalization will decrement Lock. This is a build-in-place
3751 -- -- dispatching call to Iterate.
3753 -- Cur : Cursor := First (Iter); -- or Last
3754 -- -- Dispatching call via interface.
3756 -- Control : Reference_Control_Type := Pseudo_Reference (My_Vector);
3757 -- -- Pseudo_Reference increments Busy, to detect tampering with
3758 -- -- elements, as required by RM. Also redundantly increment
3759 -- -- Lock. Finalization of Control will decrement both Busy and
3760 -- -- Lock. Pseudo_Reference returns a record containing a pointer to
3761 -- -- My_Vector, used by Finalize.
3762 -- --
3763 -- -- Control is not used below, except to finalize it -- it's purely
3764 -- -- an RAII thing. This is needed because we are eliminating the
3765 -- -- call to Reference within the loop.
3767 -- while Has_Element (Cur) loop
3768 -- declare
3769 -- X : My_Element renames Get_Element_Access (Cur).all;
3770 -- -- Get_Element_Access returns a pointer to the element
3771 -- -- designated by Cur. No dispatching here, and no horsing
3772 -- -- around with access discriminants. This is instead of the
3773 -- -- existing
3774 -- --
3775 -- -- X : My_Element renames Reference (Cur).Element.all;
3776 -- --
3777 -- -- which creates a controlled object.
3778 -- begin
3779 -- -- Any attempt to tamper with My_Vector here in the loop
3780 -- -- will correctly raise Program_Error, because of the
3781 -- -- Control.
3783 -- X.Count := X.Count + 1;
3784 -- ...
3786 -- Next (Cur); -- or Prev
3787 -- -- This is instead of "Cur := Next (Iter, Cur);"
3788 -- end;
3789 -- -- No finalization here
3790 -- end loop;
3791 -- Finalize Iter and Control here, decrementing Lock twice and Busy
3792 -- once.
3794 -- This optimization makes "for ... of" loops over 30 times faster in cases
3795 -- measured.
3797 procedure Expand_Iterator_Loop_Over_Container
3798 (N : Node_Id;
3799 Isc : Node_Id;
3800 I_Spec : Node_Id;
3801 Container : Node_Id;
3802 Container_Typ : Entity_Id)
3804 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3805 Elem_Typ : constant Entity_Id := Etype (Id);
3806 Id_Kind : constant Entity_Kind := Ekind (Id);
3807 Loc : constant Source_Ptr := Sloc (N);
3808 Stats : constant List_Id := Statements (N);
3810 Cursor : Entity_Id;
3811 Decl : Node_Id;
3812 Iter_Type : Entity_Id;
3813 Iterator : Entity_Id;
3814 Name_Init : Name_Id;
3815 Name_Step : Name_Id;
3816 New_Loop : Node_Id;
3818 Fast_Element_Access_Op : Entity_Id := Empty;
3819 Fast_Step_Op : Entity_Id := Empty;
3820 -- Only for optimized version of "for ... of"
3822 Iter_Pack : Entity_Id;
3823 -- The package in which the iterator interface is instantiated. This is
3824 -- typically an instance within the container package.
3826 Pack : Entity_Id;
3827 -- The package in which the container type is declared
3829 begin
3830 -- Determine the advancement and initialization steps for the cursor.
3831 -- Analysis of the expanded loop will verify that the container has a
3832 -- reverse iterator.
3834 if Reverse_Present (I_Spec) then
3835 Name_Init := Name_Last;
3836 Name_Step := Name_Previous;
3837 else
3838 Name_Init := Name_First;
3839 Name_Step := Name_Next;
3840 end if;
3842 -- The type of the iterator is the return type of the Iterate function
3843 -- used. For the "of" form this is the default iterator for the type,
3844 -- otherwise it is the type of the explicit function used in the
3845 -- iterator specification. The most common case will be an Iterate
3846 -- function in the container package.
3848 -- The Iterator type is declared in an instance within the container
3849 -- package itself, for example:
3851 -- package Vector_Iterator_Interfaces is new
3852 -- Ada.Iterator_Interfaces (Cursor, Has_Element);
3854 -- If the container type is a derived type, the cursor type is found in
3855 -- the package of the ultimate ancestor type.
3857 if Is_Derived_Type (Container_Typ) then
3858 Pack := Scope (Root_Type (Container_Typ));
3859 else
3860 Pack := Scope (Container_Typ);
3861 end if;
3863 if Of_Present (I_Spec) then
3864 Handle_Of : declare
3865 Container_Arg : Node_Id;
3867 function Get_Default_Iterator
3868 (T : Entity_Id) return Entity_Id;
3869 -- If the container is a derived type, the aspect holds the parent
3870 -- operation. The required one is a primitive of the derived type
3871 -- and is either inherited or overridden. Also sets Container_Arg.
3873 --------------------------
3874 -- Get_Default_Iterator --
3875 --------------------------
3877 function Get_Default_Iterator
3878 (T : Entity_Id) return Entity_Id
3880 Iter : constant Entity_Id :=
3881 Entity (Find_Value_Of_Aspect (T, Aspect_Default_Iterator));
3882 Prim : Elmt_Id;
3883 Op : Entity_Id;
3885 begin
3886 Container_Arg := New_Copy_Tree (Container);
3888 -- A previous version of GNAT allowed indexing aspects to
3889 -- be redefined on derived container types, while the
3890 -- default iterator was inherited from the parent type.
3891 -- This non-standard extension is preserved temporarily for
3892 -- use by the modelling project under debug flag d.X.
3894 if Debug_Flag_Dot_XX then
3895 if Base_Type (Etype (Container)) /=
3896 Base_Type (Etype (First_Formal (Iter)))
3897 then
3898 Container_Arg :=
3899 Make_Type_Conversion (Loc,
3900 Subtype_Mark =>
3901 New_Occurrence_Of
3902 (Etype (First_Formal (Iter)), Loc),
3903 Expression => Container_Arg);
3904 end if;
3906 return Iter;
3908 elsif Is_Derived_Type (T) then
3910 -- The default iterator must be a primitive operation of the
3911 -- type, at the same dispatch slot position. The DT position
3912 -- may not be established if type is not frozen yet.
3914 Prim := First_Elmt (Primitive_Operations (T));
3915 while Present (Prim) loop
3916 Op := Node (Prim);
3918 if Alias (Op) = Iter
3919 or else
3920 (Chars (Op) = Chars (Iter)
3921 and then Present (DTC_Entity (Op))
3922 and then DT_Position (Op) = DT_Position (Iter))
3923 then
3924 return Op;
3925 end if;
3927 Next_Elmt (Prim);
3928 end loop;
3930 -- Default iterator must exist
3932 pragma Assert (False);
3934 -- Otherwise not a derived type
3936 else
3937 return Iter;
3938 end if;
3939 end Get_Default_Iterator;
3941 -- Local variables
3943 Default_Iter : Entity_Id;
3944 Ent : Entity_Id;
3946 Reference_Control_Type : Entity_Id := Empty;
3947 Pseudo_Reference : Entity_Id := Empty;
3949 -- Start of processing for Handle_Of
3951 begin
3952 if Is_Class_Wide_Type (Container_Typ) then
3953 Default_Iter :=
3954 Get_Default_Iterator (Etype (Base_Type (Container_Typ)));
3955 else
3956 Default_Iter := Get_Default_Iterator (Etype (Container));
3957 end if;
3959 Cursor := Make_Temporary (Loc, 'C');
3961 -- For a container element iterator, the iterator type is obtained
3962 -- from the corresponding aspect, whose return type is descended
3963 -- from the corresponding interface type in some instance of
3964 -- Ada.Iterator_Interfaces. The actuals of that instantiation
3965 -- are Cursor and Has_Element.
3967 Iter_Type := Etype (Default_Iter);
3969 -- The iterator type, which is a class-wide type, may itself be
3970 -- derived locally, so the desired instantiation is the scope of
3971 -- the root type of the iterator type.
3973 Iter_Pack := Scope (Root_Type (Etype (Iter_Type)));
3975 -- Find declarations needed for "for ... of" optimization
3977 Ent := First_Entity (Pack);
3978 while Present (Ent) loop
3979 if Chars (Ent) = Name_Get_Element_Access then
3980 Fast_Element_Access_Op := Ent;
3982 elsif Chars (Ent) = Name_Step
3983 and then Ekind (Ent) = E_Procedure
3984 then
3985 Fast_Step_Op := Ent;
3987 elsif Chars (Ent) = Name_Reference_Control_Type then
3988 Reference_Control_Type := Ent;
3990 elsif Chars (Ent) = Name_Pseudo_Reference then
3991 Pseudo_Reference := Ent;
3992 end if;
3994 Next_Entity (Ent);
3995 end loop;
3997 if Present (Reference_Control_Type)
3998 and then Present (Pseudo_Reference)
3999 then
4000 Insert_Action (N,
4001 Make_Object_Declaration (Loc,
4002 Defining_Identifier => Make_Temporary (Loc, 'D'),
4003 Object_Definition =>
4004 New_Occurrence_Of (Reference_Control_Type, Loc),
4005 Expression =>
4006 Make_Function_Call (Loc,
4007 Name =>
4008 New_Occurrence_Of (Pseudo_Reference, Loc),
4009 Parameter_Associations =>
4010 New_List (New_Copy_Tree (Container_Arg)))));
4011 end if;
4013 -- Rewrite domain of iteration as a call to the default iterator
4014 -- for the container type. The formal may be an access parameter
4015 -- in which case we must build a reference to the container.
4017 declare
4018 Arg : Node_Id;
4019 begin
4020 if Is_Access_Type (Etype (First_Entity (Default_Iter))) then
4021 Arg :=
4022 Make_Attribute_Reference (Loc,
4023 Prefix => Container_Arg,
4024 Attribute_Name => Name_Unrestricted_Access);
4025 else
4026 Arg := Container_Arg;
4027 end if;
4029 Rewrite (Name (I_Spec),
4030 Make_Function_Call (Loc,
4031 Name =>
4032 New_Occurrence_Of (Default_Iter, Loc),
4033 Parameter_Associations => New_List (Arg)));
4034 end;
4036 Analyze_And_Resolve (Name (I_Spec));
4038 -- Find cursor type in proper iterator package, which is an
4039 -- instantiation of Iterator_Interfaces.
4041 Ent := First_Entity (Iter_Pack);
4042 while Present (Ent) loop
4043 if Chars (Ent) = Name_Cursor then
4044 Set_Etype (Cursor, Etype (Ent));
4045 exit;
4046 end if;
4048 Next_Entity (Ent);
4049 end loop;
4051 if Present (Fast_Element_Access_Op) then
4052 Decl :=
4053 Make_Object_Renaming_Declaration (Loc,
4054 Defining_Identifier => Id,
4055 Subtype_Mark =>
4056 New_Occurrence_Of (Elem_Typ, Loc),
4057 Name =>
4058 Make_Explicit_Dereference (Loc,
4059 Prefix =>
4060 Make_Function_Call (Loc,
4061 Name =>
4062 New_Occurrence_Of (Fast_Element_Access_Op, Loc),
4063 Parameter_Associations =>
4064 New_List (New_Occurrence_Of (Cursor, Loc)))));
4066 else
4067 Decl :=
4068 Make_Object_Renaming_Declaration (Loc,
4069 Defining_Identifier => Id,
4070 Subtype_Mark =>
4071 New_Occurrence_Of (Elem_Typ, Loc),
4072 Name =>
4073 Make_Indexed_Component (Loc,
4074 Prefix => Relocate_Node (Container_Arg),
4075 Expressions =>
4076 New_List (New_Occurrence_Of (Cursor, Loc))));
4077 end if;
4079 -- The defining identifier in the iterator is user-visible and
4080 -- must be visible in the debugger.
4082 Set_Debug_Info_Needed (Id);
4084 -- If the container does not have a variable indexing aspect,
4085 -- the element is a constant in the loop. The container itself
4086 -- may be constant, in which case the element is a constant as
4087 -- well. The container has been rewritten as a call to Iterate,
4088 -- so examine original node.
4090 if No (Find_Value_Of_Aspect
4091 (Container_Typ, Aspect_Variable_Indexing))
4092 or else not Is_Variable (Original_Node (Container))
4093 then
4094 Set_Ekind (Id, E_Constant);
4095 end if;
4097 Prepend_To (Stats, Decl);
4098 end Handle_Of;
4100 -- X in Iterate (S) : type of iterator is type of explicitly given
4101 -- Iterate function, and the loop variable is the cursor. It will be
4102 -- assigned in the loop and must be a variable.
4104 else
4105 Iter_Type := Etype (Name (I_Spec));
4107 -- The iterator type, which is a class-wide type, may itself be
4108 -- derived locally, so the desired instantiation is the scope of
4109 -- the root type of the iterator type, as in the "of" case.
4111 Iter_Pack := Scope (Root_Type (Etype (Iter_Type)));
4112 Cursor := Id;
4113 end if;
4115 Iterator := Make_Temporary (Loc, 'I');
4117 -- For both iterator forms, add a call to the step operation to advance
4118 -- the cursor. Generate:
4120 -- Cursor := Iterator.Next (Cursor);
4122 -- or else
4124 -- Cursor := Next (Cursor);
4126 if Present (Fast_Element_Access_Op) and then Present (Fast_Step_Op) then
4127 declare
4128 Curs_Name : constant Node_Id := New_Occurrence_Of (Cursor, Loc);
4129 Step_Call : Node_Id;
4131 begin
4132 Step_Call :=
4133 Make_Procedure_Call_Statement (Loc,
4134 Name =>
4135 New_Occurrence_Of (Fast_Step_Op, Loc),
4136 Parameter_Associations => New_List (Curs_Name));
4138 Append_To (Stats, Step_Call);
4139 Set_Assignment_OK (Curs_Name);
4140 end;
4142 else
4143 declare
4144 Rhs : Node_Id;
4146 begin
4147 Rhs :=
4148 Make_Function_Call (Loc,
4149 Name =>
4150 Make_Selected_Component (Loc,
4151 Prefix => New_Occurrence_Of (Iterator, Loc),
4152 Selector_Name => Make_Identifier (Loc, Name_Step)),
4153 Parameter_Associations => New_List (
4154 New_Occurrence_Of (Cursor, Loc)));
4156 Append_To (Stats,
4157 Make_Assignment_Statement (Loc,
4158 Name => New_Occurrence_Of (Cursor, Loc),
4159 Expression => Rhs));
4160 Set_Assignment_OK (Name (Last (Stats)));
4161 end;
4162 end if;
4164 -- Generate:
4165 -- while Has_Element (Cursor) loop
4166 -- <Stats>
4167 -- end loop;
4169 -- Has_Element is the second actual in the iterator package
4171 New_Loop :=
4172 Make_Loop_Statement (Loc,
4173 Iteration_Scheme =>
4174 Make_Iteration_Scheme (Loc,
4175 Condition =>
4176 Make_Function_Call (Loc,
4177 Name =>
4178 New_Occurrence_Of
4179 (Next_Entity (First_Entity (Iter_Pack)), Loc),
4180 Parameter_Associations => New_List (
4181 New_Occurrence_Of (Cursor, Loc)))),
4183 Statements => Stats,
4184 End_Label => Empty);
4186 -- If present, preserve identifier of loop, which can be used in an exit
4187 -- statement in the body.
4189 if Present (Identifier (N)) then
4190 Set_Identifier (New_Loop, Relocate_Node (Identifier (N)));
4191 end if;
4193 -- Create the declarations for Iterator and cursor and insert them
4194 -- before the source loop. Given that the domain of iteration is already
4195 -- an entity, the iterator is just a renaming of that entity. Possible
4196 -- optimization ???
4198 Insert_Action (N,
4199 Make_Object_Renaming_Declaration (Loc,
4200 Defining_Identifier => Iterator,
4201 Subtype_Mark => New_Occurrence_Of (Iter_Type, Loc),
4202 Name => Relocate_Node (Name (I_Spec))));
4204 -- Create declaration for cursor
4206 declare
4207 Cursor_Decl : constant Node_Id :=
4208 Make_Object_Declaration (Loc,
4209 Defining_Identifier => Cursor,
4210 Object_Definition =>
4211 New_Occurrence_Of (Etype (Cursor), Loc),
4212 Expression =>
4213 Make_Selected_Component (Loc,
4214 Prefix =>
4215 New_Occurrence_Of (Iterator, Loc),
4216 Selector_Name =>
4217 Make_Identifier (Loc, Name_Init)));
4219 begin
4220 -- The cursor is only modified in expanded code, so it appears
4221 -- as unassigned to the warning machinery. We must suppress this
4222 -- spurious warning explicitly. The cursor's kind is that of the
4223 -- original loop parameter (it is a constant if the domain of
4224 -- iteration is constant).
4226 Set_Warnings_Off (Cursor);
4227 Set_Assignment_OK (Cursor_Decl);
4229 Insert_Action (N, Cursor_Decl);
4230 Set_Ekind (Cursor, Id_Kind);
4231 end;
4233 -- If the range of iteration is given by a function call that returns
4234 -- a container, the finalization actions have been saved in the
4235 -- Condition_Actions of the iterator. Insert them now at the head of
4236 -- the loop.
4238 if Present (Condition_Actions (Isc)) then
4239 Insert_List_Before (N, Condition_Actions (Isc));
4240 end if;
4242 Rewrite (N, New_Loop);
4243 Analyze (N);
4244 end Expand_Iterator_Loop_Over_Container;
4246 -----------------------------
4247 -- Expand_N_Loop_Statement --
4248 -----------------------------
4250 -- 1. Remove null loop entirely
4251 -- 2. Deal with while condition for C/Fortran boolean
4252 -- 3. Deal with loops with a non-standard enumeration type range
4253 -- 4. Deal with while loops where Condition_Actions is set
4254 -- 5. Deal with loops over predicated subtypes
4255 -- 6. Deal with loops with iterators over arrays and containers
4256 -- 7. Insert polling call if required
4258 procedure Expand_N_Loop_Statement (N : Node_Id) is
4259 Loc : constant Source_Ptr := Sloc (N);
4260 Scheme : constant Node_Id := Iteration_Scheme (N);
4261 Stmt : Node_Id;
4263 begin
4264 -- Delete null loop
4266 if Is_Null_Loop (N) then
4267 Rewrite (N, Make_Null_Statement (Loc));
4268 return;
4269 end if;
4271 -- Deal with condition for C/Fortran Boolean
4273 if Present (Scheme) then
4274 Adjust_Condition (Condition (Scheme));
4275 end if;
4277 -- Generate polling call
4279 if Is_Non_Empty_List (Statements (N)) then
4280 Generate_Poll_Call (First (Statements (N)));
4281 end if;
4283 -- Nothing more to do for plain loop with no iteration scheme
4285 if No (Scheme) then
4286 null;
4288 -- Case of for loop (Loop_Parameter_Specification present)
4290 -- Note: we do not have to worry about validity checking of the for loop
4291 -- range bounds here, since they were frozen with constant declarations
4292 -- and it is during that process that the validity checking is done.
4294 elsif Present (Loop_Parameter_Specification (Scheme)) then
4295 declare
4296 LPS : constant Node_Id :=
4297 Loop_Parameter_Specification (Scheme);
4298 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4299 Ltype : constant Entity_Id := Etype (Loop_Id);
4300 Btype : constant Entity_Id := Base_Type (Ltype);
4301 Expr : Node_Id;
4302 Decls : List_Id;
4303 New_Id : Entity_Id;
4305 begin
4306 -- Deal with loop over predicates
4308 if Is_Discrete_Type (Ltype)
4309 and then Present (Predicate_Function (Ltype))
4310 then
4311 Expand_Predicated_Loop (N);
4313 -- Handle the case where we have a for loop with the range type
4314 -- being an enumeration type with non-standard representation.
4315 -- In this case we expand:
4317 -- for x in [reverse] a .. b loop
4318 -- ...
4319 -- end loop;
4321 -- to
4323 -- for xP in [reverse] integer
4324 -- range etype'Pos (a) .. etype'Pos (b)
4325 -- loop
4326 -- declare
4327 -- x : constant etype := Pos_To_Rep (xP);
4328 -- begin
4329 -- ...
4330 -- end;
4331 -- end loop;
4333 elsif Is_Enumeration_Type (Btype)
4334 and then Present (Enum_Pos_To_Rep (Btype))
4335 then
4336 New_Id :=
4337 Make_Defining_Identifier (Loc,
4338 Chars => New_External_Name (Chars (Loop_Id), 'P'));
4340 -- If the type has a contiguous representation, successive
4341 -- values can be generated as offsets from the first literal.
4343 if Has_Contiguous_Rep (Btype) then
4344 Expr :=
4345 Unchecked_Convert_To (Btype,
4346 Make_Op_Add (Loc,
4347 Left_Opnd =>
4348 Make_Integer_Literal (Loc,
4349 Enumeration_Rep (First_Literal (Btype))),
4350 Right_Opnd => New_Occurrence_Of (New_Id, Loc)));
4351 else
4352 -- Use the constructed array Enum_Pos_To_Rep
4354 Expr :=
4355 Make_Indexed_Component (Loc,
4356 Prefix =>
4357 New_Occurrence_Of (Enum_Pos_To_Rep (Btype), Loc),
4358 Expressions =>
4359 New_List (New_Occurrence_Of (New_Id, Loc)));
4360 end if;
4362 -- Build declaration for loop identifier
4364 Decls :=
4365 New_List (
4366 Make_Object_Declaration (Loc,
4367 Defining_Identifier => Loop_Id,
4368 Constant_Present => True,
4369 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4370 Expression => Expr));
4372 Rewrite (N,
4373 Make_Loop_Statement (Loc,
4374 Identifier => Identifier (N),
4376 Iteration_Scheme =>
4377 Make_Iteration_Scheme (Loc,
4378 Loop_Parameter_Specification =>
4379 Make_Loop_Parameter_Specification (Loc,
4380 Defining_Identifier => New_Id,
4381 Reverse_Present => Reverse_Present (LPS),
4383 Discrete_Subtype_Definition =>
4384 Make_Subtype_Indication (Loc,
4386 Subtype_Mark =>
4387 New_Occurrence_Of (Standard_Natural, Loc),
4389 Constraint =>
4390 Make_Range_Constraint (Loc,
4391 Range_Expression =>
4392 Make_Range (Loc,
4394 Low_Bound =>
4395 Make_Attribute_Reference (Loc,
4396 Prefix =>
4397 New_Occurrence_Of (Btype, Loc),
4399 Attribute_Name => Name_Pos,
4401 Expressions => New_List (
4402 Relocate_Node
4403 (Type_Low_Bound (Ltype)))),
4405 High_Bound =>
4406 Make_Attribute_Reference (Loc,
4407 Prefix =>
4408 New_Occurrence_Of (Btype, Loc),
4410 Attribute_Name => Name_Pos,
4412 Expressions => New_List (
4413 Relocate_Node
4414 (Type_High_Bound
4415 (Ltype))))))))),
4417 Statements => New_List (
4418 Make_Block_Statement (Loc,
4419 Declarations => Decls,
4420 Handled_Statement_Sequence =>
4421 Make_Handled_Sequence_Of_Statements (Loc,
4422 Statements => Statements (N)))),
4424 End_Label => End_Label (N)));
4426 -- The loop parameter's entity must be removed from the loop
4427 -- scope's entity list and rendered invisible, since it will
4428 -- now be located in the new block scope. Any other entities
4429 -- already associated with the loop scope, such as the loop
4430 -- parameter's subtype, will remain there.
4432 -- In an element loop, the loop will contain a declaration for
4433 -- a cursor variable; otherwise the loop id is the first entity
4434 -- in the scope constructed for the loop.
4436 if Comes_From_Source (Loop_Id) then
4437 pragma Assert (First_Entity (Scope (Loop_Id)) = Loop_Id);
4438 null;
4439 end if;
4441 Set_First_Entity (Scope (Loop_Id), Next_Entity (Loop_Id));
4442 Remove_Homonym (Loop_Id);
4444 if Last_Entity (Scope (Loop_Id)) = Loop_Id then
4445 Set_Last_Entity (Scope (Loop_Id), Empty);
4446 end if;
4448 Analyze (N);
4450 -- Nothing to do with other cases of for loops
4452 else
4453 null;
4454 end if;
4455 end;
4457 -- Second case, if we have a while loop with Condition_Actions set, then
4458 -- we change it into a plain loop:
4460 -- while C loop
4461 -- ...
4462 -- end loop;
4464 -- changed to:
4466 -- loop
4467 -- <<condition actions>>
4468 -- exit when not C;
4469 -- ...
4470 -- end loop
4472 elsif Present (Scheme)
4473 and then Present (Condition_Actions (Scheme))
4474 and then Present (Condition (Scheme))
4475 then
4476 declare
4477 ES : Node_Id;
4479 begin
4480 ES :=
4481 Make_Exit_Statement (Sloc (Condition (Scheme)),
4482 Condition =>
4483 Make_Op_Not (Sloc (Condition (Scheme)),
4484 Right_Opnd => Condition (Scheme)));
4486 Prepend (ES, Statements (N));
4487 Insert_List_Before (ES, Condition_Actions (Scheme));
4489 -- This is not an implicit loop, since it is generated in response
4490 -- to the loop statement being processed. If this is itself
4491 -- implicit, the restriction has already been checked. If not,
4492 -- it is an explicit loop.
4494 Rewrite (N,
4495 Make_Loop_Statement (Sloc (N),
4496 Identifier => Identifier (N),
4497 Statements => Statements (N),
4498 End_Label => End_Label (N)));
4500 Analyze (N);
4501 end;
4503 -- Here to deal with iterator case
4505 elsif Present (Scheme)
4506 and then Present (Iterator_Specification (Scheme))
4507 then
4508 Expand_Iterator_Loop (N);
4510 -- An iterator loop may generate renaming declarations for elements
4511 -- that require debug information. This is the case in particular
4512 -- with element iterators, where debug information must be generated
4513 -- for the temporary that holds the element value. These temporaries
4514 -- are created within a transient block whose local declarations are
4515 -- transferred to the loop, which now has nontrivial local objects.
4517 if Nkind (N) = N_Loop_Statement
4518 and then Present (Identifier (N))
4519 then
4520 Qualify_Entity_Names (N);
4521 end if;
4522 end if;
4524 -- When the iteration scheme mentiones attribute 'Loop_Entry, the loop
4525 -- is transformed into a conditional block where the original loop is
4526 -- the sole statement. Inspect the statements of the nested loop for
4527 -- controlled objects.
4529 Stmt := N;
4531 if Subject_To_Loop_Entry_Attributes (Stmt) then
4532 Stmt := Find_Loop_In_Conditional_Block (Stmt);
4533 end if;
4535 Process_Statements_For_Controlled_Objects (Stmt);
4536 end Expand_N_Loop_Statement;
4538 ----------------------------
4539 -- Expand_Predicated_Loop --
4540 ----------------------------
4542 -- Note: the expander can handle generation of loops over predicated
4543 -- subtypes for both the dynamic and static cases. Depending on what
4544 -- we decide is allowed in Ada 2012 mode and/or extensions allowed
4545 -- mode, the semantic analyzer may disallow one or both forms.
4547 procedure Expand_Predicated_Loop (N : Node_Id) is
4548 Loc : constant Source_Ptr := Sloc (N);
4549 Isc : constant Node_Id := Iteration_Scheme (N);
4550 LPS : constant Node_Id := Loop_Parameter_Specification (Isc);
4551 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4552 Ltype : constant Entity_Id := Etype (Loop_Id);
4553 Stat : constant List_Id := Static_Discrete_Predicate (Ltype);
4554 Stmts : constant List_Id := Statements (N);
4556 begin
4557 -- Case of iteration over non-static predicate, should not be possible
4558 -- since this is not allowed by the semantics and should have been
4559 -- caught during analysis of the loop statement.
4561 if No (Stat) then
4562 raise Program_Error;
4564 -- If the predicate list is empty, that corresponds to a predicate of
4565 -- False, in which case the loop won't run at all, and we rewrite the
4566 -- entire loop as a null statement.
4568 elsif Is_Empty_List (Stat) then
4569 Rewrite (N, Make_Null_Statement (Loc));
4570 Analyze (N);
4572 -- For expansion over a static predicate we generate the following
4574 -- declare
4575 -- J : Ltype := min-val;
4576 -- begin
4577 -- loop
4578 -- body
4579 -- case J is
4580 -- when endpoint => J := startpoint;
4581 -- when endpoint => J := startpoint;
4582 -- ...
4583 -- when max-val => exit;
4584 -- when others => J := Lval'Succ (J);
4585 -- end case;
4586 -- end loop;
4587 -- end;
4589 -- with min-val replaced by max-val and Succ replaced by Pred if the
4590 -- loop parameter specification carries a Reverse indicator.
4592 -- To make this a little clearer, let's take a specific example:
4594 -- type Int is range 1 .. 10;
4595 -- subtype StaticP is Int with
4596 -- predicate => StaticP in 3 | 10 | 5 .. 7;
4597 -- ...
4598 -- for L in StaticP loop
4599 -- Put_Line ("static:" & J'Img);
4600 -- end loop;
4602 -- In this case, the loop is transformed into
4604 -- begin
4605 -- J : L := 3;
4606 -- loop
4607 -- body
4608 -- case J is
4609 -- when 3 => J := 5;
4610 -- when 7 => J := 10;
4611 -- when 10 => exit;
4612 -- when others => J := L'Succ (J);
4613 -- end case;
4614 -- end loop;
4615 -- end;
4617 else
4618 Static_Predicate : declare
4619 S : Node_Id;
4620 D : Node_Id;
4621 P : Node_Id;
4622 Alts : List_Id;
4623 Cstm : Node_Id;
4625 function Lo_Val (N : Node_Id) return Node_Id;
4626 -- Given static expression or static range, returns an identifier
4627 -- whose value is the low bound of the expression value or range.
4629 function Hi_Val (N : Node_Id) return Node_Id;
4630 -- Given static expression or static range, returns an identifier
4631 -- whose value is the high bound of the expression value or range.
4633 ------------
4634 -- Hi_Val --
4635 ------------
4637 function Hi_Val (N : Node_Id) return Node_Id is
4638 begin
4639 if Is_OK_Static_Expression (N) then
4640 return New_Copy (N);
4641 else
4642 pragma Assert (Nkind (N) = N_Range);
4643 return New_Copy (High_Bound (N));
4644 end if;
4645 end Hi_Val;
4647 ------------
4648 -- Lo_Val --
4649 ------------
4651 function Lo_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 (Low_Bound (N));
4658 end if;
4659 end Lo_Val;
4661 -- Start of processing for Static_Predicate
4663 begin
4664 -- Convert loop identifier to normal variable and reanalyze it so
4665 -- that this conversion works. We have to use the same defining
4666 -- identifier, since there may be references in the loop body.
4668 Set_Analyzed (Loop_Id, False);
4669 Set_Ekind (Loop_Id, E_Variable);
4671 -- In most loops the loop variable is assigned in various
4672 -- alternatives in the body. However, in the rare case when
4673 -- the range specifies a single element, the loop variable
4674 -- may trigger a spurious warning that is could be constant.
4675 -- This warning might as well be suppressed.
4677 Set_Warnings_Off (Loop_Id);
4679 -- Loop to create branches of case statement
4681 Alts := New_List;
4683 if Reverse_Present (LPS) then
4685 -- Initial value is largest value in predicate.
4687 D :=
4688 Make_Object_Declaration (Loc,
4689 Defining_Identifier => Loop_Id,
4690 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4691 Expression => Hi_Val (Last (Stat)));
4693 P := Last (Stat);
4694 while Present (P) loop
4695 if No (Prev (P)) then
4696 S := Make_Exit_Statement (Loc);
4697 else
4698 S :=
4699 Make_Assignment_Statement (Loc,
4700 Name => New_Occurrence_Of (Loop_Id, Loc),
4701 Expression => Hi_Val (Prev (P)));
4702 Set_Suppress_Assignment_Checks (S);
4703 end if;
4705 Append_To (Alts,
4706 Make_Case_Statement_Alternative (Loc,
4707 Statements => New_List (S),
4708 Discrete_Choices => New_List (Lo_Val (P))));
4710 Prev (P);
4711 end loop;
4713 else
4715 -- Initial value is smallest value in predicate.
4717 D :=
4718 Make_Object_Declaration (Loc,
4719 Defining_Identifier => Loop_Id,
4720 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4721 Expression => Lo_Val (First (Stat)));
4723 P := First (Stat);
4724 while Present (P) loop
4725 if No (Next (P)) then
4726 S := Make_Exit_Statement (Loc);
4727 else
4728 S :=
4729 Make_Assignment_Statement (Loc,
4730 Name => New_Occurrence_Of (Loop_Id, Loc),
4731 Expression => Lo_Val (Next (P)));
4732 Set_Suppress_Assignment_Checks (S);
4733 end if;
4735 Append_To (Alts,
4736 Make_Case_Statement_Alternative (Loc,
4737 Statements => New_List (S),
4738 Discrete_Choices => New_List (Hi_Val (P))));
4740 Next (P);
4741 end loop;
4742 end if;
4744 -- Add others choice
4746 declare
4747 Name_Next : Name_Id;
4749 begin
4750 if Reverse_Present (LPS) then
4751 Name_Next := Name_Pred;
4752 else
4753 Name_Next := Name_Succ;
4754 end if;
4756 S :=
4757 Make_Assignment_Statement (Loc,
4758 Name => New_Occurrence_Of (Loop_Id, Loc),
4759 Expression =>
4760 Make_Attribute_Reference (Loc,
4761 Prefix => New_Occurrence_Of (Ltype, Loc),
4762 Attribute_Name => Name_Next,
4763 Expressions => New_List (
4764 New_Occurrence_Of (Loop_Id, Loc))));
4765 Set_Suppress_Assignment_Checks (S);
4766 end;
4768 Append_To (Alts,
4769 Make_Case_Statement_Alternative (Loc,
4770 Discrete_Choices => New_List (Make_Others_Choice (Loc)),
4771 Statements => New_List (S)));
4773 -- Construct case statement and append to body statements
4775 Cstm :=
4776 Make_Case_Statement (Loc,
4777 Expression => New_Occurrence_Of (Loop_Id, Loc),
4778 Alternatives => Alts);
4779 Append_To (Stmts, Cstm);
4781 -- Rewrite the loop
4783 Set_Suppress_Assignment_Checks (D);
4785 Rewrite (N,
4786 Make_Block_Statement (Loc,
4787 Declarations => New_List (D),
4788 Handled_Statement_Sequence =>
4789 Make_Handled_Sequence_Of_Statements (Loc,
4790 Statements => New_List (
4791 Make_Loop_Statement (Loc,
4792 Statements => Stmts,
4793 End_Label => Empty)))));
4795 Analyze (N);
4796 end Static_Predicate;
4797 end if;
4798 end Expand_Predicated_Loop;
4800 ------------------------------
4801 -- Make_Tag_Ctrl_Assignment --
4802 ------------------------------
4804 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
4805 Asn : constant Node_Id := Relocate_Node (N);
4806 L : constant Node_Id := Name (N);
4807 Loc : constant Source_Ptr := Sloc (N);
4808 Res : constant List_Id := New_List;
4809 T : constant Entity_Id := Underlying_Type (Etype (L));
4811 Comp_Asn : constant Boolean := Is_Fully_Repped_Tagged_Type (T);
4812 Ctrl_Act : constant Boolean := Needs_Finalization (T)
4813 and then not No_Ctrl_Actions (N);
4814 Save_Tag : constant Boolean := Is_Tagged_Type (T)
4815 and then not Comp_Asn
4816 and then not No_Ctrl_Actions (N)
4817 and then Tagged_Type_Expansion;
4818 Adj_Call : Node_Id;
4819 Fin_Call : Node_Id;
4820 Tag_Id : Entity_Id;
4822 begin
4823 -- Finalize the target of the assignment when controlled
4825 -- We have two exceptions here:
4827 -- 1. If we are in an init proc since it is an initialization more
4828 -- than an assignment.
4830 -- 2. If the left-hand side is a temporary that was not initialized
4831 -- (or the parent part of a temporary since it is the case in
4832 -- extension aggregates). Such a temporary does not come from
4833 -- source. We must examine the original node for the prefix, because
4834 -- it may be a component of an entry formal, in which case it has
4835 -- been rewritten and does not appear to come from source either.
4837 -- Case of init proc
4839 if not Ctrl_Act then
4840 null;
4842 -- The left-hand side is an uninitialized temporary object
4844 elsif Nkind (L) = N_Type_Conversion
4845 and then Is_Entity_Name (Expression (L))
4846 and then Nkind (Parent (Entity (Expression (L)))) =
4847 N_Object_Declaration
4848 and then No_Initialization (Parent (Entity (Expression (L))))
4849 then
4850 null;
4852 else
4853 Fin_Call :=
4854 Make_Final_Call
4855 (Obj_Ref => Duplicate_Subexpr_No_Checks (L),
4856 Typ => Etype (L));
4858 if Present (Fin_Call) then
4859 Append_To (Res, Fin_Call);
4860 end if;
4861 end if;
4863 -- Save the Tag in a local variable Tag_Id
4865 if Save_Tag then
4866 Tag_Id := Make_Temporary (Loc, 'A');
4868 Append_To (Res,
4869 Make_Object_Declaration (Loc,
4870 Defining_Identifier => Tag_Id,
4871 Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc),
4872 Expression =>
4873 Make_Selected_Component (Loc,
4874 Prefix => Duplicate_Subexpr_No_Checks (L),
4875 Selector_Name =>
4876 New_Occurrence_Of (First_Tag_Component (T), Loc))));
4878 -- Otherwise Tag_Id is not used
4880 else
4881 Tag_Id := Empty;
4882 end if;
4884 -- If the tagged type has a full rep clause, expand the assignment into
4885 -- component-wise assignments. Mark the node as unanalyzed in order to
4886 -- generate the proper code and propagate this scenario by setting a
4887 -- flag to avoid infinite recursion.
4889 if Comp_Asn then
4890 Set_Analyzed (Asn, False);
4891 Set_Componentwise_Assignment (Asn, True);
4892 end if;
4894 Append_To (Res, Asn);
4896 -- Restore the tag
4898 if Save_Tag then
4899 Append_To (Res,
4900 Make_Assignment_Statement (Loc,
4901 Name =>
4902 Make_Selected_Component (Loc,
4903 Prefix => Duplicate_Subexpr_No_Checks (L),
4904 Selector_Name =>
4905 New_Occurrence_Of (First_Tag_Component (T), Loc)),
4906 Expression => New_Occurrence_Of (Tag_Id, Loc)));
4907 end if;
4909 -- Adjust the target after the assignment when controlled (not in the
4910 -- init proc since it is an initialization more than an assignment).
4912 if Ctrl_Act then
4913 Adj_Call :=
4914 Make_Adjust_Call
4915 (Obj_Ref => Duplicate_Subexpr_Move_Checks (L),
4916 Typ => Etype (L));
4918 if Present (Adj_Call) then
4919 Append_To (Res, Adj_Call);
4920 end if;
4921 end if;
4923 return Res;
4925 exception
4927 -- Could use comment here ???
4929 when RE_Not_Available =>
4930 return Empty_List;
4931 end Make_Tag_Ctrl_Assignment;
4933 end Exp_Ch5;