* libgnarl/a-intnam__rtems.ads: Update copyright date.
[official-gcc.git] / gcc / ada / exp_ch5.adb
blobd8d22d02af961f160383402cec0e58e52e3bfbfb
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT COMPILER COMPONENTS --
4 -- --
5 -- E X P _ C H 5 --
6 -- --
7 -- B o d y --
8 -- --
9 -- Copyright (C) 1992-2017, Free Software Foundation, Inc. --
10 -- --
11 -- GNAT is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 3, or (at your option) any later ver- --
14 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
17 -- for more details. You should have received a copy of the GNU General --
18 -- Public License distributed with GNAT; see file COPYING3. If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license. --
20 -- --
21 -- GNAT was originally developed by the GNAT team at New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc. --
23 -- --
24 ------------------------------------------------------------------------------
26 with Aspects; use Aspects;
27 with Atree; use Atree;
28 with Checks; use Checks;
29 with Debug; use Debug;
30 with Einfo; use Einfo;
31 with Elists; use Elists;
32 with Errout; use Errout;
33 with Exp_Aggr; use Exp_Aggr;
34 with Exp_Ch6; use Exp_Ch6;
35 with Exp_Ch7; use Exp_Ch7;
36 with Exp_Ch11; use Exp_Ch11;
37 with Exp_Dbug; use Exp_Dbug;
38 with Exp_Pakd; use Exp_Pakd;
39 with Exp_Tss; use Exp_Tss;
40 with Exp_Util; use Exp_Util;
41 with Inline; use Inline;
42 with Namet; use Namet;
43 with Nlists; use Nlists;
44 with Nmake; use Nmake;
45 with Opt; use Opt;
46 with Restrict; use Restrict;
47 with Rident; use Rident;
48 with Rtsfind; use Rtsfind;
49 with Sinfo; use Sinfo;
50 with Sem; use Sem;
51 with Sem_Aux; use Sem_Aux;
52 with Sem_Ch3; use Sem_Ch3;
53 with Sem_Ch8; use Sem_Ch8;
54 with Sem_Ch13; use Sem_Ch13;
55 with Sem_Eval; use Sem_Eval;
56 with Sem_Res; use Sem_Res;
57 with Sem_Util; use Sem_Util;
58 with Snames; use Snames;
59 with Stand; use Stand;
60 with Stringt; use Stringt;
61 with Tbuild; use Tbuild;
62 with Uintp; use Uintp;
63 with Validsw; use Validsw;
65 package body Exp_Ch5 is
67 procedure Build_Formal_Container_Iteration
68 (N : Node_Id;
69 Container : Entity_Id;
70 Cursor : Entity_Id;
71 Init : out Node_Id;
72 Advance : out Node_Id;
73 New_Loop : out Node_Id);
74 -- Utility to create declarations and loop statement for both forms
75 -- of formal container iterators.
77 function Change_Of_Representation (N : Node_Id) return Boolean;
78 -- Determine if the right-hand side of assignment N is a type conversion
79 -- which requires a change of representation. Called only for the array
80 -- and record cases.
82 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id);
83 -- N is an assignment which assigns an array value. This routine process
84 -- the various special cases and checks required for such assignments,
85 -- including change of representation. Rhs is normally simply the right-
86 -- hand side of the assignment, except that if the right-hand side is a
87 -- type conversion or a qualified expression, then the RHS is the actual
88 -- expression inside any such type conversions or qualifications.
90 function Expand_Assign_Array_Loop
91 (N : Node_Id;
92 Larray : Entity_Id;
93 Rarray : Entity_Id;
94 L_Type : Entity_Id;
95 R_Type : Entity_Id;
96 Ndim : Pos;
97 Rev : Boolean) return Node_Id;
98 -- N is an assignment statement which assigns an array value. This routine
99 -- expands the assignment into a loop (or nested loops for the case of a
100 -- multi-dimensional array) to do the assignment component by component.
101 -- Larray and Rarray are the entities of the actual arrays on the left-hand
102 -- and right-hand sides. L_Type and R_Type are the types of these arrays
103 -- (which may not be the same, due to either sliding, or to a change of
104 -- representation case). Ndim is the number of dimensions and the parameter
105 -- Rev indicates if the loops run normally (Rev = False), or reversed
106 -- (Rev = True). The value returned is the constructed loop statement.
107 -- Auxiliary declarations are inserted before node N using the standard
108 -- Insert_Actions mechanism.
110 procedure Expand_Assign_Record (N : Node_Id);
111 -- N is an assignment of an untagged record value. This routine handles
112 -- the case where the assignment must be made component by component,
113 -- either because the target is not byte aligned, or there is a change
114 -- of representation, or when we have a tagged type with a representation
115 -- clause (this last case is required because holes in the tagged type
116 -- might be filled with components from child types).
118 procedure Expand_Assign_With_Target_Names (N : Node_Id);
119 -- (AI12-0125): N is an assignment statement whose RHS contains occurrences
120 -- of @ that designate the value of the LHS of the assignment. If the LHS
121 -- is side-effect free the target names can be replaced with a copy of the
122 -- LHS; otherwise the semantics of the assignment is described in terms of
123 -- a procedure with an in-out parameter, and expanded as such.
125 procedure Expand_Formal_Container_Loop (N : Node_Id);
126 -- Use the primitives specified in an Iterable aspect to expand a loop
127 -- over a so-called formal container, primarily for SPARK usage.
129 procedure Expand_Formal_Container_Element_Loop (N : Node_Id);
130 -- Same, for an iterator of the form " For E of C". In this case the
131 -- iterator provides the name of the element, and the cursor is generated
132 -- internally.
134 procedure Expand_Iterator_Loop (N : Node_Id);
135 -- Expand loop over arrays and containers that uses the form "for X of C"
136 -- with an optional subtype mark, or "for Y in C".
138 procedure Expand_Iterator_Loop_Over_Container
139 (N : Node_Id;
140 Isc : Node_Id;
141 I_Spec : Node_Id;
142 Container : Node_Id;
143 Container_Typ : Entity_Id);
144 -- Expand loop over containers that uses the form "for X of C" with an
145 -- optional subtype mark, or "for Y in C". Isc is the iteration scheme.
146 -- I_Spec is the iterator specification and Container is either the
147 -- Container (for OF) or the iterator (for IN).
149 procedure Expand_Predicated_Loop (N : Node_Id);
150 -- Expand for loop over predicated subtype
152 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id;
153 -- Generate the necessary code for controlled and tagged assignment, that
154 -- is to say, finalization of the target before, adjustment of the target
155 -- after and save and restore of the tag and finalization pointers which
156 -- are not 'part of the value' and must not be changed upon assignment. N
157 -- is the original Assignment node.
159 --------------------------------------
160 -- Build_Formal_Container_iteration --
161 --------------------------------------
163 procedure Build_Formal_Container_Iteration
164 (N : Node_Id;
165 Container : Entity_Id;
166 Cursor : Entity_Id;
167 Init : out Node_Id;
168 Advance : out Node_Id;
169 New_Loop : out Node_Id)
171 Loc : constant Source_Ptr := Sloc (N);
172 Stats : constant List_Id := Statements (N);
173 Typ : constant Entity_Id := Base_Type (Etype (Container));
174 First_Op : constant Entity_Id :=
175 Get_Iterable_Type_Primitive (Typ, Name_First);
176 Next_Op : constant Entity_Id :=
177 Get_Iterable_Type_Primitive (Typ, Name_Next);
179 Has_Element_Op : constant Entity_Id :=
180 Get_Iterable_Type_Primitive (Typ, Name_Has_Element);
181 begin
182 -- Declaration for Cursor
184 Init :=
185 Make_Object_Declaration (Loc,
186 Defining_Identifier => Cursor,
187 Object_Definition => New_Occurrence_Of (Etype (First_Op), Loc),
188 Expression =>
189 Make_Function_Call (Loc,
190 Name => New_Occurrence_Of (First_Op, Loc),
191 Parameter_Associations => New_List (
192 New_Occurrence_Of (Container, Loc))));
194 -- Statement that advances cursor in loop
196 Advance :=
197 Make_Assignment_Statement (Loc,
198 Name => New_Occurrence_Of (Cursor, Loc),
199 Expression =>
200 Make_Function_Call (Loc,
201 Name => New_Occurrence_Of (Next_Op, Loc),
202 Parameter_Associations => New_List (
203 New_Occurrence_Of (Container, Loc),
204 New_Occurrence_Of (Cursor, Loc))));
206 -- Iterator is rewritten as a while_loop
208 New_Loop :=
209 Make_Loop_Statement (Loc,
210 Iteration_Scheme =>
211 Make_Iteration_Scheme (Loc,
212 Condition =>
213 Make_Function_Call (Loc,
214 Name =>
215 New_Occurrence_Of (Has_Element_Op, Loc),
216 Parameter_Associations => New_List (
217 New_Occurrence_Of (Container, Loc),
218 New_Occurrence_Of (Cursor, Loc)))),
219 Statements => Stats,
220 End_Label => Empty);
221 end Build_Formal_Container_Iteration;
223 ------------------------------
224 -- Change_Of_Representation --
225 ------------------------------
227 function Change_Of_Representation (N : Node_Id) return Boolean is
228 Rhs : constant Node_Id := Expression (N);
229 begin
230 return
231 Nkind (Rhs) = N_Type_Conversion
232 and then
233 not Same_Representation (Etype (Rhs), Etype (Expression (Rhs)));
234 end Change_Of_Representation;
236 -------------------------
237 -- Expand_Assign_Array --
238 -------------------------
240 -- There are two issues here. First, do we let Gigi do a block move, or
241 -- do we expand out into a loop? Second, we need to set the two flags
242 -- Forwards_OK and Backwards_OK which show whether the block move (or
243 -- corresponding loops) can be legitimately done in a forwards (low to
244 -- high) or backwards (high to low) manner.
246 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id) is
247 Loc : constant Source_Ptr := Sloc (N);
249 Lhs : constant Node_Id := Name (N);
251 Act_Lhs : constant Node_Id := Get_Referenced_Object (Lhs);
252 Act_Rhs : Node_Id := Get_Referenced_Object (Rhs);
254 L_Type : constant Entity_Id :=
255 Underlying_Type (Get_Actual_Subtype (Act_Lhs));
256 R_Type : Entity_Id :=
257 Underlying_Type (Get_Actual_Subtype (Act_Rhs));
259 L_Slice : constant Boolean := Nkind (Act_Lhs) = N_Slice;
260 R_Slice : constant Boolean := Nkind (Act_Rhs) = N_Slice;
262 Crep : constant Boolean := Change_Of_Representation (N);
264 Larray : Node_Id;
265 Rarray : Node_Id;
267 Ndim : constant Pos := Number_Dimensions (L_Type);
269 Loop_Required : Boolean := False;
270 -- This switch is set to True if the array move must be done using
271 -- an explicit front end generated loop.
273 procedure Apply_Dereference (Arg : Node_Id);
274 -- If the argument is an access to an array, and the assignment is
275 -- converted into a procedure call, apply explicit dereference.
277 function Has_Address_Clause (Exp : Node_Id) return Boolean;
278 -- Test if Exp is a reference to an array whose declaration has
279 -- an address clause, or it is a slice of such an array.
281 function Is_Formal_Array (Exp : Node_Id) return Boolean;
282 -- Test if Exp is a reference to an array which is either a formal
283 -- parameter or a slice of a formal parameter. These are the cases
284 -- where hidden aliasing can occur.
286 function Is_Non_Local_Array (Exp : Node_Id) return Boolean;
287 -- Determine if Exp is a reference to an array variable which is other
288 -- than an object defined in the current scope, or a component or a
289 -- slice of such an object. Such objects can be aliased to parameters
290 -- (unlike local array references).
292 -----------------------
293 -- Apply_Dereference --
294 -----------------------
296 procedure Apply_Dereference (Arg : Node_Id) is
297 Typ : constant Entity_Id := Etype (Arg);
298 begin
299 if Is_Access_Type (Typ) then
300 Rewrite (Arg, Make_Explicit_Dereference (Loc,
301 Prefix => Relocate_Node (Arg)));
302 Analyze_And_Resolve (Arg, Designated_Type (Typ));
303 end if;
304 end Apply_Dereference;
306 ------------------------
307 -- Has_Address_Clause --
308 ------------------------
310 function Has_Address_Clause (Exp : Node_Id) return Boolean is
311 begin
312 return
313 (Is_Entity_Name (Exp) and then
314 Present (Address_Clause (Entity (Exp))))
315 or else
316 (Nkind (Exp) = N_Slice and then Has_Address_Clause (Prefix (Exp)));
317 end Has_Address_Clause;
319 ---------------------
320 -- Is_Formal_Array --
321 ---------------------
323 function Is_Formal_Array (Exp : Node_Id) return Boolean is
324 begin
325 return
326 (Is_Entity_Name (Exp) and then Is_Formal (Entity (Exp)))
327 or else
328 (Nkind (Exp) = N_Slice and then Is_Formal_Array (Prefix (Exp)));
329 end Is_Formal_Array;
331 ------------------------
332 -- Is_Non_Local_Array --
333 ------------------------
335 function Is_Non_Local_Array (Exp : Node_Id) return Boolean is
336 begin
337 case Nkind (Exp) is
338 when N_Indexed_Component
339 | N_Selected_Component
340 | N_Slice
342 return Is_Non_Local_Array (Prefix (Exp));
344 when others =>
345 return
346 not (Is_Entity_Name (Exp)
347 and then Scope (Entity (Exp)) = Current_Scope);
348 end case;
349 end Is_Non_Local_Array;
351 -- Determine if Lhs, Rhs are formal arrays or nonlocal arrays
353 Lhs_Formal : constant Boolean := Is_Formal_Array (Act_Lhs);
354 Rhs_Formal : constant Boolean := Is_Formal_Array (Act_Rhs);
356 Lhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Lhs);
357 Rhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Rhs);
359 -- Start of processing for Expand_Assign_Array
361 begin
362 -- Deal with length check. Note that the length check is done with
363 -- respect to the right-hand side as given, not a possible underlying
364 -- renamed object, since this would generate incorrect extra checks.
366 Apply_Length_Check (Rhs, L_Type);
368 -- We start by assuming that the move can be done in either direction,
369 -- i.e. that the two sides are completely disjoint.
371 Set_Forwards_OK (N, True);
372 Set_Backwards_OK (N, True);
374 -- Normally it is only the slice case that can lead to overlap, and
375 -- explicit checks for slices are made below. But there is one case
376 -- where the slice can be implicit and invisible to us: when we have a
377 -- one dimensional array, and either both operands are parameters, or
378 -- one is a parameter (which can be a slice passed by reference) and the
379 -- other is a non-local variable. In this case the parameter could be a
380 -- slice that overlaps with the other operand.
382 -- However, if the array subtype is a constrained first subtype in the
383 -- parameter case, then we don't have to worry about overlap, since
384 -- slice assignments aren't possible (other than for a slice denoting
385 -- the whole array).
387 -- Note: No overlap is possible if there is a change of representation,
388 -- so we can exclude this case.
390 if Ndim = 1
391 and then not Crep
392 and then
393 ((Lhs_Formal and Rhs_Formal)
394 or else
395 (Lhs_Formal and Rhs_Non_Local_Var)
396 or else
397 (Rhs_Formal and Lhs_Non_Local_Var))
398 and then
399 (not Is_Constrained (Etype (Lhs))
400 or else not Is_First_Subtype (Etype (Lhs)))
401 then
402 Set_Forwards_OK (N, False);
403 Set_Backwards_OK (N, False);
405 -- Note: the bit-packed case is not worrisome here, since if we have
406 -- a slice passed as a parameter, it is always aligned on a byte
407 -- boundary, and if there are no explicit slices, the assignment
408 -- can be performed directly.
409 end if;
411 -- If either operand has an address clause clear Backwards_OK and
412 -- Forwards_OK, since we cannot tell if the operands overlap. We
413 -- exclude this treatment when Rhs is an aggregate, since we know
414 -- that overlap can't occur.
416 if (Has_Address_Clause (Lhs) and then Nkind (Rhs) /= N_Aggregate)
417 or else Has_Address_Clause (Rhs)
418 then
419 Set_Forwards_OK (N, False);
420 Set_Backwards_OK (N, False);
421 end if;
423 -- We certainly must use a loop for change of representation and also
424 -- we use the operand of the conversion on the right-hand side as the
425 -- effective right-hand side (the component types must match in this
426 -- situation).
428 if Crep then
429 Act_Rhs := Get_Referenced_Object (Rhs);
430 R_Type := Get_Actual_Subtype (Act_Rhs);
431 Loop_Required := True;
433 -- We require a loop if the left side is possibly bit unaligned
435 elsif Possible_Bit_Aligned_Component (Lhs)
436 or else
437 Possible_Bit_Aligned_Component (Rhs)
438 then
439 Loop_Required := True;
441 -- Arrays with controlled components are expanded into a loop to force
442 -- calls to Adjust at the component level.
444 elsif Has_Controlled_Component (L_Type) then
445 Loop_Required := True;
447 -- If object is atomic/VFA, we cannot tolerate a loop
449 elsif Is_Atomic_Or_VFA_Object (Act_Lhs)
450 or else
451 Is_Atomic_Or_VFA_Object (Act_Rhs)
452 then
453 return;
455 -- Loop is required if we have atomic components since we have to
456 -- be sure to do any accesses on an element by element basis.
458 elsif Has_Atomic_Components (L_Type)
459 or else Has_Atomic_Components (R_Type)
460 or else Is_Atomic_Or_VFA (Component_Type (L_Type))
461 or else Is_Atomic_Or_VFA (Component_Type (R_Type))
462 then
463 Loop_Required := True;
465 -- Case where no slice is involved
467 elsif not L_Slice and not R_Slice then
469 -- The following code deals with the case of unconstrained bit packed
470 -- arrays. The problem is that the template for such arrays contains
471 -- the bounds of the actual source level array, but the copy of an
472 -- entire array requires the bounds of the underlying array. It would
473 -- be nice if the back end could take care of this, but right now it
474 -- does not know how, so if we have such a type, then we expand out
475 -- into a loop, which is inefficient but works correctly. If we don't
476 -- do this, we get the wrong length computed for the array to be
477 -- moved. The two cases we need to worry about are:
479 -- Explicit dereference of an unconstrained packed array type as in
480 -- the following example:
482 -- procedure C52 is
483 -- type BITS is array(INTEGER range <>) of BOOLEAN;
484 -- pragma PACK(BITS);
485 -- type A is access BITS;
486 -- P1,P2 : A;
487 -- begin
488 -- P1 := new BITS (1 .. 65_535);
489 -- P2 := new BITS (1 .. 65_535);
490 -- P2.ALL := P1.ALL;
491 -- end C52;
493 -- A formal parameter reference with an unconstrained bit array type
494 -- is the other case we need to worry about (here we assume the same
495 -- BITS type declared above):
497 -- procedure Write_All (File : out BITS; Contents : BITS);
498 -- begin
499 -- File.Storage := Contents;
500 -- end Write_All;
502 -- We expand to a loop in either of these two cases
504 -- Question for future thought. Another potentially more efficient
505 -- approach would be to create the actual subtype, and then do an
506 -- unchecked conversion to this actual subtype ???
508 Check_Unconstrained_Bit_Packed_Array : declare
510 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean;
511 -- Function to perform required test for the first case, above
512 -- (dereference of an unconstrained bit packed array).
514 -----------------------
515 -- Is_UBPA_Reference --
516 -----------------------
518 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean is
519 Typ : constant Entity_Id := Underlying_Type (Etype (Opnd));
520 P_Type : Entity_Id;
521 Des_Type : Entity_Id;
523 begin
524 if Present (Packed_Array_Impl_Type (Typ))
525 and then Is_Array_Type (Packed_Array_Impl_Type (Typ))
526 and then not Is_Constrained (Packed_Array_Impl_Type (Typ))
527 then
528 return True;
530 elsif Nkind (Opnd) = N_Explicit_Dereference then
531 P_Type := Underlying_Type (Etype (Prefix (Opnd)));
533 if not Is_Access_Type (P_Type) then
534 return False;
536 else
537 Des_Type := Designated_Type (P_Type);
538 return
539 Is_Bit_Packed_Array (Des_Type)
540 and then not Is_Constrained (Des_Type);
541 end if;
543 else
544 return False;
545 end if;
546 end Is_UBPA_Reference;
548 -- Start of processing for Check_Unconstrained_Bit_Packed_Array
550 begin
551 if Is_UBPA_Reference (Lhs)
552 or else
553 Is_UBPA_Reference (Rhs)
554 then
555 Loop_Required := True;
557 -- Here if we do not have the case of a reference to a bit packed
558 -- unconstrained array case. In this case gigi can most certainly
559 -- handle the assignment if a forwards move is allowed.
561 -- (could it handle the backwards case also???)
563 elsif Forwards_OK (N) then
564 return;
565 end if;
566 end Check_Unconstrained_Bit_Packed_Array;
568 -- The back end can always handle the assignment if the right side is a
569 -- string literal (note that overlap is definitely impossible in this
570 -- case). If the type is packed, a string literal is always converted
571 -- into an aggregate, except in the case of a null slice, for which no
572 -- aggregate can be written. In that case, rewrite the assignment as a
573 -- null statement, a length check has already been emitted to verify
574 -- that the range of the left-hand side is empty.
576 -- Note that this code is not executed if we have an assignment of a
577 -- string literal to a non-bit aligned component of a record, a case
578 -- which cannot be handled by the backend.
580 elsif Nkind (Rhs) = N_String_Literal then
581 if String_Length (Strval (Rhs)) = 0
582 and then Is_Bit_Packed_Array (L_Type)
583 then
584 Rewrite (N, Make_Null_Statement (Loc));
585 Analyze (N);
586 end if;
588 return;
590 -- If either operand is bit packed, then we need a loop, since we can't
591 -- be sure that the slice is byte aligned. Similarly, if either operand
592 -- is a possibly unaligned slice, then we need a loop (since the back
593 -- end cannot handle unaligned slices).
595 elsif Is_Bit_Packed_Array (L_Type)
596 or else Is_Bit_Packed_Array (R_Type)
597 or else Is_Possibly_Unaligned_Slice (Lhs)
598 or else Is_Possibly_Unaligned_Slice (Rhs)
599 then
600 Loop_Required := True;
602 -- If we are not bit-packed, and we have only one slice, then no overlap
603 -- is possible except in the parameter case, so we can let the back end
604 -- handle things.
606 elsif not (L_Slice and R_Slice) then
607 if Forwards_OK (N) then
608 return;
609 end if;
610 end if;
612 -- If the right-hand side is a string literal, introduce a temporary for
613 -- it, for use in the generated loop that will follow.
615 if Nkind (Rhs) = N_String_Literal then
616 declare
617 Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Rhs);
618 Decl : Node_Id;
620 begin
621 Decl :=
622 Make_Object_Declaration (Loc,
623 Defining_Identifier => Temp,
624 Object_Definition => New_Occurrence_Of (L_Type, Loc),
625 Expression => Relocate_Node (Rhs));
627 Insert_Action (N, Decl);
628 Rewrite (Rhs, New_Occurrence_Of (Temp, Loc));
629 R_Type := Etype (Temp);
630 end;
631 end if;
633 -- Come here to complete the analysis
635 -- Loop_Required: Set to True if we know that a loop is required
636 -- regardless of overlap considerations.
638 -- Forwards_OK: Set to False if we already know that a forwards
639 -- move is not safe, else set to True.
641 -- Backwards_OK: Set to False if we already know that a backwards
642 -- move is not safe, else set to True
644 -- Our task at this stage is to complete the overlap analysis, which can
645 -- result in possibly setting Forwards_OK or Backwards_OK to False, and
646 -- then generating the final code, either by deciding that it is OK
647 -- after all to let Gigi handle it, or by generating appropriate code
648 -- in the front end.
650 declare
651 L_Index_Typ : constant Node_Id := Etype (First_Index (L_Type));
652 R_Index_Typ : constant Node_Id := Etype (First_Index (R_Type));
654 Left_Lo : constant Node_Id := Type_Low_Bound (L_Index_Typ);
655 Left_Hi : constant Node_Id := Type_High_Bound (L_Index_Typ);
656 Right_Lo : constant Node_Id := Type_Low_Bound (R_Index_Typ);
657 Right_Hi : constant Node_Id := Type_High_Bound (R_Index_Typ);
659 Act_L_Array : Node_Id;
660 Act_R_Array : Node_Id;
662 Cleft_Lo : Node_Id;
663 Cright_Lo : Node_Id;
664 Condition : Node_Id;
666 Cresult : Compare_Result;
668 begin
669 -- Get the expressions for the arrays. If we are dealing with a
670 -- private type, then convert to the underlying type. We can do
671 -- direct assignments to an array that is a private type, but we
672 -- cannot assign to elements of the array without this extra
673 -- unchecked conversion.
675 -- Note: We propagate Parent to the conversion nodes to generate
676 -- a well-formed subtree.
678 if Nkind (Act_Lhs) = N_Slice then
679 Larray := Prefix (Act_Lhs);
680 else
681 Larray := Act_Lhs;
683 if Is_Private_Type (Etype (Larray)) then
684 declare
685 Par : constant Node_Id := Parent (Larray);
686 begin
687 Larray :=
688 Unchecked_Convert_To
689 (Underlying_Type (Etype (Larray)), Larray);
690 Set_Parent (Larray, Par);
691 end;
692 end if;
693 end if;
695 if Nkind (Act_Rhs) = N_Slice then
696 Rarray := Prefix (Act_Rhs);
697 else
698 Rarray := Act_Rhs;
700 if Is_Private_Type (Etype (Rarray)) then
701 declare
702 Par : constant Node_Id := Parent (Rarray);
703 begin
704 Rarray :=
705 Unchecked_Convert_To
706 (Underlying_Type (Etype (Rarray)), Rarray);
707 Set_Parent (Rarray, Par);
708 end;
709 end if;
710 end if;
712 -- If both sides are slices, we must figure out whether it is safe
713 -- to do the move in one direction or the other. It is always safe
714 -- if there is a change of representation since obviously two arrays
715 -- with different representations cannot possibly overlap.
717 if (not Crep) and L_Slice and R_Slice then
718 Act_L_Array := Get_Referenced_Object (Prefix (Act_Lhs));
719 Act_R_Array := Get_Referenced_Object (Prefix (Act_Rhs));
721 -- If both left- and right-hand arrays are entity names, and refer
722 -- to different entities, then we know that the move is safe (the
723 -- two storage areas are completely disjoint).
725 if Is_Entity_Name (Act_L_Array)
726 and then Is_Entity_Name (Act_R_Array)
727 and then Entity (Act_L_Array) /= Entity (Act_R_Array)
728 then
729 null;
731 -- Otherwise, we assume the worst, which is that the two arrays
732 -- are the same array. There is no need to check if we know that
733 -- is the case, because if we don't know it, we still have to
734 -- assume it.
736 -- Generally if the same array is involved, then we have an
737 -- overlapping case. We will have to really assume the worst (i.e.
738 -- set neither of the OK flags) unless we can determine the lower
739 -- or upper bounds at compile time and compare them.
741 else
742 Cresult :=
743 Compile_Time_Compare
744 (Left_Lo, Right_Lo, Assume_Valid => True);
746 if Cresult = Unknown then
747 Cresult :=
748 Compile_Time_Compare
749 (Left_Hi, Right_Hi, Assume_Valid => True);
750 end if;
752 case Cresult is
753 when EQ | LE | LT =>
754 Set_Backwards_OK (N, False);
756 when GE | GT =>
757 Set_Forwards_OK (N, False);
759 when NE | Unknown =>
760 Set_Backwards_OK (N, False);
761 Set_Forwards_OK (N, False);
762 end case;
763 end if;
764 end if;
766 -- If after that analysis Loop_Required is False, meaning that we
767 -- have not discovered some non-overlap reason for requiring a loop,
768 -- then the outcome depends on the capabilities of the back end.
770 if not Loop_Required then
771 -- Assume the back end can deal with all cases of overlap by
772 -- falling back to memmove if it cannot use a more efficient
773 -- approach.
775 return;
776 end if;
778 -- At this stage we have to generate an explicit loop, and we have
779 -- the following cases:
781 -- Forwards_OK = True
783 -- Rnn : right_index := right_index'First;
784 -- for Lnn in left-index loop
785 -- left (Lnn) := right (Rnn);
786 -- Rnn := right_index'Succ (Rnn);
787 -- end loop;
789 -- Note: the above code MUST be analyzed with checks off, because
790 -- otherwise the Succ could overflow. But in any case this is more
791 -- efficient.
793 -- Forwards_OK = False, Backwards_OK = True
795 -- Rnn : right_index := right_index'Last;
796 -- for Lnn in reverse left-index loop
797 -- left (Lnn) := right (Rnn);
798 -- Rnn := right_index'Pred (Rnn);
799 -- end loop;
801 -- Note: the above code MUST be analyzed with checks off, because
802 -- otherwise the Pred could overflow. But in any case this is more
803 -- efficient.
805 -- Forwards_OK = Backwards_OK = False
807 -- This only happens if we have the same array on each side. It is
808 -- possible to create situations using overlays that violate this,
809 -- but we simply do not promise to get this "right" in this case.
811 -- There are two possible subcases. If the No_Implicit_Conditionals
812 -- restriction is set, then we generate the following code:
814 -- declare
815 -- T : constant <operand-type> := rhs;
816 -- begin
817 -- lhs := T;
818 -- end;
820 -- If implicit conditionals are permitted, then we generate:
822 -- if Left_Lo <= Right_Lo then
823 -- <code for Forwards_OK = True above>
824 -- else
825 -- <code for Backwards_OK = True above>
826 -- end if;
828 -- In order to detect possible aliasing, we examine the renamed
829 -- expression when the source or target is a renaming. However,
830 -- the renaming may be intended to capture an address that may be
831 -- affected by subsequent code, and therefore we must recover
832 -- the actual entity for the expansion that follows, not the
833 -- object it renames. In particular, if source or target designate
834 -- a portion of a dynamically allocated object, the pointer to it
835 -- may be reassigned but the renaming preserves the proper location.
837 if Is_Entity_Name (Rhs)
838 and then
839 Nkind (Parent (Entity (Rhs))) = N_Object_Renaming_Declaration
840 and then Nkind (Act_Rhs) = N_Slice
841 then
842 Rarray := Rhs;
843 end if;
845 if Is_Entity_Name (Lhs)
846 and then
847 Nkind (Parent (Entity (Lhs))) = N_Object_Renaming_Declaration
848 and then Nkind (Act_Lhs) = N_Slice
849 then
850 Larray := Lhs;
851 end if;
853 -- Cases where either Forwards_OK or Backwards_OK is true
855 if Forwards_OK (N) or else Backwards_OK (N) then
856 if Needs_Finalization (Component_Type (L_Type))
857 and then Base_Type (L_Type) = Base_Type (R_Type)
858 and then Ndim = 1
859 and then not No_Ctrl_Actions (N)
860 then
861 declare
862 Proc : constant Entity_Id :=
863 TSS (Base_Type (L_Type), TSS_Slice_Assign);
864 Actuals : List_Id;
866 begin
867 Apply_Dereference (Larray);
868 Apply_Dereference (Rarray);
869 Actuals := New_List (
870 Duplicate_Subexpr (Larray, Name_Req => True),
871 Duplicate_Subexpr (Rarray, Name_Req => True),
872 Duplicate_Subexpr (Left_Lo, Name_Req => True),
873 Duplicate_Subexpr (Left_Hi, Name_Req => True),
874 Duplicate_Subexpr (Right_Lo, Name_Req => True),
875 Duplicate_Subexpr (Right_Hi, Name_Req => True));
877 Append_To (Actuals,
878 New_Occurrence_Of (
879 Boolean_Literals (not Forwards_OK (N)), Loc));
881 Rewrite (N,
882 Make_Procedure_Call_Statement (Loc,
883 Name => New_Occurrence_Of (Proc, Loc),
884 Parameter_Associations => Actuals));
885 end;
887 else
888 Rewrite (N,
889 Expand_Assign_Array_Loop
890 (N, Larray, Rarray, L_Type, R_Type, Ndim,
891 Rev => not Forwards_OK (N)));
892 end if;
894 -- Case of both are false with No_Implicit_Conditionals
896 elsif Restriction_Active (No_Implicit_Conditionals) then
897 declare
898 T : constant Entity_Id :=
899 Make_Defining_Identifier (Loc, Chars => Name_T);
901 begin
902 Rewrite (N,
903 Make_Block_Statement (Loc,
904 Declarations => New_List (
905 Make_Object_Declaration (Loc,
906 Defining_Identifier => T,
907 Constant_Present => True,
908 Object_Definition =>
909 New_Occurrence_Of (Etype (Rhs), Loc),
910 Expression => Relocate_Node (Rhs))),
912 Handled_Statement_Sequence =>
913 Make_Handled_Sequence_Of_Statements (Loc,
914 Statements => New_List (
915 Make_Assignment_Statement (Loc,
916 Name => Relocate_Node (Lhs),
917 Expression => New_Occurrence_Of (T, Loc))))));
918 end;
920 -- Case of both are false with implicit conditionals allowed
922 else
923 -- Before we generate this code, we must ensure that the left and
924 -- right side array types are defined. They may be itypes, and we
925 -- cannot let them be defined inside the if, since the first use
926 -- in the then may not be executed.
928 Ensure_Defined (L_Type, N);
929 Ensure_Defined (R_Type, N);
931 -- We normally compare addresses to find out which way round to
932 -- do the loop, since this is reliable, and handles the cases of
933 -- parameters, conversions etc. But we can't do that in the bit
934 -- packed case, because addresses don't work there.
936 if not Is_Bit_Packed_Array (L_Type) then
937 Condition :=
938 Make_Op_Le (Loc,
939 Left_Opnd =>
940 Unchecked_Convert_To (RTE (RE_Integer_Address),
941 Make_Attribute_Reference (Loc,
942 Prefix =>
943 Make_Indexed_Component (Loc,
944 Prefix =>
945 Duplicate_Subexpr_Move_Checks (Larray, True),
946 Expressions => New_List (
947 Make_Attribute_Reference (Loc,
948 Prefix =>
949 New_Occurrence_Of
950 (L_Index_Typ, Loc),
951 Attribute_Name => Name_First))),
952 Attribute_Name => Name_Address)),
954 Right_Opnd =>
955 Unchecked_Convert_To (RTE (RE_Integer_Address),
956 Make_Attribute_Reference (Loc,
957 Prefix =>
958 Make_Indexed_Component (Loc,
959 Prefix =>
960 Duplicate_Subexpr_Move_Checks (Rarray, True),
961 Expressions => New_List (
962 Make_Attribute_Reference (Loc,
963 Prefix =>
964 New_Occurrence_Of
965 (R_Index_Typ, Loc),
966 Attribute_Name => Name_First))),
967 Attribute_Name => Name_Address)));
969 -- For the bit packed and VM cases we use the bounds. That's OK,
970 -- because we don't have to worry about parameters, since they
971 -- cannot cause overlap. Perhaps we should worry about weird slice
972 -- conversions ???
974 else
975 -- Copy the bounds
977 Cleft_Lo := New_Copy_Tree (Left_Lo);
978 Cright_Lo := New_Copy_Tree (Right_Lo);
980 -- If the types do not match we add an implicit conversion
981 -- here to ensure proper match
983 if Etype (Left_Lo) /= Etype (Right_Lo) then
984 Cright_Lo :=
985 Unchecked_Convert_To (Etype (Left_Lo), Cright_Lo);
986 end if;
988 -- Reset the Analyzed flag, because the bounds of the index
989 -- type itself may be universal, and must must be reanalyzed
990 -- to acquire the proper type for the back end.
992 Set_Analyzed (Cleft_Lo, False);
993 Set_Analyzed (Cright_Lo, False);
995 Condition :=
996 Make_Op_Le (Loc,
997 Left_Opnd => Cleft_Lo,
998 Right_Opnd => Cright_Lo);
999 end if;
1001 if Needs_Finalization (Component_Type (L_Type))
1002 and then Base_Type (L_Type) = Base_Type (R_Type)
1003 and then Ndim = 1
1004 and then not No_Ctrl_Actions (N)
1005 then
1007 -- Call TSS procedure for array assignment, passing the
1008 -- explicit bounds of right- and left-hand sides.
1010 declare
1011 Proc : constant Entity_Id :=
1012 TSS (Base_Type (L_Type), TSS_Slice_Assign);
1013 Actuals : List_Id;
1015 begin
1016 Apply_Dereference (Larray);
1017 Apply_Dereference (Rarray);
1018 Actuals := New_List (
1019 Duplicate_Subexpr (Larray, Name_Req => True),
1020 Duplicate_Subexpr (Rarray, Name_Req => True),
1021 Duplicate_Subexpr (Left_Lo, Name_Req => True),
1022 Duplicate_Subexpr (Left_Hi, Name_Req => True),
1023 Duplicate_Subexpr (Right_Lo, Name_Req => True),
1024 Duplicate_Subexpr (Right_Hi, Name_Req => True));
1026 Append_To (Actuals,
1027 Make_Op_Not (Loc,
1028 Right_Opnd => Condition));
1030 Rewrite (N,
1031 Make_Procedure_Call_Statement (Loc,
1032 Name => New_Occurrence_Of (Proc, Loc),
1033 Parameter_Associations => Actuals));
1034 end;
1036 else
1037 Rewrite (N,
1038 Make_Implicit_If_Statement (N,
1039 Condition => Condition,
1041 Then_Statements => New_List (
1042 Expand_Assign_Array_Loop
1043 (N, Larray, Rarray, L_Type, R_Type, Ndim,
1044 Rev => False)),
1046 Else_Statements => New_List (
1047 Expand_Assign_Array_Loop
1048 (N, Larray, Rarray, L_Type, R_Type, Ndim,
1049 Rev => True))));
1050 end if;
1051 end if;
1053 Analyze (N, Suppress => All_Checks);
1054 end;
1056 exception
1057 when RE_Not_Available =>
1058 return;
1059 end Expand_Assign_Array;
1061 ------------------------------
1062 -- Expand_Assign_Array_Loop --
1063 ------------------------------
1065 -- The following is an example of the loop generated for the case of a
1066 -- two-dimensional array:
1068 -- declare
1069 -- R2b : Tm1X1 := 1;
1070 -- begin
1071 -- for L1b in 1 .. 100 loop
1072 -- declare
1073 -- R4b : Tm1X2 := 1;
1074 -- begin
1075 -- for L3b in 1 .. 100 loop
1076 -- vm1 (L1b, L3b) := vm2 (R2b, R4b);
1077 -- R4b := Tm1X2'succ(R4b);
1078 -- end loop;
1079 -- end;
1080 -- R2b := Tm1X1'succ(R2b);
1081 -- end loop;
1082 -- end;
1084 -- Here Rev is False, and Tm1Xn are the subscript types for the right-hand
1085 -- side. The declarations of R2b and R4b are inserted before the original
1086 -- assignment statement.
1088 function Expand_Assign_Array_Loop
1089 (N : Node_Id;
1090 Larray : Entity_Id;
1091 Rarray : Entity_Id;
1092 L_Type : Entity_Id;
1093 R_Type : Entity_Id;
1094 Ndim : Pos;
1095 Rev : Boolean) return Node_Id
1097 Loc : constant Source_Ptr := Sloc (N);
1099 Lnn : array (1 .. Ndim) of Entity_Id;
1100 Rnn : array (1 .. Ndim) of Entity_Id;
1101 -- Entities used as subscripts on left and right sides
1103 L_Index_Type : array (1 .. Ndim) of Entity_Id;
1104 R_Index_Type : array (1 .. Ndim) of Entity_Id;
1105 -- Left and right index types
1107 Assign : Node_Id;
1109 F_Or_L : Name_Id;
1110 S_Or_P : Name_Id;
1112 function Build_Step (J : Nat) return Node_Id;
1113 -- The increment step for the index of the right-hand side is written
1114 -- as an attribute reference (Succ or Pred). This function returns
1115 -- the corresponding node, which is placed at the end of the loop body.
1117 ----------------
1118 -- Build_Step --
1119 ----------------
1121 function Build_Step (J : Nat) return Node_Id is
1122 Step : Node_Id;
1123 Lim : Name_Id;
1125 begin
1126 if Rev then
1127 Lim := Name_First;
1128 else
1129 Lim := Name_Last;
1130 end if;
1132 Step :=
1133 Make_Assignment_Statement (Loc,
1134 Name => New_Occurrence_Of (Rnn (J), Loc),
1135 Expression =>
1136 Make_Attribute_Reference (Loc,
1137 Prefix =>
1138 New_Occurrence_Of (R_Index_Type (J), Loc),
1139 Attribute_Name => S_Or_P,
1140 Expressions => New_List (
1141 New_Occurrence_Of (Rnn (J), Loc))));
1143 -- Note that on the last iteration of the loop, the index is increased
1144 -- (or decreased) past the corresponding bound. This is consistent with
1145 -- the C semantics of the back-end, where such an off-by-one value on a
1146 -- dead index variable is OK. However, in CodePeer mode this leads to
1147 -- spurious warnings, and thus we place a guard around the attribute
1148 -- reference. For obvious reasons we only do this for CodePeer.
1150 if CodePeer_Mode then
1151 Step :=
1152 Make_If_Statement (Loc,
1153 Condition =>
1154 Make_Op_Ne (Loc,
1155 Left_Opnd => New_Occurrence_Of (Lnn (J), Loc),
1156 Right_Opnd =>
1157 Make_Attribute_Reference (Loc,
1158 Prefix => New_Occurrence_Of (L_Index_Type (J), Loc),
1159 Attribute_Name => Lim)),
1160 Then_Statements => New_List (Step));
1161 end if;
1163 return Step;
1164 end Build_Step;
1166 -- Start of processing for Expand_Assign_Array_Loop
1168 begin
1169 if Rev then
1170 F_Or_L := Name_Last;
1171 S_Or_P := Name_Pred;
1172 else
1173 F_Or_L := Name_First;
1174 S_Or_P := Name_Succ;
1175 end if;
1177 -- Setup index types and subscript entities
1179 declare
1180 L_Index : Node_Id;
1181 R_Index : Node_Id;
1183 begin
1184 L_Index := First_Index (L_Type);
1185 R_Index := First_Index (R_Type);
1187 for J in 1 .. Ndim loop
1188 Lnn (J) := Make_Temporary (Loc, 'L');
1189 Rnn (J) := Make_Temporary (Loc, 'R');
1191 L_Index_Type (J) := Etype (L_Index);
1192 R_Index_Type (J) := Etype (R_Index);
1194 Next_Index (L_Index);
1195 Next_Index (R_Index);
1196 end loop;
1197 end;
1199 -- Now construct the assignment statement
1201 declare
1202 ExprL : constant List_Id := New_List;
1203 ExprR : constant List_Id := New_List;
1205 begin
1206 for J in 1 .. Ndim loop
1207 Append_To (ExprL, New_Occurrence_Of (Lnn (J), Loc));
1208 Append_To (ExprR, New_Occurrence_Of (Rnn (J), Loc));
1209 end loop;
1211 Assign :=
1212 Make_Assignment_Statement (Loc,
1213 Name =>
1214 Make_Indexed_Component (Loc,
1215 Prefix => Duplicate_Subexpr (Larray, Name_Req => True),
1216 Expressions => ExprL),
1217 Expression =>
1218 Make_Indexed_Component (Loc,
1219 Prefix => Duplicate_Subexpr (Rarray, Name_Req => True),
1220 Expressions => ExprR));
1222 -- We set assignment OK, since there are some cases, e.g. in object
1223 -- declarations, where we are actually assigning into a constant.
1224 -- If there really is an illegality, it was caught long before now,
1225 -- and was flagged when the original assignment was analyzed.
1227 Set_Assignment_OK (Name (Assign));
1229 -- Propagate the No_Ctrl_Actions flag to individual assignments
1231 Set_No_Ctrl_Actions (Assign, No_Ctrl_Actions (N));
1232 end;
1234 -- Now construct the loop from the inside out, with the last subscript
1235 -- varying most rapidly. Note that Assign is first the raw assignment
1236 -- statement, and then subsequently the loop that wraps it up.
1238 for J in reverse 1 .. Ndim loop
1239 Assign :=
1240 Make_Block_Statement (Loc,
1241 Declarations => New_List (
1242 Make_Object_Declaration (Loc,
1243 Defining_Identifier => Rnn (J),
1244 Object_Definition =>
1245 New_Occurrence_Of (R_Index_Type (J), Loc),
1246 Expression =>
1247 Make_Attribute_Reference (Loc,
1248 Prefix => New_Occurrence_Of (R_Index_Type (J), Loc),
1249 Attribute_Name => F_Or_L))),
1251 Handled_Statement_Sequence =>
1252 Make_Handled_Sequence_Of_Statements (Loc,
1253 Statements => New_List (
1254 Make_Implicit_Loop_Statement (N,
1255 Iteration_Scheme =>
1256 Make_Iteration_Scheme (Loc,
1257 Loop_Parameter_Specification =>
1258 Make_Loop_Parameter_Specification (Loc,
1259 Defining_Identifier => Lnn (J),
1260 Reverse_Present => Rev,
1261 Discrete_Subtype_Definition =>
1262 New_Occurrence_Of (L_Index_Type (J), Loc))),
1264 Statements => New_List (Assign, Build_Step (J))))));
1265 end loop;
1267 return Assign;
1268 end Expand_Assign_Array_Loop;
1270 --------------------------
1271 -- Expand_Assign_Record --
1272 --------------------------
1274 procedure Expand_Assign_Record (N : Node_Id) is
1275 Lhs : constant Node_Id := Name (N);
1276 Rhs : Node_Id := Expression (N);
1277 L_Typ : constant Entity_Id := Base_Type (Etype (Lhs));
1279 begin
1280 -- If change of representation, then extract the real right-hand side
1281 -- from the type conversion, and proceed with component-wise assignment,
1282 -- since the two types are not the same as far as the back end is
1283 -- concerned.
1285 if Change_Of_Representation (N) then
1286 Rhs := Expression (Rhs);
1288 -- If this may be a case of a large bit aligned component, then proceed
1289 -- with component-wise assignment, to avoid possible clobbering of other
1290 -- components sharing bits in the first or last byte of the component to
1291 -- be assigned.
1293 elsif Possible_Bit_Aligned_Component (Lhs)
1295 Possible_Bit_Aligned_Component (Rhs)
1296 then
1297 null;
1299 -- If we have a tagged type that has a complete record representation
1300 -- clause, we must do we must do component-wise assignments, since child
1301 -- types may have used gaps for their components, and we might be
1302 -- dealing with a view conversion.
1304 elsif Is_Fully_Repped_Tagged_Type (L_Typ) then
1305 null;
1307 -- If neither condition met, then nothing special to do, the back end
1308 -- can handle assignment of the entire component as a single entity.
1310 else
1311 return;
1312 end if;
1314 -- At this stage we know that we must do a component wise assignment
1316 declare
1317 Loc : constant Source_Ptr := Sloc (N);
1318 R_Typ : constant Entity_Id := Base_Type (Etype (Rhs));
1319 Decl : constant Node_Id := Declaration_Node (R_Typ);
1320 RDef : Node_Id;
1321 F : Entity_Id;
1323 function Find_Component
1324 (Typ : Entity_Id;
1325 Comp : Entity_Id) return Entity_Id;
1326 -- Find the component with the given name in the underlying record
1327 -- declaration for Typ. We need to use the actual entity because the
1328 -- type may be private and resolution by identifier alone would fail.
1330 function Make_Component_List_Assign
1331 (CL : Node_Id;
1332 U_U : Boolean := False) return List_Id;
1333 -- Returns a sequence of statements to assign the components that
1334 -- are referenced in the given component list. The flag U_U is
1335 -- used to force the usage of the inferred value of the variant
1336 -- part expression as the switch for the generated case statement.
1338 function Make_Field_Assign
1339 (C : Entity_Id;
1340 U_U : Boolean := False) return Node_Id;
1341 -- Given C, the entity for a discriminant or component, build an
1342 -- assignment for the corresponding field values. The flag U_U
1343 -- signals the presence of an Unchecked_Union and forces the usage
1344 -- of the inferred discriminant value of C as the right-hand side
1345 -- of the assignment.
1347 function Make_Field_Assigns (CI : List_Id) return List_Id;
1348 -- Given CI, a component items list, construct series of statements
1349 -- for fieldwise assignment of the corresponding components.
1351 --------------------
1352 -- Find_Component --
1353 --------------------
1355 function Find_Component
1356 (Typ : Entity_Id;
1357 Comp : Entity_Id) return Entity_Id
1359 Utyp : constant Entity_Id := Underlying_Type (Typ);
1360 C : Entity_Id;
1362 begin
1363 C := First_Entity (Utyp);
1364 while Present (C) loop
1365 if Chars (C) = Chars (Comp) then
1366 return C;
1367 end if;
1369 Next_Entity (C);
1370 end loop;
1372 raise Program_Error;
1373 end Find_Component;
1375 --------------------------------
1376 -- Make_Component_List_Assign --
1377 --------------------------------
1379 function Make_Component_List_Assign
1380 (CL : Node_Id;
1381 U_U : Boolean := False) return List_Id
1383 CI : constant List_Id := Component_Items (CL);
1384 VP : constant Node_Id := Variant_Part (CL);
1386 Alts : List_Id;
1387 DC : Node_Id;
1388 DCH : List_Id;
1389 Expr : Node_Id;
1390 Result : List_Id;
1391 V : Node_Id;
1393 begin
1394 Result := Make_Field_Assigns (CI);
1396 if Present (VP) then
1397 V := First_Non_Pragma (Variants (VP));
1398 Alts := New_List;
1399 while Present (V) loop
1400 DCH := New_List;
1401 DC := First (Discrete_Choices (V));
1402 while Present (DC) loop
1403 Append_To (DCH, New_Copy_Tree (DC));
1404 Next (DC);
1405 end loop;
1407 Append_To (Alts,
1408 Make_Case_Statement_Alternative (Loc,
1409 Discrete_Choices => DCH,
1410 Statements =>
1411 Make_Component_List_Assign (Component_List (V))));
1412 Next_Non_Pragma (V);
1413 end loop;
1415 -- If we have an Unchecked_Union, use the value of the inferred
1416 -- discriminant of the variant part expression as the switch
1417 -- for the case statement. The case statement may later be
1418 -- folded.
1420 if U_U then
1421 Expr :=
1422 New_Copy (Get_Discriminant_Value (
1423 Entity (Name (VP)),
1424 Etype (Rhs),
1425 Discriminant_Constraint (Etype (Rhs))));
1426 else
1427 Expr :=
1428 Make_Selected_Component (Loc,
1429 Prefix => Duplicate_Subexpr (Rhs),
1430 Selector_Name =>
1431 Make_Identifier (Loc, Chars (Name (VP))));
1432 end if;
1434 Append_To (Result,
1435 Make_Case_Statement (Loc,
1436 Expression => Expr,
1437 Alternatives => Alts));
1438 end if;
1440 return Result;
1441 end Make_Component_List_Assign;
1443 -----------------------
1444 -- Make_Field_Assign --
1445 -----------------------
1447 function Make_Field_Assign
1448 (C : Entity_Id;
1449 U_U : Boolean := False) return Node_Id
1451 A : Node_Id;
1452 Disc : Entity_Id;
1453 Expr : Node_Id;
1455 begin
1456 -- The discriminant entity to be used in the retrieval below must
1457 -- be one in the corresponding type, given that the assignment may
1458 -- be between derived and parent types.
1460 if Is_Derived_Type (Etype (Rhs)) then
1461 Disc := Find_Component (R_Typ, C);
1462 else
1463 Disc := C;
1464 end if;
1466 -- In the case of an Unchecked_Union, use the discriminant
1467 -- constraint value as on the right-hand side of the assignment.
1469 if U_U then
1470 Expr :=
1471 New_Copy (Get_Discriminant_Value (C,
1472 Etype (Rhs),
1473 Discriminant_Constraint (Etype (Rhs))));
1474 else
1475 Expr :=
1476 Make_Selected_Component (Loc,
1477 Prefix => Duplicate_Subexpr (Rhs),
1478 Selector_Name => New_Occurrence_Of (Disc, Loc));
1479 end if;
1481 A :=
1482 Make_Assignment_Statement (Loc,
1483 Name =>
1484 Make_Selected_Component (Loc,
1485 Prefix => Duplicate_Subexpr (Lhs),
1486 Selector_Name =>
1487 New_Occurrence_Of (Find_Component (L_Typ, C), Loc)),
1488 Expression => Expr);
1490 -- Set Assignment_OK, so discriminants can be assigned
1492 Set_Assignment_OK (Name (A), True);
1494 if Componentwise_Assignment (N)
1495 and then Nkind (Name (A)) = N_Selected_Component
1496 and then Chars (Selector_Name (Name (A))) = Name_uParent
1497 then
1498 Set_Componentwise_Assignment (A);
1499 end if;
1501 return A;
1502 end Make_Field_Assign;
1504 ------------------------
1505 -- Make_Field_Assigns --
1506 ------------------------
1508 function Make_Field_Assigns (CI : List_Id) return List_Id is
1509 Item : Node_Id;
1510 Result : List_Id;
1512 begin
1513 Item := First (CI);
1514 Result := New_List;
1516 while Present (Item) loop
1518 -- Look for components, but exclude _tag field assignment if
1519 -- the special Componentwise_Assignment flag is set.
1521 if Nkind (Item) = N_Component_Declaration
1522 and then not (Is_Tag (Defining_Identifier (Item))
1523 and then Componentwise_Assignment (N))
1524 then
1525 Append_To
1526 (Result, Make_Field_Assign (Defining_Identifier (Item)));
1527 end if;
1529 Next (Item);
1530 end loop;
1532 return Result;
1533 end Make_Field_Assigns;
1535 -- Start of processing for Expand_Assign_Record
1537 begin
1538 -- Note that we use the base types for this processing. This results
1539 -- in some extra work in the constrained case, but the change of
1540 -- representation case is so unusual that it is not worth the effort.
1542 -- First copy the discriminants. This is done unconditionally. It
1543 -- is required in the unconstrained left side case, and also in the
1544 -- case where this assignment was constructed during the expansion
1545 -- of a type conversion (since initialization of discriminants is
1546 -- suppressed in this case). It is unnecessary but harmless in
1547 -- other cases.
1549 if Has_Discriminants (L_Typ) then
1550 F := First_Discriminant (R_Typ);
1551 while Present (F) loop
1553 -- If we are expanding the initialization of a derived record
1554 -- that constrains or renames discriminants of the parent, we
1555 -- must use the corresponding discriminant in the parent.
1557 declare
1558 CF : Entity_Id;
1560 begin
1561 if Inside_Init_Proc
1562 and then Present (Corresponding_Discriminant (F))
1563 then
1564 CF := Corresponding_Discriminant (F);
1565 else
1566 CF := F;
1567 end if;
1569 if Is_Unchecked_Union (Base_Type (R_Typ)) then
1571 -- Within an initialization procedure this is the
1572 -- assignment to an unchecked union component, in which
1573 -- case there is no discriminant to initialize.
1575 if Inside_Init_Proc then
1576 null;
1578 else
1579 -- The assignment is part of a conversion from a
1580 -- derived unchecked union type with an inferable
1581 -- discriminant, to a parent type.
1583 Insert_Action (N, Make_Field_Assign (CF, True));
1584 end if;
1586 else
1587 Insert_Action (N, Make_Field_Assign (CF));
1588 end if;
1590 Next_Discriminant (F);
1591 end;
1592 end loop;
1594 -- If the derived type has a stored constraint, assign the value
1595 -- of the corresponding discriminants explicitly, skipping those
1596 -- that are renamed discriminants. We cannot just retrieve them
1597 -- from the Rhs by selected component because they are invisible
1598 -- in the type of the right-hand side.
1600 if Stored_Constraint (R_Typ) /= No_Elist then
1601 declare
1602 Assign : Node_Id;
1603 Discr_Val : Elmt_Id;
1605 begin
1606 Discr_Val := First_Elmt (Stored_Constraint (R_Typ));
1607 F := First_Entity (R_Typ);
1608 while Present (F) loop
1609 if Ekind (F) = E_Discriminant
1610 and then Is_Completely_Hidden (F)
1611 and then Present (Corresponding_Record_Component (F))
1612 and then
1613 (not Is_Entity_Name (Node (Discr_Val))
1614 or else Ekind (Entity (Node (Discr_Val))) /=
1615 E_Discriminant)
1616 then
1617 Assign :=
1618 Make_Assignment_Statement (Loc,
1619 Name =>
1620 Make_Selected_Component (Loc,
1621 Prefix => Duplicate_Subexpr (Lhs),
1622 Selector_Name =>
1623 New_Occurrence_Of
1624 (Corresponding_Record_Component (F), Loc)),
1625 Expression => New_Copy (Node (Discr_Val)));
1627 Set_Assignment_OK (Name (Assign));
1628 Insert_Action (N, Assign);
1629 Next_Elmt (Discr_Val);
1630 end if;
1632 Next_Entity (F);
1633 end loop;
1634 end;
1635 end if;
1636 end if;
1638 -- We know the underlying type is a record, but its current view
1639 -- may be private. We must retrieve the usable record declaration.
1641 if Nkind_In (Decl, N_Private_Type_Declaration,
1642 N_Private_Extension_Declaration)
1643 and then Present (Full_View (R_Typ))
1644 then
1645 RDef := Type_Definition (Declaration_Node (Full_View (R_Typ)));
1646 else
1647 RDef := Type_Definition (Decl);
1648 end if;
1650 if Nkind (RDef) = N_Derived_Type_Definition then
1651 RDef := Record_Extension_Part (RDef);
1652 end if;
1654 if Nkind (RDef) = N_Record_Definition
1655 and then Present (Component_List (RDef))
1656 then
1657 if Is_Unchecked_Union (R_Typ) then
1658 Insert_Actions (N,
1659 Make_Component_List_Assign (Component_List (RDef), True));
1660 else
1661 Insert_Actions
1662 (N, Make_Component_List_Assign (Component_List (RDef)));
1663 end if;
1665 Rewrite (N, Make_Null_Statement (Loc));
1666 end if;
1667 end;
1668 end Expand_Assign_Record;
1670 -------------------------------------
1671 -- Expand_Assign_With_Target_Names --
1672 -------------------------------------
1674 procedure Expand_Assign_With_Target_Names (N : Node_Id) is
1675 LHS : constant Node_Id := Name (N);
1676 LHS_Typ : constant Entity_Id := Etype (LHS);
1677 Loc : constant Source_Ptr := Sloc (N);
1678 RHS : constant Node_Id := Expression (N);
1680 Ent : Entity_Id;
1681 -- The entity of the left-hand side
1683 function Replace_Target (N : Node_Id) return Traverse_Result;
1684 -- Replace occurrences of the target name by the proper entity: either
1685 -- the entity of the LHS in simple cases, or the formal of the
1686 -- constructed procedure otherwise.
1688 --------------------
1689 -- Replace_Target --
1690 --------------------
1692 function Replace_Target (N : Node_Id) return Traverse_Result is
1693 begin
1694 if Nkind (N) = N_Target_Name then
1695 Rewrite (N, New_Occurrence_Of (Ent, Sloc (N)));
1697 -- The expression will be reanalyzed when the enclosing assignment
1698 -- is reanalyzed, so reset the entity, which may be a temporary
1699 -- created during analysis, e.g. a loop variable for an iterated
1700 -- component association. However, if entity is callable then
1701 -- resolution has established its proper identity (including in
1702 -- rewritten prefixed calls) so we must preserve it.
1704 elsif Is_Entity_Name (N) then
1705 if Present (Entity (N))
1706 and then not Is_Overloadable (Entity (N))
1707 then
1708 Set_Entity (N, Empty);
1709 end if;
1710 end if;
1712 Set_Analyzed (N, False);
1713 return OK;
1714 end Replace_Target;
1716 procedure Replace_Target_Name is new Traverse_Proc (Replace_Target);
1718 -- Local variables
1720 New_RHS : Node_Id;
1721 Proc_Id : Entity_Id;
1723 -- Start of processing for Expand_Assign_With_Target_Names
1725 begin
1726 New_RHS := New_Copy_Tree (RHS);
1728 -- The left-hand side is a direct name
1730 if Is_Entity_Name (LHS)
1731 and then not Is_Renaming_Of_Object (Entity (LHS))
1732 then
1733 Ent := Entity (LHS);
1734 Replace_Target_Name (New_RHS);
1736 -- Generate:
1737 -- LHS := ... LHS ...;
1739 Rewrite (N,
1740 Make_Assignment_Statement (Loc,
1741 Name => Relocate_Node (LHS),
1742 Expression => New_RHS));
1744 -- The left-hand side is not a direct name, but is side-effect free.
1745 -- Capture its value in a temporary to avoid multiple evaluations.
1747 elsif Side_Effect_Free (LHS) then
1748 Ent := Make_Temporary (Loc, 'T');
1749 Replace_Target_Name (New_RHS);
1751 -- Generate:
1752 -- T : LHS_Typ := LHS;
1754 Insert_Before_And_Analyze (N,
1755 Make_Object_Declaration (Loc,
1756 Defining_Identifier => Ent,
1757 Object_Definition => New_Occurrence_Of (LHS_Typ, Loc),
1758 Expression => New_Copy_Tree (LHS)));
1760 -- Generate:
1761 -- LHS := ... T ...;
1763 Rewrite (N,
1764 Make_Assignment_Statement (Loc,
1765 Name => Relocate_Node (LHS),
1766 Expression => New_RHS));
1768 -- Otherwise wrap the whole assignment statement in a procedure with an
1769 -- IN OUT parameter. The original assignment then becomes a call to the
1770 -- procedure with the left-hand side as an actual.
1772 else
1773 Ent := Make_Temporary (Loc, 'T');
1774 Replace_Target_Name (New_RHS);
1776 -- Generate:
1777 -- procedure P (T : in out LHS_Typ) is
1778 -- begin
1779 -- T := ... T ...;
1780 -- end P;
1782 Proc_Id := Make_Temporary (Loc, 'P');
1784 Insert_Before_And_Analyze (N,
1785 Make_Subprogram_Body (Loc,
1786 Specification =>
1787 Make_Procedure_Specification (Loc,
1788 Defining_Unit_Name => Proc_Id,
1789 Parameter_Specifications => New_List (
1790 Make_Parameter_Specification (Loc,
1791 Defining_Identifier => Ent,
1792 In_Present => True,
1793 Out_Present => True,
1794 Parameter_Type =>
1795 New_Occurrence_Of (LHS_Typ, Loc)))),
1797 Declarations => Empty_List,
1799 Handled_Statement_Sequence =>
1800 Make_Handled_Sequence_Of_Statements (Loc,
1801 Statements => New_List (
1802 Make_Assignment_Statement (Loc,
1803 Name => New_Occurrence_Of (Ent, Loc),
1804 Expression => New_RHS)))));
1806 -- Generate:
1807 -- P (LHS);
1809 Rewrite (N,
1810 Make_Procedure_Call_Statement (Loc,
1811 Name => New_Occurrence_Of (Proc_Id, Loc),
1812 Parameter_Associations => New_List (Relocate_Node (LHS))));
1813 end if;
1815 -- Analyze rewritten node, either as assignment or procedure call
1817 Analyze (N);
1818 end Expand_Assign_With_Target_Names;
1820 -----------------------------------
1821 -- Expand_N_Assignment_Statement --
1822 -----------------------------------
1824 -- This procedure implements various cases where an assignment statement
1825 -- cannot just be passed on to the back end in untransformed state.
1827 procedure Expand_N_Assignment_Statement (N : Node_Id) is
1828 Crep : constant Boolean := Change_Of_Representation (N);
1829 Lhs : constant Node_Id := Name (N);
1830 Loc : constant Source_Ptr := Sloc (N);
1831 Rhs : constant Node_Id := Expression (N);
1832 Typ : constant Entity_Id := Underlying_Type (Etype (Lhs));
1833 Exp : Node_Id;
1835 begin
1836 -- Special case to check right away, if the Componentwise_Assignment
1837 -- flag is set, this is a reanalysis from the expansion of the primitive
1838 -- assignment procedure for a tagged type, and all we need to do is to
1839 -- expand to assignment of components, because otherwise, we would get
1840 -- infinite recursion (since this looks like a tagged assignment which
1841 -- would normally try to *call* the primitive assignment procedure).
1843 if Componentwise_Assignment (N) then
1844 Expand_Assign_Record (N);
1845 return;
1846 end if;
1848 -- Defend against invalid subscripts on left side if we are in standard
1849 -- validity checking mode. No need to do this if we are checking all
1850 -- subscripts.
1852 -- Note that we do this right away, because there are some early return
1853 -- paths in this procedure, and this is required on all paths.
1855 if Validity_Checks_On
1856 and then Validity_Check_Default
1857 and then not Validity_Check_Subscripts
1858 then
1859 Check_Valid_Lvalue_Subscripts (Lhs);
1860 end if;
1862 -- Separate expansion if RHS contain target names. Note that assignment
1863 -- may already have been expanded if RHS is aggregate.
1865 if Nkind (N) = N_Assignment_Statement and then Has_Target_Names (N) then
1866 Expand_Assign_With_Target_Names (N);
1867 return;
1868 end if;
1870 -- Ada 2005 (AI-327): Handle assignment to priority of protected object
1872 -- Rewrite an assignment to X'Priority into a run-time call
1874 -- For example: X'Priority := New_Prio_Expr;
1875 -- ...is expanded into Set_Ceiling (X._Object, New_Prio_Expr);
1877 -- Note that although X'Priority is notionally an object, it is quite
1878 -- deliberately not defined as an aliased object in the RM. This means
1879 -- that it works fine to rewrite it as a call, without having to worry
1880 -- about complications that would other arise from X'Priority'Access,
1881 -- which is illegal, because of the lack of aliasing.
1883 if Ada_Version >= Ada_2005 then
1884 declare
1885 Call : Node_Id;
1886 Conctyp : Entity_Id;
1887 Ent : Entity_Id;
1888 Subprg : Entity_Id;
1889 RT_Subprg_Name : Node_Id;
1891 begin
1892 -- Handle chains of renamings
1894 Ent := Name (N);
1895 while Nkind (Ent) in N_Has_Entity
1896 and then Present (Entity (Ent))
1897 and then Present (Renamed_Object (Entity (Ent)))
1898 loop
1899 Ent := Renamed_Object (Entity (Ent));
1900 end loop;
1902 -- The attribute Priority applied to protected objects has been
1903 -- previously expanded into a call to the Get_Ceiling run-time
1904 -- subprogram. In restricted profiles this is not available.
1906 if Is_Expanded_Priority_Attribute (Ent) then
1908 -- Look for the enclosing concurrent type
1910 Conctyp := Current_Scope;
1911 while not Is_Concurrent_Type (Conctyp) loop
1912 Conctyp := Scope (Conctyp);
1913 end loop;
1915 pragma Assert (Is_Protected_Type (Conctyp));
1917 -- Generate the first actual of the call
1919 Subprg := Current_Scope;
1920 while not Present (Protected_Body_Subprogram (Subprg)) loop
1921 Subprg := Scope (Subprg);
1922 end loop;
1924 -- Select the appropriate run-time call
1926 if Number_Entries (Conctyp) = 0 then
1927 RT_Subprg_Name :=
1928 New_Occurrence_Of (RTE (RE_Set_Ceiling), Loc);
1929 else
1930 RT_Subprg_Name :=
1931 New_Occurrence_Of (RTE (RO_PE_Set_Ceiling), Loc);
1932 end if;
1934 Call :=
1935 Make_Procedure_Call_Statement (Loc,
1936 Name => RT_Subprg_Name,
1937 Parameter_Associations => New_List (
1938 New_Copy_Tree (First (Parameter_Associations (Ent))),
1939 Relocate_Node (Expression (N))));
1941 Rewrite (N, Call);
1942 Analyze (N);
1944 return;
1945 end if;
1946 end;
1947 end if;
1949 -- Deal with assignment checks unless suppressed
1951 if not Suppress_Assignment_Checks (N) then
1953 -- First deal with generation of range check if required
1955 if Do_Range_Check (Rhs) then
1956 Generate_Range_Check (Rhs, Typ, CE_Range_Check_Failed);
1957 end if;
1959 -- Then generate predicate check if required
1961 Apply_Predicate_Check (Rhs, Typ);
1962 end if;
1964 -- Check for a special case where a high level transformation is
1965 -- required. If we have either of:
1967 -- P.field := rhs;
1968 -- P (sub) := rhs;
1970 -- where P is a reference to a bit packed array, then we have to unwind
1971 -- the assignment. The exact meaning of being a reference to a bit
1972 -- packed array is as follows:
1974 -- An indexed component whose prefix is a bit packed array is a
1975 -- reference to a bit packed array.
1977 -- An indexed component or selected component whose prefix is a
1978 -- reference to a bit packed array is itself a reference ot a
1979 -- bit packed array.
1981 -- The required transformation is
1983 -- Tnn : prefix_type := P;
1984 -- Tnn.field := rhs;
1985 -- P := Tnn;
1987 -- or
1989 -- Tnn : prefix_type := P;
1990 -- Tnn (subscr) := rhs;
1991 -- P := Tnn;
1993 -- Since P is going to be evaluated more than once, any subscripts
1994 -- in P must have their evaluation forced.
1996 if Nkind_In (Lhs, N_Indexed_Component, N_Selected_Component)
1997 and then Is_Ref_To_Bit_Packed_Array (Prefix (Lhs))
1998 then
1999 declare
2000 BPAR_Expr : constant Node_Id := Relocate_Node (Prefix (Lhs));
2001 BPAR_Typ : constant Entity_Id := Etype (BPAR_Expr);
2002 Tnn : constant Entity_Id :=
2003 Make_Temporary (Loc, 'T', BPAR_Expr);
2005 begin
2006 -- Insert the post assignment first, because we want to copy the
2007 -- BPAR_Expr tree before it gets analyzed in the context of the
2008 -- pre assignment. Note that we do not analyze the post assignment
2009 -- yet (we cannot till we have completed the analysis of the pre
2010 -- assignment). As usual, the analysis of this post assignment
2011 -- will happen on its own when we "run into" it after finishing
2012 -- the current assignment.
2014 Insert_After (N,
2015 Make_Assignment_Statement (Loc,
2016 Name => New_Copy_Tree (BPAR_Expr),
2017 Expression => New_Occurrence_Of (Tnn, Loc)));
2019 -- At this stage BPAR_Expr is a reference to a bit packed array
2020 -- where the reference was not expanded in the original tree,
2021 -- since it was on the left side of an assignment. But in the
2022 -- pre-assignment statement (the object definition), BPAR_Expr
2023 -- will end up on the right-hand side, and must be reexpanded. To
2024 -- achieve this, we reset the analyzed flag of all selected and
2025 -- indexed components down to the actual indexed component for
2026 -- the packed array.
2028 Exp := BPAR_Expr;
2029 loop
2030 Set_Analyzed (Exp, False);
2032 if Nkind_In (Exp, N_Indexed_Component,
2033 N_Selected_Component)
2034 then
2035 Exp := Prefix (Exp);
2036 else
2037 exit;
2038 end if;
2039 end loop;
2041 -- Now we can insert and analyze the pre-assignment
2043 -- If the right-hand side requires a transient scope, it has
2044 -- already been placed on the stack. However, the declaration is
2045 -- inserted in the tree outside of this scope, and must reflect
2046 -- the proper scope for its variable. This awkward bit is forced
2047 -- by the stricter scope discipline imposed by GCC 2.97.
2049 declare
2050 Uses_Transient_Scope : constant Boolean :=
2051 Scope_Is_Transient
2052 and then N = Node_To_Be_Wrapped;
2054 begin
2055 if Uses_Transient_Scope then
2056 Push_Scope (Scope (Current_Scope));
2057 end if;
2059 Insert_Before_And_Analyze (N,
2060 Make_Object_Declaration (Loc,
2061 Defining_Identifier => Tnn,
2062 Object_Definition => New_Occurrence_Of (BPAR_Typ, Loc),
2063 Expression => BPAR_Expr));
2065 if Uses_Transient_Scope then
2066 Pop_Scope;
2067 end if;
2068 end;
2070 -- Now fix up the original assignment and continue processing
2072 Rewrite (Prefix (Lhs),
2073 New_Occurrence_Of (Tnn, Loc));
2075 -- We do not need to reanalyze that assignment, and we do not need
2076 -- to worry about references to the temporary, but we do need to
2077 -- make sure that the temporary is not marked as a true constant
2078 -- since we now have a generated assignment to it.
2080 Set_Is_True_Constant (Tnn, False);
2081 end;
2082 end if;
2084 -- When we have the appropriate type of aggregate in the expression (it
2085 -- has been determined during analysis of the aggregate by setting the
2086 -- delay flag), let's perform in place assignment and thus avoid
2087 -- creating a temporary.
2089 if Is_Delayed_Aggregate (Rhs) then
2090 Convert_Aggr_In_Assignment (N);
2091 Rewrite (N, Make_Null_Statement (Loc));
2092 Analyze (N);
2094 return;
2095 end if;
2097 -- Apply discriminant check if required. If Lhs is an access type to a
2098 -- designated type with discriminants, we must always check. If the
2099 -- type has unknown discriminants, more elaborate processing below.
2101 if Has_Discriminants (Etype (Lhs))
2102 and then not Has_Unknown_Discriminants (Etype (Lhs))
2103 then
2104 -- Skip discriminant check if change of representation. Will be
2105 -- done when the change of representation is expanded out.
2107 if not Crep then
2108 Apply_Discriminant_Check (Rhs, Etype (Lhs), Lhs);
2109 end if;
2111 -- If the type is private without discriminants, and the full type
2112 -- has discriminants (necessarily with defaults) a check may still be
2113 -- necessary if the Lhs is aliased. The private discriminants must be
2114 -- visible to build the discriminant constraints.
2116 -- Only an explicit dereference that comes from source indicates
2117 -- aliasing. Access to formals of protected operations and entries
2118 -- create dereferences but are not semantic aliasings.
2120 elsif Is_Private_Type (Etype (Lhs))
2121 and then Has_Discriminants (Typ)
2122 and then Nkind (Lhs) = N_Explicit_Dereference
2123 and then Comes_From_Source (Lhs)
2124 then
2125 declare
2126 Lt : constant Entity_Id := Etype (Lhs);
2127 Ubt : Entity_Id := Base_Type (Typ);
2129 begin
2130 -- In the case of an expander-generated record subtype whose base
2131 -- type still appears private, Typ will have been set to that
2132 -- private type rather than the underlying record type (because
2133 -- Underlying type will have returned the record subtype), so it's
2134 -- necessary to apply Underlying_Type again to the base type to
2135 -- get the record type we need for the discriminant check. Such
2136 -- subtypes can be created for assignments in certain cases, such
2137 -- as within an instantiation passed this kind of private type.
2138 -- It would be good to avoid this special test, but making changes
2139 -- to prevent this odd form of record subtype seems difficult. ???
2141 if Is_Private_Type (Ubt) then
2142 Ubt := Underlying_Type (Ubt);
2143 end if;
2145 Set_Etype (Lhs, Ubt);
2146 Rewrite (Rhs, OK_Convert_To (Base_Type (Ubt), Rhs));
2147 Apply_Discriminant_Check (Rhs, Ubt, Lhs);
2148 Set_Etype (Lhs, Lt);
2149 end;
2151 -- If the Lhs has a private type with unknown discriminants, it may
2152 -- have a full view with discriminants, but those are nameable only
2153 -- in the underlying type, so convert the Rhs to it before potential
2154 -- checking. Convert Lhs as well, otherwise the actual subtype might
2155 -- not be constructible. If the discriminants have defaults the type
2156 -- is unconstrained and there is nothing to check.
2158 elsif Has_Unknown_Discriminants (Base_Type (Etype (Lhs)))
2159 and then Has_Discriminants (Typ)
2160 and then not Has_Defaulted_Discriminants (Typ)
2161 then
2162 Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
2163 Rewrite (Lhs, OK_Convert_To (Base_Type (Typ), Lhs));
2164 Apply_Discriminant_Check (Rhs, Typ, Lhs);
2166 -- In the access type case, we need the same discriminant check, and
2167 -- also range checks if we have an access to constrained array.
2169 elsif Is_Access_Type (Etype (Lhs))
2170 and then Is_Constrained (Designated_Type (Etype (Lhs)))
2171 then
2172 if Has_Discriminants (Designated_Type (Etype (Lhs))) then
2174 -- Skip discriminant check if change of representation. Will be
2175 -- done when the change of representation is expanded out.
2177 if not Crep then
2178 Apply_Discriminant_Check (Rhs, Etype (Lhs));
2179 end if;
2181 elsif Is_Array_Type (Designated_Type (Etype (Lhs))) then
2182 Apply_Range_Check (Rhs, Etype (Lhs));
2184 if Is_Constrained (Etype (Lhs)) then
2185 Apply_Length_Check (Rhs, Etype (Lhs));
2186 end if;
2188 if Nkind (Rhs) = N_Allocator then
2189 declare
2190 Target_Typ : constant Entity_Id := Etype (Expression (Rhs));
2191 C_Es : Check_Result;
2193 begin
2194 C_Es :=
2195 Get_Range_Checks
2196 (Lhs,
2197 Target_Typ,
2198 Etype (Designated_Type (Etype (Lhs))));
2200 Insert_Range_Checks
2201 (C_Es,
2203 Target_Typ,
2204 Sloc (Lhs),
2205 Lhs);
2206 end;
2207 end if;
2208 end if;
2210 -- Apply range check for access type case
2212 elsif Is_Access_Type (Etype (Lhs))
2213 and then Nkind (Rhs) = N_Allocator
2214 and then Nkind (Expression (Rhs)) = N_Qualified_Expression
2215 then
2216 Analyze_And_Resolve (Expression (Rhs));
2217 Apply_Range_Check
2218 (Expression (Rhs), Designated_Type (Etype (Lhs)));
2219 end if;
2221 -- Ada 2005 (AI-231): Generate the run-time check
2223 if Is_Access_Type (Typ)
2224 and then Can_Never_Be_Null (Etype (Lhs))
2225 and then not Can_Never_Be_Null (Etype (Rhs))
2227 -- If an actual is an out parameter of a null-excluding access
2228 -- type, there is access check on entry, so we set the flag
2229 -- Suppress_Assignment_Checks on the generated statement to
2230 -- assign the actual to the parameter block, and we do not want
2231 -- to generate an additional check at this point.
2233 and then not Suppress_Assignment_Checks (N)
2234 then
2235 Apply_Constraint_Check (Rhs, Etype (Lhs));
2236 end if;
2238 -- Ada 2012 (AI05-148): Update current accessibility level if Rhs is a
2239 -- stand-alone obj of an anonymous access type. Do not install the check
2240 -- when the Lhs denotes a container cursor and the Next function employs
2241 -- an access type, because this can never result in a dangling pointer.
2243 if Is_Access_Type (Typ)
2244 and then Is_Entity_Name (Lhs)
2245 and then Ekind (Entity (Lhs)) /= E_Loop_Parameter
2246 and then Present (Effective_Extra_Accessibility (Entity (Lhs)))
2247 then
2248 declare
2249 function Lhs_Entity return Entity_Id;
2250 -- Look through renames to find the underlying entity.
2251 -- For assignment to a rename, we don't care about the
2252 -- Enclosing_Dynamic_Scope of the rename declaration.
2254 ----------------
2255 -- Lhs_Entity --
2256 ----------------
2258 function Lhs_Entity return Entity_Id is
2259 Result : Entity_Id := Entity (Lhs);
2261 begin
2262 while Present (Renamed_Object (Result)) loop
2264 -- Renamed_Object must return an Entity_Name here
2265 -- because of preceding "Present (E_E_A (...))" test.
2267 Result := Entity (Renamed_Object (Result));
2268 end loop;
2270 return Result;
2271 end Lhs_Entity;
2273 -- Local Declarations
2275 Access_Check : constant Node_Id :=
2276 Make_Raise_Program_Error (Loc,
2277 Condition =>
2278 Make_Op_Gt (Loc,
2279 Left_Opnd =>
2280 Dynamic_Accessibility_Level (Rhs),
2281 Right_Opnd =>
2282 Make_Integer_Literal (Loc,
2283 Intval =>
2284 Scope_Depth
2285 (Enclosing_Dynamic_Scope
2286 (Lhs_Entity)))),
2287 Reason => PE_Accessibility_Check_Failed);
2289 Access_Level_Update : constant Node_Id :=
2290 Make_Assignment_Statement (Loc,
2291 Name =>
2292 New_Occurrence_Of
2293 (Effective_Extra_Accessibility
2294 (Entity (Lhs)), Loc),
2295 Expression =>
2296 Dynamic_Accessibility_Level (Rhs));
2298 begin
2299 if not Accessibility_Checks_Suppressed (Entity (Lhs)) then
2300 Insert_Action (N, Access_Check);
2301 end if;
2303 Insert_Action (N, Access_Level_Update);
2304 end;
2305 end if;
2307 -- Case of assignment to a bit packed array element. If there is a
2308 -- change of representation this must be expanded into components,
2309 -- otherwise this is a bit-field assignment.
2311 if Nkind (Lhs) = N_Indexed_Component
2312 and then Is_Bit_Packed_Array (Etype (Prefix (Lhs)))
2313 then
2314 -- Normal case, no change of representation
2316 if not Crep then
2317 Expand_Bit_Packed_Element_Set (N);
2318 return;
2320 -- Change of representation case
2322 else
2323 -- Generate the following, to force component-by-component
2324 -- assignments in an efficient way. Otherwise each component
2325 -- will require a temporary and two bit-field manipulations.
2327 -- T1 : Elmt_Type;
2328 -- T1 := RhS;
2329 -- Lhs := T1;
2331 declare
2332 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T');
2333 Stats : List_Id;
2335 begin
2336 Stats :=
2337 New_List (
2338 Make_Object_Declaration (Loc,
2339 Defining_Identifier => Tnn,
2340 Object_Definition =>
2341 New_Occurrence_Of (Etype (Lhs), Loc)),
2342 Make_Assignment_Statement (Loc,
2343 Name => New_Occurrence_Of (Tnn, Loc),
2344 Expression => Relocate_Node (Rhs)),
2345 Make_Assignment_Statement (Loc,
2346 Name => Relocate_Node (Lhs),
2347 Expression => New_Occurrence_Of (Tnn, Loc)));
2349 Insert_Actions (N, Stats);
2350 Rewrite (N, Make_Null_Statement (Loc));
2351 Analyze (N);
2352 end;
2353 end if;
2355 -- Build-in-place function call case. Note that we're not yet doing
2356 -- build-in-place for user-written assignment statements (the assignment
2357 -- here came from an aggregate.)
2359 elsif Ada_Version >= Ada_2005
2360 and then Is_Build_In_Place_Function_Call (Rhs)
2361 then
2362 Make_Build_In_Place_Call_In_Assignment (N, Rhs);
2364 elsif Is_Tagged_Type (Typ)
2365 or else (Needs_Finalization (Typ) and then not Is_Array_Type (Typ))
2366 then
2367 Tagged_Case : declare
2368 L : List_Id := No_List;
2369 Expand_Ctrl_Actions : constant Boolean := not No_Ctrl_Actions (N);
2371 begin
2372 -- In the controlled case, we ensure that function calls are
2373 -- evaluated before finalizing the target. In all cases, it makes
2374 -- the expansion easier if the side effects are removed first.
2376 Remove_Side_Effects (Lhs);
2377 Remove_Side_Effects (Rhs);
2379 -- Avoid recursion in the mechanism
2381 Set_Analyzed (N);
2383 -- If dispatching assignment, we need to dispatch to _assign
2385 if Is_Class_Wide_Type (Typ)
2387 -- If the type is tagged, we may as well use the predefined
2388 -- primitive assignment. This avoids inlining a lot of code
2389 -- and in the class-wide case, the assignment is replaced
2390 -- by a dispatching call to _assign. It is suppressed in the
2391 -- case of assignments created by the expander that correspond
2392 -- to initializations, where we do want to copy the tag
2393 -- (Expand_Ctrl_Actions flag is set False in this case). It is
2394 -- also suppressed if restriction No_Dispatching_Calls is in
2395 -- force because in that case predefined primitives are not
2396 -- generated.
2398 or else (Is_Tagged_Type (Typ)
2399 and then Chars (Current_Scope) /= Name_uAssign
2400 and then Expand_Ctrl_Actions
2401 and then
2402 not Restriction_Active (No_Dispatching_Calls))
2403 then
2404 if Is_Limited_Type (Typ) then
2406 -- This can happen in an instance when the formal is an
2407 -- extension of a limited interface, and the actual is
2408 -- limited. This is an error according to AI05-0087, but
2409 -- is not caught at the point of instantiation in earlier
2410 -- versions.
2412 -- This is wrong, error messages cannot be issued during
2413 -- expansion, since they would be missed in -gnatc mode ???
2415 Error_Msg_N ("assignment not available on limited type", N);
2416 return;
2417 end if;
2419 -- Fetch the primitive op _assign and proper type to call it.
2420 -- Because of possible conflicts between private and full view,
2421 -- fetch the proper type directly from the operation profile.
2423 declare
2424 Op : constant Entity_Id :=
2425 Find_Prim_Op (Typ, Name_uAssign);
2426 F_Typ : Entity_Id := Etype (First_Formal (Op));
2428 begin
2429 -- If the assignment is dispatching, make sure to use the
2430 -- proper type.
2432 if Is_Class_Wide_Type (Typ) then
2433 F_Typ := Class_Wide_Type (F_Typ);
2434 end if;
2436 L := New_List;
2438 -- In case of assignment to a class-wide tagged type, before
2439 -- the assignment we generate run-time check to ensure that
2440 -- the tags of source and target match.
2442 if not Tag_Checks_Suppressed (Typ)
2443 and then Is_Class_Wide_Type (Typ)
2444 and then Is_Tagged_Type (Typ)
2445 and then Is_Tagged_Type (Underlying_Type (Etype (Rhs)))
2446 then
2447 declare
2448 Lhs_Tag : Node_Id;
2449 Rhs_Tag : Node_Id;
2451 begin
2452 if not Is_Interface (Typ) then
2453 Lhs_Tag :=
2454 Make_Selected_Component (Loc,
2455 Prefix => Duplicate_Subexpr (Lhs),
2456 Selector_Name =>
2457 Make_Identifier (Loc, Name_uTag));
2458 Rhs_Tag :=
2459 Make_Selected_Component (Loc,
2460 Prefix => Duplicate_Subexpr (Rhs),
2461 Selector_Name =>
2462 Make_Identifier (Loc, Name_uTag));
2463 else
2464 -- Displace the pointer to the base of the objects
2465 -- applying 'Address, which is later expanded into
2466 -- a call to RE_Base_Address.
2468 Lhs_Tag :=
2469 Make_Explicit_Dereference (Loc,
2470 Prefix =>
2471 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
2472 Make_Attribute_Reference (Loc,
2473 Prefix => Duplicate_Subexpr (Lhs),
2474 Attribute_Name => Name_Address)));
2475 Rhs_Tag :=
2476 Make_Explicit_Dereference (Loc,
2477 Prefix =>
2478 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
2479 Make_Attribute_Reference (Loc,
2480 Prefix => Duplicate_Subexpr (Rhs),
2481 Attribute_Name => Name_Address)));
2482 end if;
2484 Append_To (L,
2485 Make_Raise_Constraint_Error (Loc,
2486 Condition =>
2487 Make_Op_Ne (Loc,
2488 Left_Opnd => Lhs_Tag,
2489 Right_Opnd => Rhs_Tag),
2490 Reason => CE_Tag_Check_Failed));
2491 end;
2492 end if;
2494 declare
2495 Left_N : Node_Id := Duplicate_Subexpr (Lhs);
2496 Right_N : Node_Id := Duplicate_Subexpr (Rhs);
2498 begin
2499 -- In order to dispatch the call to _assign the type of
2500 -- the actuals must match. Add conversion (if required).
2502 if Etype (Lhs) /= F_Typ then
2503 Left_N := Unchecked_Convert_To (F_Typ, Left_N);
2504 end if;
2506 if Etype (Rhs) /= F_Typ then
2507 Right_N := Unchecked_Convert_To (F_Typ, Right_N);
2508 end if;
2510 Append_To (L,
2511 Make_Procedure_Call_Statement (Loc,
2512 Name => New_Occurrence_Of (Op, Loc),
2513 Parameter_Associations => New_List (
2514 Node1 => Left_N,
2515 Node2 => Right_N)));
2516 end;
2517 end;
2519 else
2520 L := Make_Tag_Ctrl_Assignment (N);
2522 -- We can't afford to have destructive Finalization Actions in
2523 -- the Self assignment case, so if the target and the source
2524 -- are not obviously different, code is generated to avoid the
2525 -- self assignment case:
2527 -- if lhs'address /= rhs'address then
2528 -- <code for controlled and/or tagged assignment>
2529 -- end if;
2531 -- Skip this if Restriction (No_Finalization) is active
2533 if not Statically_Different (Lhs, Rhs)
2534 and then Expand_Ctrl_Actions
2535 and then not Restriction_Active (No_Finalization)
2536 then
2537 L := New_List (
2538 Make_Implicit_If_Statement (N,
2539 Condition =>
2540 Make_Op_Ne (Loc,
2541 Left_Opnd =>
2542 Make_Attribute_Reference (Loc,
2543 Prefix => Duplicate_Subexpr (Lhs),
2544 Attribute_Name => Name_Address),
2546 Right_Opnd =>
2547 Make_Attribute_Reference (Loc,
2548 Prefix => Duplicate_Subexpr (Rhs),
2549 Attribute_Name => Name_Address)),
2551 Then_Statements => L));
2552 end if;
2554 -- We need to set up an exception handler for implementing
2555 -- 7.6.1(18). The remaining adjustments are tackled by the
2556 -- implementation of adjust for record_controllers (see
2557 -- s-finimp.adb).
2559 -- This is skipped if we have no finalization
2561 if Expand_Ctrl_Actions
2562 and then not Restriction_Active (No_Finalization)
2563 then
2564 L := New_List (
2565 Make_Block_Statement (Loc,
2566 Handled_Statement_Sequence =>
2567 Make_Handled_Sequence_Of_Statements (Loc,
2568 Statements => L,
2569 Exception_Handlers => New_List (
2570 Make_Handler_For_Ctrl_Operation (Loc)))));
2571 end if;
2572 end if;
2574 Rewrite (N,
2575 Make_Block_Statement (Loc,
2576 Handled_Statement_Sequence =>
2577 Make_Handled_Sequence_Of_Statements (Loc, Statements => L)));
2579 -- If no restrictions on aborts, protect the whole assignment
2580 -- for controlled objects as per 9.8(11).
2582 if Needs_Finalization (Typ)
2583 and then Expand_Ctrl_Actions
2584 and then Abort_Allowed
2585 then
2586 declare
2587 Blk : constant Entity_Id :=
2588 New_Internal_Entity
2589 (E_Block, Current_Scope, Sloc (N), 'B');
2590 AUD : constant Entity_Id := RTE (RE_Abort_Undefer_Direct);
2592 begin
2593 Set_Is_Abort_Block (N);
2595 Set_Scope (Blk, Current_Scope);
2596 Set_Etype (Blk, Standard_Void_Type);
2597 Set_Identifier (N, New_Occurrence_Of (Blk, Sloc (N)));
2599 Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
2600 Set_At_End_Proc (Handled_Statement_Sequence (N),
2601 New_Occurrence_Of (AUD, Loc));
2603 -- Present the Abort_Undefer_Direct function to the backend
2604 -- so that it can inline the call to the function.
2606 Add_Inlined_Body (AUD, N);
2608 Expand_At_End_Handler
2609 (Handled_Statement_Sequence (N), Blk);
2610 end;
2611 end if;
2613 -- N has been rewritten to a block statement for which it is
2614 -- known by construction that no checks are necessary: analyze
2615 -- it with all checks suppressed.
2617 Analyze (N, Suppress => All_Checks);
2618 return;
2619 end Tagged_Case;
2621 -- Array types
2623 elsif Is_Array_Type (Typ) then
2624 declare
2625 Actual_Rhs : Node_Id := Rhs;
2627 begin
2628 while Nkind_In (Actual_Rhs, N_Type_Conversion,
2629 N_Qualified_Expression)
2630 loop
2631 Actual_Rhs := Expression (Actual_Rhs);
2632 end loop;
2634 Expand_Assign_Array (N, Actual_Rhs);
2635 return;
2636 end;
2638 -- Record types
2640 elsif Is_Record_Type (Typ) then
2641 Expand_Assign_Record (N);
2642 return;
2644 -- Scalar types. This is where we perform the processing related to the
2645 -- requirements of (RM 13.9.1(9-11)) concerning the handling of invalid
2646 -- scalar values.
2648 elsif Is_Scalar_Type (Typ) then
2650 -- Case where right side is known valid
2652 if Expr_Known_Valid (Rhs) then
2654 -- Here the right side is valid, so it is fine. The case to deal
2655 -- with is when the left side is a local variable reference whose
2656 -- value is not currently known to be valid. If this is the case,
2657 -- and the assignment appears in an unconditional context, then
2658 -- we can mark the left side as now being valid if one of these
2659 -- conditions holds:
2661 -- The expression of the right side has Do_Range_Check set so
2662 -- that we know a range check will be performed. Note that it
2663 -- can be the case that a range check is omitted because we
2664 -- make the assumption that we can assume validity for operands
2665 -- appearing in the right side in determining whether a range
2666 -- check is required
2668 -- The subtype of the right side matches the subtype of the
2669 -- left side. In this case, even though we have not checked
2670 -- the range of the right side, we know it is in range of its
2671 -- subtype if the expression is valid.
2673 if Is_Local_Variable_Reference (Lhs)
2674 and then not Is_Known_Valid (Entity (Lhs))
2675 and then In_Unconditional_Context (N)
2676 then
2677 if Do_Range_Check (Rhs)
2678 or else Etype (Lhs) = Etype (Rhs)
2679 then
2680 Set_Is_Known_Valid (Entity (Lhs), True);
2681 end if;
2682 end if;
2684 -- Case where right side may be invalid in the sense of the RM
2685 -- reference above. The RM does not require that we check for the
2686 -- validity on an assignment, but it does require that the assignment
2687 -- of an invalid value not cause erroneous behavior.
2689 -- The general approach in GNAT is to use the Is_Known_Valid flag
2690 -- to avoid the need for validity checking on assignments. However
2691 -- in some cases, we have to do validity checking in order to make
2692 -- sure that the setting of this flag is correct.
2694 else
2695 -- Validate right side if we are validating copies
2697 if Validity_Checks_On
2698 and then Validity_Check_Copies
2699 then
2700 -- Skip this if left-hand side is an array or record component
2701 -- and elementary component validity checks are suppressed.
2703 if Nkind_In (Lhs, N_Selected_Component, N_Indexed_Component)
2704 and then not Validity_Check_Components
2705 then
2706 null;
2707 else
2708 Ensure_Valid (Rhs);
2709 end if;
2711 -- We can propagate this to the left side where appropriate
2713 if Is_Local_Variable_Reference (Lhs)
2714 and then not Is_Known_Valid (Entity (Lhs))
2715 and then In_Unconditional_Context (N)
2716 then
2717 Set_Is_Known_Valid (Entity (Lhs), True);
2718 end if;
2720 -- Otherwise check to see what should be done
2722 -- If left side is a local variable, then we just set its flag to
2723 -- indicate that its value may no longer be valid, since we are
2724 -- copying a potentially invalid value.
2726 elsif Is_Local_Variable_Reference (Lhs) then
2727 Set_Is_Known_Valid (Entity (Lhs), False);
2729 -- Check for case of a nonlocal variable on the left side which
2730 -- is currently known to be valid. In this case, we simply ensure
2731 -- that the right side is valid. We only play the game of copying
2732 -- validity status for local variables, since we are doing this
2733 -- statically, not by tracing the full flow graph.
2735 elsif Is_Entity_Name (Lhs)
2736 and then Is_Known_Valid (Entity (Lhs))
2737 then
2738 -- Note: If Validity_Checking mode is set to none, we ignore
2739 -- the Ensure_Valid call so don't worry about that case here.
2741 Ensure_Valid (Rhs);
2743 -- In all other cases, we can safely copy an invalid value without
2744 -- worrying about the status of the left side. Since it is not a
2745 -- variable reference it will not be considered
2746 -- as being known to be valid in any case.
2748 else
2749 null;
2750 end if;
2751 end if;
2752 end if;
2754 exception
2755 when RE_Not_Available =>
2756 return;
2757 end Expand_N_Assignment_Statement;
2759 ------------------------------
2760 -- Expand_N_Block_Statement --
2761 ------------------------------
2763 -- Encode entity names defined in block statement
2765 procedure Expand_N_Block_Statement (N : Node_Id) is
2766 begin
2767 Qualify_Entity_Names (N);
2768 end Expand_N_Block_Statement;
2770 -----------------------------
2771 -- Expand_N_Case_Statement --
2772 -----------------------------
2774 procedure Expand_N_Case_Statement (N : Node_Id) is
2775 Loc : constant Source_Ptr := Sloc (N);
2776 Expr : constant Node_Id := Expression (N);
2777 Alt : Node_Id;
2778 Len : Nat;
2779 Cond : Node_Id;
2780 Choice : Node_Id;
2781 Chlist : List_Id;
2783 begin
2784 -- Check for the situation where we know at compile time which branch
2785 -- will be taken.
2787 -- If the value is static but its subtype is predicated and the value
2788 -- does not obey the predicate, the value is marked non-static, and
2789 -- there can be no corresponding static alternative. In that case we
2790 -- replace the case statement with an exception, regardless of whether
2791 -- assertions are enabled or not, unless predicates are ignored.
2793 if Compile_Time_Known_Value (Expr)
2794 and then Has_Predicates (Etype (Expr))
2795 and then not Predicates_Ignored (Etype (Expr))
2796 and then not Is_OK_Static_Expression (Expr)
2797 then
2798 Rewrite (N,
2799 Make_Raise_Constraint_Error (Loc, Reason => CE_Invalid_Data));
2800 Analyze (N);
2801 return;
2803 elsif Compile_Time_Known_Value (Expr)
2804 and then (not Has_Predicates (Etype (Expr))
2805 or else Is_Static_Expression (Expr))
2806 then
2807 Alt := Find_Static_Alternative (N);
2809 -- Do not consider controlled objects found in a case statement which
2810 -- actually models a case expression because their early finalization
2811 -- will affect the result of the expression.
2813 if not From_Conditional_Expression (N) then
2814 Process_Statements_For_Controlled_Objects (Alt);
2815 end if;
2817 -- Move statements from this alternative after the case statement.
2818 -- They are already analyzed, so will be skipped by the analyzer.
2820 Insert_List_After (N, Statements (Alt));
2822 -- That leaves the case statement as a shell. So now we can kill all
2823 -- other alternatives in the case statement.
2825 Kill_Dead_Code (Expression (N));
2827 declare
2828 Dead_Alt : Node_Id;
2830 begin
2831 -- Loop through case alternatives, skipping pragmas, and skipping
2832 -- the one alternative that we select (and therefore retain).
2834 Dead_Alt := First (Alternatives (N));
2835 while Present (Dead_Alt) loop
2836 if Dead_Alt /= Alt
2837 and then Nkind (Dead_Alt) = N_Case_Statement_Alternative
2838 then
2839 Kill_Dead_Code (Statements (Dead_Alt), Warn_On_Deleted_Code);
2840 end if;
2842 Next (Dead_Alt);
2843 end loop;
2844 end;
2846 Rewrite (N, Make_Null_Statement (Loc));
2847 return;
2848 end if;
2850 -- Here if the choice is not determined at compile time
2852 declare
2853 Last_Alt : constant Node_Id := Last (Alternatives (N));
2855 Others_Present : Boolean;
2856 Others_Node : Node_Id;
2858 Then_Stms : List_Id;
2859 Else_Stms : List_Id;
2861 begin
2862 if Nkind (First (Discrete_Choices (Last_Alt))) = N_Others_Choice then
2863 Others_Present := True;
2864 Others_Node := Last_Alt;
2865 else
2866 Others_Present := False;
2867 end if;
2869 -- First step is to worry about possible invalid argument. The RM
2870 -- requires (RM 5.4(13)) that if the result is invalid (e.g. it is
2871 -- outside the base range), then Constraint_Error must be raised.
2873 -- Case of validity check required (validity checks are on, the
2874 -- expression is not known to be valid, and the case statement
2875 -- comes from source -- no need to validity check internally
2876 -- generated case statements).
2878 if Validity_Check_Default
2879 and then not Predicates_Ignored (Etype (Expr))
2880 then
2881 Ensure_Valid (Expr);
2882 end if;
2884 -- If there is only a single alternative, just replace it with the
2885 -- sequence of statements since obviously that is what is going to
2886 -- be executed in all cases.
2888 Len := List_Length (Alternatives (N));
2890 if Len = 1 then
2892 -- We still need to evaluate the expression if it has any side
2893 -- effects.
2895 Remove_Side_Effects (Expression (N));
2896 Alt := First (Alternatives (N));
2898 -- Do not consider controlled objects found in a case statement
2899 -- which actually models a case expression because their early
2900 -- finalization will affect the result of the expression.
2902 if not From_Conditional_Expression (N) then
2903 Process_Statements_For_Controlled_Objects (Alt);
2904 end if;
2906 Insert_List_After (N, Statements (Alt));
2908 -- That leaves the case statement as a shell. The alternative that
2909 -- will be executed is reset to a null list. So now we can kill
2910 -- the entire case statement.
2912 Kill_Dead_Code (Expression (N));
2913 Rewrite (N, Make_Null_Statement (Loc));
2914 return;
2916 -- An optimization. If there are only two alternatives, and only
2917 -- a single choice, then rewrite the whole case statement as an
2918 -- if statement, since this can result in subsequent optimizations.
2919 -- This helps not only with case statements in the source of a
2920 -- simple form, but also with generated code (discriminant check
2921 -- functions in particular).
2923 -- Note: it is OK to do this before expanding out choices for any
2924 -- static predicates, since the if statement processing will handle
2925 -- the static predicate case fine.
2927 elsif Len = 2 then
2928 Chlist := Discrete_Choices (First (Alternatives (N)));
2930 if List_Length (Chlist) = 1 then
2931 Choice := First (Chlist);
2933 Then_Stms := Statements (First (Alternatives (N)));
2934 Else_Stms := Statements (Last (Alternatives (N)));
2936 -- For TRUE, generate "expression", not expression = true
2938 if Nkind (Choice) = N_Identifier
2939 and then Entity (Choice) = Standard_True
2940 then
2941 Cond := Expression (N);
2943 -- For FALSE, generate "expression" and switch then/else
2945 elsif Nkind (Choice) = N_Identifier
2946 and then Entity (Choice) = Standard_False
2947 then
2948 Cond := Expression (N);
2949 Else_Stms := Statements (First (Alternatives (N)));
2950 Then_Stms := Statements (Last (Alternatives (N)));
2952 -- For a range, generate "expression in range"
2954 elsif Nkind (Choice) = N_Range
2955 or else (Nkind (Choice) = N_Attribute_Reference
2956 and then Attribute_Name (Choice) = Name_Range)
2957 or else (Is_Entity_Name (Choice)
2958 and then Is_Type (Entity (Choice)))
2959 then
2960 Cond :=
2961 Make_In (Loc,
2962 Left_Opnd => Expression (N),
2963 Right_Opnd => Relocate_Node (Choice));
2965 -- A subtype indication is not a legal operator in a membership
2966 -- test, so retrieve its range.
2968 elsif Nkind (Choice) = N_Subtype_Indication then
2969 Cond :=
2970 Make_In (Loc,
2971 Left_Opnd => Expression (N),
2972 Right_Opnd =>
2973 Relocate_Node
2974 (Range_Expression (Constraint (Choice))));
2976 -- For any other subexpression "expression = value"
2978 else
2979 Cond :=
2980 Make_Op_Eq (Loc,
2981 Left_Opnd => Expression (N),
2982 Right_Opnd => Relocate_Node (Choice));
2983 end if;
2985 -- Now rewrite the case as an IF
2987 Rewrite (N,
2988 Make_If_Statement (Loc,
2989 Condition => Cond,
2990 Then_Statements => Then_Stms,
2991 Else_Statements => Else_Stms));
2992 Analyze (N);
2993 return;
2994 end if;
2995 end if;
2997 -- If the last alternative is not an Others choice, replace it with
2998 -- an N_Others_Choice. Note that we do not bother to call Analyze on
2999 -- the modified case statement, since it's only effect would be to
3000 -- compute the contents of the Others_Discrete_Choices which is not
3001 -- needed by the back end anyway.
3003 -- The reason for this is that the back end always needs some default
3004 -- for a switch, so if we have not supplied one in the processing
3005 -- above for validity checking, then we need to supply one here.
3007 if not Others_Present then
3008 Others_Node := Make_Others_Choice (Sloc (Last_Alt));
3010 -- If Predicates_Ignored is true the value does not satisfy the
3011 -- predicate, and there is no Others choice, Constraint_Error
3012 -- must be raised (4.5.7 (21/3)).
3014 if Predicates_Ignored (Etype (Expr)) then
3015 declare
3016 Except : constant Node_Id :=
3017 Make_Raise_Constraint_Error (Loc,
3018 Reason => CE_Invalid_Data);
3019 New_Alt : constant Node_Id :=
3020 Make_Case_Statement_Alternative (Loc,
3021 Discrete_Choices => New_List (
3022 Make_Others_Choice (Loc)),
3023 Statements => New_List (Except));
3025 begin
3026 Append (New_Alt, Alternatives (N));
3027 Analyze_And_Resolve (Except);
3028 end;
3030 else
3031 Set_Others_Discrete_Choices
3032 (Others_Node, Discrete_Choices (Last_Alt));
3033 Set_Discrete_Choices (Last_Alt, New_List (Others_Node));
3034 end if;
3036 end if;
3038 -- Deal with possible declarations of controlled objects, and also
3039 -- with rewriting choice sequences for static predicate references.
3041 Alt := First_Non_Pragma (Alternatives (N));
3042 while Present (Alt) loop
3044 -- Do not consider controlled objects found in a case statement
3045 -- which actually models a case expression because their early
3046 -- finalization will affect the result of the expression.
3048 if not From_Conditional_Expression (N) then
3049 Process_Statements_For_Controlled_Objects (Alt);
3050 end if;
3052 if Has_SP_Choice (Alt) then
3053 Expand_Static_Predicates_In_Choices (Alt);
3054 end if;
3056 Next_Non_Pragma (Alt);
3057 end loop;
3058 end;
3059 end Expand_N_Case_Statement;
3061 -----------------------------
3062 -- Expand_N_Exit_Statement --
3063 -----------------------------
3065 -- The only processing required is to deal with a possible C/Fortran
3066 -- boolean value used as the condition for the exit statement.
3068 procedure Expand_N_Exit_Statement (N : Node_Id) is
3069 begin
3070 Adjust_Condition (Condition (N));
3071 end Expand_N_Exit_Statement;
3073 ----------------------------------
3074 -- Expand_Formal_Container_Loop --
3075 ----------------------------------
3077 procedure Expand_Formal_Container_Loop (N : Node_Id) is
3078 Loc : constant Source_Ptr := Sloc (N);
3079 Isc : constant Node_Id := Iteration_Scheme (N);
3080 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3081 Cursor : constant Entity_Id := Defining_Identifier (I_Spec);
3082 Container : constant Node_Id := Entity (Name (I_Spec));
3083 Stats : constant List_Id := Statements (N);
3085 Advance : Node_Id;
3086 Init_Decl : Node_Id;
3087 New_Loop : Node_Id;
3089 begin
3090 -- The expansion of a formal container loop resembles the one for Ada
3091 -- containers. The only difference is that the primitives mention the
3092 -- domain of iteration explicitly, and function First applied to the
3093 -- container yields a cursor directly.
3095 -- Cursor : Cursor_type := First (Container);
3096 -- while Has_Element (Cursor, Container) loop
3097 -- <original loop statements>
3098 -- Cursor := Next (Container, Cursor);
3099 -- end loop;
3101 Build_Formal_Container_Iteration
3102 (N, Container, Cursor, Init_Decl, Advance, New_Loop);
3104 Append_To (Stats, Advance);
3106 -- Build a block to capture declaration of the cursor
3108 Rewrite (N,
3109 Make_Block_Statement (Loc,
3110 Declarations => New_List (Init_Decl),
3111 Handled_Statement_Sequence =>
3112 Make_Handled_Sequence_Of_Statements (Loc,
3113 Statements => New_List (New_Loop))));
3115 -- The loop parameter is declared by an object declaration, but within
3116 -- the loop we must prevent user assignments to it, so we analyze the
3117 -- declaration and reset the entity kind, before analyzing the rest of
3118 -- the loop.
3120 Analyze (Init_Decl);
3121 Set_Ekind (Defining_Identifier (Init_Decl), E_Loop_Parameter);
3123 -- The cursor was marked as a loop parameter to prevent user assignments
3124 -- to it, however this renders the advancement step illegal as it is not
3125 -- possible to change the value of a constant. Flag the advancement step
3126 -- as a legal form of assignment to remedy this side effect.
3128 Set_Assignment_OK (Name (Advance));
3129 Analyze (N);
3131 -- Because we have to analyze the initial declaration of the loop
3132 -- parameter multiple times its scope is incorrectly set at this point
3133 -- to the one surrounding the block statement - so set the scope
3134 -- manually to be the actual block statement.
3136 Set_Scope (Defining_Identifier (Init_Decl), Entity (Identifier (N)));
3137 end Expand_Formal_Container_Loop;
3139 ------------------------------------------
3140 -- Expand_Formal_Container_Element_Loop --
3141 ------------------------------------------
3143 procedure Expand_Formal_Container_Element_Loop (N : Node_Id) is
3144 Loc : constant Source_Ptr := Sloc (N);
3145 Isc : constant Node_Id := Iteration_Scheme (N);
3146 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3147 Element : constant Entity_Id := Defining_Identifier (I_Spec);
3148 Container : constant Node_Id := Entity (Name (I_Spec));
3149 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
3150 Stats : constant List_Id := Statements (N);
3152 Cursor : constant Entity_Id :=
3153 Make_Defining_Identifier (Loc,
3154 Chars => New_External_Name (Chars (Element), 'C'));
3155 Elmt_Decl : Node_Id;
3156 Elmt_Ref : Node_Id;
3158 Element_Op : constant Entity_Id :=
3159 Get_Iterable_Type_Primitive (Container_Typ, Name_Element);
3161 Advance : Node_Id;
3162 Init : Node_Id;
3163 New_Loop : Node_Id;
3165 begin
3166 -- For an element iterator, the Element aspect must be present,
3167 -- (this is checked during analysis) and the expansion takes the form:
3169 -- Cursor : Cursor_Type := First (Container);
3170 -- Elmt : Element_Type;
3171 -- while Has_Element (Cursor, Container) loop
3172 -- Elmt := Element (Container, Cursor);
3173 -- <original loop statements>
3174 -- Cursor := Next (Container, Cursor);
3175 -- end loop;
3177 -- However this expansion is not legal if the element is indefinite.
3178 -- In that case we create a block to hold a variable declaration
3179 -- initialized with a call to Element, and generate:
3181 -- Cursor : Cursor_Type := First (Container);
3182 -- while Has_Element (Cursor, Container) loop
3183 -- declare
3184 -- Elmt : Element_Type := Element (Container, Cursor);
3185 -- begin
3186 -- <original loop statements>
3187 -- Cursor := Next (Container, Cursor);
3188 -- end;
3189 -- end loop;
3191 Build_Formal_Container_Iteration
3192 (N, Container, Cursor, Init, Advance, New_Loop);
3193 Append_To (Stats, Advance);
3195 Set_Ekind (Cursor, E_Variable);
3196 Insert_Action (N, Init);
3198 -- Declaration for Element
3200 Elmt_Decl :=
3201 Make_Object_Declaration (Loc,
3202 Defining_Identifier => Element,
3203 Object_Definition => New_Occurrence_Of (Etype (Element_Op), Loc));
3205 if not Is_Constrained (Etype (Element_Op)) then
3206 Set_Expression (Elmt_Decl,
3207 Make_Function_Call (Loc,
3208 Name => New_Occurrence_Of (Element_Op, Loc),
3209 Parameter_Associations => New_List (
3210 New_Occurrence_Of (Container, Loc),
3211 New_Occurrence_Of (Cursor, Loc))));
3213 Set_Statements (New_Loop,
3214 New_List
3215 (Make_Block_Statement (Loc,
3216 Declarations => New_List (Elmt_Decl),
3217 Handled_Statement_Sequence =>
3218 Make_Handled_Sequence_Of_Statements (Loc,
3219 Statements => Stats))));
3221 else
3222 Elmt_Ref :=
3223 Make_Assignment_Statement (Loc,
3224 Name => New_Occurrence_Of (Element, Loc),
3225 Expression =>
3226 Make_Function_Call (Loc,
3227 Name => New_Occurrence_Of (Element_Op, Loc),
3228 Parameter_Associations => New_List (
3229 New_Occurrence_Of (Container, Loc),
3230 New_Occurrence_Of (Cursor, Loc))));
3232 Prepend (Elmt_Ref, Stats);
3234 -- The element is assignable in the expanded code
3236 Set_Assignment_OK (Name (Elmt_Ref));
3238 -- The loop is rewritten as a block, to hold the element declaration
3240 New_Loop :=
3241 Make_Block_Statement (Loc,
3242 Declarations => New_List (Elmt_Decl),
3243 Handled_Statement_Sequence =>
3244 Make_Handled_Sequence_Of_Statements (Loc,
3245 Statements => New_List (New_Loop)));
3246 end if;
3248 -- The element is only modified in expanded code, so it appears as
3249 -- unassigned to the warning machinery. We must suppress this spurious
3250 -- warning explicitly.
3252 Set_Warnings_Off (Element);
3254 Rewrite (N, New_Loop);
3256 -- The loop parameter is declared by an object declaration, but within
3257 -- the loop we must prevent user assignments to it, so we analyze the
3258 -- declaration and reset the entity kind, before analyzing the rest of
3259 -- the loop.
3261 Analyze (Elmt_Decl);
3262 Set_Ekind (Defining_Identifier (Elmt_Decl), E_Loop_Parameter);
3264 Analyze (N);
3265 end Expand_Formal_Container_Element_Loop;
3267 -----------------------------
3268 -- Expand_N_Goto_Statement --
3269 -----------------------------
3271 -- Add poll before goto if polling active
3273 procedure Expand_N_Goto_Statement (N : Node_Id) is
3274 begin
3275 Generate_Poll_Call (N);
3276 end Expand_N_Goto_Statement;
3278 ---------------------------
3279 -- Expand_N_If_Statement --
3280 ---------------------------
3282 -- First we deal with the case of C and Fortran convention boolean values,
3283 -- with zero/non-zero semantics.
3285 -- Second, we deal with the obvious rewriting for the cases where the
3286 -- condition of the IF is known at compile time to be True or False.
3288 -- Third, we remove elsif parts which have non-empty Condition_Actions and
3289 -- rewrite as independent if statements. For example:
3291 -- if x then xs
3292 -- elsif y then ys
3293 -- ...
3294 -- end if;
3296 -- becomes
3298 -- if x then xs
3299 -- else
3300 -- <<condition actions of y>>
3301 -- if y then ys
3302 -- ...
3303 -- end if;
3304 -- end if;
3306 -- This rewriting is needed if at least one elsif part has a non-empty
3307 -- Condition_Actions list. We also do the same processing if there is a
3308 -- constant condition in an elsif part (in conjunction with the first
3309 -- processing step mentioned above, for the recursive call made to deal
3310 -- with the created inner if, this deals with properly optimizing the
3311 -- cases of constant elsif conditions).
3313 procedure Expand_N_If_Statement (N : Node_Id) is
3314 Loc : constant Source_Ptr := Sloc (N);
3315 Hed : Node_Id;
3316 E : Node_Id;
3317 New_If : Node_Id;
3319 Warn_If_Deleted : constant Boolean :=
3320 Warn_On_Deleted_Code and then Comes_From_Source (N);
3321 -- Indicates whether we want warnings when we delete branches of the
3322 -- if statement based on constant condition analysis. We never want
3323 -- these warnings for expander generated code.
3325 begin
3326 -- Do not consider controlled objects found in an if statement which
3327 -- actually models an if expression because their early finalization
3328 -- will affect the result of the expression.
3330 if not From_Conditional_Expression (N) then
3331 Process_Statements_For_Controlled_Objects (N);
3332 end if;
3334 Adjust_Condition (Condition (N));
3336 -- The following loop deals with constant conditions for the IF. We
3337 -- need a loop because as we eliminate False conditions, we grab the
3338 -- first elsif condition and use it as the primary condition.
3340 while Compile_Time_Known_Value (Condition (N)) loop
3342 -- If condition is True, we can simply rewrite the if statement now
3343 -- by replacing it by the series of then statements.
3345 if Is_True (Expr_Value (Condition (N))) then
3347 -- All the else parts can be killed
3349 Kill_Dead_Code (Elsif_Parts (N), Warn_If_Deleted);
3350 Kill_Dead_Code (Else_Statements (N), Warn_If_Deleted);
3352 Hed := Remove_Head (Then_Statements (N));
3353 Insert_List_After (N, Then_Statements (N));
3354 Rewrite (N, Hed);
3355 return;
3357 -- If condition is False, then we can delete the condition and
3358 -- the Then statements
3360 else
3361 -- We do not delete the condition if constant condition warnings
3362 -- are enabled, since otherwise we end up deleting the desired
3363 -- warning. Of course the backend will get rid of this True/False
3364 -- test anyway, so nothing is lost here.
3366 if not Constant_Condition_Warnings then
3367 Kill_Dead_Code (Condition (N));
3368 end if;
3370 Kill_Dead_Code (Then_Statements (N), Warn_If_Deleted);
3372 -- If there are no elsif statements, then we simply replace the
3373 -- entire if statement by the sequence of else statements.
3375 if No (Elsif_Parts (N)) then
3376 if No (Else_Statements (N))
3377 or else Is_Empty_List (Else_Statements (N))
3378 then
3379 Rewrite (N,
3380 Make_Null_Statement (Sloc (N)));
3381 else
3382 Hed := Remove_Head (Else_Statements (N));
3383 Insert_List_After (N, Else_Statements (N));
3384 Rewrite (N, Hed);
3385 end if;
3387 return;
3389 -- If there are elsif statements, the first of them becomes the
3390 -- if/then section of the rebuilt if statement This is the case
3391 -- where we loop to reprocess this copied condition.
3393 else
3394 Hed := Remove_Head (Elsif_Parts (N));
3395 Insert_Actions (N, Condition_Actions (Hed));
3396 Set_Condition (N, Condition (Hed));
3397 Set_Then_Statements (N, Then_Statements (Hed));
3399 -- Hed might have been captured as the condition determining
3400 -- the current value for an entity. Now it is detached from
3401 -- the tree, so a Current_Value pointer in the condition might
3402 -- need to be updated.
3404 Set_Current_Value_Condition (N);
3406 if Is_Empty_List (Elsif_Parts (N)) then
3407 Set_Elsif_Parts (N, No_List);
3408 end if;
3409 end if;
3410 end if;
3411 end loop;
3413 -- Loop through elsif parts, dealing with constant conditions and
3414 -- possible condition actions that are present.
3416 if Present (Elsif_Parts (N)) then
3417 E := First (Elsif_Parts (N));
3418 while Present (E) loop
3420 -- Do not consider controlled objects found in an if statement
3421 -- which actually models an if expression because their early
3422 -- finalization will affect the result of the expression.
3424 if not From_Conditional_Expression (N) then
3425 Process_Statements_For_Controlled_Objects (E);
3426 end if;
3428 Adjust_Condition (Condition (E));
3430 -- If there are condition actions, then rewrite the if statement
3431 -- as indicated above. We also do the same rewrite for a True or
3432 -- False condition. The further processing of this constant
3433 -- condition is then done by the recursive call to expand the
3434 -- newly created if statement
3436 if Present (Condition_Actions (E))
3437 or else Compile_Time_Known_Value (Condition (E))
3438 then
3439 New_If :=
3440 Make_If_Statement (Sloc (E),
3441 Condition => Condition (E),
3442 Then_Statements => Then_Statements (E),
3443 Elsif_Parts => No_List,
3444 Else_Statements => Else_Statements (N));
3446 -- Elsif parts for new if come from remaining elsif's of parent
3448 while Present (Next (E)) loop
3449 if No (Elsif_Parts (New_If)) then
3450 Set_Elsif_Parts (New_If, New_List);
3451 end if;
3453 Append (Remove_Next (E), Elsif_Parts (New_If));
3454 end loop;
3456 Set_Else_Statements (N, New_List (New_If));
3458 if Present (Condition_Actions (E)) then
3459 Insert_List_Before (New_If, Condition_Actions (E));
3460 end if;
3462 Remove (E);
3464 if Is_Empty_List (Elsif_Parts (N)) then
3465 Set_Elsif_Parts (N, No_List);
3466 end if;
3468 Analyze (New_If);
3470 -- Note this is not an implicit if statement, since it is part
3471 -- of an explicit if statement in the source (or of an implicit
3472 -- if statement that has already been tested). We set the flag
3473 -- after calling Analyze to avoid generating extra warnings
3474 -- specific to pure if statements, however (see
3475 -- Sem_Ch5.Analyze_If_Statement).
3477 Set_Comes_From_Source (New_If, Comes_From_Source (N));
3478 return;
3480 -- No special processing for that elsif part, move to next
3482 else
3483 Next (E);
3484 end if;
3485 end loop;
3486 end if;
3488 -- Some more optimizations applicable if we still have an IF statement
3490 if Nkind (N) /= N_If_Statement then
3491 return;
3492 end if;
3494 -- Another optimization, special cases that can be simplified
3496 -- if expression then
3497 -- return true;
3498 -- else
3499 -- return false;
3500 -- end if;
3502 -- can be changed to:
3504 -- return expression;
3506 -- and
3508 -- if expression then
3509 -- return false;
3510 -- else
3511 -- return true;
3512 -- end if;
3514 -- can be changed to:
3516 -- return not (expression);
3518 -- Only do these optimizations if we are at least at -O1 level and
3519 -- do not do them if control flow optimizations are suppressed.
3521 if Optimization_Level > 0
3522 and then not Opt.Suppress_Control_Flow_Optimizations
3523 then
3524 if Nkind (N) = N_If_Statement
3525 and then No (Elsif_Parts (N))
3526 and then Present (Else_Statements (N))
3527 and then List_Length (Then_Statements (N)) = 1
3528 and then List_Length (Else_Statements (N)) = 1
3529 then
3530 declare
3531 Then_Stm : constant Node_Id := First (Then_Statements (N));
3532 Else_Stm : constant Node_Id := First (Else_Statements (N));
3534 begin
3535 if Nkind (Then_Stm) = N_Simple_Return_Statement
3536 and then
3537 Nkind (Else_Stm) = N_Simple_Return_Statement
3538 then
3539 declare
3540 Then_Expr : constant Node_Id := Expression (Then_Stm);
3541 Else_Expr : constant Node_Id := Expression (Else_Stm);
3543 begin
3544 if Nkind (Then_Expr) = N_Identifier
3545 and then
3546 Nkind (Else_Expr) = N_Identifier
3547 then
3548 if Entity (Then_Expr) = Standard_True
3549 and then Entity (Else_Expr) = Standard_False
3550 then
3551 Rewrite (N,
3552 Make_Simple_Return_Statement (Loc,
3553 Expression => Relocate_Node (Condition (N))));
3554 Analyze (N);
3555 return;
3557 elsif Entity (Then_Expr) = Standard_False
3558 and then Entity (Else_Expr) = Standard_True
3559 then
3560 Rewrite (N,
3561 Make_Simple_Return_Statement (Loc,
3562 Expression =>
3563 Make_Op_Not (Loc,
3564 Right_Opnd =>
3565 Relocate_Node (Condition (N)))));
3566 Analyze (N);
3567 return;
3568 end if;
3569 end if;
3570 end;
3571 end if;
3572 end;
3573 end if;
3574 end if;
3575 end Expand_N_If_Statement;
3577 --------------------------
3578 -- Expand_Iterator_Loop --
3579 --------------------------
3581 procedure Expand_Iterator_Loop (N : Node_Id) is
3582 Isc : constant Node_Id := Iteration_Scheme (N);
3583 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3585 Container : constant Node_Id := Name (I_Spec);
3586 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
3588 begin
3589 -- Processing for arrays
3591 if Is_Array_Type (Container_Typ) then
3592 pragma Assert (Of_Present (I_Spec));
3593 Expand_Iterator_Loop_Over_Array (N);
3595 elsif Has_Aspect (Container_Typ, Aspect_Iterable) then
3596 if Of_Present (I_Spec) then
3597 Expand_Formal_Container_Element_Loop (N);
3598 else
3599 Expand_Formal_Container_Loop (N);
3600 end if;
3602 -- Processing for containers
3604 else
3605 Expand_Iterator_Loop_Over_Container
3606 (N, Isc, I_Spec, Container, Container_Typ);
3607 end if;
3608 end Expand_Iterator_Loop;
3610 -------------------------------------
3611 -- Expand_Iterator_Loop_Over_Array --
3612 -------------------------------------
3614 procedure Expand_Iterator_Loop_Over_Array (N : Node_Id) is
3615 Isc : constant Node_Id := Iteration_Scheme (N);
3616 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3617 Array_Node : constant Node_Id := Name (I_Spec);
3618 Array_Typ : constant Entity_Id := Base_Type (Etype (Array_Node));
3619 Array_Dim : constant Pos := Number_Dimensions (Array_Typ);
3620 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3621 Loc : constant Source_Ptr := Sloc (N);
3622 Stats : constant List_Id := Statements (N);
3623 Core_Loop : Node_Id;
3624 Dim1 : Int;
3625 Ind_Comp : Node_Id;
3626 Iterator : Entity_Id;
3628 -- Start of processing for Expand_Iterator_Loop_Over_Array
3630 begin
3631 -- for Element of Array loop
3633 -- It requires an internally generated cursor to iterate over the array
3635 pragma Assert (Of_Present (I_Spec));
3637 Iterator := Make_Temporary (Loc, 'C');
3639 -- Generate:
3640 -- Element : Component_Type renames Array (Iterator);
3641 -- Iterator is the index value, or a list of index values
3642 -- in the case of a multidimensional array.
3644 Ind_Comp :=
3645 Make_Indexed_Component (Loc,
3646 Prefix => Relocate_Node (Array_Node),
3647 Expressions => New_List (New_Occurrence_Of (Iterator, Loc)));
3649 Prepend_To (Stats,
3650 Make_Object_Renaming_Declaration (Loc,
3651 Defining_Identifier => Id,
3652 Subtype_Mark =>
3653 New_Occurrence_Of (Component_Type (Array_Typ), Loc),
3654 Name => Ind_Comp));
3656 -- Mark the loop variable as needing debug info, so that expansion
3657 -- of the renaming will result in Materialize_Entity getting set via
3658 -- Debug_Renaming_Declaration. (This setting is needed here because
3659 -- the setting in Freeze_Entity comes after the expansion, which is
3660 -- too late. ???)
3662 Set_Debug_Info_Needed (Id);
3664 -- Generate:
3666 -- for Iterator in [reverse] Array'Range (Array_Dim) loop
3667 -- Element : Component_Type renames Array (Iterator);
3668 -- <original loop statements>
3669 -- end loop;
3671 -- If this is an iteration over a multidimensional array, the
3672 -- innermost loop is over the last dimension in Ada, and over
3673 -- the first dimension in Fortran.
3675 if Convention (Array_Typ) = Convention_Fortran then
3676 Dim1 := 1;
3677 else
3678 Dim1 := Array_Dim;
3679 end if;
3681 Core_Loop :=
3682 Make_Loop_Statement (Loc,
3683 Iteration_Scheme =>
3684 Make_Iteration_Scheme (Loc,
3685 Loop_Parameter_Specification =>
3686 Make_Loop_Parameter_Specification (Loc,
3687 Defining_Identifier => Iterator,
3688 Discrete_Subtype_Definition =>
3689 Make_Attribute_Reference (Loc,
3690 Prefix => Relocate_Node (Array_Node),
3691 Attribute_Name => Name_Range,
3692 Expressions => New_List (
3693 Make_Integer_Literal (Loc, Dim1))),
3694 Reverse_Present => Reverse_Present (I_Spec))),
3695 Statements => Stats,
3696 End_Label => Empty);
3698 -- Processing for multidimensional array. The body of each loop is
3699 -- a loop over a previous dimension, going in decreasing order in Ada
3700 -- and in increasing order in Fortran.
3702 if Array_Dim > 1 then
3703 for Dim in 1 .. Array_Dim - 1 loop
3704 if Convention (Array_Typ) = Convention_Fortran then
3705 Dim1 := Dim + 1;
3706 else
3707 Dim1 := Array_Dim - Dim;
3708 end if;
3710 Iterator := Make_Temporary (Loc, 'C');
3712 -- Generate the dimension loops starting from the innermost one
3714 -- for Iterator in [reverse] Array'Range (Array_Dim - Dim) loop
3715 -- <core loop>
3716 -- end loop;
3718 Core_Loop :=
3719 Make_Loop_Statement (Loc,
3720 Iteration_Scheme =>
3721 Make_Iteration_Scheme (Loc,
3722 Loop_Parameter_Specification =>
3723 Make_Loop_Parameter_Specification (Loc,
3724 Defining_Identifier => Iterator,
3725 Discrete_Subtype_Definition =>
3726 Make_Attribute_Reference (Loc,
3727 Prefix => Relocate_Node (Array_Node),
3728 Attribute_Name => Name_Range,
3729 Expressions => New_List (
3730 Make_Integer_Literal (Loc, Dim1))),
3731 Reverse_Present => Reverse_Present (I_Spec))),
3732 Statements => New_List (Core_Loop),
3733 End_Label => Empty);
3735 -- Update the previously created object renaming declaration with
3736 -- the new iterator, by adding the index of the next loop to the
3737 -- indexed component, in the order that corresponds to the
3738 -- convention.
3740 if Convention (Array_Typ) = Convention_Fortran then
3741 Append_To (Expressions (Ind_Comp),
3742 New_Occurrence_Of (Iterator, Loc));
3743 else
3744 Prepend_To (Expressions (Ind_Comp),
3745 New_Occurrence_Of (Iterator, Loc));
3746 end if;
3747 end loop;
3748 end if;
3750 -- Inherit the loop identifier from the original loop. This ensures that
3751 -- the scope stack is consistent after the rewriting.
3753 if Present (Identifier (N)) then
3754 Set_Identifier (Core_Loop, Relocate_Node (Identifier (N)));
3755 end if;
3757 Rewrite (N, Core_Loop);
3758 Analyze (N);
3759 end Expand_Iterator_Loop_Over_Array;
3761 -----------------------------------------
3762 -- Expand_Iterator_Loop_Over_Container --
3763 -----------------------------------------
3765 -- For a 'for ... in' loop, such as:
3767 -- for Cursor in Iterator_Function (...) loop
3768 -- ...
3769 -- end loop;
3771 -- we generate:
3773 -- Iter : Iterator_Type := Iterator_Function (...);
3774 -- Cursor : Cursor_type := First (Iter); -- or Last for "reverse"
3775 -- while Has_Element (Cursor) loop
3776 -- ...
3778 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
3779 -- end loop;
3781 -- For a 'for ... of' loop, such as:
3783 -- for X of Container loop
3784 -- ...
3785 -- end loop;
3787 -- the RM implies the generation of:
3789 -- Iter : Iterator_Type := Container.Iterate; -- the Default_Iterator
3790 -- Cursor : Cursor_Type := First (Iter); -- or Last for "reverse"
3791 -- while Has_Element (Cursor) loop
3792 -- declare
3793 -- X : Element_Type renames Element (Cursor).Element.all;
3794 -- -- or Constant_Element
3795 -- begin
3796 -- ...
3797 -- end;
3798 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
3799 -- end loop;
3801 -- In the general case, we do what the RM says. However, the operations
3802 -- Element and Iter.Next are slow, which is bad inside a loop, because they
3803 -- involve dispatching via interfaces, secondary stack manipulation,
3804 -- Busy/Lock incr/decr, and adjust/finalization/at-end handling. So for the
3805 -- predefined containers, we use an equivalent but optimized expansion.
3807 -- In the optimized case, we make use of these:
3809 -- procedure Next (Position : in out Cursor); -- instead of Iter.Next
3811 -- function Pseudo_Reference
3812 -- (Container : aliased Vector'Class) return Reference_Control_Type;
3814 -- type Element_Access is access all Element_Type;
3816 -- function Get_Element_Access
3817 -- (Position : Cursor) return not null Element_Access;
3819 -- Next is declared in the visible part of the container packages.
3820 -- The other three are added in the private part. (We're not supposed to
3821 -- pollute the namespace for clients. The compiler has no trouble breaking
3822 -- privacy to call things in the private part of an instance.)
3824 -- Source:
3826 -- for X of My_Vector loop
3827 -- X.Count := X.Count + 1;
3828 -- ...
3829 -- end loop;
3831 -- The compiler will generate:
3833 -- Iter : Reversible_Iterator'Class := Iterate (My_Vector);
3834 -- -- Reversible_Iterator is an interface. Iterate is the
3835 -- -- Default_Iterator aspect of Vector. This increments Lock,
3836 -- -- disallowing tampering with cursors. Unfortunately, it does not
3837 -- -- increment Busy. The result of Iterate is Limited_Controlled;
3838 -- -- finalization will decrement Lock. This is a build-in-place
3839 -- -- dispatching call to Iterate.
3841 -- Cur : Cursor := First (Iter); -- or Last
3842 -- -- Dispatching call via interface.
3844 -- Control : Reference_Control_Type := Pseudo_Reference (My_Vector);
3845 -- -- Pseudo_Reference increments Busy, to detect tampering with
3846 -- -- elements, as required by RM. Also redundantly increment
3847 -- -- Lock. Finalization of Control will decrement both Busy and
3848 -- -- Lock. Pseudo_Reference returns a record containing a pointer to
3849 -- -- My_Vector, used by Finalize.
3850 -- --
3851 -- -- Control is not used below, except to finalize it -- it's purely
3852 -- -- an RAII thing. This is needed because we are eliminating the
3853 -- -- call to Reference within the loop.
3855 -- while Has_Element (Cur) loop
3856 -- declare
3857 -- X : My_Element renames Get_Element_Access (Cur).all;
3858 -- -- Get_Element_Access returns a pointer to the element
3859 -- -- designated by Cur. No dispatching here, and no horsing
3860 -- -- around with access discriminants. This is instead of the
3861 -- -- existing
3862 -- --
3863 -- -- X : My_Element renames Reference (Cur).Element.all;
3864 -- --
3865 -- -- which creates a controlled object.
3866 -- begin
3867 -- -- Any attempt to tamper with My_Vector here in the loop
3868 -- -- will correctly raise Program_Error, because of the
3869 -- -- Control.
3871 -- X.Count := X.Count + 1;
3872 -- ...
3874 -- Next (Cur); -- or Prev
3875 -- -- This is instead of "Cur := Next (Iter, Cur);"
3876 -- end;
3877 -- -- No finalization here
3878 -- end loop;
3879 -- Finalize Iter and Control here, decrementing Lock twice and Busy
3880 -- once.
3882 -- This optimization makes "for ... of" loops over 30 times faster in cases
3883 -- measured.
3885 procedure Expand_Iterator_Loop_Over_Container
3886 (N : Node_Id;
3887 Isc : Node_Id;
3888 I_Spec : Node_Id;
3889 Container : Node_Id;
3890 Container_Typ : Entity_Id)
3892 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3893 Elem_Typ : constant Entity_Id := Etype (Id);
3894 Id_Kind : constant Entity_Kind := Ekind (Id);
3895 Loc : constant Source_Ptr := Sloc (N);
3896 Stats : constant List_Id := Statements (N);
3898 Cursor : Entity_Id;
3899 Decl : Node_Id;
3900 Iter_Type : Entity_Id;
3901 Iterator : Entity_Id;
3902 Name_Init : Name_Id;
3903 Name_Step : Name_Id;
3904 New_Loop : Node_Id;
3906 Fast_Element_Access_Op : Entity_Id := Empty;
3907 Fast_Step_Op : Entity_Id := Empty;
3908 -- Only for optimized version of "for ... of"
3910 Iter_Pack : Entity_Id;
3911 -- The package in which the iterator interface is instantiated. This is
3912 -- typically an instance within the container package.
3914 Pack : Entity_Id;
3915 -- The package in which the container type is declared
3917 begin
3918 -- Determine the advancement and initialization steps for the cursor.
3919 -- Analysis of the expanded loop will verify that the container has a
3920 -- reverse iterator.
3922 if Reverse_Present (I_Spec) then
3923 Name_Init := Name_Last;
3924 Name_Step := Name_Previous;
3925 else
3926 Name_Init := Name_First;
3927 Name_Step := Name_Next;
3928 end if;
3930 -- The type of the iterator is the return type of the Iterate function
3931 -- used. For the "of" form this is the default iterator for the type,
3932 -- otherwise it is the type of the explicit function used in the
3933 -- iterator specification. The most common case will be an Iterate
3934 -- function in the container package.
3936 -- The Iterator type is declared in an instance within the container
3937 -- package itself, for example:
3939 -- package Vector_Iterator_Interfaces is new
3940 -- Ada.Iterator_Interfaces (Cursor, Has_Element);
3942 -- If the container type is a derived type, the cursor type is found in
3943 -- the package of the ultimate ancestor type.
3945 if Is_Derived_Type (Container_Typ) then
3946 Pack := Scope (Root_Type (Container_Typ));
3947 else
3948 Pack := Scope (Container_Typ);
3949 end if;
3951 if Of_Present (I_Spec) then
3952 Handle_Of : declare
3953 Container_Arg : Node_Id;
3955 function Get_Default_Iterator
3956 (T : Entity_Id) return Entity_Id;
3957 -- Return the default iterator for a specific type. If the type is
3958 -- derived, we return the inherited or overridden one if
3959 -- appropriate.
3961 --------------------------
3962 -- Get_Default_Iterator --
3963 --------------------------
3965 function Get_Default_Iterator
3966 (T : Entity_Id) return Entity_Id
3968 Iter : constant Entity_Id :=
3969 Entity (Find_Value_Of_Aspect (T, Aspect_Default_Iterator));
3970 Prim : Elmt_Id;
3971 Op : Entity_Id;
3973 begin
3974 Container_Arg := New_Copy_Tree (Container);
3976 -- A previous version of GNAT allowed indexing aspects to be
3977 -- redefined on derived container types, while the default
3978 -- iterator was inherited from the parent type. This
3979 -- nonstandard extension is preserved for use by the
3980 -- modeling project under debug flag -gnatd.X.
3982 if Debug_Flag_Dot_XX then
3983 if Base_Type (Etype (Container)) /=
3984 Base_Type (Etype (First_Formal (Iter)))
3985 then
3986 Container_Arg :=
3987 Make_Type_Conversion (Loc,
3988 Subtype_Mark =>
3989 New_Occurrence_Of
3990 (Etype (First_Formal (Iter)), Loc),
3991 Expression => Container_Arg);
3992 end if;
3994 return Iter;
3996 elsif Is_Derived_Type (T) then
3998 -- The default iterator must be a primitive operation of the
3999 -- type, at the same dispatch slot position. The DT position
4000 -- may not be established if type is not frozen yet.
4002 Prim := First_Elmt (Primitive_Operations (T));
4003 while Present (Prim) loop
4004 Op := Node (Prim);
4006 if Alias (Op) = Iter
4007 or else
4008 (Chars (Op) = Chars (Iter)
4009 and then Present (DTC_Entity (Op))
4010 and then DT_Position (Op) = DT_Position (Iter))
4011 then
4012 return Op;
4013 end if;
4015 Next_Elmt (Prim);
4016 end loop;
4018 -- If we didn't find it, then our parent type is not
4019 -- iterable, so we return the Default_Iterator aspect of
4020 -- this type.
4022 return Iter;
4024 -- Otherwise not a derived type
4026 else
4027 return Iter;
4028 end if;
4029 end Get_Default_Iterator;
4031 -- Local variables
4033 Default_Iter : Entity_Id;
4034 Ent : Entity_Id;
4036 Reference_Control_Type : Entity_Id := Empty;
4037 Pseudo_Reference : Entity_Id := Empty;
4039 -- Start of processing for Handle_Of
4041 begin
4042 if Is_Class_Wide_Type (Container_Typ) then
4043 Default_Iter :=
4044 Get_Default_Iterator (Etype (Base_Type (Container_Typ)));
4045 else
4046 Default_Iter := Get_Default_Iterator (Etype (Container));
4047 end if;
4049 Cursor := Make_Temporary (Loc, 'C');
4051 -- For a container element iterator, the iterator type is obtained
4052 -- from the corresponding aspect, whose return type is descended
4053 -- from the corresponding interface type in some instance of
4054 -- Ada.Iterator_Interfaces. The actuals of that instantiation
4055 -- are Cursor and Has_Element.
4057 Iter_Type := Etype (Default_Iter);
4059 -- The iterator type, which is a class-wide type, may itself be
4060 -- derived locally, so the desired instantiation is the scope of
4061 -- the root type of the iterator type.
4063 Iter_Pack := Scope (Root_Type (Etype (Iter_Type)));
4065 -- Find declarations needed for "for ... of" optimization
4067 Ent := First_Entity (Pack);
4068 while Present (Ent) loop
4069 if Chars (Ent) = Name_Get_Element_Access then
4070 Fast_Element_Access_Op := Ent;
4072 elsif Chars (Ent) = Name_Step
4073 and then Ekind (Ent) = E_Procedure
4074 then
4075 Fast_Step_Op := Ent;
4077 elsif Chars (Ent) = Name_Reference_Control_Type then
4078 Reference_Control_Type := Ent;
4080 elsif Chars (Ent) = Name_Pseudo_Reference then
4081 Pseudo_Reference := Ent;
4082 end if;
4084 Next_Entity (Ent);
4085 end loop;
4087 if Present (Reference_Control_Type)
4088 and then Present (Pseudo_Reference)
4089 then
4090 Insert_Action (N,
4091 Make_Object_Declaration (Loc,
4092 Defining_Identifier => Make_Temporary (Loc, 'D'),
4093 Object_Definition =>
4094 New_Occurrence_Of (Reference_Control_Type, Loc),
4095 Expression =>
4096 Make_Function_Call (Loc,
4097 Name =>
4098 New_Occurrence_Of (Pseudo_Reference, Loc),
4099 Parameter_Associations =>
4100 New_List (New_Copy_Tree (Container_Arg)))));
4101 end if;
4103 -- Rewrite domain of iteration as a call to the default iterator
4104 -- for the container type. The formal may be an access parameter
4105 -- in which case we must build a reference to the container.
4107 declare
4108 Arg : Node_Id;
4109 begin
4110 if Is_Access_Type (Etype (First_Entity (Default_Iter))) then
4111 Arg :=
4112 Make_Attribute_Reference (Loc,
4113 Prefix => Container_Arg,
4114 Attribute_Name => Name_Unrestricted_Access);
4115 else
4116 Arg := Container_Arg;
4117 end if;
4119 Rewrite (Name (I_Spec),
4120 Make_Function_Call (Loc,
4121 Name =>
4122 New_Occurrence_Of (Default_Iter, Loc),
4123 Parameter_Associations => New_List (Arg)));
4124 end;
4126 Analyze_And_Resolve (Name (I_Spec));
4128 -- Find cursor type in proper iterator package, which is an
4129 -- instantiation of Iterator_Interfaces.
4131 Ent := First_Entity (Iter_Pack);
4132 while Present (Ent) loop
4133 if Chars (Ent) = Name_Cursor then
4134 Set_Etype (Cursor, Etype (Ent));
4135 exit;
4136 end if;
4138 Next_Entity (Ent);
4139 end loop;
4141 if Present (Fast_Element_Access_Op) then
4142 Decl :=
4143 Make_Object_Renaming_Declaration (Loc,
4144 Defining_Identifier => Id,
4145 Subtype_Mark =>
4146 New_Occurrence_Of (Elem_Typ, Loc),
4147 Name =>
4148 Make_Explicit_Dereference (Loc,
4149 Prefix =>
4150 Make_Function_Call (Loc,
4151 Name =>
4152 New_Occurrence_Of (Fast_Element_Access_Op, Loc),
4153 Parameter_Associations =>
4154 New_List (New_Occurrence_Of (Cursor, Loc)))));
4156 else
4157 Decl :=
4158 Make_Object_Renaming_Declaration (Loc,
4159 Defining_Identifier => Id,
4160 Subtype_Mark =>
4161 New_Occurrence_Of (Elem_Typ, Loc),
4162 Name =>
4163 Make_Indexed_Component (Loc,
4164 Prefix => Relocate_Node (Container_Arg),
4165 Expressions =>
4166 New_List (New_Occurrence_Of (Cursor, Loc))));
4167 end if;
4169 -- The defining identifier in the iterator is user-visible and
4170 -- must be visible in the debugger.
4172 Set_Debug_Info_Needed (Id);
4174 -- If the container does not have a variable indexing aspect,
4175 -- the element is a constant in the loop. The container itself
4176 -- may be constant, in which case the element is a constant as
4177 -- well. The container has been rewritten as a call to Iterate,
4178 -- so examine original node.
4180 if No (Find_Value_Of_Aspect
4181 (Container_Typ, Aspect_Variable_Indexing))
4182 or else not Is_Variable (Original_Node (Container))
4183 then
4184 Set_Ekind (Id, E_Constant);
4185 end if;
4187 Prepend_To (Stats, Decl);
4188 end Handle_Of;
4190 -- X in Iterate (S) : type of iterator is type of explicitly given
4191 -- Iterate function, and the loop variable is the cursor. It will be
4192 -- assigned in the loop and must be a variable.
4194 else
4195 Iter_Type := Etype (Name (I_Spec));
4197 -- The iterator type, which is a class-wide type, may itself be
4198 -- derived locally, so the desired instantiation is the scope of
4199 -- the root type of the iterator type, as in the "of" case.
4201 Iter_Pack := Scope (Root_Type (Etype (Iter_Type)));
4202 Cursor := Id;
4203 end if;
4205 Iterator := Make_Temporary (Loc, 'I');
4207 -- For both iterator forms, add a call to the step operation to advance
4208 -- the cursor. Generate:
4210 -- Cursor := Iterator.Next (Cursor);
4212 -- or else
4214 -- Cursor := Next (Cursor);
4216 if Present (Fast_Element_Access_Op) and then Present (Fast_Step_Op) then
4217 declare
4218 Curs_Name : constant Node_Id := New_Occurrence_Of (Cursor, Loc);
4219 Step_Call : Node_Id;
4221 begin
4222 Step_Call :=
4223 Make_Procedure_Call_Statement (Loc,
4224 Name =>
4225 New_Occurrence_Of (Fast_Step_Op, Loc),
4226 Parameter_Associations => New_List (Curs_Name));
4228 Append_To (Stats, Step_Call);
4229 Set_Assignment_OK (Curs_Name);
4230 end;
4232 else
4233 declare
4234 Rhs : Node_Id;
4236 begin
4237 Rhs :=
4238 Make_Function_Call (Loc,
4239 Name =>
4240 Make_Selected_Component (Loc,
4241 Prefix => New_Occurrence_Of (Iterator, Loc),
4242 Selector_Name => Make_Identifier (Loc, Name_Step)),
4243 Parameter_Associations => New_List (
4244 New_Occurrence_Of (Cursor, Loc)));
4246 Append_To (Stats,
4247 Make_Assignment_Statement (Loc,
4248 Name => New_Occurrence_Of (Cursor, Loc),
4249 Expression => Rhs));
4250 Set_Assignment_OK (Name (Last (Stats)));
4251 end;
4252 end if;
4254 -- Generate:
4255 -- while Has_Element (Cursor) loop
4256 -- <Stats>
4257 -- end loop;
4259 -- Has_Element is the second actual in the iterator package
4261 New_Loop :=
4262 Make_Loop_Statement (Loc,
4263 Iteration_Scheme =>
4264 Make_Iteration_Scheme (Loc,
4265 Condition =>
4266 Make_Function_Call (Loc,
4267 Name =>
4268 New_Occurrence_Of
4269 (Next_Entity (First_Entity (Iter_Pack)), Loc),
4270 Parameter_Associations => New_List (
4271 New_Occurrence_Of (Cursor, Loc)))),
4273 Statements => Stats,
4274 End_Label => Empty);
4276 -- If present, preserve identifier of loop, which can be used in an exit
4277 -- statement in the body.
4279 if Present (Identifier (N)) then
4280 Set_Identifier (New_Loop, Relocate_Node (Identifier (N)));
4281 end if;
4283 -- Create the declarations for Iterator and cursor and insert them
4284 -- before the source loop. Given that the domain of iteration is already
4285 -- an entity, the iterator is just a renaming of that entity. Possible
4286 -- optimization ???
4288 Insert_Action (N,
4289 Make_Object_Renaming_Declaration (Loc,
4290 Defining_Identifier => Iterator,
4291 Subtype_Mark => New_Occurrence_Of (Iter_Type, Loc),
4292 Name => Relocate_Node (Name (I_Spec))));
4294 -- Create declaration for cursor
4296 declare
4297 Cursor_Decl : constant Node_Id :=
4298 Make_Object_Declaration (Loc,
4299 Defining_Identifier => Cursor,
4300 Object_Definition =>
4301 New_Occurrence_Of (Etype (Cursor), Loc),
4302 Expression =>
4303 Make_Selected_Component (Loc,
4304 Prefix =>
4305 New_Occurrence_Of (Iterator, Loc),
4306 Selector_Name =>
4307 Make_Identifier (Loc, Name_Init)));
4309 begin
4310 -- The cursor is only modified in expanded code, so it appears
4311 -- as unassigned to the warning machinery. We must suppress this
4312 -- spurious warning explicitly. The cursor's kind is that of the
4313 -- original loop parameter (it is a constant if the domain of
4314 -- iteration is constant).
4316 Set_Warnings_Off (Cursor);
4317 Set_Assignment_OK (Cursor_Decl);
4319 Insert_Action (N, Cursor_Decl);
4320 Set_Ekind (Cursor, Id_Kind);
4321 end;
4323 -- If the range of iteration is given by a function call that returns
4324 -- a container, the finalization actions have been saved in the
4325 -- Condition_Actions of the iterator. Insert them now at the head of
4326 -- the loop.
4328 if Present (Condition_Actions (Isc)) then
4329 Insert_List_Before (N, Condition_Actions (Isc));
4330 end if;
4332 Rewrite (N, New_Loop);
4333 Analyze (N);
4334 end Expand_Iterator_Loop_Over_Container;
4336 -----------------------------
4337 -- Expand_N_Loop_Statement --
4338 -----------------------------
4340 -- 1. Remove null loop entirely
4341 -- 2. Deal with while condition for C/Fortran boolean
4342 -- 3. Deal with loops with a non-standard enumeration type range
4343 -- 4. Deal with while loops where Condition_Actions is set
4344 -- 5. Deal with loops over predicated subtypes
4345 -- 6. Deal with loops with iterators over arrays and containers
4346 -- 7. Insert polling call if required
4348 procedure Expand_N_Loop_Statement (N : Node_Id) is
4349 Loc : constant Source_Ptr := Sloc (N);
4350 Scheme : constant Node_Id := Iteration_Scheme (N);
4351 Stmt : Node_Id;
4353 begin
4354 -- Delete null loop
4356 if Is_Null_Loop (N) then
4357 Rewrite (N, Make_Null_Statement (Loc));
4358 return;
4359 end if;
4361 -- Deal with condition for C/Fortran Boolean
4363 if Present (Scheme) then
4364 Adjust_Condition (Condition (Scheme));
4365 end if;
4367 -- Generate polling call
4369 if Is_Non_Empty_List (Statements (N)) then
4370 Generate_Poll_Call (First (Statements (N)));
4371 end if;
4373 -- Nothing more to do for plain loop with no iteration scheme
4375 if No (Scheme) then
4376 null;
4378 -- Case of for loop (Loop_Parameter_Specification present)
4380 -- Note: we do not have to worry about validity checking of the for loop
4381 -- range bounds here, since they were frozen with constant declarations
4382 -- and it is during that process that the validity checking is done.
4384 elsif Present (Loop_Parameter_Specification (Scheme)) then
4385 declare
4386 LPS : constant Node_Id :=
4387 Loop_Parameter_Specification (Scheme);
4388 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4389 Ltype : constant Entity_Id := Etype (Loop_Id);
4390 Btype : constant Entity_Id := Base_Type (Ltype);
4391 Expr : Node_Id;
4392 Decls : List_Id;
4393 New_Id : Entity_Id;
4395 begin
4396 -- Deal with loop over predicates
4398 if Is_Discrete_Type (Ltype)
4399 and then Present (Predicate_Function (Ltype))
4400 then
4401 Expand_Predicated_Loop (N);
4403 -- Handle the case where we have a for loop with the range type
4404 -- being an enumeration type with non-standard representation.
4405 -- In this case we expand:
4407 -- for x in [reverse] a .. b loop
4408 -- ...
4409 -- end loop;
4411 -- to
4413 -- for xP in [reverse] integer
4414 -- range etype'Pos (a) .. etype'Pos (b)
4415 -- loop
4416 -- declare
4417 -- x : constant etype := Pos_To_Rep (xP);
4418 -- begin
4419 -- ...
4420 -- end;
4421 -- end loop;
4423 elsif Is_Enumeration_Type (Btype)
4424 and then Present (Enum_Pos_To_Rep (Btype))
4425 then
4426 New_Id :=
4427 Make_Defining_Identifier (Loc,
4428 Chars => New_External_Name (Chars (Loop_Id), 'P'));
4430 -- If the type has a contiguous representation, successive
4431 -- values can be generated as offsets from the first literal.
4433 if Has_Contiguous_Rep (Btype) then
4434 Expr :=
4435 Unchecked_Convert_To (Btype,
4436 Make_Op_Add (Loc,
4437 Left_Opnd =>
4438 Make_Integer_Literal (Loc,
4439 Enumeration_Rep (First_Literal (Btype))),
4440 Right_Opnd => New_Occurrence_Of (New_Id, Loc)));
4441 else
4442 -- Use the constructed array Enum_Pos_To_Rep
4444 Expr :=
4445 Make_Indexed_Component (Loc,
4446 Prefix =>
4447 New_Occurrence_Of (Enum_Pos_To_Rep (Btype), Loc),
4448 Expressions =>
4449 New_List (New_Occurrence_Of (New_Id, Loc)));
4450 end if;
4452 -- Build declaration for loop identifier
4454 Decls :=
4455 New_List (
4456 Make_Object_Declaration (Loc,
4457 Defining_Identifier => Loop_Id,
4458 Constant_Present => True,
4459 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4460 Expression => Expr));
4462 Rewrite (N,
4463 Make_Loop_Statement (Loc,
4464 Identifier => Identifier (N),
4466 Iteration_Scheme =>
4467 Make_Iteration_Scheme (Loc,
4468 Loop_Parameter_Specification =>
4469 Make_Loop_Parameter_Specification (Loc,
4470 Defining_Identifier => New_Id,
4471 Reverse_Present => Reverse_Present (LPS),
4473 Discrete_Subtype_Definition =>
4474 Make_Subtype_Indication (Loc,
4476 Subtype_Mark =>
4477 New_Occurrence_Of (Standard_Natural, Loc),
4479 Constraint =>
4480 Make_Range_Constraint (Loc,
4481 Range_Expression =>
4482 Make_Range (Loc,
4484 Low_Bound =>
4485 Make_Attribute_Reference (Loc,
4486 Prefix =>
4487 New_Occurrence_Of (Btype, Loc),
4489 Attribute_Name => Name_Pos,
4491 Expressions => New_List (
4492 Relocate_Node
4493 (Type_Low_Bound (Ltype)))),
4495 High_Bound =>
4496 Make_Attribute_Reference (Loc,
4497 Prefix =>
4498 New_Occurrence_Of (Btype, Loc),
4500 Attribute_Name => Name_Pos,
4502 Expressions => New_List (
4503 Relocate_Node
4504 (Type_High_Bound
4505 (Ltype))))))))),
4507 Statements => New_List (
4508 Make_Block_Statement (Loc,
4509 Declarations => Decls,
4510 Handled_Statement_Sequence =>
4511 Make_Handled_Sequence_Of_Statements (Loc,
4512 Statements => Statements (N)))),
4514 End_Label => End_Label (N)));
4516 -- The loop parameter's entity must be removed from the loop
4517 -- scope's entity list and rendered invisible, since it will
4518 -- now be located in the new block scope. Any other entities
4519 -- already associated with the loop scope, such as the loop
4520 -- parameter's subtype, will remain there.
4522 -- In an element loop, the loop will contain a declaration for
4523 -- a cursor variable; otherwise the loop id is the first entity
4524 -- in the scope constructed for the loop.
4526 if Comes_From_Source (Loop_Id) then
4527 pragma Assert (First_Entity (Scope (Loop_Id)) = Loop_Id);
4528 null;
4529 end if;
4531 Set_First_Entity (Scope (Loop_Id), Next_Entity (Loop_Id));
4532 Remove_Homonym (Loop_Id);
4534 if Last_Entity (Scope (Loop_Id)) = Loop_Id then
4535 Set_Last_Entity (Scope (Loop_Id), Empty);
4536 end if;
4538 Analyze (N);
4540 -- Nothing to do with other cases of for loops
4542 else
4543 null;
4544 end if;
4545 end;
4547 -- Second case, if we have a while loop with Condition_Actions set, then
4548 -- we change it into a plain loop:
4550 -- while C loop
4551 -- ...
4552 -- end loop;
4554 -- changed to:
4556 -- loop
4557 -- <<condition actions>>
4558 -- exit when not C;
4559 -- ...
4560 -- end loop
4562 elsif Present (Scheme)
4563 and then Present (Condition_Actions (Scheme))
4564 and then Present (Condition (Scheme))
4565 then
4566 declare
4567 ES : Node_Id;
4569 begin
4570 ES :=
4571 Make_Exit_Statement (Sloc (Condition (Scheme)),
4572 Condition =>
4573 Make_Op_Not (Sloc (Condition (Scheme)),
4574 Right_Opnd => Condition (Scheme)));
4576 Prepend (ES, Statements (N));
4577 Insert_List_Before (ES, Condition_Actions (Scheme));
4579 -- This is not an implicit loop, since it is generated in response
4580 -- to the loop statement being processed. If this is itself
4581 -- implicit, the restriction has already been checked. If not,
4582 -- it is an explicit loop.
4584 Rewrite (N,
4585 Make_Loop_Statement (Sloc (N),
4586 Identifier => Identifier (N),
4587 Statements => Statements (N),
4588 End_Label => End_Label (N)));
4590 Analyze (N);
4591 end;
4593 -- Here to deal with iterator case
4595 elsif Present (Scheme)
4596 and then Present (Iterator_Specification (Scheme))
4597 then
4598 Expand_Iterator_Loop (N);
4600 -- An iterator loop may generate renaming declarations for elements
4601 -- that require debug information. This is the case in particular
4602 -- with element iterators, where debug information must be generated
4603 -- for the temporary that holds the element value. These temporaries
4604 -- are created within a transient block whose local declarations are
4605 -- transferred to the loop, which now has nontrivial local objects.
4607 if Nkind (N) = N_Loop_Statement
4608 and then Present (Identifier (N))
4609 then
4610 Qualify_Entity_Names (N);
4611 end if;
4612 end if;
4614 -- When the iteration scheme mentiones attribute 'Loop_Entry, the loop
4615 -- is transformed into a conditional block where the original loop is
4616 -- the sole statement. Inspect the statements of the nested loop for
4617 -- controlled objects.
4619 Stmt := N;
4621 if Subject_To_Loop_Entry_Attributes (Stmt) then
4622 Stmt := Find_Loop_In_Conditional_Block (Stmt);
4623 end if;
4625 Process_Statements_For_Controlled_Objects (Stmt);
4626 end Expand_N_Loop_Statement;
4628 ----------------------------
4629 -- Expand_Predicated_Loop --
4630 ----------------------------
4632 -- Note: the expander can handle generation of loops over predicated
4633 -- subtypes for both the dynamic and static cases. Depending on what
4634 -- we decide is allowed in Ada 2012 mode and/or extensions allowed
4635 -- mode, the semantic analyzer may disallow one or both forms.
4637 procedure Expand_Predicated_Loop (N : Node_Id) is
4638 Loc : constant Source_Ptr := Sloc (N);
4639 Isc : constant Node_Id := Iteration_Scheme (N);
4640 LPS : constant Node_Id := Loop_Parameter_Specification (Isc);
4641 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4642 Ltype : constant Entity_Id := Etype (Loop_Id);
4643 Stat : constant List_Id := Static_Discrete_Predicate (Ltype);
4644 Stmts : constant List_Id := Statements (N);
4646 begin
4647 -- Case of iteration over non-static predicate, should not be possible
4648 -- since this is not allowed by the semantics and should have been
4649 -- caught during analysis of the loop statement.
4651 if No (Stat) then
4652 raise Program_Error;
4654 -- If the predicate list is empty, that corresponds to a predicate of
4655 -- False, in which case the loop won't run at all, and we rewrite the
4656 -- entire loop as a null statement.
4658 elsif Is_Empty_List (Stat) then
4659 Rewrite (N, Make_Null_Statement (Loc));
4660 Analyze (N);
4662 -- For expansion over a static predicate we generate the following
4664 -- declare
4665 -- J : Ltype := min-val;
4666 -- begin
4667 -- loop
4668 -- body
4669 -- case J is
4670 -- when endpoint => J := startpoint;
4671 -- when endpoint => J := startpoint;
4672 -- ...
4673 -- when max-val => exit;
4674 -- when others => J := Lval'Succ (J);
4675 -- end case;
4676 -- end loop;
4677 -- end;
4679 -- with min-val replaced by max-val and Succ replaced by Pred if the
4680 -- loop parameter specification carries a Reverse indicator.
4682 -- To make this a little clearer, let's take a specific example:
4684 -- type Int is range 1 .. 10;
4685 -- subtype StaticP is Int with
4686 -- predicate => StaticP in 3 | 10 | 5 .. 7;
4687 -- ...
4688 -- for L in StaticP loop
4689 -- Put_Line ("static:" & J'Img);
4690 -- end loop;
4692 -- In this case, the loop is transformed into
4694 -- begin
4695 -- J : L := 3;
4696 -- loop
4697 -- body
4698 -- case J is
4699 -- when 3 => J := 5;
4700 -- when 7 => J := 10;
4701 -- when 10 => exit;
4702 -- when others => J := L'Succ (J);
4703 -- end case;
4704 -- end loop;
4705 -- end;
4707 -- In addition, if the loop specification is given by a subtype
4708 -- indication that constrains a predicated type, the bounds of
4709 -- iteration are given by those of the subtype indication.
4711 else
4712 Static_Predicate : declare
4713 S : Node_Id;
4714 D : Node_Id;
4715 P : Node_Id;
4716 Alts : List_Id;
4717 Cstm : Node_Id;
4719 -- If the domain is an itype, note the bounds of its range.
4721 L_Hi : Node_Id;
4722 L_Lo : Node_Id;
4724 function Lo_Val (N : Node_Id) return Node_Id;
4725 -- Given static expression or static range, returns an identifier
4726 -- whose value is the low bound of the expression value or range.
4728 function Hi_Val (N : Node_Id) return Node_Id;
4729 -- Given static expression or static range, returns an identifier
4730 -- whose value is the high bound of the expression value or range.
4732 ------------
4733 -- Hi_Val --
4734 ------------
4736 function Hi_Val (N : Node_Id) return Node_Id is
4737 begin
4738 if Is_OK_Static_Expression (N) then
4739 return New_Copy (N);
4740 else
4741 pragma Assert (Nkind (N) = N_Range);
4742 return New_Copy (High_Bound (N));
4743 end if;
4744 end Hi_Val;
4746 ------------
4747 -- Lo_Val --
4748 ------------
4750 function Lo_Val (N : Node_Id) return Node_Id is
4751 begin
4752 if Is_OK_Static_Expression (N) then
4753 return New_Copy (N);
4754 else
4755 pragma Assert (Nkind (N) = N_Range);
4756 return New_Copy (Low_Bound (N));
4757 end if;
4758 end Lo_Val;
4760 -- Start of processing for Static_Predicate
4762 begin
4763 -- Convert loop identifier to normal variable and reanalyze it so
4764 -- that this conversion works. We have to use the same defining
4765 -- identifier, since there may be references in the loop body.
4767 Set_Analyzed (Loop_Id, False);
4768 Set_Ekind (Loop_Id, E_Variable);
4770 -- In most loops the loop variable is assigned in various
4771 -- alternatives in the body. However, in the rare case when
4772 -- the range specifies a single element, the loop variable
4773 -- may trigger a spurious warning that is could be constant.
4774 -- This warning might as well be suppressed.
4776 Set_Warnings_Off (Loop_Id);
4778 if Is_Itype (Ltype) then
4779 L_Hi := High_Bound (Scalar_Range (Ltype));
4780 L_Lo := Low_Bound (Scalar_Range (Ltype));
4781 end if;
4783 -- Loop to create branches of case statement
4785 Alts := New_List;
4787 if Reverse_Present (LPS) then
4789 -- Initial value is largest value in predicate.
4791 if Is_Itype (Ltype) then
4792 D :=
4793 Make_Object_Declaration (Loc,
4794 Defining_Identifier => Loop_Id,
4795 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4796 Expression => L_Hi);
4798 else
4799 D :=
4800 Make_Object_Declaration (Loc,
4801 Defining_Identifier => Loop_Id,
4802 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4803 Expression => Hi_Val (Last (Stat)));
4804 end if;
4806 P := Last (Stat);
4807 while Present (P) loop
4808 if No (Prev (P)) then
4809 S := Make_Exit_Statement (Loc);
4810 else
4811 S :=
4812 Make_Assignment_Statement (Loc,
4813 Name => New_Occurrence_Of (Loop_Id, Loc),
4814 Expression => Hi_Val (Prev (P)));
4815 Set_Suppress_Assignment_Checks (S);
4816 end if;
4818 Append_To (Alts,
4819 Make_Case_Statement_Alternative (Loc,
4820 Statements => New_List (S),
4821 Discrete_Choices => New_List (Lo_Val (P))));
4823 Prev (P);
4824 end loop;
4826 if Is_Itype (Ltype)
4827 and then Is_OK_Static_Expression (L_Lo)
4828 and then
4829 Expr_Value (L_Lo) /= Expr_Value (Lo_Val (First (Stat)))
4830 then
4831 Append_To (Alts,
4832 Make_Case_Statement_Alternative (Loc,
4833 Statements => New_List (Make_Exit_Statement (Loc)),
4834 Discrete_Choices => New_List (L_Lo)));
4835 end if;
4837 else
4838 -- Initial value is smallest value in predicate
4840 if Is_Itype (Ltype) then
4841 D :=
4842 Make_Object_Declaration (Loc,
4843 Defining_Identifier => Loop_Id,
4844 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4845 Expression => L_Lo);
4846 else
4847 D :=
4848 Make_Object_Declaration (Loc,
4849 Defining_Identifier => Loop_Id,
4850 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4851 Expression => Lo_Val (First (Stat)));
4852 end if;
4854 P := First (Stat);
4855 while Present (P) loop
4856 if No (Next (P)) then
4857 S := Make_Exit_Statement (Loc);
4858 else
4859 S :=
4860 Make_Assignment_Statement (Loc,
4861 Name => New_Occurrence_Of (Loop_Id, Loc),
4862 Expression => Lo_Val (Next (P)));
4863 Set_Suppress_Assignment_Checks (S);
4864 end if;
4866 Append_To (Alts,
4867 Make_Case_Statement_Alternative (Loc,
4868 Statements => New_List (S),
4869 Discrete_Choices => New_List (Hi_Val (P))));
4871 Next (P);
4872 end loop;
4874 if Is_Itype (Ltype)
4875 and then Is_OK_Static_Expression (L_Hi)
4876 and then
4877 Expr_Value (L_Hi) /= Expr_Value (Lo_Val (Last (Stat)))
4878 then
4879 Append_To (Alts,
4880 Make_Case_Statement_Alternative (Loc,
4881 Statements => New_List (Make_Exit_Statement (Loc)),
4882 Discrete_Choices => New_List (L_Hi)));
4883 end if;
4884 end if;
4886 -- Add others choice
4888 declare
4889 Name_Next : Name_Id;
4891 begin
4892 if Reverse_Present (LPS) then
4893 Name_Next := Name_Pred;
4894 else
4895 Name_Next := Name_Succ;
4896 end if;
4898 S :=
4899 Make_Assignment_Statement (Loc,
4900 Name => New_Occurrence_Of (Loop_Id, Loc),
4901 Expression =>
4902 Make_Attribute_Reference (Loc,
4903 Prefix => New_Occurrence_Of (Ltype, Loc),
4904 Attribute_Name => Name_Next,
4905 Expressions => New_List (
4906 New_Occurrence_Of (Loop_Id, Loc))));
4907 Set_Suppress_Assignment_Checks (S);
4908 end;
4910 Append_To (Alts,
4911 Make_Case_Statement_Alternative (Loc,
4912 Discrete_Choices => New_List (Make_Others_Choice (Loc)),
4913 Statements => New_List (S)));
4915 -- Construct case statement and append to body statements
4917 Cstm :=
4918 Make_Case_Statement (Loc,
4919 Expression => New_Occurrence_Of (Loop_Id, Loc),
4920 Alternatives => Alts);
4921 Append_To (Stmts, Cstm);
4923 -- Rewrite the loop
4925 Set_Suppress_Assignment_Checks (D);
4927 Rewrite (N,
4928 Make_Block_Statement (Loc,
4929 Declarations => New_List (D),
4930 Handled_Statement_Sequence =>
4931 Make_Handled_Sequence_Of_Statements (Loc,
4932 Statements => New_List (
4933 Make_Loop_Statement (Loc,
4934 Statements => Stmts,
4935 End_Label => Empty)))));
4937 Analyze (N);
4938 end Static_Predicate;
4939 end if;
4940 end Expand_Predicated_Loop;
4942 ------------------------------
4943 -- Make_Tag_Ctrl_Assignment --
4944 ------------------------------
4946 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
4947 Asn : constant Node_Id := Relocate_Node (N);
4948 L : constant Node_Id := Name (N);
4949 Loc : constant Source_Ptr := Sloc (N);
4950 Res : constant List_Id := New_List;
4951 T : constant Entity_Id := Underlying_Type (Etype (L));
4953 Comp_Asn : constant Boolean := Is_Fully_Repped_Tagged_Type (T);
4954 Ctrl_Act : constant Boolean := Needs_Finalization (T)
4955 and then not No_Ctrl_Actions (N);
4956 Save_Tag : constant Boolean := Is_Tagged_Type (T)
4957 and then not Comp_Asn
4958 and then not No_Ctrl_Actions (N)
4959 and then Tagged_Type_Expansion;
4960 Adj_Call : Node_Id;
4961 Fin_Call : Node_Id;
4962 Tag_Id : Entity_Id;
4964 begin
4965 -- Finalize the target of the assignment when controlled
4967 -- We have two exceptions here:
4969 -- 1. If we are in an init proc since it is an initialization more
4970 -- than an assignment.
4972 -- 2. If the left-hand side is a temporary that was not initialized
4973 -- (or the parent part of a temporary since it is the case in
4974 -- extension aggregates). Such a temporary does not come from
4975 -- source. We must examine the original node for the prefix, because
4976 -- it may be a component of an entry formal, in which case it has
4977 -- been rewritten and does not appear to come from source either.
4979 -- Case of init proc
4981 if not Ctrl_Act then
4982 null;
4984 -- The left-hand side is an uninitialized temporary object
4986 elsif Nkind (L) = N_Type_Conversion
4987 and then Is_Entity_Name (Expression (L))
4988 and then Nkind (Parent (Entity (Expression (L)))) =
4989 N_Object_Declaration
4990 and then No_Initialization (Parent (Entity (Expression (L))))
4991 then
4992 null;
4994 else
4995 Fin_Call :=
4996 Make_Final_Call
4997 (Obj_Ref => Duplicate_Subexpr_No_Checks (L),
4998 Typ => Etype (L));
5000 if Present (Fin_Call) then
5001 Append_To (Res, Fin_Call);
5002 end if;
5003 end if;
5005 -- Save the Tag in a local variable Tag_Id
5007 if Save_Tag then
5008 Tag_Id := Make_Temporary (Loc, 'A');
5010 Append_To (Res,
5011 Make_Object_Declaration (Loc,
5012 Defining_Identifier => Tag_Id,
5013 Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc),
5014 Expression =>
5015 Make_Selected_Component (Loc,
5016 Prefix => Duplicate_Subexpr_No_Checks (L),
5017 Selector_Name =>
5018 New_Occurrence_Of (First_Tag_Component (T), Loc))));
5020 -- Otherwise Tag_Id is not used
5022 else
5023 Tag_Id := Empty;
5024 end if;
5026 -- If the tagged type has a full rep clause, expand the assignment into
5027 -- component-wise assignments. Mark the node as unanalyzed in order to
5028 -- generate the proper code and propagate this scenario by setting a
5029 -- flag to avoid infinite recursion.
5031 if Comp_Asn then
5032 Set_Analyzed (Asn, False);
5033 Set_Componentwise_Assignment (Asn, True);
5034 end if;
5036 Append_To (Res, Asn);
5038 -- Restore the tag
5040 if Save_Tag then
5041 Append_To (Res,
5042 Make_Assignment_Statement (Loc,
5043 Name =>
5044 Make_Selected_Component (Loc,
5045 Prefix => Duplicate_Subexpr_No_Checks (L),
5046 Selector_Name =>
5047 New_Occurrence_Of (First_Tag_Component (T), Loc)),
5048 Expression => New_Occurrence_Of (Tag_Id, Loc)));
5049 end if;
5051 -- Adjust the target after the assignment when controlled (not in the
5052 -- init proc since it is an initialization more than an assignment).
5054 if Ctrl_Act then
5055 Adj_Call :=
5056 Make_Adjust_Call
5057 (Obj_Ref => Duplicate_Subexpr_Move_Checks (L),
5058 Typ => Etype (L));
5060 if Present (Adj_Call) then
5061 Append_To (Res, Adj_Call);
5062 end if;
5063 end if;
5065 return Res;
5067 exception
5069 -- Could use comment here ???
5071 when RE_Not_Available =>
5072 return Empty_List;
5073 end Make_Tag_Ctrl_Assignment;
5075 end Exp_Ch5;