* lto.c (do_stream_out): Add PART parameter; open dump file.
[official-gcc.git] / gcc / ada / exp_ch5.adb
blobe0cff915bca95334ee54c1f9af4f9c2f05a737e6
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT COMPILER COMPONENTS --
4 -- --
5 -- E X P _ C H 5 --
6 -- --
7 -- B o d y --
8 -- --
9 -- Copyright (C) 1992-2018, Free Software Foundation, Inc. --
10 -- --
11 -- GNAT is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 3, or (at your option) any later ver- --
14 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
17 -- for more details. You should have received a copy of the GNU General --
18 -- Public License distributed with GNAT; see file COPYING3. If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license. --
20 -- --
21 -- GNAT was originally developed by the GNAT team at New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc. --
23 -- --
24 ------------------------------------------------------------------------------
26 with Aspects; use Aspects;
27 with Atree; use Atree;
28 with Checks; use Checks;
29 with Debug; use Debug;
30 with Einfo; use Einfo;
31 with Elists; use Elists;
32 with Errout; use Errout;
33 with Exp_Aggr; use Exp_Aggr;
34 with Exp_Ch6; use Exp_Ch6;
35 with Exp_Ch7; use Exp_Ch7;
36 with Exp_Ch11; use Exp_Ch11;
37 with Exp_Dbug; use Exp_Dbug;
38 with Exp_Pakd; use Exp_Pakd;
39 with Exp_Tss; use Exp_Tss;
40 with Exp_Util; use Exp_Util;
41 with Inline; use Inline;
42 with Namet; use Namet;
43 with Nlists; use Nlists;
44 with Nmake; use Nmake;
45 with Opt; use Opt;
46 with Restrict; use Restrict;
47 with Rident; use Rident;
48 with Rtsfind; use Rtsfind;
49 with Sinfo; use Sinfo;
50 with Sem; use Sem;
51 with Sem_Aux; use Sem_Aux;
52 with Sem_Ch3; use Sem_Ch3;
53 with Sem_Ch8; use Sem_Ch8;
54 with Sem_Ch13; use Sem_Ch13;
55 with Sem_Eval; use Sem_Eval;
56 with Sem_Res; use Sem_Res;
57 with Sem_Util; use Sem_Util;
58 with Snames; use Snames;
59 with Stand; use Stand;
60 with Stringt; use Stringt;
61 with Tbuild; use Tbuild;
62 with Uintp; use Uintp;
63 with Validsw; use Validsw;
65 package body Exp_Ch5 is
67 procedure Build_Formal_Container_Iteration
68 (N : Node_Id;
69 Container : Entity_Id;
70 Cursor : Entity_Id;
71 Init : out Node_Id;
72 Advance : out Node_Id;
73 New_Loop : out Node_Id);
74 -- Utility to create declarations and loop statement for both forms
75 -- of formal container iterators.
77 function Convert_To_Iterable_Type
78 (Container : Entity_Id;
79 Loc : Source_Ptr) return Node_Id;
80 -- Returns New_Occurrence_Of (Container), possibly converted to an ancestor
81 -- type, if the type of Container inherited the Iterable aspect from that
82 -- ancestor.
84 function Change_Of_Representation (N : Node_Id) return Boolean;
85 -- Determine if the right-hand side of assignment N is a type conversion
86 -- which requires a change of representation. Called only for the array
87 -- and record cases.
89 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id);
90 -- N is an assignment which assigns an array value. This routine process
91 -- the various special cases and checks required for such assignments,
92 -- including change of representation. Rhs is normally simply the right-
93 -- hand side of the assignment, except that if the right-hand side is a
94 -- type conversion or a qualified expression, then the RHS is the actual
95 -- expression inside any such type conversions or qualifications.
97 function Expand_Assign_Array_Loop
98 (N : Node_Id;
99 Larray : Entity_Id;
100 Rarray : Entity_Id;
101 L_Type : Entity_Id;
102 R_Type : Entity_Id;
103 Ndim : Pos;
104 Rev : Boolean) return Node_Id;
105 -- N is an assignment statement which assigns an array value. This routine
106 -- expands the assignment into a loop (or nested loops for the case of a
107 -- multi-dimensional array) to do the assignment component by component.
108 -- Larray and Rarray are the entities of the actual arrays on the left-hand
109 -- and right-hand sides. L_Type and R_Type are the types of these arrays
110 -- (which may not be the same, due to either sliding, or to a change of
111 -- representation case). Ndim is the number of dimensions and the parameter
112 -- Rev indicates if the loops run normally (Rev = False), or reversed
113 -- (Rev = True). The value returned is the constructed loop statement.
114 -- Auxiliary declarations are inserted before node N using the standard
115 -- Insert_Actions mechanism.
117 procedure Expand_Assign_Record (N : Node_Id);
118 -- N is an assignment of an untagged record value. This routine handles
119 -- the case where the assignment must be made component by component,
120 -- either because the target is not byte aligned, or there is a change
121 -- of representation, or when we have a tagged type with a representation
122 -- clause (this last case is required because holes in the tagged type
123 -- might be filled with components from child types).
125 procedure Expand_Assign_With_Target_Names (N : Node_Id);
126 -- (AI12-0125): N is an assignment statement whose RHS contains occurrences
127 -- of @ that designate the value of the LHS of the assignment. If the LHS
128 -- is side-effect free the target names can be replaced with a copy of the
129 -- LHS; otherwise the semantics of the assignment is described in terms of
130 -- a procedure with an in-out parameter, and expanded as such.
132 procedure Expand_Formal_Container_Loop (N : Node_Id);
133 -- Use the primitives specified in an Iterable aspect to expand a loop
134 -- over a so-called formal container, primarily for SPARK usage.
136 procedure Expand_Formal_Container_Element_Loop (N : Node_Id);
137 -- Same, for an iterator of the form " For E of C". In this case the
138 -- iterator provides the name of the element, and the cursor is generated
139 -- internally.
141 procedure Expand_Iterator_Loop (N : Node_Id);
142 -- Expand loop over arrays and containers that uses the form "for X of C"
143 -- with an optional subtype mark, or "for Y in C".
145 procedure Expand_Iterator_Loop_Over_Container
146 (N : Node_Id;
147 Isc : Node_Id;
148 I_Spec : Node_Id;
149 Container : Node_Id;
150 Container_Typ : Entity_Id);
151 -- Expand loop over containers that uses the form "for X of C" with an
152 -- optional subtype mark, or "for Y in C". Isc is the iteration scheme.
153 -- I_Spec is the iterator specification and Container is either the
154 -- Container (for OF) or the iterator (for IN).
156 procedure Expand_Predicated_Loop (N : Node_Id);
157 -- Expand for loop over predicated subtype
159 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id;
160 -- Generate the necessary code for controlled and tagged assignment, that
161 -- is to say, finalization of the target before, adjustment of the target
162 -- after and save and restore of the tag and finalization pointers which
163 -- are not 'part of the value' and must not be changed upon assignment. N
164 -- is the original Assignment node.
166 --------------------------------------
167 -- Build_Formal_Container_Iteration --
168 --------------------------------------
170 procedure Build_Formal_Container_Iteration
171 (N : Node_Id;
172 Container : Entity_Id;
173 Cursor : Entity_Id;
174 Init : out Node_Id;
175 Advance : out Node_Id;
176 New_Loop : out Node_Id)
178 Loc : constant Source_Ptr := Sloc (N);
179 Stats : constant List_Id := Statements (N);
180 Typ : constant Entity_Id := Base_Type (Etype (Container));
182 Has_Element_Op : constant Entity_Id :=
183 Get_Iterable_Type_Primitive (Typ, Name_Has_Element);
185 First_Op : Entity_Id;
186 Next_Op : Entity_Id;
188 begin
189 -- Use the proper set of primitives depending on the direction of
190 -- iteration. The legality of a reverse iteration has been checked
191 -- during analysis.
193 if Reverse_Present (Iterator_Specification (Iteration_Scheme (N))) then
194 First_Op := Get_Iterable_Type_Primitive (Typ, Name_Last);
195 Next_Op := Get_Iterable_Type_Primitive (Typ, Name_Previous);
197 else
198 First_Op := Get_Iterable_Type_Primitive (Typ, Name_First);
199 Next_Op := Get_Iterable_Type_Primitive (Typ, Name_Next);
200 end if;
202 -- Declaration for Cursor
204 Init :=
205 Make_Object_Declaration (Loc,
206 Defining_Identifier => Cursor,
207 Object_Definition => New_Occurrence_Of (Etype (First_Op), Loc),
208 Expression =>
209 Make_Function_Call (Loc,
210 Name => New_Occurrence_Of (First_Op, Loc),
211 Parameter_Associations => New_List (
212 Convert_To_Iterable_Type (Container, Loc))));
214 -- Statement that advances (in the right direction) cursor in loop
216 Advance :=
217 Make_Assignment_Statement (Loc,
218 Name => New_Occurrence_Of (Cursor, Loc),
219 Expression =>
220 Make_Function_Call (Loc,
221 Name => New_Occurrence_Of (Next_Op, Loc),
222 Parameter_Associations => New_List (
223 Convert_To_Iterable_Type (Container, Loc),
224 New_Occurrence_Of (Cursor, Loc))));
226 -- Iterator is rewritten as a while_loop
228 New_Loop :=
229 Make_Loop_Statement (Loc,
230 Iteration_Scheme =>
231 Make_Iteration_Scheme (Loc,
232 Condition =>
233 Make_Function_Call (Loc,
234 Name => New_Occurrence_Of (Has_Element_Op, Loc),
235 Parameter_Associations => New_List (
236 Convert_To_Iterable_Type (Container, Loc),
237 New_Occurrence_Of (Cursor, Loc)))),
238 Statements => Stats,
239 End_Label => Empty);
241 -- If the contruct has a specified loop name, preserve it in the new
242 -- loop, for possible use in exit statements.
244 if Present (Identifier (N))
245 and then Comes_From_Source (Identifier (N))
246 then
247 Set_Identifier (New_Loop, Identifier (N));
248 end if;
249 end Build_Formal_Container_Iteration;
251 ------------------------------
252 -- Change_Of_Representation --
253 ------------------------------
255 function Change_Of_Representation (N : Node_Id) return Boolean is
256 Rhs : constant Node_Id := Expression (N);
257 begin
258 return
259 Nkind (Rhs) = N_Type_Conversion
260 and then
261 not Same_Representation (Etype (Rhs), Etype (Expression (Rhs)));
262 end Change_Of_Representation;
264 ------------------------------
265 -- Convert_To_Iterable_Type --
266 ------------------------------
268 function Convert_To_Iterable_Type
269 (Container : Entity_Id;
270 Loc : Source_Ptr) return Node_Id
272 Typ : constant Entity_Id := Base_Type (Etype (Container));
273 Aspect : constant Node_Id := Find_Aspect (Typ, Aspect_Iterable);
274 Result : Node_Id;
276 begin
277 Result := New_Occurrence_Of (Container, Loc);
279 if Entity (Aspect) /= Typ then
280 Result :=
281 Make_Type_Conversion (Loc,
282 Subtype_Mark => New_Occurrence_Of (Entity (Aspect), Loc),
283 Expression => Result);
284 end if;
286 return Result;
287 end Convert_To_Iterable_Type;
289 -------------------------
290 -- Expand_Assign_Array --
291 -------------------------
293 -- There are two issues here. First, do we let Gigi do a block move, or
294 -- do we expand out into a loop? Second, we need to set the two flags
295 -- Forwards_OK and Backwards_OK which show whether the block move (or
296 -- corresponding loops) can be legitimately done in a forwards (low to
297 -- high) or backwards (high to low) manner.
299 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id) is
300 Loc : constant Source_Ptr := Sloc (N);
302 Lhs : constant Node_Id := Name (N);
304 Act_Lhs : constant Node_Id := Get_Referenced_Object (Lhs);
305 Act_Rhs : Node_Id := Get_Referenced_Object (Rhs);
307 L_Type : constant Entity_Id :=
308 Underlying_Type (Get_Actual_Subtype (Act_Lhs));
309 R_Type : Entity_Id :=
310 Underlying_Type (Get_Actual_Subtype (Act_Rhs));
312 L_Slice : constant Boolean := Nkind (Act_Lhs) = N_Slice;
313 R_Slice : constant Boolean := Nkind (Act_Rhs) = N_Slice;
315 Crep : constant Boolean := Change_Of_Representation (N);
317 Larray : Node_Id;
318 Rarray : Node_Id;
320 Ndim : constant Pos := Number_Dimensions (L_Type);
322 Loop_Required : Boolean := False;
323 -- This switch is set to True if the array move must be done using
324 -- an explicit front end generated loop.
326 procedure Apply_Dereference (Arg : Node_Id);
327 -- If the argument is an access to an array, and the assignment is
328 -- converted into a procedure call, apply explicit dereference.
330 function Has_Address_Clause (Exp : Node_Id) return Boolean;
331 -- Test if Exp is a reference to an array whose declaration has
332 -- an address clause, or it is a slice of such an array.
334 function Is_Formal_Array (Exp : Node_Id) return Boolean;
335 -- Test if Exp is a reference to an array which is either a formal
336 -- parameter or a slice of a formal parameter. These are the cases
337 -- where hidden aliasing can occur.
339 function Is_Non_Local_Array (Exp : Node_Id) return Boolean;
340 -- Determine if Exp is a reference to an array variable which is other
341 -- than an object defined in the current scope, or a component or a
342 -- slice of such an object. Such objects can be aliased to parameters
343 -- (unlike local array references).
345 -----------------------
346 -- Apply_Dereference --
347 -----------------------
349 procedure Apply_Dereference (Arg : Node_Id) is
350 Typ : constant Entity_Id := Etype (Arg);
351 begin
352 if Is_Access_Type (Typ) then
353 Rewrite (Arg, Make_Explicit_Dereference (Loc,
354 Prefix => Relocate_Node (Arg)));
355 Analyze_And_Resolve (Arg, Designated_Type (Typ));
356 end if;
357 end Apply_Dereference;
359 ------------------------
360 -- Has_Address_Clause --
361 ------------------------
363 function Has_Address_Clause (Exp : Node_Id) return Boolean is
364 begin
365 return
366 (Is_Entity_Name (Exp) and then
367 Present (Address_Clause (Entity (Exp))))
368 or else
369 (Nkind (Exp) = N_Slice and then Has_Address_Clause (Prefix (Exp)));
370 end Has_Address_Clause;
372 ---------------------
373 -- Is_Formal_Array --
374 ---------------------
376 function Is_Formal_Array (Exp : Node_Id) return Boolean is
377 begin
378 return
379 (Is_Entity_Name (Exp) and then Is_Formal (Entity (Exp)))
380 or else
381 (Nkind (Exp) = N_Slice and then Is_Formal_Array (Prefix (Exp)));
382 end Is_Formal_Array;
384 ------------------------
385 -- Is_Non_Local_Array --
386 ------------------------
388 function Is_Non_Local_Array (Exp : Node_Id) return Boolean is
389 begin
390 case Nkind (Exp) is
391 when N_Indexed_Component
392 | N_Selected_Component
393 | N_Slice
395 return Is_Non_Local_Array (Prefix (Exp));
397 when others =>
398 return
399 not (Is_Entity_Name (Exp)
400 and then Scope (Entity (Exp)) = Current_Scope);
401 end case;
402 end Is_Non_Local_Array;
404 -- Determine if Lhs, Rhs are formal arrays or nonlocal arrays
406 Lhs_Formal : constant Boolean := Is_Formal_Array (Act_Lhs);
407 Rhs_Formal : constant Boolean := Is_Formal_Array (Act_Rhs);
409 Lhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Lhs);
410 Rhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Rhs);
412 -- Start of processing for Expand_Assign_Array
414 begin
415 -- Deal with length check. Note that the length check is done with
416 -- respect to the right-hand side as given, not a possible underlying
417 -- renamed object, since this would generate incorrect extra checks.
419 Apply_Length_Check (Rhs, L_Type);
421 -- We start by assuming that the move can be done in either direction,
422 -- i.e. that the two sides are completely disjoint.
424 Set_Forwards_OK (N, True);
425 Set_Backwards_OK (N, True);
427 -- Normally it is only the slice case that can lead to overlap, and
428 -- explicit checks for slices are made below. But there is one case
429 -- where the slice can be implicit and invisible to us: when we have a
430 -- one dimensional array, and either both operands are parameters, or
431 -- one is a parameter (which can be a slice passed by reference) and the
432 -- other is a non-local variable. In this case the parameter could be a
433 -- slice that overlaps with the other operand.
435 -- However, if the array subtype is a constrained first subtype in the
436 -- parameter case, then we don't have to worry about overlap, since
437 -- slice assignments aren't possible (other than for a slice denoting
438 -- the whole array).
440 -- Note: No overlap is possible if there is a change of representation,
441 -- so we can exclude this case.
443 if Ndim = 1
444 and then not Crep
445 and then
446 ((Lhs_Formal and Rhs_Formal)
447 or else
448 (Lhs_Formal and Rhs_Non_Local_Var)
449 or else
450 (Rhs_Formal and Lhs_Non_Local_Var))
451 and then
452 (not Is_Constrained (Etype (Lhs))
453 or else not Is_First_Subtype (Etype (Lhs)))
454 then
455 Set_Forwards_OK (N, False);
456 Set_Backwards_OK (N, False);
458 -- Note: the bit-packed case is not worrisome here, since if we have
459 -- a slice passed as a parameter, it is always aligned on a byte
460 -- boundary, and if there are no explicit slices, the assignment
461 -- can be performed directly.
462 end if;
464 -- If either operand has an address clause clear Backwards_OK and
465 -- Forwards_OK, since we cannot tell if the operands overlap. We
466 -- exclude this treatment when Rhs is an aggregate, since we know
467 -- that overlap can't occur.
469 if (Has_Address_Clause (Lhs) and then Nkind (Rhs) /= N_Aggregate)
470 or else Has_Address_Clause (Rhs)
471 then
472 Set_Forwards_OK (N, False);
473 Set_Backwards_OK (N, False);
474 end if;
476 -- We certainly must use a loop for change of representation and also
477 -- we use the operand of the conversion on the right-hand side as the
478 -- effective right-hand side (the component types must match in this
479 -- situation).
481 if Crep then
482 Act_Rhs := Get_Referenced_Object (Rhs);
483 R_Type := Get_Actual_Subtype (Act_Rhs);
484 Loop_Required := True;
486 -- We require a loop if the left side is possibly bit unaligned
488 elsif Possible_Bit_Aligned_Component (Lhs)
489 or else
490 Possible_Bit_Aligned_Component (Rhs)
491 then
492 Loop_Required := True;
494 -- Arrays with controlled components are expanded into a loop to force
495 -- calls to Adjust at the component level.
497 elsif Has_Controlled_Component (L_Type) then
498 Loop_Required := True;
500 -- If object is atomic/VFA, we cannot tolerate a loop
502 elsif Is_Atomic_Or_VFA_Object (Act_Lhs)
503 or else
504 Is_Atomic_Or_VFA_Object (Act_Rhs)
505 then
506 return;
508 -- Loop is required if we have atomic components since we have to
509 -- be sure to do any accesses on an element by element basis.
511 elsif Has_Atomic_Components (L_Type)
512 or else Has_Atomic_Components (R_Type)
513 or else Is_Atomic_Or_VFA (Component_Type (L_Type))
514 or else Is_Atomic_Or_VFA (Component_Type (R_Type))
515 then
516 Loop_Required := True;
518 -- Case where no slice is involved
520 elsif not L_Slice and not R_Slice then
522 -- The following code deals with the case of unconstrained bit packed
523 -- arrays. The problem is that the template for such arrays contains
524 -- the bounds of the actual source level array, but the copy of an
525 -- entire array requires the bounds of the underlying array. It would
526 -- be nice if the back end could take care of this, but right now it
527 -- does not know how, so if we have such a type, then we expand out
528 -- into a loop, which is inefficient but works correctly. If we don't
529 -- do this, we get the wrong length computed for the array to be
530 -- moved. The two cases we need to worry about are:
532 -- Explicit dereference of an unconstrained packed array type as in
533 -- the following example:
535 -- procedure C52 is
536 -- type BITS is array(INTEGER range <>) of BOOLEAN;
537 -- pragma PACK(BITS);
538 -- type A is access BITS;
539 -- P1,P2 : A;
540 -- begin
541 -- P1 := new BITS (1 .. 65_535);
542 -- P2 := new BITS (1 .. 65_535);
543 -- P2.ALL := P1.ALL;
544 -- end C52;
546 -- A formal parameter reference with an unconstrained bit array type
547 -- is the other case we need to worry about (here we assume the same
548 -- BITS type declared above):
550 -- procedure Write_All (File : out BITS; Contents : BITS);
551 -- begin
552 -- File.Storage := Contents;
553 -- end Write_All;
555 -- We expand to a loop in either of these two cases
557 -- Question for future thought. Another potentially more efficient
558 -- approach would be to create the actual subtype, and then do an
559 -- unchecked conversion to this actual subtype ???
561 Check_Unconstrained_Bit_Packed_Array : declare
563 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean;
564 -- Function to perform required test for the first case, above
565 -- (dereference of an unconstrained bit packed array).
567 -----------------------
568 -- Is_UBPA_Reference --
569 -----------------------
571 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean is
572 Typ : constant Entity_Id := Underlying_Type (Etype (Opnd));
573 P_Type : Entity_Id;
574 Des_Type : Entity_Id;
576 begin
577 if Present (Packed_Array_Impl_Type (Typ))
578 and then Is_Array_Type (Packed_Array_Impl_Type (Typ))
579 and then not Is_Constrained (Packed_Array_Impl_Type (Typ))
580 then
581 return True;
583 elsif Nkind (Opnd) = N_Explicit_Dereference then
584 P_Type := Underlying_Type (Etype (Prefix (Opnd)));
586 if not Is_Access_Type (P_Type) then
587 return False;
589 else
590 Des_Type := Designated_Type (P_Type);
591 return
592 Is_Bit_Packed_Array (Des_Type)
593 and then not Is_Constrained (Des_Type);
594 end if;
596 else
597 return False;
598 end if;
599 end Is_UBPA_Reference;
601 -- Start of processing for Check_Unconstrained_Bit_Packed_Array
603 begin
604 if Is_UBPA_Reference (Lhs)
605 or else
606 Is_UBPA_Reference (Rhs)
607 then
608 Loop_Required := True;
610 -- Here if we do not have the case of a reference to a bit packed
611 -- unconstrained array case. In this case gigi can most certainly
612 -- handle the assignment if a forwards move is allowed.
614 -- (could it handle the backwards case also???)
616 elsif Forwards_OK (N) then
617 return;
618 end if;
619 end Check_Unconstrained_Bit_Packed_Array;
621 -- The back end can always handle the assignment if the right side is a
622 -- string literal (note that overlap is definitely impossible in this
623 -- case). If the type is packed, a string literal is always converted
624 -- into an aggregate, except in the case of a null slice, for which no
625 -- aggregate can be written. In that case, rewrite the assignment as a
626 -- null statement, a length check has already been emitted to verify
627 -- that the range of the left-hand side is empty.
629 -- Note that this code is not executed if we have an assignment of a
630 -- string literal to a non-bit aligned component of a record, a case
631 -- which cannot be handled by the backend.
633 elsif Nkind (Rhs) = N_String_Literal then
634 if String_Length (Strval (Rhs)) = 0
635 and then Is_Bit_Packed_Array (L_Type)
636 then
637 Rewrite (N, Make_Null_Statement (Loc));
638 Analyze (N);
639 end if;
641 return;
643 -- If either operand is bit packed, then we need a loop, since we can't
644 -- be sure that the slice is byte aligned. Similarly, if either operand
645 -- is a possibly unaligned slice, then we need a loop (since the back
646 -- end cannot handle unaligned slices).
648 elsif Is_Bit_Packed_Array (L_Type)
649 or else Is_Bit_Packed_Array (R_Type)
650 or else Is_Possibly_Unaligned_Slice (Lhs)
651 or else Is_Possibly_Unaligned_Slice (Rhs)
652 then
653 Loop_Required := True;
655 -- If we are not bit-packed, and we have only one slice, then no overlap
656 -- is possible except in the parameter case, so we can let the back end
657 -- handle things.
659 elsif not (L_Slice and R_Slice) then
660 if Forwards_OK (N) then
661 return;
662 end if;
663 end if;
665 -- If the right-hand side is a string literal, introduce a temporary for
666 -- it, for use in the generated loop that will follow.
668 if Nkind (Rhs) = N_String_Literal then
669 declare
670 Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Rhs);
671 Decl : Node_Id;
673 begin
674 Decl :=
675 Make_Object_Declaration (Loc,
676 Defining_Identifier => Temp,
677 Object_Definition => New_Occurrence_Of (L_Type, Loc),
678 Expression => Relocate_Node (Rhs));
680 Insert_Action (N, Decl);
681 Rewrite (Rhs, New_Occurrence_Of (Temp, Loc));
682 R_Type := Etype (Temp);
683 end;
684 end if;
686 -- Come here to complete the analysis
688 -- Loop_Required: Set to True if we know that a loop is required
689 -- regardless of overlap considerations.
691 -- Forwards_OK: Set to False if we already know that a forwards
692 -- move is not safe, else set to True.
694 -- Backwards_OK: Set to False if we already know that a backwards
695 -- move is not safe, else set to True
697 -- Our task at this stage is to complete the overlap analysis, which can
698 -- result in possibly setting Forwards_OK or Backwards_OK to False, and
699 -- then generating the final code, either by deciding that it is OK
700 -- after all to let Gigi handle it, or by generating appropriate code
701 -- in the front end.
703 declare
704 L_Index_Typ : constant Node_Id := Etype (First_Index (L_Type));
705 R_Index_Typ : constant Node_Id := Etype (First_Index (R_Type));
707 Left_Lo : constant Node_Id := Type_Low_Bound (L_Index_Typ);
708 Left_Hi : constant Node_Id := Type_High_Bound (L_Index_Typ);
709 Right_Lo : constant Node_Id := Type_Low_Bound (R_Index_Typ);
710 Right_Hi : constant Node_Id := Type_High_Bound (R_Index_Typ);
712 Act_L_Array : Node_Id;
713 Act_R_Array : Node_Id;
715 Cleft_Lo : Node_Id;
716 Cright_Lo : Node_Id;
717 Condition : Node_Id;
719 Cresult : Compare_Result;
721 begin
722 -- Get the expressions for the arrays. If we are dealing with a
723 -- private type, then convert to the underlying type. We can do
724 -- direct assignments to an array that is a private type, but we
725 -- cannot assign to elements of the array without this extra
726 -- unchecked conversion.
728 -- Note: We propagate Parent to the conversion nodes to generate
729 -- a well-formed subtree.
731 if Nkind (Act_Lhs) = N_Slice then
732 Larray := Prefix (Act_Lhs);
733 else
734 Larray := Act_Lhs;
736 if Is_Private_Type (Etype (Larray)) then
737 declare
738 Par : constant Node_Id := Parent (Larray);
739 begin
740 Larray :=
741 Unchecked_Convert_To
742 (Underlying_Type (Etype (Larray)), Larray);
743 Set_Parent (Larray, Par);
744 end;
745 end if;
746 end if;
748 if Nkind (Act_Rhs) = N_Slice then
749 Rarray := Prefix (Act_Rhs);
750 else
751 Rarray := Act_Rhs;
753 if Is_Private_Type (Etype (Rarray)) then
754 declare
755 Par : constant Node_Id := Parent (Rarray);
756 begin
757 Rarray :=
758 Unchecked_Convert_To
759 (Underlying_Type (Etype (Rarray)), Rarray);
760 Set_Parent (Rarray, Par);
761 end;
762 end if;
763 end if;
765 -- If both sides are slices, we must figure out whether it is safe
766 -- to do the move in one direction or the other. It is always safe
767 -- if there is a change of representation since obviously two arrays
768 -- with different representations cannot possibly overlap.
770 if (not Crep) and L_Slice and R_Slice then
771 Act_L_Array := Get_Referenced_Object (Prefix (Act_Lhs));
772 Act_R_Array := Get_Referenced_Object (Prefix (Act_Rhs));
774 -- If both left- and right-hand arrays are entity names, and refer
775 -- to different entities, then we know that the move is safe (the
776 -- two storage areas are completely disjoint).
778 if Is_Entity_Name (Act_L_Array)
779 and then Is_Entity_Name (Act_R_Array)
780 and then Entity (Act_L_Array) /= Entity (Act_R_Array)
781 then
782 null;
784 -- Otherwise, we assume the worst, which is that the two arrays
785 -- are the same array. There is no need to check if we know that
786 -- is the case, because if we don't know it, we still have to
787 -- assume it.
789 -- Generally if the same array is involved, then we have an
790 -- overlapping case. We will have to really assume the worst (i.e.
791 -- set neither of the OK flags) unless we can determine the lower
792 -- or upper bounds at compile time and compare them.
794 else
795 Cresult :=
796 Compile_Time_Compare
797 (Left_Lo, Right_Lo, Assume_Valid => True);
799 if Cresult = Unknown then
800 Cresult :=
801 Compile_Time_Compare
802 (Left_Hi, Right_Hi, Assume_Valid => True);
803 end if;
805 case Cresult is
806 when EQ | LE | LT =>
807 Set_Backwards_OK (N, False);
809 when GE | GT =>
810 Set_Forwards_OK (N, False);
812 when NE | Unknown =>
813 Set_Backwards_OK (N, False);
814 Set_Forwards_OK (N, False);
815 end case;
816 end if;
817 end if;
819 -- If after that analysis Loop_Required is False, meaning that we
820 -- have not discovered some non-overlap reason for requiring a loop,
821 -- then the outcome depends on the capabilities of the back end.
823 if not Loop_Required then
824 -- Assume the back end can deal with all cases of overlap by
825 -- falling back to memmove if it cannot use a more efficient
826 -- approach.
828 return;
829 end if;
831 -- At this stage we have to generate an explicit loop, and we have
832 -- the following cases:
834 -- Forwards_OK = True
836 -- Rnn : right_index := right_index'First;
837 -- for Lnn in left-index loop
838 -- left (Lnn) := right (Rnn);
839 -- Rnn := right_index'Succ (Rnn);
840 -- end loop;
842 -- Note: the above code MUST be analyzed with checks off, because
843 -- otherwise the Succ could overflow. But in any case this is more
844 -- efficient.
846 -- Forwards_OK = False, Backwards_OK = True
848 -- Rnn : right_index := right_index'Last;
849 -- for Lnn in reverse left-index loop
850 -- left (Lnn) := right (Rnn);
851 -- Rnn := right_index'Pred (Rnn);
852 -- end loop;
854 -- Note: the above code MUST be analyzed with checks off, because
855 -- otherwise the Pred could overflow. But in any case this is more
856 -- efficient.
858 -- Forwards_OK = Backwards_OK = False
860 -- This only happens if we have the same array on each side. It is
861 -- possible to create situations using overlays that violate this,
862 -- but we simply do not promise to get this "right" in this case.
864 -- There are two possible subcases. If the No_Implicit_Conditionals
865 -- restriction is set, then we generate the following code:
867 -- declare
868 -- T : constant <operand-type> := rhs;
869 -- begin
870 -- lhs := T;
871 -- end;
873 -- If implicit conditionals are permitted, then we generate:
875 -- if Left_Lo <= Right_Lo then
876 -- <code for Forwards_OK = True above>
877 -- else
878 -- <code for Backwards_OK = True above>
879 -- end if;
881 -- In order to detect possible aliasing, we examine the renamed
882 -- expression when the source or target is a renaming. However,
883 -- the renaming may be intended to capture an address that may be
884 -- affected by subsequent code, and therefore we must recover
885 -- the actual entity for the expansion that follows, not the
886 -- object it renames. In particular, if source or target designate
887 -- a portion of a dynamically allocated object, the pointer to it
888 -- may be reassigned but the renaming preserves the proper location.
890 if Is_Entity_Name (Rhs)
891 and then
892 Nkind (Parent (Entity (Rhs))) = N_Object_Renaming_Declaration
893 and then Nkind (Act_Rhs) = N_Slice
894 then
895 Rarray := Rhs;
896 end if;
898 if Is_Entity_Name (Lhs)
899 and then
900 Nkind (Parent (Entity (Lhs))) = N_Object_Renaming_Declaration
901 and then Nkind (Act_Lhs) = N_Slice
902 then
903 Larray := Lhs;
904 end if;
906 -- Cases where either Forwards_OK or Backwards_OK is true
908 if Forwards_OK (N) or else Backwards_OK (N) then
909 if Needs_Finalization (Component_Type (L_Type))
910 and then Base_Type (L_Type) = Base_Type (R_Type)
911 and then Ndim = 1
912 and then not No_Ctrl_Actions (N)
913 then
914 declare
915 Proc : constant Entity_Id :=
916 TSS (Base_Type (L_Type), TSS_Slice_Assign);
917 Actuals : List_Id;
919 begin
920 Apply_Dereference (Larray);
921 Apply_Dereference (Rarray);
922 Actuals := New_List (
923 Duplicate_Subexpr (Larray, Name_Req => True),
924 Duplicate_Subexpr (Rarray, Name_Req => True),
925 Duplicate_Subexpr (Left_Lo, Name_Req => True),
926 Duplicate_Subexpr (Left_Hi, Name_Req => True),
927 Duplicate_Subexpr (Right_Lo, Name_Req => True),
928 Duplicate_Subexpr (Right_Hi, Name_Req => True));
930 Append_To (Actuals,
931 New_Occurrence_Of (
932 Boolean_Literals (not Forwards_OK (N)), Loc));
934 Rewrite (N,
935 Make_Procedure_Call_Statement (Loc,
936 Name => New_Occurrence_Of (Proc, Loc),
937 Parameter_Associations => Actuals));
938 end;
940 else
941 Rewrite (N,
942 Expand_Assign_Array_Loop
943 (N, Larray, Rarray, L_Type, R_Type, Ndim,
944 Rev => not Forwards_OK (N)));
945 end if;
947 -- Case of both are false with No_Implicit_Conditionals
949 elsif Restriction_Active (No_Implicit_Conditionals) then
950 declare
951 T : constant Entity_Id :=
952 Make_Defining_Identifier (Loc, Chars => Name_T);
954 begin
955 Rewrite (N,
956 Make_Block_Statement (Loc,
957 Declarations => New_List (
958 Make_Object_Declaration (Loc,
959 Defining_Identifier => T,
960 Constant_Present => True,
961 Object_Definition =>
962 New_Occurrence_Of (Etype (Rhs), Loc),
963 Expression => Relocate_Node (Rhs))),
965 Handled_Statement_Sequence =>
966 Make_Handled_Sequence_Of_Statements (Loc,
967 Statements => New_List (
968 Make_Assignment_Statement (Loc,
969 Name => Relocate_Node (Lhs),
970 Expression => New_Occurrence_Of (T, Loc))))));
971 end;
973 -- Case of both are false with implicit conditionals allowed
975 else
976 -- Before we generate this code, we must ensure that the left and
977 -- right side array types are defined. They may be itypes, and we
978 -- cannot let them be defined inside the if, since the first use
979 -- in the then may not be executed.
981 Ensure_Defined (L_Type, N);
982 Ensure_Defined (R_Type, N);
984 -- We normally compare addresses to find out which way round to
985 -- do the loop, since this is reliable, and handles the cases of
986 -- parameters, conversions etc. But we can't do that in the bit
987 -- packed case, because addresses don't work there.
989 if not Is_Bit_Packed_Array (L_Type) then
990 Condition :=
991 Make_Op_Le (Loc,
992 Left_Opnd =>
993 Unchecked_Convert_To (RTE (RE_Integer_Address),
994 Make_Attribute_Reference (Loc,
995 Prefix =>
996 Make_Indexed_Component (Loc,
997 Prefix =>
998 Duplicate_Subexpr_Move_Checks (Larray, True),
999 Expressions => New_List (
1000 Make_Attribute_Reference (Loc,
1001 Prefix =>
1002 New_Occurrence_Of
1003 (L_Index_Typ, Loc),
1004 Attribute_Name => Name_First))),
1005 Attribute_Name => Name_Address)),
1007 Right_Opnd =>
1008 Unchecked_Convert_To (RTE (RE_Integer_Address),
1009 Make_Attribute_Reference (Loc,
1010 Prefix =>
1011 Make_Indexed_Component (Loc,
1012 Prefix =>
1013 Duplicate_Subexpr_Move_Checks (Rarray, True),
1014 Expressions => New_List (
1015 Make_Attribute_Reference (Loc,
1016 Prefix =>
1017 New_Occurrence_Of
1018 (R_Index_Typ, Loc),
1019 Attribute_Name => Name_First))),
1020 Attribute_Name => Name_Address)));
1022 -- For the bit packed and VM cases we use the bounds. That's OK,
1023 -- because we don't have to worry about parameters, since they
1024 -- cannot cause overlap. Perhaps we should worry about weird slice
1025 -- conversions ???
1027 else
1028 -- Copy the bounds
1030 Cleft_Lo := New_Copy_Tree (Left_Lo);
1031 Cright_Lo := New_Copy_Tree (Right_Lo);
1033 -- If the types do not match we add an implicit conversion
1034 -- here to ensure proper match
1036 if Etype (Left_Lo) /= Etype (Right_Lo) then
1037 Cright_Lo :=
1038 Unchecked_Convert_To (Etype (Left_Lo), Cright_Lo);
1039 end if;
1041 -- Reset the Analyzed flag, because the bounds of the index
1042 -- type itself may be universal, and must must be reanalyzed
1043 -- to acquire the proper type for the back end.
1045 Set_Analyzed (Cleft_Lo, False);
1046 Set_Analyzed (Cright_Lo, False);
1048 Condition :=
1049 Make_Op_Le (Loc,
1050 Left_Opnd => Cleft_Lo,
1051 Right_Opnd => Cright_Lo);
1052 end if;
1054 if Needs_Finalization (Component_Type (L_Type))
1055 and then Base_Type (L_Type) = Base_Type (R_Type)
1056 and then Ndim = 1
1057 and then not No_Ctrl_Actions (N)
1058 then
1060 -- Call TSS procedure for array assignment, passing the
1061 -- explicit bounds of right- and left-hand sides.
1063 declare
1064 Proc : constant Entity_Id :=
1065 TSS (Base_Type (L_Type), TSS_Slice_Assign);
1066 Actuals : List_Id;
1068 begin
1069 Apply_Dereference (Larray);
1070 Apply_Dereference (Rarray);
1071 Actuals := New_List (
1072 Duplicate_Subexpr (Larray, Name_Req => True),
1073 Duplicate_Subexpr (Rarray, Name_Req => True),
1074 Duplicate_Subexpr (Left_Lo, Name_Req => True),
1075 Duplicate_Subexpr (Left_Hi, Name_Req => True),
1076 Duplicate_Subexpr (Right_Lo, Name_Req => True),
1077 Duplicate_Subexpr (Right_Hi, Name_Req => True));
1079 Append_To (Actuals,
1080 Make_Op_Not (Loc,
1081 Right_Opnd => Condition));
1083 Rewrite (N,
1084 Make_Procedure_Call_Statement (Loc,
1085 Name => New_Occurrence_Of (Proc, Loc),
1086 Parameter_Associations => Actuals));
1087 end;
1089 else
1090 Rewrite (N,
1091 Make_Implicit_If_Statement (N,
1092 Condition => Condition,
1094 Then_Statements => New_List (
1095 Expand_Assign_Array_Loop
1096 (N, Larray, Rarray, L_Type, R_Type, Ndim,
1097 Rev => False)),
1099 Else_Statements => New_List (
1100 Expand_Assign_Array_Loop
1101 (N, Larray, Rarray, L_Type, R_Type, Ndim,
1102 Rev => True))));
1103 end if;
1104 end if;
1106 Analyze (N, Suppress => All_Checks);
1107 end;
1109 exception
1110 when RE_Not_Available =>
1111 return;
1112 end Expand_Assign_Array;
1114 ------------------------------
1115 -- Expand_Assign_Array_Loop --
1116 ------------------------------
1118 -- The following is an example of the loop generated for the case of a
1119 -- two-dimensional array:
1121 -- declare
1122 -- R2b : Tm1X1 := 1;
1123 -- begin
1124 -- for L1b in 1 .. 100 loop
1125 -- declare
1126 -- R4b : Tm1X2 := 1;
1127 -- begin
1128 -- for L3b in 1 .. 100 loop
1129 -- vm1 (L1b, L3b) := vm2 (R2b, R4b);
1130 -- R4b := Tm1X2'succ(R4b);
1131 -- end loop;
1132 -- end;
1133 -- R2b := Tm1X1'succ(R2b);
1134 -- end loop;
1135 -- end;
1137 -- Here Rev is False, and Tm1Xn are the subscript types for the right-hand
1138 -- side. The declarations of R2b and R4b are inserted before the original
1139 -- assignment statement.
1141 function Expand_Assign_Array_Loop
1142 (N : Node_Id;
1143 Larray : Entity_Id;
1144 Rarray : Entity_Id;
1145 L_Type : Entity_Id;
1146 R_Type : Entity_Id;
1147 Ndim : Pos;
1148 Rev : Boolean) return Node_Id
1150 Loc : constant Source_Ptr := Sloc (N);
1152 Lnn : array (1 .. Ndim) of Entity_Id;
1153 Rnn : array (1 .. Ndim) of Entity_Id;
1154 -- Entities used as subscripts on left and right sides
1156 L_Index_Type : array (1 .. Ndim) of Entity_Id;
1157 R_Index_Type : array (1 .. Ndim) of Entity_Id;
1158 -- Left and right index types
1160 Assign : Node_Id;
1162 F_Or_L : Name_Id;
1163 S_Or_P : Name_Id;
1165 function Build_Step (J : Nat) return Node_Id;
1166 -- The increment step for the index of the right-hand side is written
1167 -- as an attribute reference (Succ or Pred). This function returns
1168 -- the corresponding node, which is placed at the end of the loop body.
1170 ----------------
1171 -- Build_Step --
1172 ----------------
1174 function Build_Step (J : Nat) return Node_Id is
1175 Step : Node_Id;
1176 Lim : Name_Id;
1178 begin
1179 if Rev then
1180 Lim := Name_First;
1181 else
1182 Lim := Name_Last;
1183 end if;
1185 Step :=
1186 Make_Assignment_Statement (Loc,
1187 Name => New_Occurrence_Of (Rnn (J), Loc),
1188 Expression =>
1189 Make_Attribute_Reference (Loc,
1190 Prefix =>
1191 New_Occurrence_Of (R_Index_Type (J), Loc),
1192 Attribute_Name => S_Or_P,
1193 Expressions => New_List (
1194 New_Occurrence_Of (Rnn (J), Loc))));
1196 -- Note that on the last iteration of the loop, the index is increased
1197 -- (or decreased) past the corresponding bound. This is consistent with
1198 -- the C semantics of the back-end, where such an off-by-one value on a
1199 -- dead index variable is OK. However, in CodePeer mode this leads to
1200 -- spurious warnings, and thus we place a guard around the attribute
1201 -- reference. For obvious reasons we only do this for CodePeer.
1203 if CodePeer_Mode then
1204 Step :=
1205 Make_If_Statement (Loc,
1206 Condition =>
1207 Make_Op_Ne (Loc,
1208 Left_Opnd => New_Occurrence_Of (Lnn (J), Loc),
1209 Right_Opnd =>
1210 Make_Attribute_Reference (Loc,
1211 Prefix => New_Occurrence_Of (L_Index_Type (J), Loc),
1212 Attribute_Name => Lim)),
1213 Then_Statements => New_List (Step));
1214 end if;
1216 return Step;
1217 end Build_Step;
1219 -- Start of processing for Expand_Assign_Array_Loop
1221 begin
1222 if Rev then
1223 F_Or_L := Name_Last;
1224 S_Or_P := Name_Pred;
1225 else
1226 F_Or_L := Name_First;
1227 S_Or_P := Name_Succ;
1228 end if;
1230 -- Setup index types and subscript entities
1232 declare
1233 L_Index : Node_Id;
1234 R_Index : Node_Id;
1236 begin
1237 L_Index := First_Index (L_Type);
1238 R_Index := First_Index (R_Type);
1240 for J in 1 .. Ndim loop
1241 Lnn (J) := Make_Temporary (Loc, 'L');
1242 Rnn (J) := Make_Temporary (Loc, 'R');
1244 L_Index_Type (J) := Etype (L_Index);
1245 R_Index_Type (J) := Etype (R_Index);
1247 Next_Index (L_Index);
1248 Next_Index (R_Index);
1249 end loop;
1250 end;
1252 -- Now construct the assignment statement
1254 declare
1255 ExprL : constant List_Id := New_List;
1256 ExprR : constant List_Id := New_List;
1258 begin
1259 for J in 1 .. Ndim loop
1260 Append_To (ExprL, New_Occurrence_Of (Lnn (J), Loc));
1261 Append_To (ExprR, New_Occurrence_Of (Rnn (J), Loc));
1262 end loop;
1264 Assign :=
1265 Make_Assignment_Statement (Loc,
1266 Name =>
1267 Make_Indexed_Component (Loc,
1268 Prefix => Duplicate_Subexpr (Larray, Name_Req => True),
1269 Expressions => ExprL),
1270 Expression =>
1271 Make_Indexed_Component (Loc,
1272 Prefix => Duplicate_Subexpr (Rarray, Name_Req => True),
1273 Expressions => ExprR));
1275 -- We set assignment OK, since there are some cases, e.g. in object
1276 -- declarations, where we are actually assigning into a constant.
1277 -- If there really is an illegality, it was caught long before now,
1278 -- and was flagged when the original assignment was analyzed.
1280 Set_Assignment_OK (Name (Assign));
1282 -- Propagate the No_Ctrl_Actions flag to individual assignments
1284 Set_No_Ctrl_Actions (Assign, No_Ctrl_Actions (N));
1285 end;
1287 -- Now construct the loop from the inside out, with the last subscript
1288 -- varying most rapidly. Note that Assign is first the raw assignment
1289 -- statement, and then subsequently the loop that wraps it up.
1291 for J in reverse 1 .. Ndim loop
1292 Assign :=
1293 Make_Block_Statement (Loc,
1294 Declarations => New_List (
1295 Make_Object_Declaration (Loc,
1296 Defining_Identifier => Rnn (J),
1297 Object_Definition =>
1298 New_Occurrence_Of (R_Index_Type (J), Loc),
1299 Expression =>
1300 Make_Attribute_Reference (Loc,
1301 Prefix => New_Occurrence_Of (R_Index_Type (J), Loc),
1302 Attribute_Name => F_Or_L))),
1304 Handled_Statement_Sequence =>
1305 Make_Handled_Sequence_Of_Statements (Loc,
1306 Statements => New_List (
1307 Make_Implicit_Loop_Statement (N,
1308 Iteration_Scheme =>
1309 Make_Iteration_Scheme (Loc,
1310 Loop_Parameter_Specification =>
1311 Make_Loop_Parameter_Specification (Loc,
1312 Defining_Identifier => Lnn (J),
1313 Reverse_Present => Rev,
1314 Discrete_Subtype_Definition =>
1315 New_Occurrence_Of (L_Index_Type (J), Loc))),
1317 Statements => New_List (Assign, Build_Step (J))))));
1318 end loop;
1320 return Assign;
1321 end Expand_Assign_Array_Loop;
1323 --------------------------
1324 -- Expand_Assign_Record --
1325 --------------------------
1327 procedure Expand_Assign_Record (N : Node_Id) is
1328 Lhs : constant Node_Id := Name (N);
1329 Rhs : Node_Id := Expression (N);
1330 L_Typ : constant Entity_Id := Base_Type (Etype (Lhs));
1332 begin
1333 -- If change of representation, then extract the real right-hand side
1334 -- from the type conversion, and proceed with component-wise assignment,
1335 -- since the two types are not the same as far as the back end is
1336 -- concerned.
1338 if Change_Of_Representation (N) then
1339 Rhs := Expression (Rhs);
1341 -- If this may be a case of a large bit aligned component, then proceed
1342 -- with component-wise assignment, to avoid possible clobbering of other
1343 -- components sharing bits in the first or last byte of the component to
1344 -- be assigned.
1346 elsif Possible_Bit_Aligned_Component (Lhs)
1348 Possible_Bit_Aligned_Component (Rhs)
1349 then
1350 null;
1352 -- If we have a tagged type that has a complete record representation
1353 -- clause, we must do we must do component-wise assignments, since child
1354 -- types may have used gaps for their components, and we might be
1355 -- dealing with a view conversion.
1357 elsif Is_Fully_Repped_Tagged_Type (L_Typ) then
1358 null;
1360 -- If neither condition met, then nothing special to do, the back end
1361 -- can handle assignment of the entire component as a single entity.
1363 else
1364 return;
1365 end if;
1367 -- At this stage we know that we must do a component wise assignment
1369 declare
1370 Loc : constant Source_Ptr := Sloc (N);
1371 R_Typ : constant Entity_Id := Base_Type (Etype (Rhs));
1372 Decl : constant Node_Id := Declaration_Node (R_Typ);
1373 RDef : Node_Id;
1374 F : Entity_Id;
1376 function Find_Component
1377 (Typ : Entity_Id;
1378 Comp : Entity_Id) return Entity_Id;
1379 -- Find the component with the given name in the underlying record
1380 -- declaration for Typ. We need to use the actual entity because the
1381 -- type may be private and resolution by identifier alone would fail.
1383 function Make_Component_List_Assign
1384 (CL : Node_Id;
1385 U_U : Boolean := False) return List_Id;
1386 -- Returns a sequence of statements to assign the components that
1387 -- are referenced in the given component list. The flag U_U is
1388 -- used to force the usage of the inferred value of the variant
1389 -- part expression as the switch for the generated case statement.
1391 function Make_Field_Assign
1392 (C : Entity_Id;
1393 U_U : Boolean := False) return Node_Id;
1394 -- Given C, the entity for a discriminant or component, build an
1395 -- assignment for the corresponding field values. The flag U_U
1396 -- signals the presence of an Unchecked_Union and forces the usage
1397 -- of the inferred discriminant value of C as the right-hand side
1398 -- of the assignment.
1400 function Make_Field_Assigns (CI : List_Id) return List_Id;
1401 -- Given CI, a component items list, construct series of statements
1402 -- for fieldwise assignment of the corresponding components.
1404 --------------------
1405 -- Find_Component --
1406 --------------------
1408 function Find_Component
1409 (Typ : Entity_Id;
1410 Comp : Entity_Id) return Entity_Id
1412 Utyp : constant Entity_Id := Underlying_Type (Typ);
1413 C : Entity_Id;
1415 begin
1416 C := First_Entity (Utyp);
1417 while Present (C) loop
1418 if Chars (C) = Chars (Comp) then
1419 return C;
1420 end if;
1422 Next_Entity (C);
1423 end loop;
1425 raise Program_Error;
1426 end Find_Component;
1428 --------------------------------
1429 -- Make_Component_List_Assign --
1430 --------------------------------
1432 function Make_Component_List_Assign
1433 (CL : Node_Id;
1434 U_U : Boolean := False) return List_Id
1436 CI : constant List_Id := Component_Items (CL);
1437 VP : constant Node_Id := Variant_Part (CL);
1439 Alts : List_Id;
1440 DC : Node_Id;
1441 DCH : List_Id;
1442 Expr : Node_Id;
1443 Result : List_Id;
1444 V : Node_Id;
1446 begin
1447 Result := Make_Field_Assigns (CI);
1449 if Present (VP) then
1450 V := First_Non_Pragma (Variants (VP));
1451 Alts := New_List;
1452 while Present (V) loop
1453 DCH := New_List;
1454 DC := First (Discrete_Choices (V));
1455 while Present (DC) loop
1456 Append_To (DCH, New_Copy_Tree (DC));
1457 Next (DC);
1458 end loop;
1460 Append_To (Alts,
1461 Make_Case_Statement_Alternative (Loc,
1462 Discrete_Choices => DCH,
1463 Statements =>
1464 Make_Component_List_Assign (Component_List (V))));
1465 Next_Non_Pragma (V);
1466 end loop;
1468 -- If we have an Unchecked_Union, use the value of the inferred
1469 -- discriminant of the variant part expression as the switch
1470 -- for the case statement. The case statement may later be
1471 -- folded.
1473 if U_U then
1474 Expr :=
1475 New_Copy (Get_Discriminant_Value (
1476 Entity (Name (VP)),
1477 Etype (Rhs),
1478 Discriminant_Constraint (Etype (Rhs))));
1479 else
1480 Expr :=
1481 Make_Selected_Component (Loc,
1482 Prefix => Duplicate_Subexpr (Rhs),
1483 Selector_Name =>
1484 Make_Identifier (Loc, Chars (Name (VP))));
1485 end if;
1487 Append_To (Result,
1488 Make_Case_Statement (Loc,
1489 Expression => Expr,
1490 Alternatives => Alts));
1491 end if;
1493 return Result;
1494 end Make_Component_List_Assign;
1496 -----------------------
1497 -- Make_Field_Assign --
1498 -----------------------
1500 function Make_Field_Assign
1501 (C : Entity_Id;
1502 U_U : Boolean := False) return Node_Id
1504 A : Node_Id;
1505 Disc : Entity_Id;
1506 Expr : Node_Id;
1508 begin
1509 -- The discriminant entity to be used in the retrieval below must
1510 -- be one in the corresponding type, given that the assignment may
1511 -- be between derived and parent types.
1513 if Is_Derived_Type (Etype (Rhs)) then
1514 Disc := Find_Component (R_Typ, C);
1515 else
1516 Disc := C;
1517 end if;
1519 -- In the case of an Unchecked_Union, use the discriminant
1520 -- constraint value as on the right-hand side of the assignment.
1522 if U_U then
1523 Expr :=
1524 New_Copy (Get_Discriminant_Value (C,
1525 Etype (Rhs),
1526 Discriminant_Constraint (Etype (Rhs))));
1527 else
1528 Expr :=
1529 Make_Selected_Component (Loc,
1530 Prefix => Duplicate_Subexpr (Rhs),
1531 Selector_Name => New_Occurrence_Of (Disc, Loc));
1532 end if;
1534 A :=
1535 Make_Assignment_Statement (Loc,
1536 Name =>
1537 Make_Selected_Component (Loc,
1538 Prefix => Duplicate_Subexpr (Lhs),
1539 Selector_Name =>
1540 New_Occurrence_Of (Find_Component (L_Typ, C), Loc)),
1541 Expression => Expr);
1543 -- Set Assignment_OK, so discriminants can be assigned
1545 Set_Assignment_OK (Name (A), True);
1547 if Componentwise_Assignment (N)
1548 and then Nkind (Name (A)) = N_Selected_Component
1549 and then Chars (Selector_Name (Name (A))) = Name_uParent
1550 then
1551 Set_Componentwise_Assignment (A);
1552 end if;
1554 return A;
1555 end Make_Field_Assign;
1557 ------------------------
1558 -- Make_Field_Assigns --
1559 ------------------------
1561 function Make_Field_Assigns (CI : List_Id) return List_Id is
1562 Item : Node_Id;
1563 Result : List_Id;
1565 begin
1566 Item := First (CI);
1567 Result := New_List;
1569 while Present (Item) loop
1571 -- Look for components, but exclude _tag field assignment if
1572 -- the special Componentwise_Assignment flag is set.
1574 if Nkind (Item) = N_Component_Declaration
1575 and then not (Is_Tag (Defining_Identifier (Item))
1576 and then Componentwise_Assignment (N))
1577 then
1578 Append_To
1579 (Result, Make_Field_Assign (Defining_Identifier (Item)));
1580 end if;
1582 Next (Item);
1583 end loop;
1585 return Result;
1586 end Make_Field_Assigns;
1588 -- Start of processing for Expand_Assign_Record
1590 begin
1591 -- Note that we use the base types for this processing. This results
1592 -- in some extra work in the constrained case, but the change of
1593 -- representation case is so unusual that it is not worth the effort.
1595 -- First copy the discriminants. This is done unconditionally. It
1596 -- is required in the unconstrained left side case, and also in the
1597 -- case where this assignment was constructed during the expansion
1598 -- of a type conversion (since initialization of discriminants is
1599 -- suppressed in this case). It is unnecessary but harmless in
1600 -- other cases.
1602 -- Special case: no copy if the target has no discriminants
1604 if Has_Discriminants (L_Typ)
1605 and then Is_Unchecked_Union (Base_Type (L_Typ))
1606 then
1607 null;
1609 elsif Has_Discriminants (L_Typ) then
1610 F := First_Discriminant (R_Typ);
1611 while Present (F) loop
1613 -- If we are expanding the initialization of a derived record
1614 -- that constrains or renames discriminants of the parent, we
1615 -- must use the corresponding discriminant in the parent.
1617 declare
1618 CF : Entity_Id;
1620 begin
1621 if Inside_Init_Proc
1622 and then Present (Corresponding_Discriminant (F))
1623 then
1624 CF := Corresponding_Discriminant (F);
1625 else
1626 CF := F;
1627 end if;
1629 if Is_Unchecked_Union (Base_Type (R_Typ)) then
1631 -- Within an initialization procedure this is the
1632 -- assignment to an unchecked union component, in which
1633 -- case there is no discriminant to initialize.
1635 if Inside_Init_Proc then
1636 null;
1638 else
1639 -- The assignment is part of a conversion from a
1640 -- derived unchecked union type with an inferable
1641 -- discriminant, to a parent type.
1643 Insert_Action (N, Make_Field_Assign (CF, True));
1644 end if;
1646 else
1647 Insert_Action (N, Make_Field_Assign (CF));
1648 end if;
1650 Next_Discriminant (F);
1651 end;
1652 end loop;
1654 -- If the derived type has a stored constraint, assign the value
1655 -- of the corresponding discriminants explicitly, skipping those
1656 -- that are renamed discriminants. We cannot just retrieve them
1657 -- from the Rhs by selected component because they are invisible
1658 -- in the type of the right-hand side.
1660 if Stored_Constraint (R_Typ) /= No_Elist then
1661 declare
1662 Assign : Node_Id;
1663 Discr_Val : Elmt_Id;
1665 begin
1666 Discr_Val := First_Elmt (Stored_Constraint (R_Typ));
1667 F := First_Entity (R_Typ);
1668 while Present (F) loop
1669 if Ekind (F) = E_Discriminant
1670 and then Is_Completely_Hidden (F)
1671 and then Present (Corresponding_Record_Component (F))
1672 and then
1673 (not Is_Entity_Name (Node (Discr_Val))
1674 or else Ekind (Entity (Node (Discr_Val))) /=
1675 E_Discriminant)
1676 then
1677 Assign :=
1678 Make_Assignment_Statement (Loc,
1679 Name =>
1680 Make_Selected_Component (Loc,
1681 Prefix => Duplicate_Subexpr (Lhs),
1682 Selector_Name =>
1683 New_Occurrence_Of
1684 (Corresponding_Record_Component (F), Loc)),
1685 Expression => New_Copy (Node (Discr_Val)));
1687 Set_Assignment_OK (Name (Assign));
1688 Insert_Action (N, Assign);
1689 Next_Elmt (Discr_Val);
1690 end if;
1692 Next_Entity (F);
1693 end loop;
1694 end;
1695 end if;
1696 end if;
1698 -- We know the underlying type is a record, but its current view
1699 -- may be private. We must retrieve the usable record declaration.
1701 if Nkind_In (Decl, N_Private_Type_Declaration,
1702 N_Private_Extension_Declaration)
1703 and then Present (Full_View (R_Typ))
1704 then
1705 RDef := Type_Definition (Declaration_Node (Full_View (R_Typ)));
1706 else
1707 RDef := Type_Definition (Decl);
1708 end if;
1710 if Nkind (RDef) = N_Derived_Type_Definition then
1711 RDef := Record_Extension_Part (RDef);
1712 end if;
1714 if Nkind (RDef) = N_Record_Definition
1715 and then Present (Component_List (RDef))
1716 then
1717 if Is_Unchecked_Union (R_Typ) then
1718 Insert_Actions (N,
1719 Make_Component_List_Assign (Component_List (RDef), True));
1720 else
1721 Insert_Actions
1722 (N, Make_Component_List_Assign (Component_List (RDef)));
1723 end if;
1725 Rewrite (N, Make_Null_Statement (Loc));
1726 end if;
1727 end;
1728 end Expand_Assign_Record;
1730 -------------------------------------
1731 -- Expand_Assign_With_Target_Names --
1732 -------------------------------------
1734 procedure Expand_Assign_With_Target_Names (N : Node_Id) is
1735 LHS : constant Node_Id := Name (N);
1736 LHS_Typ : constant Entity_Id := Etype (LHS);
1737 Loc : constant Source_Ptr := Sloc (N);
1738 RHS : constant Node_Id := Expression (N);
1740 Ent : Entity_Id;
1741 -- The entity of the left-hand side
1743 function Replace_Target (N : Node_Id) return Traverse_Result;
1744 -- Replace occurrences of the target name by the proper entity: either
1745 -- the entity of the LHS in simple cases, or the formal of the
1746 -- constructed procedure otherwise.
1748 --------------------
1749 -- Replace_Target --
1750 --------------------
1752 function Replace_Target (N : Node_Id) return Traverse_Result is
1753 begin
1754 if Nkind (N) = N_Target_Name then
1755 Rewrite (N, New_Occurrence_Of (Ent, Sloc (N)));
1757 -- The expression will be reanalyzed when the enclosing assignment
1758 -- is reanalyzed, so reset the entity, which may be a temporary
1759 -- created during analysis, e.g. a loop variable for an iterated
1760 -- component association. However, if entity is callable then
1761 -- resolution has established its proper identity (including in
1762 -- rewritten prefixed calls) so we must preserve it.
1764 elsif Is_Entity_Name (N) then
1765 if Present (Entity (N))
1766 and then not Is_Overloadable (Entity (N))
1767 then
1768 Set_Entity (N, Empty);
1769 end if;
1770 end if;
1772 Set_Analyzed (N, False);
1773 return OK;
1774 end Replace_Target;
1776 procedure Replace_Target_Name is new Traverse_Proc (Replace_Target);
1778 -- Local variables
1780 New_RHS : Node_Id;
1781 Proc_Id : Entity_Id;
1783 -- Start of processing for Expand_Assign_With_Target_Names
1785 begin
1786 New_RHS := New_Copy_Tree (RHS);
1788 -- The left-hand side is a direct name
1790 if Is_Entity_Name (LHS)
1791 and then not Is_Renaming_Of_Object (Entity (LHS))
1792 then
1793 Ent := Entity (LHS);
1794 Replace_Target_Name (New_RHS);
1796 -- Generate:
1797 -- LHS := ... LHS ...;
1799 Rewrite (N,
1800 Make_Assignment_Statement (Loc,
1801 Name => Relocate_Node (LHS),
1802 Expression => New_RHS));
1804 -- The left-hand side is not a direct name, but is side-effect free.
1805 -- Capture its value in a temporary to avoid multiple evaluations.
1807 elsif Side_Effect_Free (LHS) then
1808 Ent := Make_Temporary (Loc, 'T');
1809 Replace_Target_Name (New_RHS);
1811 -- Generate:
1812 -- T : LHS_Typ := LHS;
1814 Insert_Before_And_Analyze (N,
1815 Make_Object_Declaration (Loc,
1816 Defining_Identifier => Ent,
1817 Object_Definition => New_Occurrence_Of (LHS_Typ, Loc),
1818 Expression => New_Copy_Tree (LHS)));
1820 -- Generate:
1821 -- LHS := ... T ...;
1823 Rewrite (N,
1824 Make_Assignment_Statement (Loc,
1825 Name => Relocate_Node (LHS),
1826 Expression => New_RHS));
1828 -- Otherwise wrap the whole assignment statement in a procedure with an
1829 -- IN OUT parameter. The original assignment then becomes a call to the
1830 -- procedure with the left-hand side as an actual.
1832 else
1833 Ent := Make_Temporary (Loc, 'T');
1834 Replace_Target_Name (New_RHS);
1836 -- Generate:
1837 -- procedure P (T : in out LHS_Typ) is
1838 -- begin
1839 -- T := ... T ...;
1840 -- end P;
1842 Proc_Id := Make_Temporary (Loc, 'P');
1844 Insert_Before_And_Analyze (N,
1845 Make_Subprogram_Body (Loc,
1846 Specification =>
1847 Make_Procedure_Specification (Loc,
1848 Defining_Unit_Name => Proc_Id,
1849 Parameter_Specifications => New_List (
1850 Make_Parameter_Specification (Loc,
1851 Defining_Identifier => Ent,
1852 In_Present => True,
1853 Out_Present => True,
1854 Parameter_Type =>
1855 New_Occurrence_Of (LHS_Typ, Loc)))),
1857 Declarations => Empty_List,
1859 Handled_Statement_Sequence =>
1860 Make_Handled_Sequence_Of_Statements (Loc,
1861 Statements => New_List (
1862 Make_Assignment_Statement (Loc,
1863 Name => New_Occurrence_Of (Ent, Loc),
1864 Expression => New_RHS)))));
1866 -- Generate:
1867 -- P (LHS);
1869 Rewrite (N,
1870 Make_Procedure_Call_Statement (Loc,
1871 Name => New_Occurrence_Of (Proc_Id, Loc),
1872 Parameter_Associations => New_List (Relocate_Node (LHS))));
1873 end if;
1875 -- Analyze rewritten node, either as assignment or procedure call
1877 Analyze (N);
1878 end Expand_Assign_With_Target_Names;
1880 -----------------------------------
1881 -- Expand_N_Assignment_Statement --
1882 -----------------------------------
1884 -- This procedure implements various cases where an assignment statement
1885 -- cannot just be passed on to the back end in untransformed state.
1887 procedure Expand_N_Assignment_Statement (N : Node_Id) is
1888 Crep : constant Boolean := Change_Of_Representation (N);
1889 Lhs : constant Node_Id := Name (N);
1890 Loc : constant Source_Ptr := Sloc (N);
1891 Rhs : constant Node_Id := Expression (N);
1892 Typ : constant Entity_Id := Underlying_Type (Etype (Lhs));
1893 Exp : Node_Id;
1895 begin
1896 -- Special case to check right away, if the Componentwise_Assignment
1897 -- flag is set, this is a reanalysis from the expansion of the primitive
1898 -- assignment procedure for a tagged type, and all we need to do is to
1899 -- expand to assignment of components, because otherwise, we would get
1900 -- infinite recursion (since this looks like a tagged assignment which
1901 -- would normally try to *call* the primitive assignment procedure).
1903 if Componentwise_Assignment (N) then
1904 Expand_Assign_Record (N);
1905 return;
1906 end if;
1908 -- Defend against invalid subscripts on left side if we are in standard
1909 -- validity checking mode. No need to do this if we are checking all
1910 -- subscripts.
1912 -- Note that we do this right away, because there are some early return
1913 -- paths in this procedure, and this is required on all paths.
1915 if Validity_Checks_On
1916 and then Validity_Check_Default
1917 and then not Validity_Check_Subscripts
1918 then
1919 Check_Valid_Lvalue_Subscripts (Lhs);
1920 end if;
1922 -- Separate expansion if RHS contain target names. Note that assignment
1923 -- may already have been expanded if RHS is aggregate.
1925 if Nkind (N) = N_Assignment_Statement and then Has_Target_Names (N) then
1926 Expand_Assign_With_Target_Names (N);
1927 return;
1928 end if;
1930 -- Ada 2005 (AI-327): Handle assignment to priority of protected object
1932 -- Rewrite an assignment to X'Priority into a run-time call
1934 -- For example: X'Priority := New_Prio_Expr;
1935 -- ...is expanded into Set_Ceiling (X._Object, New_Prio_Expr);
1937 -- Note that although X'Priority is notionally an object, it is quite
1938 -- deliberately not defined as an aliased object in the RM. This means
1939 -- that it works fine to rewrite it as a call, without having to worry
1940 -- about complications that would other arise from X'Priority'Access,
1941 -- which is illegal, because of the lack of aliasing.
1943 if Ada_Version >= Ada_2005 then
1944 declare
1945 Call : Node_Id;
1946 Conctyp : Entity_Id;
1947 Ent : Entity_Id;
1948 Subprg : Entity_Id;
1949 RT_Subprg_Name : Node_Id;
1951 begin
1952 -- Handle chains of renamings
1954 Ent := Name (N);
1955 while Nkind (Ent) in N_Has_Entity
1956 and then Present (Entity (Ent))
1957 and then Present (Renamed_Object (Entity (Ent)))
1958 loop
1959 Ent := Renamed_Object (Entity (Ent));
1960 end loop;
1962 -- The attribute Priority applied to protected objects has been
1963 -- previously expanded into a call to the Get_Ceiling run-time
1964 -- subprogram. In restricted profiles this is not available.
1966 if Is_Expanded_Priority_Attribute (Ent) then
1968 -- Look for the enclosing concurrent type
1970 Conctyp := Current_Scope;
1971 while not Is_Concurrent_Type (Conctyp) loop
1972 Conctyp := Scope (Conctyp);
1973 end loop;
1975 pragma Assert (Is_Protected_Type (Conctyp));
1977 -- Generate the first actual of the call
1979 Subprg := Current_Scope;
1980 while not Present (Protected_Body_Subprogram (Subprg)) loop
1981 Subprg := Scope (Subprg);
1982 end loop;
1984 -- Select the appropriate run-time call
1986 if Number_Entries (Conctyp) = 0 then
1987 RT_Subprg_Name :=
1988 New_Occurrence_Of (RTE (RE_Set_Ceiling), Loc);
1989 else
1990 RT_Subprg_Name :=
1991 New_Occurrence_Of (RTE (RO_PE_Set_Ceiling), Loc);
1992 end if;
1994 Call :=
1995 Make_Procedure_Call_Statement (Loc,
1996 Name => RT_Subprg_Name,
1997 Parameter_Associations => New_List (
1998 New_Copy_Tree (First (Parameter_Associations (Ent))),
1999 Relocate_Node (Expression (N))));
2001 Rewrite (N, Call);
2002 Analyze (N);
2004 return;
2005 end if;
2006 end;
2007 end if;
2009 -- Deal with assignment checks unless suppressed
2011 if not Suppress_Assignment_Checks (N) then
2013 -- First deal with generation of range check if required
2015 if Do_Range_Check (Rhs) then
2016 Generate_Range_Check (Rhs, Typ, CE_Range_Check_Failed);
2017 end if;
2019 -- Then generate predicate check if required
2021 Apply_Predicate_Check (Rhs, Typ);
2022 end if;
2024 -- Check for a special case where a high level transformation is
2025 -- required. If we have either of:
2027 -- P.field := rhs;
2028 -- P (sub) := rhs;
2030 -- where P is a reference to a bit packed array, then we have to unwind
2031 -- the assignment. The exact meaning of being a reference to a bit
2032 -- packed array is as follows:
2034 -- An indexed component whose prefix is a bit packed array is a
2035 -- reference to a bit packed array.
2037 -- An indexed component or selected component whose prefix is a
2038 -- reference to a bit packed array is itself a reference ot a
2039 -- bit packed array.
2041 -- The required transformation is
2043 -- Tnn : prefix_type := P;
2044 -- Tnn.field := rhs;
2045 -- P := Tnn;
2047 -- or
2049 -- Tnn : prefix_type := P;
2050 -- Tnn (subscr) := rhs;
2051 -- P := Tnn;
2053 -- Since P is going to be evaluated more than once, any subscripts
2054 -- in P must have their evaluation forced.
2056 if Nkind_In (Lhs, N_Indexed_Component, N_Selected_Component)
2057 and then Is_Ref_To_Bit_Packed_Array (Prefix (Lhs))
2058 then
2059 declare
2060 BPAR_Expr : constant Node_Id := Relocate_Node (Prefix (Lhs));
2061 BPAR_Typ : constant Entity_Id := Etype (BPAR_Expr);
2062 Tnn : constant Entity_Id :=
2063 Make_Temporary (Loc, 'T', BPAR_Expr);
2065 begin
2066 -- Insert the post assignment first, because we want to copy the
2067 -- BPAR_Expr tree before it gets analyzed in the context of the
2068 -- pre assignment. Note that we do not analyze the post assignment
2069 -- yet (we cannot till we have completed the analysis of the pre
2070 -- assignment). As usual, the analysis of this post assignment
2071 -- will happen on its own when we "run into" it after finishing
2072 -- the current assignment.
2074 Insert_After (N,
2075 Make_Assignment_Statement (Loc,
2076 Name => New_Copy_Tree (BPAR_Expr),
2077 Expression => New_Occurrence_Of (Tnn, Loc)));
2079 -- At this stage BPAR_Expr is a reference to a bit packed array
2080 -- where the reference was not expanded in the original tree,
2081 -- since it was on the left side of an assignment. But in the
2082 -- pre-assignment statement (the object definition), BPAR_Expr
2083 -- will end up on the right-hand side, and must be reexpanded. To
2084 -- achieve this, we reset the analyzed flag of all selected and
2085 -- indexed components down to the actual indexed component for
2086 -- the packed array.
2088 Exp := BPAR_Expr;
2089 loop
2090 Set_Analyzed (Exp, False);
2092 if Nkind_In (Exp, N_Indexed_Component,
2093 N_Selected_Component)
2094 then
2095 Exp := Prefix (Exp);
2096 else
2097 exit;
2098 end if;
2099 end loop;
2101 -- Now we can insert and analyze the pre-assignment
2103 -- If the right-hand side requires a transient scope, it has
2104 -- already been placed on the stack. However, the declaration is
2105 -- inserted in the tree outside of this scope, and must reflect
2106 -- the proper scope for its variable. This awkward bit is forced
2107 -- by the stricter scope discipline imposed by GCC 2.97.
2109 declare
2110 Uses_Transient_Scope : constant Boolean :=
2111 Scope_Is_Transient
2112 and then N = Node_To_Be_Wrapped;
2114 begin
2115 if Uses_Transient_Scope then
2116 Push_Scope (Scope (Current_Scope));
2117 end if;
2119 Insert_Before_And_Analyze (N,
2120 Make_Object_Declaration (Loc,
2121 Defining_Identifier => Tnn,
2122 Object_Definition => New_Occurrence_Of (BPAR_Typ, Loc),
2123 Expression => BPAR_Expr));
2125 if Uses_Transient_Scope then
2126 Pop_Scope;
2127 end if;
2128 end;
2130 -- Now fix up the original assignment and continue processing
2132 Rewrite (Prefix (Lhs),
2133 New_Occurrence_Of (Tnn, Loc));
2135 -- We do not need to reanalyze that assignment, and we do not need
2136 -- to worry about references to the temporary, but we do need to
2137 -- make sure that the temporary is not marked as a true constant
2138 -- since we now have a generated assignment to it.
2140 Set_Is_True_Constant (Tnn, False);
2141 end;
2142 end if;
2144 -- When we have the appropriate type of aggregate in the expression (it
2145 -- has been determined during analysis of the aggregate by setting the
2146 -- delay flag), let's perform in place assignment and thus avoid
2147 -- creating a temporary.
2149 if Is_Delayed_Aggregate (Rhs) then
2150 Convert_Aggr_In_Assignment (N);
2151 Rewrite (N, Make_Null_Statement (Loc));
2152 Analyze (N);
2154 return;
2155 end if;
2157 -- Apply discriminant check if required. If Lhs is an access type to a
2158 -- designated type with discriminants, we must always check. If the
2159 -- type has unknown discriminants, more elaborate processing below.
2161 if Has_Discriminants (Etype (Lhs))
2162 and then not Has_Unknown_Discriminants (Etype (Lhs))
2163 then
2164 -- Skip discriminant check if change of representation. Will be
2165 -- done when the change of representation is expanded out.
2167 if not Crep then
2168 Apply_Discriminant_Check (Rhs, Etype (Lhs), Lhs);
2169 end if;
2171 -- If the type is private without discriminants, and the full type
2172 -- has discriminants (necessarily with defaults) a check may still be
2173 -- necessary if the Lhs is aliased. The private discriminants must be
2174 -- visible to build the discriminant constraints.
2176 -- Only an explicit dereference that comes from source indicates
2177 -- aliasing. Access to formals of protected operations and entries
2178 -- create dereferences but are not semantic aliasings.
2180 elsif Is_Private_Type (Etype (Lhs))
2181 and then Has_Discriminants (Typ)
2182 and then Nkind (Lhs) = N_Explicit_Dereference
2183 and then Comes_From_Source (Lhs)
2184 then
2185 declare
2186 Lt : constant Entity_Id := Etype (Lhs);
2187 Ubt : Entity_Id := Base_Type (Typ);
2189 begin
2190 -- In the case of an expander-generated record subtype whose base
2191 -- type still appears private, Typ will have been set to that
2192 -- private type rather than the underlying record type (because
2193 -- Underlying type will have returned the record subtype), so it's
2194 -- necessary to apply Underlying_Type again to the base type to
2195 -- get the record type we need for the discriminant check. Such
2196 -- subtypes can be created for assignments in certain cases, such
2197 -- as within an instantiation passed this kind of private type.
2198 -- It would be good to avoid this special test, but making changes
2199 -- to prevent this odd form of record subtype seems difficult. ???
2201 if Is_Private_Type (Ubt) then
2202 Ubt := Underlying_Type (Ubt);
2203 end if;
2205 Set_Etype (Lhs, Ubt);
2206 Rewrite (Rhs, OK_Convert_To (Base_Type (Ubt), Rhs));
2207 Apply_Discriminant_Check (Rhs, Ubt, Lhs);
2208 Set_Etype (Lhs, Lt);
2209 end;
2211 -- If the Lhs has a private type with unknown discriminants, it may
2212 -- have a full view with discriminants, but those are nameable only
2213 -- in the underlying type, so convert the Rhs to it before potential
2214 -- checking. Convert Lhs as well, otherwise the actual subtype might
2215 -- not be constructible. If the discriminants have defaults the type
2216 -- is unconstrained and there is nothing to check.
2218 elsif Has_Unknown_Discriminants (Base_Type (Etype (Lhs)))
2219 and then Has_Discriminants (Typ)
2220 and then not Has_Defaulted_Discriminants (Typ)
2221 then
2222 Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
2223 Rewrite (Lhs, OK_Convert_To (Base_Type (Typ), Lhs));
2224 Apply_Discriminant_Check (Rhs, Typ, Lhs);
2226 -- In the access type case, we need the same discriminant check, and
2227 -- also range checks if we have an access to constrained array.
2229 elsif Is_Access_Type (Etype (Lhs))
2230 and then Is_Constrained (Designated_Type (Etype (Lhs)))
2231 then
2232 if Has_Discriminants (Designated_Type (Etype (Lhs))) then
2234 -- Skip discriminant check if change of representation. Will be
2235 -- done when the change of representation is expanded out.
2237 if not Crep then
2238 Apply_Discriminant_Check (Rhs, Etype (Lhs));
2239 end if;
2241 elsif Is_Array_Type (Designated_Type (Etype (Lhs))) then
2242 Apply_Range_Check (Rhs, Etype (Lhs));
2244 if Is_Constrained (Etype (Lhs)) then
2245 Apply_Length_Check (Rhs, Etype (Lhs));
2246 end if;
2248 if Nkind (Rhs) = N_Allocator then
2249 declare
2250 Target_Typ : constant Entity_Id := Etype (Expression (Rhs));
2251 C_Es : Check_Result;
2253 begin
2254 C_Es :=
2255 Get_Range_Checks
2256 (Lhs,
2257 Target_Typ,
2258 Etype (Designated_Type (Etype (Lhs))));
2260 Insert_Range_Checks
2261 (C_Es,
2263 Target_Typ,
2264 Sloc (Lhs),
2265 Lhs);
2266 end;
2267 end if;
2268 end if;
2270 -- Apply range check for access type case
2272 elsif Is_Access_Type (Etype (Lhs))
2273 and then Nkind (Rhs) = N_Allocator
2274 and then Nkind (Expression (Rhs)) = N_Qualified_Expression
2275 then
2276 Analyze_And_Resolve (Expression (Rhs));
2277 Apply_Range_Check
2278 (Expression (Rhs), Designated_Type (Etype (Lhs)));
2279 end if;
2281 -- Ada 2005 (AI-231): Generate the run-time check
2283 if Is_Access_Type (Typ)
2284 and then Can_Never_Be_Null (Etype (Lhs))
2285 and then not Can_Never_Be_Null (Etype (Rhs))
2287 -- If an actual is an out parameter of a null-excluding access
2288 -- type, there is access check on entry, so we set the flag
2289 -- Suppress_Assignment_Checks on the generated statement to
2290 -- assign the actual to the parameter block, and we do not want
2291 -- to generate an additional check at this point.
2293 and then not Suppress_Assignment_Checks (N)
2294 then
2295 Apply_Constraint_Check (Rhs, Etype (Lhs));
2296 end if;
2298 -- Ada 2012 (AI05-148): Update current accessibility level if Rhs is a
2299 -- stand-alone obj of an anonymous access type. Do not install the check
2300 -- when the Lhs denotes a container cursor and the Next function employs
2301 -- an access type, because this can never result in a dangling pointer.
2303 if Is_Access_Type (Typ)
2304 and then Is_Entity_Name (Lhs)
2305 and then Ekind (Entity (Lhs)) /= E_Loop_Parameter
2306 and then Present (Effective_Extra_Accessibility (Entity (Lhs)))
2307 then
2308 declare
2309 function Lhs_Entity return Entity_Id;
2310 -- Look through renames to find the underlying entity.
2311 -- For assignment to a rename, we don't care about the
2312 -- Enclosing_Dynamic_Scope of the rename declaration.
2314 ----------------
2315 -- Lhs_Entity --
2316 ----------------
2318 function Lhs_Entity return Entity_Id is
2319 Result : Entity_Id := Entity (Lhs);
2321 begin
2322 while Present (Renamed_Object (Result)) loop
2324 -- Renamed_Object must return an Entity_Name here
2325 -- because of preceding "Present (E_E_A (...))" test.
2327 Result := Entity (Renamed_Object (Result));
2328 end loop;
2330 return Result;
2331 end Lhs_Entity;
2333 -- Local Declarations
2335 Access_Check : constant Node_Id :=
2336 Make_Raise_Program_Error (Loc,
2337 Condition =>
2338 Make_Op_Gt (Loc,
2339 Left_Opnd =>
2340 Dynamic_Accessibility_Level (Rhs),
2341 Right_Opnd =>
2342 Make_Integer_Literal (Loc,
2343 Intval =>
2344 Scope_Depth
2345 (Enclosing_Dynamic_Scope
2346 (Lhs_Entity)))),
2347 Reason => PE_Accessibility_Check_Failed);
2349 Access_Level_Update : constant Node_Id :=
2350 Make_Assignment_Statement (Loc,
2351 Name =>
2352 New_Occurrence_Of
2353 (Effective_Extra_Accessibility
2354 (Entity (Lhs)), Loc),
2355 Expression =>
2356 Dynamic_Accessibility_Level (Rhs));
2358 begin
2359 if not Accessibility_Checks_Suppressed (Entity (Lhs)) then
2360 Insert_Action (N, Access_Check);
2361 end if;
2363 Insert_Action (N, Access_Level_Update);
2364 end;
2365 end if;
2367 -- Case of assignment to a bit packed array element. If there is a
2368 -- change of representation this must be expanded into components,
2369 -- otherwise this is a bit-field assignment.
2371 if Nkind (Lhs) = N_Indexed_Component
2372 and then Is_Bit_Packed_Array (Etype (Prefix (Lhs)))
2373 then
2374 -- Normal case, no change of representation
2376 if not Crep then
2377 Expand_Bit_Packed_Element_Set (N);
2378 return;
2380 -- Change of representation case
2382 else
2383 -- Generate the following, to force component-by-component
2384 -- assignments in an efficient way. Otherwise each component
2385 -- will require a temporary and two bit-field manipulations.
2387 -- T1 : Elmt_Type;
2388 -- T1 := RhS;
2389 -- Lhs := T1;
2391 declare
2392 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T');
2393 Stats : List_Id;
2395 begin
2396 Stats :=
2397 New_List (
2398 Make_Object_Declaration (Loc,
2399 Defining_Identifier => Tnn,
2400 Object_Definition =>
2401 New_Occurrence_Of (Etype (Lhs), Loc)),
2402 Make_Assignment_Statement (Loc,
2403 Name => New_Occurrence_Of (Tnn, Loc),
2404 Expression => Relocate_Node (Rhs)),
2405 Make_Assignment_Statement (Loc,
2406 Name => Relocate_Node (Lhs),
2407 Expression => New_Occurrence_Of (Tnn, Loc)));
2409 Insert_Actions (N, Stats);
2410 Rewrite (N, Make_Null_Statement (Loc));
2411 Analyze (N);
2412 end;
2413 end if;
2415 -- Build-in-place function call case. This is for assignment statements
2416 -- that come from aggregate component associations or from init procs.
2417 -- User-written assignment statements with b-i-p calls are handled
2418 -- elsewhere.
2420 elsif Is_Build_In_Place_Function_Call (Rhs) then
2421 pragma Assert (not Comes_From_Source (N));
2422 Make_Build_In_Place_Call_In_Assignment (N, Rhs);
2424 elsif Is_Tagged_Type (Typ)
2425 or else (Needs_Finalization (Typ) and then not Is_Array_Type (Typ))
2426 then
2427 Tagged_Case : declare
2428 L : List_Id := No_List;
2429 Expand_Ctrl_Actions : constant Boolean := not No_Ctrl_Actions (N);
2431 begin
2432 -- In the controlled case, we ensure that function calls are
2433 -- evaluated before finalizing the target. In all cases, it makes
2434 -- the expansion easier if the side effects are removed first.
2436 Remove_Side_Effects (Lhs);
2437 Remove_Side_Effects (Rhs);
2439 -- Avoid recursion in the mechanism
2441 Set_Analyzed (N);
2443 -- If dispatching assignment, we need to dispatch to _assign
2445 if Is_Class_Wide_Type (Typ)
2447 -- If the type is tagged, we may as well use the predefined
2448 -- primitive assignment. This avoids inlining a lot of code
2449 -- and in the class-wide case, the assignment is replaced
2450 -- by a dispatching call to _assign. It is suppressed in the
2451 -- case of assignments created by the expander that correspond
2452 -- to initializations, where we do want to copy the tag
2453 -- (Expand_Ctrl_Actions flag is set False in this case). It is
2454 -- also suppressed if restriction No_Dispatching_Calls is in
2455 -- force because in that case predefined primitives are not
2456 -- generated.
2458 or else (Is_Tagged_Type (Typ)
2459 and then Chars (Current_Scope) /= Name_uAssign
2460 and then Expand_Ctrl_Actions
2461 and then
2462 not Restriction_Active (No_Dispatching_Calls))
2463 then
2464 if Is_Limited_Type (Typ) then
2466 -- This can happen in an instance when the formal is an
2467 -- extension of a limited interface, and the actual is
2468 -- limited. This is an error according to AI05-0087, but
2469 -- is not caught at the point of instantiation in earlier
2470 -- versions. We also must verify that the limited type does
2471 -- not come from source as corner cases may exist where
2472 -- an assignment was not intended like the pathological case
2473 -- of a raise expression within a return statement.
2475 -- This is wrong, error messages cannot be issued during
2476 -- expansion, since they would be missed in -gnatc mode ???
2478 if Comes_From_Source (N) then
2479 Error_Msg_N
2480 ("assignment not available on limited type", N);
2481 end if;
2483 return;
2484 end if;
2486 -- Fetch the primitive op _assign and proper type to call it.
2487 -- Because of possible conflicts between private and full view,
2488 -- fetch the proper type directly from the operation profile.
2490 declare
2491 Op : constant Entity_Id :=
2492 Find_Prim_Op (Typ, Name_uAssign);
2493 F_Typ : Entity_Id := Etype (First_Formal (Op));
2495 begin
2496 -- If the assignment is dispatching, make sure to use the
2497 -- proper type.
2499 if Is_Class_Wide_Type (Typ) then
2500 F_Typ := Class_Wide_Type (F_Typ);
2501 end if;
2503 L := New_List;
2505 -- In case of assignment to a class-wide tagged type, before
2506 -- the assignment we generate run-time check to ensure that
2507 -- the tags of source and target match.
2509 if not Tag_Checks_Suppressed (Typ)
2510 and then Is_Class_Wide_Type (Typ)
2511 and then Is_Tagged_Type (Typ)
2512 and then Is_Tagged_Type (Underlying_Type (Etype (Rhs)))
2513 then
2514 declare
2515 Lhs_Tag : Node_Id;
2516 Rhs_Tag : Node_Id;
2518 begin
2519 if not Is_Interface (Typ) then
2520 Lhs_Tag :=
2521 Make_Selected_Component (Loc,
2522 Prefix => Duplicate_Subexpr (Lhs),
2523 Selector_Name =>
2524 Make_Identifier (Loc, Name_uTag));
2525 Rhs_Tag :=
2526 Make_Selected_Component (Loc,
2527 Prefix => Duplicate_Subexpr (Rhs),
2528 Selector_Name =>
2529 Make_Identifier (Loc, Name_uTag));
2530 else
2531 -- Displace the pointer to the base of the objects
2532 -- applying 'Address, which is later expanded into
2533 -- a call to RE_Base_Address.
2535 Lhs_Tag :=
2536 Make_Explicit_Dereference (Loc,
2537 Prefix =>
2538 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
2539 Make_Attribute_Reference (Loc,
2540 Prefix => Duplicate_Subexpr (Lhs),
2541 Attribute_Name => Name_Address)));
2542 Rhs_Tag :=
2543 Make_Explicit_Dereference (Loc,
2544 Prefix =>
2545 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
2546 Make_Attribute_Reference (Loc,
2547 Prefix => Duplicate_Subexpr (Rhs),
2548 Attribute_Name => Name_Address)));
2549 end if;
2551 Append_To (L,
2552 Make_Raise_Constraint_Error (Loc,
2553 Condition =>
2554 Make_Op_Ne (Loc,
2555 Left_Opnd => Lhs_Tag,
2556 Right_Opnd => Rhs_Tag),
2557 Reason => CE_Tag_Check_Failed));
2558 end;
2559 end if;
2561 declare
2562 Left_N : Node_Id := Duplicate_Subexpr (Lhs);
2563 Right_N : Node_Id := Duplicate_Subexpr (Rhs);
2565 begin
2566 -- In order to dispatch the call to _assign the type of
2567 -- the actuals must match. Add conversion (if required).
2569 if Etype (Lhs) /= F_Typ then
2570 Left_N := Unchecked_Convert_To (F_Typ, Left_N);
2571 end if;
2573 if Etype (Rhs) /= F_Typ then
2574 Right_N := Unchecked_Convert_To (F_Typ, Right_N);
2575 end if;
2577 Append_To (L,
2578 Make_Procedure_Call_Statement (Loc,
2579 Name => New_Occurrence_Of (Op, Loc),
2580 Parameter_Associations => New_List (
2581 Node1 => Left_N,
2582 Node2 => Right_N)));
2583 end;
2584 end;
2586 else
2587 L := Make_Tag_Ctrl_Assignment (N);
2589 -- We can't afford to have destructive Finalization Actions in
2590 -- the Self assignment case, so if the target and the source
2591 -- are not obviously different, code is generated to avoid the
2592 -- self assignment case:
2594 -- if lhs'address /= rhs'address then
2595 -- <code for controlled and/or tagged assignment>
2596 -- end if;
2598 -- Skip this if Restriction (No_Finalization) is active
2600 if not Statically_Different (Lhs, Rhs)
2601 and then Expand_Ctrl_Actions
2602 and then not Restriction_Active (No_Finalization)
2603 then
2604 L := New_List (
2605 Make_Implicit_If_Statement (N,
2606 Condition =>
2607 Make_Op_Ne (Loc,
2608 Left_Opnd =>
2609 Make_Attribute_Reference (Loc,
2610 Prefix => Duplicate_Subexpr (Lhs),
2611 Attribute_Name => Name_Address),
2613 Right_Opnd =>
2614 Make_Attribute_Reference (Loc,
2615 Prefix => Duplicate_Subexpr (Rhs),
2616 Attribute_Name => Name_Address)),
2618 Then_Statements => L));
2619 end if;
2621 -- We need to set up an exception handler for implementing
2622 -- 7.6.1(18). The remaining adjustments are tackled by the
2623 -- implementation of adjust for record_controllers (see
2624 -- s-finimp.adb).
2626 -- This is skipped if we have no finalization
2628 if Expand_Ctrl_Actions
2629 and then not Restriction_Active (No_Finalization)
2630 then
2631 L := New_List (
2632 Make_Block_Statement (Loc,
2633 Handled_Statement_Sequence =>
2634 Make_Handled_Sequence_Of_Statements (Loc,
2635 Statements => L,
2636 Exception_Handlers => New_List (
2637 Make_Handler_For_Ctrl_Operation (Loc)))));
2638 end if;
2639 end if;
2641 Rewrite (N,
2642 Make_Block_Statement (Loc,
2643 Handled_Statement_Sequence =>
2644 Make_Handled_Sequence_Of_Statements (Loc, Statements => L)));
2646 -- If no restrictions on aborts, protect the whole assignment
2647 -- for controlled objects as per 9.8(11).
2649 if Needs_Finalization (Typ)
2650 and then Expand_Ctrl_Actions
2651 and then Abort_Allowed
2652 then
2653 declare
2654 Blk : constant Entity_Id :=
2655 New_Internal_Entity
2656 (E_Block, Current_Scope, Sloc (N), 'B');
2657 AUD : constant Entity_Id := RTE (RE_Abort_Undefer_Direct);
2659 begin
2660 Set_Is_Abort_Block (N);
2662 Set_Scope (Blk, Current_Scope);
2663 Set_Etype (Blk, Standard_Void_Type);
2664 Set_Identifier (N, New_Occurrence_Of (Blk, Sloc (N)));
2666 Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
2667 Set_At_End_Proc (Handled_Statement_Sequence (N),
2668 New_Occurrence_Of (AUD, Loc));
2670 -- Present the Abort_Undefer_Direct function to the backend
2671 -- so that it can inline the call to the function.
2673 Add_Inlined_Body (AUD, N);
2675 Expand_At_End_Handler
2676 (Handled_Statement_Sequence (N), Blk);
2677 end;
2678 end if;
2680 -- N has been rewritten to a block statement for which it is
2681 -- known by construction that no checks are necessary: analyze
2682 -- it with all checks suppressed.
2684 Analyze (N, Suppress => All_Checks);
2685 return;
2686 end Tagged_Case;
2688 -- Array types
2690 elsif Is_Array_Type (Typ) then
2691 declare
2692 Actual_Rhs : Node_Id := Rhs;
2694 begin
2695 while Nkind_In (Actual_Rhs, N_Type_Conversion,
2696 N_Qualified_Expression)
2697 loop
2698 Actual_Rhs := Expression (Actual_Rhs);
2699 end loop;
2701 Expand_Assign_Array (N, Actual_Rhs);
2702 return;
2703 end;
2705 -- Record types
2707 elsif Is_Record_Type (Typ) then
2708 Expand_Assign_Record (N);
2709 return;
2711 -- Scalar types. This is where we perform the processing related to the
2712 -- requirements of (RM 13.9.1(9-11)) concerning the handling of invalid
2713 -- scalar values.
2715 elsif Is_Scalar_Type (Typ) then
2717 -- Case where right side is known valid
2719 if Expr_Known_Valid (Rhs) then
2721 -- Here the right side is valid, so it is fine. The case to deal
2722 -- with is when the left side is a local variable reference whose
2723 -- value is not currently known to be valid. If this is the case,
2724 -- and the assignment appears in an unconditional context, then
2725 -- we can mark the left side as now being valid if one of these
2726 -- conditions holds:
2728 -- The expression of the right side has Do_Range_Check set so
2729 -- that we know a range check will be performed. Note that it
2730 -- can be the case that a range check is omitted because we
2731 -- make the assumption that we can assume validity for operands
2732 -- appearing in the right side in determining whether a range
2733 -- check is required
2735 -- The subtype of the right side matches the subtype of the
2736 -- left side. In this case, even though we have not checked
2737 -- the range of the right side, we know it is in range of its
2738 -- subtype if the expression is valid.
2740 if Is_Local_Variable_Reference (Lhs)
2741 and then not Is_Known_Valid (Entity (Lhs))
2742 and then In_Unconditional_Context (N)
2743 then
2744 if Do_Range_Check (Rhs)
2745 or else Etype (Lhs) = Etype (Rhs)
2746 then
2747 Set_Is_Known_Valid (Entity (Lhs), True);
2748 end if;
2749 end if;
2751 -- Case where right side may be invalid in the sense of the RM
2752 -- reference above. The RM does not require that we check for the
2753 -- validity on an assignment, but it does require that the assignment
2754 -- of an invalid value not cause erroneous behavior.
2756 -- The general approach in GNAT is to use the Is_Known_Valid flag
2757 -- to avoid the need for validity checking on assignments. However
2758 -- in some cases, we have to do validity checking in order to make
2759 -- sure that the setting of this flag is correct.
2761 else
2762 -- Validate right side if we are validating copies
2764 if Validity_Checks_On
2765 and then Validity_Check_Copies
2766 then
2767 -- Skip this if left-hand side is an array or record component
2768 -- and elementary component validity checks are suppressed.
2770 if Nkind_In (Lhs, N_Selected_Component, N_Indexed_Component)
2771 and then not Validity_Check_Components
2772 then
2773 null;
2774 else
2775 Ensure_Valid (Rhs);
2776 end if;
2778 -- We can propagate this to the left side where appropriate
2780 if Is_Local_Variable_Reference (Lhs)
2781 and then not Is_Known_Valid (Entity (Lhs))
2782 and then In_Unconditional_Context (N)
2783 then
2784 Set_Is_Known_Valid (Entity (Lhs), True);
2785 end if;
2787 -- Otherwise check to see what should be done
2789 -- If left side is a local variable, then we just set its flag to
2790 -- indicate that its value may no longer be valid, since we are
2791 -- copying a potentially invalid value.
2793 elsif Is_Local_Variable_Reference (Lhs) then
2794 Set_Is_Known_Valid (Entity (Lhs), False);
2796 -- Check for case of a nonlocal variable on the left side which
2797 -- is currently known to be valid. In this case, we simply ensure
2798 -- that the right side is valid. We only play the game of copying
2799 -- validity status for local variables, since we are doing this
2800 -- statically, not by tracing the full flow graph.
2802 elsif Is_Entity_Name (Lhs)
2803 and then Is_Known_Valid (Entity (Lhs))
2804 then
2805 -- Note: If Validity_Checking mode is set to none, we ignore
2806 -- the Ensure_Valid call so don't worry about that case here.
2808 Ensure_Valid (Rhs);
2810 -- In all other cases, we can safely copy an invalid value without
2811 -- worrying about the status of the left side. Since it is not a
2812 -- variable reference it will not be considered
2813 -- as being known to be valid in any case.
2815 else
2816 null;
2817 end if;
2818 end if;
2819 end if;
2821 exception
2822 when RE_Not_Available =>
2823 return;
2824 end Expand_N_Assignment_Statement;
2826 ------------------------------
2827 -- Expand_N_Block_Statement --
2828 ------------------------------
2830 -- Encode entity names defined in block statement
2832 procedure Expand_N_Block_Statement (N : Node_Id) is
2833 begin
2834 Qualify_Entity_Names (N);
2835 end Expand_N_Block_Statement;
2837 -----------------------------
2838 -- Expand_N_Case_Statement --
2839 -----------------------------
2841 procedure Expand_N_Case_Statement (N : Node_Id) is
2842 Loc : constant Source_Ptr := Sloc (N);
2843 Expr : constant Node_Id := Expression (N);
2844 Alt : Node_Id;
2845 Len : Nat;
2846 Cond : Node_Id;
2847 Choice : Node_Id;
2848 Chlist : List_Id;
2850 begin
2851 -- Check for the situation where we know at compile time which branch
2852 -- will be taken.
2854 -- If the value is static but its subtype is predicated and the value
2855 -- does not obey the predicate, the value is marked non-static, and
2856 -- there can be no corresponding static alternative. In that case we
2857 -- replace the case statement with an exception, regardless of whether
2858 -- assertions are enabled or not, unless predicates are ignored.
2860 if Compile_Time_Known_Value (Expr)
2861 and then Has_Predicates (Etype (Expr))
2862 and then not Predicates_Ignored (Etype (Expr))
2863 and then not Is_OK_Static_Expression (Expr)
2864 then
2865 Rewrite (N,
2866 Make_Raise_Constraint_Error (Loc, Reason => CE_Invalid_Data));
2867 Analyze (N);
2868 return;
2870 elsif Compile_Time_Known_Value (Expr)
2871 and then (not Has_Predicates (Etype (Expr))
2872 or else Is_Static_Expression (Expr))
2873 then
2874 Alt := Find_Static_Alternative (N);
2876 -- Do not consider controlled objects found in a case statement which
2877 -- actually models a case expression because their early finalization
2878 -- will affect the result of the expression.
2880 if not From_Conditional_Expression (N) then
2881 Process_Statements_For_Controlled_Objects (Alt);
2882 end if;
2884 -- Move statements from this alternative after the case statement.
2885 -- They are already analyzed, so will be skipped by the analyzer.
2887 Insert_List_After (N, Statements (Alt));
2889 -- That leaves the case statement as a shell. So now we can kill all
2890 -- other alternatives in the case statement.
2892 Kill_Dead_Code (Expression (N));
2894 declare
2895 Dead_Alt : Node_Id;
2897 begin
2898 -- Loop through case alternatives, skipping pragmas, and skipping
2899 -- the one alternative that we select (and therefore retain).
2901 Dead_Alt := First (Alternatives (N));
2902 while Present (Dead_Alt) loop
2903 if Dead_Alt /= Alt
2904 and then Nkind (Dead_Alt) = N_Case_Statement_Alternative
2905 then
2906 Kill_Dead_Code (Statements (Dead_Alt), Warn_On_Deleted_Code);
2907 end if;
2909 Next (Dead_Alt);
2910 end loop;
2911 end;
2913 Rewrite (N, Make_Null_Statement (Loc));
2914 return;
2915 end if;
2917 -- Here if the choice is not determined at compile time
2919 declare
2920 Last_Alt : constant Node_Id := Last (Alternatives (N));
2922 Others_Present : Boolean;
2923 Others_Node : Node_Id;
2925 Then_Stms : List_Id;
2926 Else_Stms : List_Id;
2928 begin
2929 if Nkind (First (Discrete_Choices (Last_Alt))) = N_Others_Choice then
2930 Others_Present := True;
2931 Others_Node := Last_Alt;
2932 else
2933 Others_Present := False;
2934 end if;
2936 -- First step is to worry about possible invalid argument. The RM
2937 -- requires (RM 5.4(13)) that if the result is invalid (e.g. it is
2938 -- outside the base range), then Constraint_Error must be raised.
2940 -- Case of validity check required (validity checks are on, the
2941 -- expression is not known to be valid, and the case statement
2942 -- comes from source -- no need to validity check internally
2943 -- generated case statements).
2945 if Validity_Check_Default
2946 and then not Predicates_Ignored (Etype (Expr))
2947 then
2948 Ensure_Valid (Expr);
2949 end if;
2951 -- If there is only a single alternative, just replace it with the
2952 -- sequence of statements since obviously that is what is going to
2953 -- be executed in all cases.
2955 Len := List_Length (Alternatives (N));
2957 if Len = 1 then
2959 -- We still need to evaluate the expression if it has any side
2960 -- effects.
2962 Remove_Side_Effects (Expression (N));
2963 Alt := First (Alternatives (N));
2965 -- Do not consider controlled objects found in a case statement
2966 -- which actually models a case expression because their early
2967 -- finalization will affect the result of the expression.
2969 if not From_Conditional_Expression (N) then
2970 Process_Statements_For_Controlled_Objects (Alt);
2971 end if;
2973 Insert_List_After (N, Statements (Alt));
2975 -- That leaves the case statement as a shell. The alternative that
2976 -- will be executed is reset to a null list. So now we can kill
2977 -- the entire case statement.
2979 Kill_Dead_Code (Expression (N));
2980 Rewrite (N, Make_Null_Statement (Loc));
2981 return;
2983 -- An optimization. If there are only two alternatives, and only
2984 -- a single choice, then rewrite the whole case statement as an
2985 -- if statement, since this can result in subsequent optimizations.
2986 -- This helps not only with case statements in the source of a
2987 -- simple form, but also with generated code (discriminant check
2988 -- functions in particular).
2990 -- Note: it is OK to do this before expanding out choices for any
2991 -- static predicates, since the if statement processing will handle
2992 -- the static predicate case fine.
2994 elsif Len = 2 then
2995 Chlist := Discrete_Choices (First (Alternatives (N)));
2997 if List_Length (Chlist) = 1 then
2998 Choice := First (Chlist);
3000 Then_Stms := Statements (First (Alternatives (N)));
3001 Else_Stms := Statements (Last (Alternatives (N)));
3003 -- For TRUE, generate "expression", not expression = true
3005 if Nkind (Choice) = N_Identifier
3006 and then Entity (Choice) = Standard_True
3007 then
3008 Cond := Expression (N);
3010 -- For FALSE, generate "expression" and switch then/else
3012 elsif Nkind (Choice) = N_Identifier
3013 and then Entity (Choice) = Standard_False
3014 then
3015 Cond := Expression (N);
3016 Else_Stms := Statements (First (Alternatives (N)));
3017 Then_Stms := Statements (Last (Alternatives (N)));
3019 -- For a range, generate "expression in range"
3021 elsif Nkind (Choice) = N_Range
3022 or else (Nkind (Choice) = N_Attribute_Reference
3023 and then Attribute_Name (Choice) = Name_Range)
3024 or else (Is_Entity_Name (Choice)
3025 and then Is_Type (Entity (Choice)))
3026 then
3027 Cond :=
3028 Make_In (Loc,
3029 Left_Opnd => Expression (N),
3030 Right_Opnd => Relocate_Node (Choice));
3032 -- A subtype indication is not a legal operator in a membership
3033 -- test, so retrieve its range.
3035 elsif Nkind (Choice) = N_Subtype_Indication then
3036 Cond :=
3037 Make_In (Loc,
3038 Left_Opnd => Expression (N),
3039 Right_Opnd =>
3040 Relocate_Node
3041 (Range_Expression (Constraint (Choice))));
3043 -- For any other subexpression "expression = value"
3045 else
3046 Cond :=
3047 Make_Op_Eq (Loc,
3048 Left_Opnd => Expression (N),
3049 Right_Opnd => Relocate_Node (Choice));
3050 end if;
3052 -- Now rewrite the case as an IF
3054 Rewrite (N,
3055 Make_If_Statement (Loc,
3056 Condition => Cond,
3057 Then_Statements => Then_Stms,
3058 Else_Statements => Else_Stms));
3059 Analyze (N);
3060 return;
3061 end if;
3062 end if;
3064 -- If the last alternative is not an Others choice, replace it with
3065 -- an N_Others_Choice. Note that we do not bother to call Analyze on
3066 -- the modified case statement, since it's only effect would be to
3067 -- compute the contents of the Others_Discrete_Choices which is not
3068 -- needed by the back end anyway.
3070 -- The reason for this is that the back end always needs some default
3071 -- for a switch, so if we have not supplied one in the processing
3072 -- above for validity checking, then we need to supply one here.
3074 if not Others_Present then
3075 Others_Node := Make_Others_Choice (Sloc (Last_Alt));
3077 -- If Predicates_Ignored is true the value does not satisfy the
3078 -- predicate, and there is no Others choice, Constraint_Error
3079 -- must be raised (4.5.7 (21/3)).
3081 if Predicates_Ignored (Etype (Expr)) then
3082 declare
3083 Except : constant Node_Id :=
3084 Make_Raise_Constraint_Error (Loc,
3085 Reason => CE_Invalid_Data);
3086 New_Alt : constant Node_Id :=
3087 Make_Case_Statement_Alternative (Loc,
3088 Discrete_Choices => New_List (
3089 Make_Others_Choice (Loc)),
3090 Statements => New_List (Except));
3092 begin
3093 Append (New_Alt, Alternatives (N));
3094 Analyze_And_Resolve (Except);
3095 end;
3097 else
3098 Set_Others_Discrete_Choices
3099 (Others_Node, Discrete_Choices (Last_Alt));
3100 Set_Discrete_Choices (Last_Alt, New_List (Others_Node));
3101 end if;
3103 end if;
3105 -- Deal with possible declarations of controlled objects, and also
3106 -- with rewriting choice sequences for static predicate references.
3108 Alt := First_Non_Pragma (Alternatives (N));
3109 while Present (Alt) loop
3111 -- Do not consider controlled objects found in a case statement
3112 -- which actually models a case expression because their early
3113 -- finalization will affect the result of the expression.
3115 if not From_Conditional_Expression (N) then
3116 Process_Statements_For_Controlled_Objects (Alt);
3117 end if;
3119 if Has_SP_Choice (Alt) then
3120 Expand_Static_Predicates_In_Choices (Alt);
3121 end if;
3123 Next_Non_Pragma (Alt);
3124 end loop;
3125 end;
3126 end Expand_N_Case_Statement;
3128 -----------------------------
3129 -- Expand_N_Exit_Statement --
3130 -----------------------------
3132 -- The only processing required is to deal with a possible C/Fortran
3133 -- boolean value used as the condition for the exit statement.
3135 procedure Expand_N_Exit_Statement (N : Node_Id) is
3136 begin
3137 Adjust_Condition (Condition (N));
3138 end Expand_N_Exit_Statement;
3140 ----------------------------------
3141 -- Expand_Formal_Container_Loop --
3142 ----------------------------------
3144 procedure Expand_Formal_Container_Loop (N : Node_Id) is
3145 Loc : constant Source_Ptr := Sloc (N);
3146 Isc : constant Node_Id := Iteration_Scheme (N);
3147 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3148 Cursor : constant Entity_Id := Defining_Identifier (I_Spec);
3149 Container : constant Node_Id := Entity (Name (I_Spec));
3150 Stats : constant List_Id := Statements (N);
3152 Advance : Node_Id;
3153 Init_Decl : Node_Id;
3154 Init_Name : Entity_Id;
3155 New_Loop : Node_Id;
3157 begin
3158 -- The expansion of a formal container loop resembles the one for Ada
3159 -- containers. The only difference is that the primitives mention the
3160 -- domain of iteration explicitly, and function First applied to the
3161 -- container yields a cursor directly.
3163 -- Cursor : Cursor_type := First (Container);
3164 -- while Has_Element (Cursor, Container) loop
3165 -- <original loop statements>
3166 -- Cursor := Next (Container, Cursor);
3167 -- end loop;
3169 Build_Formal_Container_Iteration
3170 (N, Container, Cursor, Init_Decl, Advance, New_Loop);
3172 Append_To (Stats, Advance);
3174 -- Build a block to capture declaration of the cursor
3176 Rewrite (N,
3177 Make_Block_Statement (Loc,
3178 Declarations => New_List (Init_Decl),
3179 Handled_Statement_Sequence =>
3180 Make_Handled_Sequence_Of_Statements (Loc,
3181 Statements => New_List (New_Loop))));
3183 -- The loop parameter is declared by an object declaration, but within
3184 -- the loop we must prevent user assignments to it, so we analyze the
3185 -- declaration and reset the entity kind, before analyzing the rest of
3186 -- the loop.
3188 Analyze (Init_Decl);
3189 Init_Name := Defining_Identifier (Init_Decl);
3190 Set_Ekind (Init_Name, E_Loop_Parameter);
3192 -- The cursor was marked as a loop parameter to prevent user assignments
3193 -- to it, however this renders the advancement step illegal as it is not
3194 -- possible to change the value of a constant. Flag the advancement step
3195 -- as a legal form of assignment to remedy this side effect.
3197 Set_Assignment_OK (Name (Advance));
3198 Analyze (N);
3200 -- Because we have to analyze the initial declaration of the loop
3201 -- parameter multiple times its scope is incorrectly set at this point
3202 -- to the one surrounding the block statement - so set the scope
3203 -- manually to be the actual block statement, and indicate that it is
3204 -- not visible after the block has been analyzed.
3206 Set_Scope (Init_Name, Entity (Identifier (N)));
3207 Set_Is_Immediately_Visible (Init_Name, False);
3208 end Expand_Formal_Container_Loop;
3210 ------------------------------------------
3211 -- Expand_Formal_Container_Element_Loop --
3212 ------------------------------------------
3214 procedure Expand_Formal_Container_Element_Loop (N : Node_Id) is
3215 Loc : constant Source_Ptr := Sloc (N);
3216 Isc : constant Node_Id := Iteration_Scheme (N);
3217 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3218 Element : constant Entity_Id := Defining_Identifier (I_Spec);
3219 Container : constant Node_Id := Entity (Name (I_Spec));
3220 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
3221 Stats : constant List_Id := Statements (N);
3223 Cursor : constant Entity_Id :=
3224 Make_Defining_Identifier (Loc,
3225 Chars => New_External_Name (Chars (Element), 'C'));
3226 Elmt_Decl : Node_Id;
3227 Elmt_Ref : Node_Id;
3229 Element_Op : constant Entity_Id :=
3230 Get_Iterable_Type_Primitive (Container_Typ, Name_Element);
3232 Advance : Node_Id;
3233 Init : Node_Id;
3234 New_Loop : Node_Id;
3236 begin
3237 -- For an element iterator, the Element aspect must be present,
3238 -- (this is checked during analysis) and the expansion takes the form:
3240 -- Cursor : Cursor_Type := First (Container);
3241 -- Elmt : Element_Type;
3242 -- while Has_Element (Cursor, Container) loop
3243 -- Elmt := Element (Container, Cursor);
3244 -- <original loop statements>
3245 -- Cursor := Next (Container, Cursor);
3246 -- end loop;
3248 -- However this expansion is not legal if the element is indefinite.
3249 -- In that case we create a block to hold a variable declaration
3250 -- initialized with a call to Element, and generate:
3252 -- Cursor : Cursor_Type := First (Container);
3253 -- while Has_Element (Cursor, Container) loop
3254 -- declare
3255 -- Elmt : Element_Type := Element (Container, Cursor);
3256 -- begin
3257 -- <original loop statements>
3258 -- Cursor := Next (Container, Cursor);
3259 -- end;
3260 -- end loop;
3262 Build_Formal_Container_Iteration
3263 (N, Container, Cursor, Init, Advance, New_Loop);
3264 Append_To (Stats, Advance);
3266 Set_Ekind (Cursor, E_Variable);
3267 Insert_Action (N, Init);
3269 -- The loop parameter is declared by an object declaration, but within
3270 -- the loop we must prevent user assignments to it; the following flag
3271 -- accomplishes that.
3273 Set_Is_Loop_Parameter (Element);
3275 -- Declaration for Element
3277 Elmt_Decl :=
3278 Make_Object_Declaration (Loc,
3279 Defining_Identifier => Element,
3280 Object_Definition => New_Occurrence_Of (Etype (Element_Op), Loc));
3282 if not Is_Constrained (Etype (Element_Op)) then
3283 Set_Expression (Elmt_Decl,
3284 Make_Function_Call (Loc,
3285 Name => New_Occurrence_Of (Element_Op, Loc),
3286 Parameter_Associations => New_List (
3287 Convert_To_Iterable_Type (Container, Loc),
3288 New_Occurrence_Of (Cursor, Loc))));
3290 Set_Statements (New_Loop,
3291 New_List
3292 (Make_Block_Statement (Loc,
3293 Declarations => New_List (Elmt_Decl),
3294 Handled_Statement_Sequence =>
3295 Make_Handled_Sequence_Of_Statements (Loc,
3296 Statements => Stats))));
3298 else
3299 Elmt_Ref :=
3300 Make_Assignment_Statement (Loc,
3301 Name => New_Occurrence_Of (Element, Loc),
3302 Expression =>
3303 Make_Function_Call (Loc,
3304 Name => New_Occurrence_Of (Element_Op, Loc),
3305 Parameter_Associations => New_List (
3306 Convert_To_Iterable_Type (Container, Loc),
3307 New_Occurrence_Of (Cursor, Loc))));
3309 Prepend (Elmt_Ref, Stats);
3311 -- The element is assignable in the expanded code
3313 Set_Assignment_OK (Name (Elmt_Ref));
3315 -- The loop is rewritten as a block, to hold the element declaration
3317 New_Loop :=
3318 Make_Block_Statement (Loc,
3319 Declarations => New_List (Elmt_Decl),
3320 Handled_Statement_Sequence =>
3321 Make_Handled_Sequence_Of_Statements (Loc,
3322 Statements => New_List (New_Loop)));
3323 end if;
3325 -- The element is only modified in expanded code, so it appears as
3326 -- unassigned to the warning machinery. We must suppress this spurious
3327 -- warning explicitly.
3329 Set_Warnings_Off (Element);
3331 Rewrite (N, New_Loop);
3332 Analyze (N);
3333 end Expand_Formal_Container_Element_Loop;
3335 -----------------------------
3336 -- Expand_N_Goto_Statement --
3337 -----------------------------
3339 -- Add poll before goto if polling active
3341 procedure Expand_N_Goto_Statement (N : Node_Id) is
3342 begin
3343 Generate_Poll_Call (N);
3344 end Expand_N_Goto_Statement;
3346 ---------------------------
3347 -- Expand_N_If_Statement --
3348 ---------------------------
3350 -- First we deal with the case of C and Fortran convention boolean values,
3351 -- with zero/non-zero semantics.
3353 -- Second, we deal with the obvious rewriting for the cases where the
3354 -- condition of the IF is known at compile time to be True or False.
3356 -- Third, we remove elsif parts which have non-empty Condition_Actions and
3357 -- rewrite as independent if statements. For example:
3359 -- if x then xs
3360 -- elsif y then ys
3361 -- ...
3362 -- end if;
3364 -- becomes
3366 -- if x then xs
3367 -- else
3368 -- <<condition actions of y>>
3369 -- if y then ys
3370 -- ...
3371 -- end if;
3372 -- end if;
3374 -- This rewriting is needed if at least one elsif part has a non-empty
3375 -- Condition_Actions list. We also do the same processing if there is a
3376 -- constant condition in an elsif part (in conjunction with the first
3377 -- processing step mentioned above, for the recursive call made to deal
3378 -- with the created inner if, this deals with properly optimizing the
3379 -- cases of constant elsif conditions).
3381 procedure Expand_N_If_Statement (N : Node_Id) is
3382 Loc : constant Source_Ptr := Sloc (N);
3383 Hed : Node_Id;
3384 E : Node_Id;
3385 New_If : Node_Id;
3387 Warn_If_Deleted : constant Boolean :=
3388 Warn_On_Deleted_Code and then Comes_From_Source (N);
3389 -- Indicates whether we want warnings when we delete branches of the
3390 -- if statement based on constant condition analysis. We never want
3391 -- these warnings for expander generated code.
3393 begin
3394 -- Do not consider controlled objects found in an if statement which
3395 -- actually models an if expression because their early finalization
3396 -- will affect the result of the expression.
3398 if not From_Conditional_Expression (N) then
3399 Process_Statements_For_Controlled_Objects (N);
3400 end if;
3402 Adjust_Condition (Condition (N));
3404 -- The following loop deals with constant conditions for the IF. We
3405 -- need a loop because as we eliminate False conditions, we grab the
3406 -- first elsif condition and use it as the primary condition.
3408 while Compile_Time_Known_Value (Condition (N)) loop
3410 -- If condition is True, we can simply rewrite the if statement now
3411 -- by replacing it by the series of then statements.
3413 if Is_True (Expr_Value (Condition (N))) then
3415 -- All the else parts can be killed
3417 Kill_Dead_Code (Elsif_Parts (N), Warn_If_Deleted);
3418 Kill_Dead_Code (Else_Statements (N), Warn_If_Deleted);
3420 Hed := Remove_Head (Then_Statements (N));
3421 Insert_List_After (N, Then_Statements (N));
3422 Rewrite (N, Hed);
3423 return;
3425 -- If condition is False, then we can delete the condition and
3426 -- the Then statements
3428 else
3429 -- We do not delete the condition if constant condition warnings
3430 -- are enabled, since otherwise we end up deleting the desired
3431 -- warning. Of course the backend will get rid of this True/False
3432 -- test anyway, so nothing is lost here.
3434 if not Constant_Condition_Warnings then
3435 Kill_Dead_Code (Condition (N));
3436 end if;
3438 Kill_Dead_Code (Then_Statements (N), Warn_If_Deleted);
3440 -- If there are no elsif statements, then we simply replace the
3441 -- entire if statement by the sequence of else statements.
3443 if No (Elsif_Parts (N)) then
3444 if No (Else_Statements (N))
3445 or else Is_Empty_List (Else_Statements (N))
3446 then
3447 Rewrite (N,
3448 Make_Null_Statement (Sloc (N)));
3449 else
3450 Hed := Remove_Head (Else_Statements (N));
3451 Insert_List_After (N, Else_Statements (N));
3452 Rewrite (N, Hed);
3453 end if;
3455 return;
3457 -- If there are elsif statements, the first of them becomes the
3458 -- if/then section of the rebuilt if statement This is the case
3459 -- where we loop to reprocess this copied condition.
3461 else
3462 Hed := Remove_Head (Elsif_Parts (N));
3463 Insert_Actions (N, Condition_Actions (Hed));
3464 Set_Condition (N, Condition (Hed));
3465 Set_Then_Statements (N, Then_Statements (Hed));
3467 -- Hed might have been captured as the condition determining
3468 -- the current value for an entity. Now it is detached from
3469 -- the tree, so a Current_Value pointer in the condition might
3470 -- need to be updated.
3472 Set_Current_Value_Condition (N);
3474 if Is_Empty_List (Elsif_Parts (N)) then
3475 Set_Elsif_Parts (N, No_List);
3476 end if;
3477 end if;
3478 end if;
3479 end loop;
3481 -- Loop through elsif parts, dealing with constant conditions and
3482 -- possible condition actions that are present.
3484 if Present (Elsif_Parts (N)) then
3485 E := First (Elsif_Parts (N));
3486 while Present (E) loop
3488 -- Do not consider controlled objects found in an if statement
3489 -- which actually models an if expression because their early
3490 -- finalization will affect the result of the expression.
3492 if not From_Conditional_Expression (N) then
3493 Process_Statements_For_Controlled_Objects (E);
3494 end if;
3496 Adjust_Condition (Condition (E));
3498 -- If there are condition actions, then rewrite the if statement
3499 -- as indicated above. We also do the same rewrite for a True or
3500 -- False condition. The further processing of this constant
3501 -- condition is then done by the recursive call to expand the
3502 -- newly created if statement
3504 if Present (Condition_Actions (E))
3505 or else Compile_Time_Known_Value (Condition (E))
3506 then
3507 New_If :=
3508 Make_If_Statement (Sloc (E),
3509 Condition => Condition (E),
3510 Then_Statements => Then_Statements (E),
3511 Elsif_Parts => No_List,
3512 Else_Statements => Else_Statements (N));
3514 -- Elsif parts for new if come from remaining elsif's of parent
3516 while Present (Next (E)) loop
3517 if No (Elsif_Parts (New_If)) then
3518 Set_Elsif_Parts (New_If, New_List);
3519 end if;
3521 Append (Remove_Next (E), Elsif_Parts (New_If));
3522 end loop;
3524 Set_Else_Statements (N, New_List (New_If));
3526 if Present (Condition_Actions (E)) then
3527 Insert_List_Before (New_If, Condition_Actions (E));
3528 end if;
3530 Remove (E);
3532 if Is_Empty_List (Elsif_Parts (N)) then
3533 Set_Elsif_Parts (N, No_List);
3534 end if;
3536 Analyze (New_If);
3538 -- Note this is not an implicit if statement, since it is part
3539 -- of an explicit if statement in the source (or of an implicit
3540 -- if statement that has already been tested). We set the flag
3541 -- after calling Analyze to avoid generating extra warnings
3542 -- specific to pure if statements, however (see
3543 -- Sem_Ch5.Analyze_If_Statement).
3545 Set_Comes_From_Source (New_If, Comes_From_Source (N));
3546 return;
3548 -- No special processing for that elsif part, move to next
3550 else
3551 Next (E);
3552 end if;
3553 end loop;
3554 end if;
3556 -- Some more optimizations applicable if we still have an IF statement
3558 if Nkind (N) /= N_If_Statement then
3559 return;
3560 end if;
3562 -- Another optimization, special cases that can be simplified
3564 -- if expression then
3565 -- return true;
3566 -- else
3567 -- return false;
3568 -- end if;
3570 -- can be changed to:
3572 -- return expression;
3574 -- and
3576 -- if expression then
3577 -- return false;
3578 -- else
3579 -- return true;
3580 -- end if;
3582 -- can be changed to:
3584 -- return not (expression);
3586 -- Only do these optimizations if we are at least at -O1 level and
3587 -- do not do them if control flow optimizations are suppressed.
3589 if Optimization_Level > 0
3590 and then not Opt.Suppress_Control_Flow_Optimizations
3591 then
3592 if Nkind (N) = N_If_Statement
3593 and then No (Elsif_Parts (N))
3594 and then Present (Else_Statements (N))
3595 and then List_Length (Then_Statements (N)) = 1
3596 and then List_Length (Else_Statements (N)) = 1
3597 then
3598 declare
3599 Then_Stm : constant Node_Id := First (Then_Statements (N));
3600 Else_Stm : constant Node_Id := First (Else_Statements (N));
3602 begin
3603 if Nkind (Then_Stm) = N_Simple_Return_Statement
3604 and then
3605 Nkind (Else_Stm) = N_Simple_Return_Statement
3606 then
3607 declare
3608 Then_Expr : constant Node_Id := Expression (Then_Stm);
3609 Else_Expr : constant Node_Id := Expression (Else_Stm);
3611 begin
3612 if Nkind (Then_Expr) = N_Identifier
3613 and then
3614 Nkind (Else_Expr) = N_Identifier
3615 then
3616 if Entity (Then_Expr) = Standard_True
3617 and then Entity (Else_Expr) = Standard_False
3618 then
3619 Rewrite (N,
3620 Make_Simple_Return_Statement (Loc,
3621 Expression => Relocate_Node (Condition (N))));
3622 Analyze (N);
3623 return;
3625 elsif Entity (Then_Expr) = Standard_False
3626 and then Entity (Else_Expr) = Standard_True
3627 then
3628 Rewrite (N,
3629 Make_Simple_Return_Statement (Loc,
3630 Expression =>
3631 Make_Op_Not (Loc,
3632 Right_Opnd =>
3633 Relocate_Node (Condition (N)))));
3634 Analyze (N);
3635 return;
3636 end if;
3637 end if;
3638 end;
3639 end if;
3640 end;
3641 end if;
3642 end if;
3643 end Expand_N_If_Statement;
3645 --------------------------
3646 -- Expand_Iterator_Loop --
3647 --------------------------
3649 procedure Expand_Iterator_Loop (N : Node_Id) is
3650 Isc : constant Node_Id := Iteration_Scheme (N);
3651 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3653 Container : constant Node_Id := Name (I_Spec);
3654 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
3656 begin
3657 -- Processing for arrays
3659 if Is_Array_Type (Container_Typ) then
3660 pragma Assert (Of_Present (I_Spec));
3661 Expand_Iterator_Loop_Over_Array (N);
3663 elsif Has_Aspect (Container_Typ, Aspect_Iterable) then
3664 if Of_Present (I_Spec) then
3665 Expand_Formal_Container_Element_Loop (N);
3666 else
3667 Expand_Formal_Container_Loop (N);
3668 end if;
3670 -- Processing for containers
3672 else
3673 Expand_Iterator_Loop_Over_Container
3674 (N, Isc, I_Spec, Container, Container_Typ);
3675 end if;
3676 end Expand_Iterator_Loop;
3678 -------------------------------------
3679 -- Expand_Iterator_Loop_Over_Array --
3680 -------------------------------------
3682 procedure Expand_Iterator_Loop_Over_Array (N : Node_Id) is
3683 Isc : constant Node_Id := Iteration_Scheme (N);
3684 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3685 Array_Node : constant Node_Id := Name (I_Spec);
3686 Array_Typ : constant Entity_Id := Base_Type (Etype (Array_Node));
3687 Array_Dim : constant Pos := Number_Dimensions (Array_Typ);
3688 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3689 Loc : constant Source_Ptr := Sloc (Isc);
3690 Stats : constant List_Id := Statements (N);
3691 Core_Loop : Node_Id;
3692 Dim1 : Int;
3693 Ind_Comp : Node_Id;
3694 Iterator : Entity_Id;
3696 -- Start of processing for Expand_Iterator_Loop_Over_Array
3698 begin
3699 -- for Element of Array loop
3701 -- It requires an internally generated cursor to iterate over the array
3703 pragma Assert (Of_Present (I_Spec));
3705 Iterator := Make_Temporary (Loc, 'C');
3707 -- Generate:
3708 -- Element : Component_Type renames Array (Iterator);
3709 -- Iterator is the index value, or a list of index values
3710 -- in the case of a multidimensional array.
3712 Ind_Comp :=
3713 Make_Indexed_Component (Loc,
3714 Prefix => Relocate_Node (Array_Node),
3715 Expressions => New_List (New_Occurrence_Of (Iterator, Loc)));
3717 Prepend_To (Stats,
3718 Make_Object_Renaming_Declaration (Loc,
3719 Defining_Identifier => Id,
3720 Subtype_Mark =>
3721 New_Occurrence_Of (Component_Type (Array_Typ), Loc),
3722 Name => Ind_Comp));
3724 -- Mark the loop variable as needing debug info, so that expansion
3725 -- of the renaming will result in Materialize_Entity getting set via
3726 -- Debug_Renaming_Declaration. (This setting is needed here because
3727 -- the setting in Freeze_Entity comes after the expansion, which is
3728 -- too late. ???)
3730 Set_Debug_Info_Needed (Id);
3732 -- Generate:
3734 -- for Iterator in [reverse] Array'Range (Array_Dim) loop
3735 -- Element : Component_Type renames Array (Iterator);
3736 -- <original loop statements>
3737 -- end loop;
3739 -- If this is an iteration over a multidimensional array, the
3740 -- innermost loop is over the last dimension in Ada, and over
3741 -- the first dimension in Fortran.
3743 if Convention (Array_Typ) = Convention_Fortran then
3744 Dim1 := 1;
3745 else
3746 Dim1 := Array_Dim;
3747 end if;
3749 Core_Loop :=
3750 Make_Loop_Statement (Sloc (N),
3751 Iteration_Scheme =>
3752 Make_Iteration_Scheme (Loc,
3753 Loop_Parameter_Specification =>
3754 Make_Loop_Parameter_Specification (Loc,
3755 Defining_Identifier => Iterator,
3756 Discrete_Subtype_Definition =>
3757 Make_Attribute_Reference (Loc,
3758 Prefix => Relocate_Node (Array_Node),
3759 Attribute_Name => Name_Range,
3760 Expressions => New_List (
3761 Make_Integer_Literal (Loc, Dim1))),
3762 Reverse_Present => Reverse_Present (I_Spec))),
3763 Statements => Stats,
3764 End_Label => Empty);
3766 -- Processing for multidimensional array. The body of each loop is
3767 -- a loop over a previous dimension, going in decreasing order in Ada
3768 -- and in increasing order in Fortran.
3770 if Array_Dim > 1 then
3771 for Dim in 1 .. Array_Dim - 1 loop
3772 if Convention (Array_Typ) = Convention_Fortran then
3773 Dim1 := Dim + 1;
3774 else
3775 Dim1 := Array_Dim - Dim;
3776 end if;
3778 Iterator := Make_Temporary (Loc, 'C');
3780 -- Generate the dimension loops starting from the innermost one
3782 -- for Iterator in [reverse] Array'Range (Array_Dim - Dim) loop
3783 -- <core loop>
3784 -- end loop;
3786 Core_Loop :=
3787 Make_Loop_Statement (Sloc (N),
3788 Iteration_Scheme =>
3789 Make_Iteration_Scheme (Loc,
3790 Loop_Parameter_Specification =>
3791 Make_Loop_Parameter_Specification (Loc,
3792 Defining_Identifier => Iterator,
3793 Discrete_Subtype_Definition =>
3794 Make_Attribute_Reference (Loc,
3795 Prefix => Relocate_Node (Array_Node),
3796 Attribute_Name => Name_Range,
3797 Expressions => New_List (
3798 Make_Integer_Literal (Loc, Dim1))),
3799 Reverse_Present => Reverse_Present (I_Spec))),
3800 Statements => New_List (Core_Loop),
3801 End_Label => Empty);
3803 -- Update the previously created object renaming declaration with
3804 -- the new iterator, by adding the index of the next loop to the
3805 -- indexed component, in the order that corresponds to the
3806 -- convention.
3808 if Convention (Array_Typ) = Convention_Fortran then
3809 Append_To (Expressions (Ind_Comp),
3810 New_Occurrence_Of (Iterator, Loc));
3811 else
3812 Prepend_To (Expressions (Ind_Comp),
3813 New_Occurrence_Of (Iterator, Loc));
3814 end if;
3815 end loop;
3816 end if;
3818 -- Inherit the loop identifier from the original loop. This ensures that
3819 -- the scope stack is consistent after the rewriting.
3821 if Present (Identifier (N)) then
3822 Set_Identifier (Core_Loop, Relocate_Node (Identifier (N)));
3823 end if;
3825 Rewrite (N, Core_Loop);
3826 Analyze (N);
3827 end Expand_Iterator_Loop_Over_Array;
3829 -----------------------------------------
3830 -- Expand_Iterator_Loop_Over_Container --
3831 -----------------------------------------
3833 -- For a 'for ... in' loop, such as:
3835 -- for Cursor in Iterator_Function (...) loop
3836 -- ...
3837 -- end loop;
3839 -- we generate:
3841 -- Iter : Iterator_Type := Iterator_Function (...);
3842 -- Cursor : Cursor_type := First (Iter); -- or Last for "reverse"
3843 -- while Has_Element (Cursor) loop
3844 -- ...
3846 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
3847 -- end loop;
3849 -- For a 'for ... of' loop, such as:
3851 -- for X of Container loop
3852 -- ...
3853 -- end loop;
3855 -- the RM implies the generation of:
3857 -- Iter : Iterator_Type := Container.Iterate; -- the Default_Iterator
3858 -- Cursor : Cursor_Type := First (Iter); -- or Last for "reverse"
3859 -- while Has_Element (Cursor) loop
3860 -- declare
3861 -- X : Element_Type renames Element (Cursor).Element.all;
3862 -- -- or Constant_Element
3863 -- begin
3864 -- ...
3865 -- end;
3866 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
3867 -- end loop;
3869 -- In the general case, we do what the RM says. However, the operations
3870 -- Element and Iter.Next are slow, which is bad inside a loop, because they
3871 -- involve dispatching via interfaces, secondary stack manipulation,
3872 -- Busy/Lock incr/decr, and adjust/finalization/at-end handling. So for the
3873 -- predefined containers, we use an equivalent but optimized expansion.
3875 -- In the optimized case, we make use of these:
3877 -- procedure Next (Position : in out Cursor); -- instead of Iter.Next
3879 -- function Pseudo_Reference
3880 -- (Container : aliased Vector'Class) return Reference_Control_Type;
3882 -- type Element_Access is access all Element_Type;
3884 -- function Get_Element_Access
3885 -- (Position : Cursor) return not null Element_Access;
3887 -- Next is declared in the visible part of the container packages.
3888 -- The other three are added in the private part. (We're not supposed to
3889 -- pollute the namespace for clients. The compiler has no trouble breaking
3890 -- privacy to call things in the private part of an instance.)
3892 -- Source:
3894 -- for X of My_Vector loop
3895 -- X.Count := X.Count + 1;
3896 -- ...
3897 -- end loop;
3899 -- The compiler will generate:
3901 -- Iter : Reversible_Iterator'Class := Iterate (My_Vector);
3902 -- -- Reversible_Iterator is an interface. Iterate is the
3903 -- -- Default_Iterator aspect of Vector. This increments Lock,
3904 -- -- disallowing tampering with cursors. Unfortunately, it does not
3905 -- -- increment Busy. The result of Iterate is Limited_Controlled;
3906 -- -- finalization will decrement Lock. This is a build-in-place
3907 -- -- dispatching call to Iterate.
3909 -- Cur : Cursor := First (Iter); -- or Last
3910 -- -- Dispatching call via interface.
3912 -- Control : Reference_Control_Type := Pseudo_Reference (My_Vector);
3913 -- -- Pseudo_Reference increments Busy, to detect tampering with
3914 -- -- elements, as required by RM. Also redundantly increment
3915 -- -- Lock. Finalization of Control will decrement both Busy and
3916 -- -- Lock. Pseudo_Reference returns a record containing a pointer to
3917 -- -- My_Vector, used by Finalize.
3918 -- --
3919 -- -- Control is not used below, except to finalize it -- it's purely
3920 -- -- an RAII thing. This is needed because we are eliminating the
3921 -- -- call to Reference within the loop.
3923 -- while Has_Element (Cur) loop
3924 -- declare
3925 -- X : My_Element renames Get_Element_Access (Cur).all;
3926 -- -- Get_Element_Access returns a pointer to the element
3927 -- -- designated by Cur. No dispatching here, and no horsing
3928 -- -- around with access discriminants. This is instead of the
3929 -- -- existing
3930 -- --
3931 -- -- X : My_Element renames Reference (Cur).Element.all;
3932 -- --
3933 -- -- which creates a controlled object.
3934 -- begin
3935 -- -- Any attempt to tamper with My_Vector here in the loop
3936 -- -- will correctly raise Program_Error, because of the
3937 -- -- Control.
3939 -- X.Count := X.Count + 1;
3940 -- ...
3942 -- Next (Cur); -- or Prev
3943 -- -- This is instead of "Cur := Next (Iter, Cur);"
3944 -- end;
3945 -- -- No finalization here
3946 -- end loop;
3947 -- Finalize Iter and Control here, decrementing Lock twice and Busy
3948 -- once.
3950 -- This optimization makes "for ... of" loops over 30 times faster in cases
3951 -- measured.
3953 procedure Expand_Iterator_Loop_Over_Container
3954 (N : Node_Id;
3955 Isc : Node_Id;
3956 I_Spec : Node_Id;
3957 Container : Node_Id;
3958 Container_Typ : Entity_Id)
3960 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3961 Elem_Typ : constant Entity_Id := Etype (Id);
3962 Id_Kind : constant Entity_Kind := Ekind (Id);
3963 Loc : constant Source_Ptr := Sloc (N);
3964 Stats : constant List_Id := Statements (N);
3966 Cursor : Entity_Id;
3967 Decl : Node_Id;
3968 Iter_Type : Entity_Id;
3969 Iterator : Entity_Id;
3970 Name_Init : Name_Id;
3971 Name_Step : Name_Id;
3972 New_Loop : Node_Id;
3974 Fast_Element_Access_Op : Entity_Id := Empty;
3975 Fast_Step_Op : Entity_Id := Empty;
3976 -- Only for optimized version of "for ... of"
3978 Iter_Pack : Entity_Id;
3979 -- The package in which the iterator interface is instantiated. This is
3980 -- typically an instance within the container package.
3982 Pack : Entity_Id;
3983 -- The package in which the container type is declared
3985 begin
3986 -- Determine the advancement and initialization steps for the cursor.
3987 -- Analysis of the expanded loop will verify that the container has a
3988 -- reverse iterator.
3990 if Reverse_Present (I_Spec) then
3991 Name_Init := Name_Last;
3992 Name_Step := Name_Previous;
3993 else
3994 Name_Init := Name_First;
3995 Name_Step := Name_Next;
3996 end if;
3998 -- The type of the iterator is the return type of the Iterate function
3999 -- used. For the "of" form this is the default iterator for the type,
4000 -- otherwise it is the type of the explicit function used in the
4001 -- iterator specification. The most common case will be an Iterate
4002 -- function in the container package.
4004 -- The Iterator type is declared in an instance within the container
4005 -- package itself, for example:
4007 -- package Vector_Iterator_Interfaces is new
4008 -- Ada.Iterator_Interfaces (Cursor, Has_Element);
4010 -- If the container type is a derived type, the cursor type is found in
4011 -- the package of the ultimate ancestor type.
4013 if Is_Derived_Type (Container_Typ) then
4014 Pack := Scope (Root_Type (Container_Typ));
4015 else
4016 Pack := Scope (Container_Typ);
4017 end if;
4019 if Of_Present (I_Spec) then
4020 Handle_Of : declare
4021 Container_Arg : Node_Id;
4023 function Get_Default_Iterator
4024 (T : Entity_Id) return Entity_Id;
4025 -- Return the default iterator for a specific type. If the type is
4026 -- derived, we return the inherited or overridden one if
4027 -- appropriate.
4029 --------------------------
4030 -- Get_Default_Iterator --
4031 --------------------------
4033 function Get_Default_Iterator
4034 (T : Entity_Id) return Entity_Id
4036 Iter : constant Entity_Id :=
4037 Entity (Find_Value_Of_Aspect (T, Aspect_Default_Iterator));
4038 Prim : Elmt_Id;
4039 Op : Entity_Id;
4041 begin
4042 Container_Arg := New_Copy_Tree (Container);
4044 -- A previous version of GNAT allowed indexing aspects to be
4045 -- redefined on derived container types, while the default
4046 -- iterator was inherited from the parent type. This
4047 -- nonstandard extension is preserved for use by the
4048 -- modeling project under debug flag -gnatd.X.
4050 if Debug_Flag_Dot_XX then
4051 if Base_Type (Etype (Container)) /=
4052 Base_Type (Etype (First_Formal (Iter)))
4053 then
4054 Container_Arg :=
4055 Make_Type_Conversion (Loc,
4056 Subtype_Mark =>
4057 New_Occurrence_Of
4058 (Etype (First_Formal (Iter)), Loc),
4059 Expression => Container_Arg);
4060 end if;
4062 return Iter;
4064 elsif Is_Derived_Type (T) then
4066 -- The default iterator must be a primitive operation of the
4067 -- type, at the same dispatch slot position. The DT position
4068 -- may not be established if type is not frozen yet.
4070 Prim := First_Elmt (Primitive_Operations (T));
4071 while Present (Prim) loop
4072 Op := Node (Prim);
4074 if Alias (Op) = Iter
4075 or else
4076 (Chars (Op) = Chars (Iter)
4077 and then Present (DTC_Entity (Op))
4078 and then DT_Position (Op) = DT_Position (Iter))
4079 then
4080 return Op;
4081 end if;
4083 Next_Elmt (Prim);
4084 end loop;
4086 -- If we didn't find it, then our parent type is not
4087 -- iterable, so we return the Default_Iterator aspect of
4088 -- this type.
4090 return Iter;
4092 -- Otherwise not a derived type
4094 else
4095 return Iter;
4096 end if;
4097 end Get_Default_Iterator;
4099 -- Local variables
4101 Default_Iter : Entity_Id;
4102 Ent : Entity_Id;
4104 Reference_Control_Type : Entity_Id := Empty;
4105 Pseudo_Reference : Entity_Id := Empty;
4107 -- Start of processing for Handle_Of
4109 begin
4110 if Is_Class_Wide_Type (Container_Typ) then
4111 Default_Iter :=
4112 Get_Default_Iterator (Etype (Base_Type (Container_Typ)));
4113 else
4114 Default_Iter := Get_Default_Iterator (Etype (Container));
4115 end if;
4117 Cursor := Make_Temporary (Loc, 'C');
4119 -- For a container element iterator, the iterator type is obtained
4120 -- from the corresponding aspect, whose return type is descended
4121 -- from the corresponding interface type in some instance of
4122 -- Ada.Iterator_Interfaces. The actuals of that instantiation
4123 -- are Cursor and Has_Element.
4125 Iter_Type := Etype (Default_Iter);
4127 -- The iterator type, which is a class-wide type, may itself be
4128 -- derived locally, so the desired instantiation is the scope of
4129 -- the root type of the iterator type.
4131 Iter_Pack := Scope (Root_Type (Etype (Iter_Type)));
4133 -- Find declarations needed for "for ... of" optimization
4135 Ent := First_Entity (Pack);
4136 while Present (Ent) loop
4137 if Chars (Ent) = Name_Get_Element_Access then
4138 Fast_Element_Access_Op := Ent;
4140 elsif Chars (Ent) = Name_Step
4141 and then Ekind (Ent) = E_Procedure
4142 then
4143 Fast_Step_Op := Ent;
4145 elsif Chars (Ent) = Name_Reference_Control_Type then
4146 Reference_Control_Type := Ent;
4148 elsif Chars (Ent) = Name_Pseudo_Reference then
4149 Pseudo_Reference := Ent;
4150 end if;
4152 Next_Entity (Ent);
4153 end loop;
4155 if Present (Reference_Control_Type)
4156 and then Present (Pseudo_Reference)
4157 then
4158 Insert_Action (N,
4159 Make_Object_Declaration (Loc,
4160 Defining_Identifier => Make_Temporary (Loc, 'D'),
4161 Object_Definition =>
4162 New_Occurrence_Of (Reference_Control_Type, Loc),
4163 Expression =>
4164 Make_Function_Call (Loc,
4165 Name =>
4166 New_Occurrence_Of (Pseudo_Reference, Loc),
4167 Parameter_Associations =>
4168 New_List (New_Copy_Tree (Container_Arg)))));
4169 end if;
4171 -- Rewrite domain of iteration as a call to the default iterator
4172 -- for the container type. The formal may be an access parameter
4173 -- in which case we must build a reference to the container.
4175 declare
4176 Arg : Node_Id;
4177 begin
4178 if Is_Access_Type (Etype (First_Entity (Default_Iter))) then
4179 Arg :=
4180 Make_Attribute_Reference (Loc,
4181 Prefix => Container_Arg,
4182 Attribute_Name => Name_Unrestricted_Access);
4183 else
4184 Arg := Container_Arg;
4185 end if;
4187 Rewrite (Name (I_Spec),
4188 Make_Function_Call (Loc,
4189 Name =>
4190 New_Occurrence_Of (Default_Iter, Loc),
4191 Parameter_Associations => New_List (Arg)));
4192 end;
4194 Analyze_And_Resolve (Name (I_Spec));
4196 -- Find cursor type in proper iterator package, which is an
4197 -- instantiation of Iterator_Interfaces.
4199 Ent := First_Entity (Iter_Pack);
4200 while Present (Ent) loop
4201 if Chars (Ent) = Name_Cursor then
4202 Set_Etype (Cursor, Etype (Ent));
4203 exit;
4204 end if;
4206 Next_Entity (Ent);
4207 end loop;
4209 if Present (Fast_Element_Access_Op) then
4210 Decl :=
4211 Make_Object_Renaming_Declaration (Loc,
4212 Defining_Identifier => Id,
4213 Subtype_Mark =>
4214 New_Occurrence_Of (Elem_Typ, Loc),
4215 Name =>
4216 Make_Explicit_Dereference (Loc,
4217 Prefix =>
4218 Make_Function_Call (Loc,
4219 Name =>
4220 New_Occurrence_Of (Fast_Element_Access_Op, Loc),
4221 Parameter_Associations =>
4222 New_List (New_Occurrence_Of (Cursor, Loc)))));
4224 else
4225 Decl :=
4226 Make_Object_Renaming_Declaration (Loc,
4227 Defining_Identifier => Id,
4228 Subtype_Mark =>
4229 New_Occurrence_Of (Elem_Typ, Loc),
4230 Name =>
4231 Make_Indexed_Component (Loc,
4232 Prefix => Relocate_Node (Container_Arg),
4233 Expressions =>
4234 New_List (New_Occurrence_Of (Cursor, Loc))));
4235 end if;
4237 -- The defining identifier in the iterator is user-visible and
4238 -- must be visible in the debugger.
4240 Set_Debug_Info_Needed (Id);
4242 -- If the container does not have a variable indexing aspect,
4243 -- the element is a constant in the loop. The container itself
4244 -- may be constant, in which case the element is a constant as
4245 -- well. The container has been rewritten as a call to Iterate,
4246 -- so examine original node.
4248 if No (Find_Value_Of_Aspect
4249 (Container_Typ, Aspect_Variable_Indexing))
4250 or else not Is_Variable (Original_Node (Container))
4251 then
4252 Set_Ekind (Id, E_Constant);
4253 end if;
4255 Prepend_To (Stats, Decl);
4256 end Handle_Of;
4258 -- X in Iterate (S) : type of iterator is type of explicitly given
4259 -- Iterate function, and the loop variable is the cursor. It will be
4260 -- assigned in the loop and must be a variable.
4262 else
4263 Iter_Type := Etype (Name (I_Spec));
4265 -- The iterator type, which is a class-wide type, may itself be
4266 -- derived locally, so the desired instantiation is the scope of
4267 -- the root type of the iterator type, as in the "of" case.
4269 Iter_Pack := Scope (Root_Type (Etype (Iter_Type)));
4270 Cursor := Id;
4271 end if;
4273 Iterator := Make_Temporary (Loc, 'I');
4275 -- For both iterator forms, add a call to the step operation to advance
4276 -- the cursor. Generate:
4278 -- Cursor := Iterator.Next (Cursor);
4280 -- or else
4282 -- Cursor := Next (Cursor);
4284 if Present (Fast_Element_Access_Op) and then Present (Fast_Step_Op) then
4285 declare
4286 Curs_Name : constant Node_Id := New_Occurrence_Of (Cursor, Loc);
4287 Step_Call : Node_Id;
4289 begin
4290 Step_Call :=
4291 Make_Procedure_Call_Statement (Loc,
4292 Name =>
4293 New_Occurrence_Of (Fast_Step_Op, Loc),
4294 Parameter_Associations => New_List (Curs_Name));
4296 Append_To (Stats, Step_Call);
4297 Set_Assignment_OK (Curs_Name);
4298 end;
4300 else
4301 declare
4302 Rhs : Node_Id;
4304 begin
4305 Rhs :=
4306 Make_Function_Call (Loc,
4307 Name =>
4308 Make_Selected_Component (Loc,
4309 Prefix => New_Occurrence_Of (Iterator, Loc),
4310 Selector_Name => Make_Identifier (Loc, Name_Step)),
4311 Parameter_Associations => New_List (
4312 New_Occurrence_Of (Cursor, Loc)));
4314 Append_To (Stats,
4315 Make_Assignment_Statement (Loc,
4316 Name => New_Occurrence_Of (Cursor, Loc),
4317 Expression => Rhs));
4318 Set_Assignment_OK (Name (Last (Stats)));
4319 end;
4320 end if;
4322 -- Generate:
4323 -- while Has_Element (Cursor) loop
4324 -- <Stats>
4325 -- end loop;
4327 -- Has_Element is the second actual in the iterator package
4329 New_Loop :=
4330 Make_Loop_Statement (Loc,
4331 Iteration_Scheme =>
4332 Make_Iteration_Scheme (Loc,
4333 Condition =>
4334 Make_Function_Call (Loc,
4335 Name =>
4336 New_Occurrence_Of
4337 (Next_Entity (First_Entity (Iter_Pack)), Loc),
4338 Parameter_Associations => New_List (
4339 New_Occurrence_Of (Cursor, Loc)))),
4341 Statements => Stats,
4342 End_Label => Empty);
4344 -- If present, preserve identifier of loop, which can be used in an exit
4345 -- statement in the body.
4347 if Present (Identifier (N)) then
4348 Set_Identifier (New_Loop, Relocate_Node (Identifier (N)));
4349 end if;
4351 -- Create the declarations for Iterator and cursor and insert them
4352 -- before the source loop. Given that the domain of iteration is already
4353 -- an entity, the iterator is just a renaming of that entity. Possible
4354 -- optimization ???
4356 Insert_Action (N,
4357 Make_Object_Renaming_Declaration (Loc,
4358 Defining_Identifier => Iterator,
4359 Subtype_Mark => New_Occurrence_Of (Iter_Type, Loc),
4360 Name => Relocate_Node (Name (I_Spec))));
4362 -- Create declaration for cursor
4364 declare
4365 Cursor_Decl : constant Node_Id :=
4366 Make_Object_Declaration (Loc,
4367 Defining_Identifier => Cursor,
4368 Object_Definition =>
4369 New_Occurrence_Of (Etype (Cursor), Loc),
4370 Expression =>
4371 Make_Selected_Component (Loc,
4372 Prefix =>
4373 New_Occurrence_Of (Iterator, Loc),
4374 Selector_Name =>
4375 Make_Identifier (Loc, Name_Init)));
4377 begin
4378 -- The cursor is only modified in expanded code, so it appears
4379 -- as unassigned to the warning machinery. We must suppress this
4380 -- spurious warning explicitly. The cursor's kind is that of the
4381 -- original loop parameter (it is a constant if the domain of
4382 -- iteration is constant).
4384 Set_Warnings_Off (Cursor);
4385 Set_Assignment_OK (Cursor_Decl);
4387 Insert_Action (N, Cursor_Decl);
4388 Set_Ekind (Cursor, Id_Kind);
4389 end;
4391 -- If the range of iteration is given by a function call that returns
4392 -- a container, the finalization actions have been saved in the
4393 -- Condition_Actions of the iterator. Insert them now at the head of
4394 -- the loop.
4396 if Present (Condition_Actions (Isc)) then
4397 Insert_List_Before (N, Condition_Actions (Isc));
4398 end if;
4400 Rewrite (N, New_Loop);
4401 Analyze (N);
4402 end Expand_Iterator_Loop_Over_Container;
4404 -----------------------------
4405 -- Expand_N_Loop_Statement --
4406 -----------------------------
4408 -- 1. Remove null loop entirely
4409 -- 2. Deal with while condition for C/Fortran boolean
4410 -- 3. Deal with loops with a non-standard enumeration type range
4411 -- 4. Deal with while loops where Condition_Actions is set
4412 -- 5. Deal with loops over predicated subtypes
4413 -- 6. Deal with loops with iterators over arrays and containers
4414 -- 7. Insert polling call if required
4416 procedure Expand_N_Loop_Statement (N : Node_Id) is
4417 Loc : constant Source_Ptr := Sloc (N);
4418 Scheme : constant Node_Id := Iteration_Scheme (N);
4419 Stmt : Node_Id;
4421 begin
4422 -- Delete null loop
4424 if Is_Null_Loop (N) then
4425 Rewrite (N, Make_Null_Statement (Loc));
4426 return;
4427 end if;
4429 -- Deal with condition for C/Fortran Boolean
4431 if Present (Scheme) then
4432 Adjust_Condition (Condition (Scheme));
4433 end if;
4435 -- Generate polling call
4437 if Is_Non_Empty_List (Statements (N)) then
4438 Generate_Poll_Call (First (Statements (N)));
4439 end if;
4441 -- Nothing more to do for plain loop with no iteration scheme
4443 if No (Scheme) then
4444 null;
4446 -- Case of for loop (Loop_Parameter_Specification present)
4448 -- Note: we do not have to worry about validity checking of the for loop
4449 -- range bounds here, since they were frozen with constant declarations
4450 -- and it is during that process that the validity checking is done.
4452 elsif Present (Loop_Parameter_Specification (Scheme)) then
4453 declare
4454 LPS : constant Node_Id :=
4455 Loop_Parameter_Specification (Scheme);
4456 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4457 Ltype : constant Entity_Id := Etype (Loop_Id);
4458 Btype : constant Entity_Id := Base_Type (Ltype);
4459 Expr : Node_Id;
4460 Decls : List_Id;
4461 New_Id : Entity_Id;
4463 begin
4464 -- Deal with loop over predicates
4466 if Is_Discrete_Type (Ltype)
4467 and then Present (Predicate_Function (Ltype))
4468 then
4469 Expand_Predicated_Loop (N);
4471 -- Handle the case where we have a for loop with the range type
4472 -- being an enumeration type with non-standard representation.
4473 -- In this case we expand:
4475 -- for x in [reverse] a .. b loop
4476 -- ...
4477 -- end loop;
4479 -- to
4481 -- for xP in [reverse] integer
4482 -- range etype'Pos (a) .. etype'Pos (b)
4483 -- loop
4484 -- declare
4485 -- x : constant etype := Pos_To_Rep (xP);
4486 -- begin
4487 -- ...
4488 -- end;
4489 -- end loop;
4491 elsif Is_Enumeration_Type (Btype)
4492 and then Present (Enum_Pos_To_Rep (Btype))
4493 then
4494 New_Id :=
4495 Make_Defining_Identifier (Loc,
4496 Chars => New_External_Name (Chars (Loop_Id), 'P'));
4498 -- If the type has a contiguous representation, successive
4499 -- values can be generated as offsets from the first literal.
4501 if Has_Contiguous_Rep (Btype) then
4502 Expr :=
4503 Unchecked_Convert_To (Btype,
4504 Make_Op_Add (Loc,
4505 Left_Opnd =>
4506 Make_Integer_Literal (Loc,
4507 Enumeration_Rep (First_Literal (Btype))),
4508 Right_Opnd => New_Occurrence_Of (New_Id, Loc)));
4509 else
4510 -- Use the constructed array Enum_Pos_To_Rep
4512 Expr :=
4513 Make_Indexed_Component (Loc,
4514 Prefix =>
4515 New_Occurrence_Of (Enum_Pos_To_Rep (Btype), Loc),
4516 Expressions =>
4517 New_List (New_Occurrence_Of (New_Id, Loc)));
4518 end if;
4520 -- Build declaration for loop identifier
4522 Decls :=
4523 New_List (
4524 Make_Object_Declaration (Loc,
4525 Defining_Identifier => Loop_Id,
4526 Constant_Present => True,
4527 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4528 Expression => Expr));
4530 Rewrite (N,
4531 Make_Loop_Statement (Loc,
4532 Identifier => Identifier (N),
4534 Iteration_Scheme =>
4535 Make_Iteration_Scheme (Loc,
4536 Loop_Parameter_Specification =>
4537 Make_Loop_Parameter_Specification (Loc,
4538 Defining_Identifier => New_Id,
4539 Reverse_Present => Reverse_Present (LPS),
4541 Discrete_Subtype_Definition =>
4542 Make_Subtype_Indication (Loc,
4544 Subtype_Mark =>
4545 New_Occurrence_Of (Standard_Natural, Loc),
4547 Constraint =>
4548 Make_Range_Constraint (Loc,
4549 Range_Expression =>
4550 Make_Range (Loc,
4552 Low_Bound =>
4553 Make_Attribute_Reference (Loc,
4554 Prefix =>
4555 New_Occurrence_Of (Btype, Loc),
4557 Attribute_Name => Name_Pos,
4559 Expressions => New_List (
4560 Relocate_Node
4561 (Type_Low_Bound (Ltype)))),
4563 High_Bound =>
4564 Make_Attribute_Reference (Loc,
4565 Prefix =>
4566 New_Occurrence_Of (Btype, Loc),
4568 Attribute_Name => Name_Pos,
4570 Expressions => New_List (
4571 Relocate_Node
4572 (Type_High_Bound
4573 (Ltype))))))))),
4575 Statements => New_List (
4576 Make_Block_Statement (Loc,
4577 Declarations => Decls,
4578 Handled_Statement_Sequence =>
4579 Make_Handled_Sequence_Of_Statements (Loc,
4580 Statements => Statements (N)))),
4582 End_Label => End_Label (N)));
4584 -- The loop parameter's entity must be removed from the loop
4585 -- scope's entity list and rendered invisible, since it will
4586 -- now be located in the new block scope. Any other entities
4587 -- already associated with the loop scope, such as the loop
4588 -- parameter's subtype, will remain there.
4590 -- In an element loop, the loop will contain a declaration for
4591 -- a cursor variable; otherwise the loop id is the first entity
4592 -- in the scope constructed for the loop.
4594 if Comes_From_Source (Loop_Id) then
4595 pragma Assert (First_Entity (Scope (Loop_Id)) = Loop_Id);
4596 null;
4597 end if;
4599 Set_First_Entity (Scope (Loop_Id), Next_Entity (Loop_Id));
4600 Remove_Homonym (Loop_Id);
4602 if Last_Entity (Scope (Loop_Id)) = Loop_Id then
4603 Set_Last_Entity (Scope (Loop_Id), Empty);
4604 end if;
4606 Analyze (N);
4608 -- Nothing to do with other cases of for loops
4610 else
4611 null;
4612 end if;
4613 end;
4615 -- Second case, if we have a while loop with Condition_Actions set, then
4616 -- we change it into a plain loop:
4618 -- while C loop
4619 -- ...
4620 -- end loop;
4622 -- changed to:
4624 -- loop
4625 -- <<condition actions>>
4626 -- exit when not C;
4627 -- ...
4628 -- end loop
4630 elsif Present (Scheme)
4631 and then Present (Condition_Actions (Scheme))
4632 and then Present (Condition (Scheme))
4633 then
4634 declare
4635 ES : Node_Id;
4637 begin
4638 ES :=
4639 Make_Exit_Statement (Sloc (Condition (Scheme)),
4640 Condition =>
4641 Make_Op_Not (Sloc (Condition (Scheme)),
4642 Right_Opnd => Condition (Scheme)));
4644 Prepend (ES, Statements (N));
4645 Insert_List_Before (ES, Condition_Actions (Scheme));
4647 -- This is not an implicit loop, since it is generated in response
4648 -- to the loop statement being processed. If this is itself
4649 -- implicit, the restriction has already been checked. If not,
4650 -- it is an explicit loop.
4652 Rewrite (N,
4653 Make_Loop_Statement (Sloc (N),
4654 Identifier => Identifier (N),
4655 Statements => Statements (N),
4656 End_Label => End_Label (N)));
4658 Analyze (N);
4659 end;
4661 -- Here to deal with iterator case
4663 elsif Present (Scheme)
4664 and then Present (Iterator_Specification (Scheme))
4665 then
4666 Expand_Iterator_Loop (N);
4668 -- An iterator loop may generate renaming declarations for elements
4669 -- that require debug information. This is the case in particular
4670 -- with element iterators, where debug information must be generated
4671 -- for the temporary that holds the element value. These temporaries
4672 -- are created within a transient block whose local declarations are
4673 -- transferred to the loop, which now has nontrivial local objects.
4675 if Nkind (N) = N_Loop_Statement
4676 and then Present (Identifier (N))
4677 then
4678 Qualify_Entity_Names (N);
4679 end if;
4680 end if;
4682 -- When the iteration scheme mentiones attribute 'Loop_Entry, the loop
4683 -- is transformed into a conditional block where the original loop is
4684 -- the sole statement. Inspect the statements of the nested loop for
4685 -- controlled objects.
4687 Stmt := N;
4689 if Subject_To_Loop_Entry_Attributes (Stmt) then
4690 Stmt := Find_Loop_In_Conditional_Block (Stmt);
4691 end if;
4693 Process_Statements_For_Controlled_Objects (Stmt);
4694 end Expand_N_Loop_Statement;
4696 ----------------------------
4697 -- Expand_Predicated_Loop --
4698 ----------------------------
4700 -- Note: the expander can handle generation of loops over predicated
4701 -- subtypes for both the dynamic and static cases. Depending on what
4702 -- we decide is allowed in Ada 2012 mode and/or extensions allowed
4703 -- mode, the semantic analyzer may disallow one or both forms.
4705 procedure Expand_Predicated_Loop (N : Node_Id) is
4706 Loc : constant Source_Ptr := Sloc (N);
4707 Isc : constant Node_Id := Iteration_Scheme (N);
4708 LPS : constant Node_Id := Loop_Parameter_Specification (Isc);
4709 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4710 Ltype : constant Entity_Id := Etype (Loop_Id);
4711 Stat : constant List_Id := Static_Discrete_Predicate (Ltype);
4712 Stmts : constant List_Id := Statements (N);
4714 begin
4715 -- Case of iteration over non-static predicate, should not be possible
4716 -- since this is not allowed by the semantics and should have been
4717 -- caught during analysis of the loop statement.
4719 if No (Stat) then
4720 raise Program_Error;
4722 -- If the predicate list is empty, that corresponds to a predicate of
4723 -- False, in which case the loop won't run at all, and we rewrite the
4724 -- entire loop as a null statement.
4726 elsif Is_Empty_List (Stat) then
4727 Rewrite (N, Make_Null_Statement (Loc));
4728 Analyze (N);
4730 -- For expansion over a static predicate we generate the following
4732 -- declare
4733 -- J : Ltype := min-val;
4734 -- begin
4735 -- loop
4736 -- body
4737 -- case J is
4738 -- when endpoint => J := startpoint;
4739 -- when endpoint => J := startpoint;
4740 -- ...
4741 -- when max-val => exit;
4742 -- when others => J := Lval'Succ (J);
4743 -- end case;
4744 -- end loop;
4745 -- end;
4747 -- with min-val replaced by max-val and Succ replaced by Pred if the
4748 -- loop parameter specification carries a Reverse indicator.
4750 -- To make this a little clearer, let's take a specific example:
4752 -- type Int is range 1 .. 10;
4753 -- subtype StaticP is Int with
4754 -- predicate => StaticP in 3 | 10 | 5 .. 7;
4755 -- ...
4756 -- for L in StaticP loop
4757 -- Put_Line ("static:" & J'Img);
4758 -- end loop;
4760 -- In this case, the loop is transformed into
4762 -- begin
4763 -- J : L := 3;
4764 -- loop
4765 -- body
4766 -- case J is
4767 -- when 3 => J := 5;
4768 -- when 7 => J := 10;
4769 -- when 10 => exit;
4770 -- when others => J := L'Succ (J);
4771 -- end case;
4772 -- end loop;
4773 -- end;
4775 -- In addition, if the loop specification is given by a subtype
4776 -- indication that constrains a predicated type, the bounds of
4777 -- iteration are given by those of the subtype indication.
4779 else
4780 Static_Predicate : declare
4781 S : Node_Id;
4782 D : Node_Id;
4783 P : Node_Id;
4784 Alts : List_Id;
4785 Cstm : Node_Id;
4787 -- If the domain is an itype, note the bounds of its range.
4789 L_Hi : Node_Id := Empty;
4790 L_Lo : Node_Id := Empty;
4792 function Lo_Val (N : Node_Id) return Node_Id;
4793 -- Given static expression or static range, returns an identifier
4794 -- whose value is the low bound of the expression value or range.
4796 function Hi_Val (N : Node_Id) return Node_Id;
4797 -- Given static expression or static range, returns an identifier
4798 -- whose value is the high bound of the expression value or range.
4800 ------------
4801 -- Hi_Val --
4802 ------------
4804 function Hi_Val (N : Node_Id) return Node_Id is
4805 begin
4806 if Is_OK_Static_Expression (N) then
4807 return New_Copy (N);
4808 else
4809 pragma Assert (Nkind (N) = N_Range);
4810 return New_Copy (High_Bound (N));
4811 end if;
4812 end Hi_Val;
4814 ------------
4815 -- Lo_Val --
4816 ------------
4818 function Lo_Val (N : Node_Id) return Node_Id is
4819 begin
4820 if Is_OK_Static_Expression (N) then
4821 return New_Copy (N);
4822 else
4823 pragma Assert (Nkind (N) = N_Range);
4824 return New_Copy (Low_Bound (N));
4825 end if;
4826 end Lo_Val;
4828 -- Start of processing for Static_Predicate
4830 begin
4831 -- Convert loop identifier to normal variable and reanalyze it so
4832 -- that this conversion works. We have to use the same defining
4833 -- identifier, since there may be references in the loop body.
4835 Set_Analyzed (Loop_Id, False);
4836 Set_Ekind (Loop_Id, E_Variable);
4838 -- In most loops the loop variable is assigned in various
4839 -- alternatives in the body. However, in the rare case when
4840 -- the range specifies a single element, the loop variable
4841 -- may trigger a spurious warning that is could be constant.
4842 -- This warning might as well be suppressed.
4844 Set_Warnings_Off (Loop_Id);
4846 if Is_Itype (Ltype) then
4847 L_Hi := High_Bound (Scalar_Range (Ltype));
4848 L_Lo := Low_Bound (Scalar_Range (Ltype));
4849 end if;
4851 -- Loop to create branches of case statement
4853 Alts := New_List;
4855 if Reverse_Present (LPS) then
4857 -- Initial value is largest value in predicate.
4859 if Is_Itype (Ltype) then
4860 D :=
4861 Make_Object_Declaration (Loc,
4862 Defining_Identifier => Loop_Id,
4863 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4864 Expression => L_Hi);
4866 else
4867 D :=
4868 Make_Object_Declaration (Loc,
4869 Defining_Identifier => Loop_Id,
4870 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4871 Expression => Hi_Val (Last (Stat)));
4872 end if;
4874 P := Last (Stat);
4875 while Present (P) loop
4876 if No (Prev (P)) then
4877 S := Make_Exit_Statement (Loc);
4878 else
4879 S :=
4880 Make_Assignment_Statement (Loc,
4881 Name => New_Occurrence_Of (Loop_Id, Loc),
4882 Expression => Hi_Val (Prev (P)));
4883 Set_Suppress_Assignment_Checks (S);
4884 end if;
4886 Append_To (Alts,
4887 Make_Case_Statement_Alternative (Loc,
4888 Statements => New_List (S),
4889 Discrete_Choices => New_List (Lo_Val (P))));
4891 Prev (P);
4892 end loop;
4894 if Is_Itype (Ltype)
4895 and then Is_OK_Static_Expression (L_Lo)
4896 and then
4897 Expr_Value (L_Lo) /= Expr_Value (Lo_Val (First (Stat)))
4898 then
4899 Append_To (Alts,
4900 Make_Case_Statement_Alternative (Loc,
4901 Statements => New_List (Make_Exit_Statement (Loc)),
4902 Discrete_Choices => New_List (L_Lo)));
4903 end if;
4905 else
4906 -- Initial value is smallest value in predicate
4908 if Is_Itype (Ltype) then
4909 D :=
4910 Make_Object_Declaration (Loc,
4911 Defining_Identifier => Loop_Id,
4912 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4913 Expression => L_Lo);
4914 else
4915 D :=
4916 Make_Object_Declaration (Loc,
4917 Defining_Identifier => Loop_Id,
4918 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4919 Expression => Lo_Val (First (Stat)));
4920 end if;
4922 P := First (Stat);
4923 while Present (P) loop
4924 if No (Next (P)) then
4925 S := Make_Exit_Statement (Loc);
4926 else
4927 S :=
4928 Make_Assignment_Statement (Loc,
4929 Name => New_Occurrence_Of (Loop_Id, Loc),
4930 Expression => Lo_Val (Next (P)));
4931 Set_Suppress_Assignment_Checks (S);
4932 end if;
4934 Append_To (Alts,
4935 Make_Case_Statement_Alternative (Loc,
4936 Statements => New_List (S),
4937 Discrete_Choices => New_List (Hi_Val (P))));
4939 Next (P);
4940 end loop;
4942 if Is_Itype (Ltype)
4943 and then Is_OK_Static_Expression (L_Hi)
4944 and then
4945 Expr_Value (L_Hi) /= Expr_Value (Lo_Val (Last (Stat)))
4946 then
4947 Append_To (Alts,
4948 Make_Case_Statement_Alternative (Loc,
4949 Statements => New_List (Make_Exit_Statement (Loc)),
4950 Discrete_Choices => New_List (L_Hi)));
4951 end if;
4952 end if;
4954 -- Add others choice
4956 declare
4957 Name_Next : Name_Id;
4959 begin
4960 if Reverse_Present (LPS) then
4961 Name_Next := Name_Pred;
4962 else
4963 Name_Next := Name_Succ;
4964 end if;
4966 S :=
4967 Make_Assignment_Statement (Loc,
4968 Name => New_Occurrence_Of (Loop_Id, Loc),
4969 Expression =>
4970 Make_Attribute_Reference (Loc,
4971 Prefix => New_Occurrence_Of (Ltype, Loc),
4972 Attribute_Name => Name_Next,
4973 Expressions => New_List (
4974 New_Occurrence_Of (Loop_Id, Loc))));
4975 Set_Suppress_Assignment_Checks (S);
4976 end;
4978 Append_To (Alts,
4979 Make_Case_Statement_Alternative (Loc,
4980 Discrete_Choices => New_List (Make_Others_Choice (Loc)),
4981 Statements => New_List (S)));
4983 -- Construct case statement and append to body statements
4985 Cstm :=
4986 Make_Case_Statement (Loc,
4987 Expression => New_Occurrence_Of (Loop_Id, Loc),
4988 Alternatives => Alts);
4989 Append_To (Stmts, Cstm);
4991 -- Rewrite the loop
4993 Set_Suppress_Assignment_Checks (D);
4995 Rewrite (N,
4996 Make_Block_Statement (Loc,
4997 Declarations => New_List (D),
4998 Handled_Statement_Sequence =>
4999 Make_Handled_Sequence_Of_Statements (Loc,
5000 Statements => New_List (
5001 Make_Loop_Statement (Loc,
5002 Statements => Stmts,
5003 End_Label => Empty)))));
5005 Analyze (N);
5006 end Static_Predicate;
5007 end if;
5008 end Expand_Predicated_Loop;
5010 ------------------------------
5011 -- Make_Tag_Ctrl_Assignment --
5012 ------------------------------
5014 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
5015 Asn : constant Node_Id := Relocate_Node (N);
5016 L : constant Node_Id := Name (N);
5017 Loc : constant Source_Ptr := Sloc (N);
5018 Res : constant List_Id := New_List;
5019 T : constant Entity_Id := Underlying_Type (Etype (L));
5021 Comp_Asn : constant Boolean := Is_Fully_Repped_Tagged_Type (T);
5022 Ctrl_Act : constant Boolean := Needs_Finalization (T)
5023 and then not No_Ctrl_Actions (N);
5024 Save_Tag : constant Boolean := Is_Tagged_Type (T)
5025 and then not Comp_Asn
5026 and then not No_Ctrl_Actions (N)
5027 and then Tagged_Type_Expansion;
5028 Adj_Call : Node_Id;
5029 Fin_Call : Node_Id;
5030 Tag_Id : Entity_Id;
5032 begin
5033 -- Finalize the target of the assignment when controlled
5035 -- We have two exceptions here:
5037 -- 1. If we are in an init proc since it is an initialization more
5038 -- than an assignment.
5040 -- 2. If the left-hand side is a temporary that was not initialized
5041 -- (or the parent part of a temporary since it is the case in
5042 -- extension aggregates). Such a temporary does not come from
5043 -- source. We must examine the original node for the prefix, because
5044 -- it may be a component of an entry formal, in which case it has
5045 -- been rewritten and does not appear to come from source either.
5047 -- Case of init proc
5049 if not Ctrl_Act then
5050 null;
5052 -- The left-hand side is an uninitialized temporary object
5054 elsif Nkind (L) = N_Type_Conversion
5055 and then Is_Entity_Name (Expression (L))
5056 and then Nkind (Parent (Entity (Expression (L)))) =
5057 N_Object_Declaration
5058 and then No_Initialization (Parent (Entity (Expression (L))))
5059 then
5060 null;
5062 else
5063 Fin_Call :=
5064 Make_Final_Call
5065 (Obj_Ref => Duplicate_Subexpr_No_Checks (L),
5066 Typ => Etype (L));
5068 if Present (Fin_Call) then
5069 Append_To (Res, Fin_Call);
5070 end if;
5071 end if;
5073 -- Save the Tag in a local variable Tag_Id
5075 if Save_Tag then
5076 Tag_Id := Make_Temporary (Loc, 'A');
5078 Append_To (Res,
5079 Make_Object_Declaration (Loc,
5080 Defining_Identifier => Tag_Id,
5081 Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc),
5082 Expression =>
5083 Make_Selected_Component (Loc,
5084 Prefix => Duplicate_Subexpr_No_Checks (L),
5085 Selector_Name =>
5086 New_Occurrence_Of (First_Tag_Component (T), Loc))));
5088 -- Otherwise Tag_Id is not used
5090 else
5091 Tag_Id := Empty;
5092 end if;
5094 -- If the tagged type has a full rep clause, expand the assignment into
5095 -- component-wise assignments. Mark the node as unanalyzed in order to
5096 -- generate the proper code and propagate this scenario by setting a
5097 -- flag to avoid infinite recursion.
5099 if Comp_Asn then
5100 Set_Analyzed (Asn, False);
5101 Set_Componentwise_Assignment (Asn, True);
5102 end if;
5104 Append_To (Res, Asn);
5106 -- Restore the tag
5108 if Save_Tag then
5109 Append_To (Res,
5110 Make_Assignment_Statement (Loc,
5111 Name =>
5112 Make_Selected_Component (Loc,
5113 Prefix => Duplicate_Subexpr_No_Checks (L),
5114 Selector_Name =>
5115 New_Occurrence_Of (First_Tag_Component (T), Loc)),
5116 Expression => New_Occurrence_Of (Tag_Id, Loc)));
5117 end if;
5119 -- Adjust the target after the assignment when controlled (not in the
5120 -- init proc since it is an initialization more than an assignment).
5122 if Ctrl_Act then
5123 Adj_Call :=
5124 Make_Adjust_Call
5125 (Obj_Ref => Duplicate_Subexpr_Move_Checks (L),
5126 Typ => Etype (L));
5128 if Present (Adj_Call) then
5129 Append_To (Res, Adj_Call);
5130 end if;
5131 end if;
5133 return Res;
5135 exception
5137 -- Could use comment here ???
5139 when RE_Not_Available =>
5140 return Empty_List;
5141 end Make_Tag_Ctrl_Assignment;
5143 end Exp_Ch5;