compiler: don't generate stubs for ambiguous direct interface methods
[official-gcc.git] / gcc / ada / exp_ch5.adb
blob2072935d2ca61a9b3d228ccad3135cd72bee1d25
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-2022, 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 Einfo.Entities; use Einfo.Entities;
32 with Einfo.Utils; use Einfo.Utils;
33 with Elists; use Elists;
34 with Exp_Aggr; use Exp_Aggr;
35 with Exp_Ch6; use Exp_Ch6;
36 with Exp_Ch7; use Exp_Ch7;
37 with Exp_Ch11; use Exp_Ch11;
38 with Exp_Dbug; use Exp_Dbug;
39 with Exp_Pakd; use Exp_Pakd;
40 with Exp_Tss; use Exp_Tss;
41 with Exp_Util; use Exp_Util;
42 with Inline; use Inline;
43 with Namet; use Namet;
44 with Nlists; use Nlists;
45 with Nmake; use Nmake;
46 with Opt; use Opt;
47 with Restrict; use Restrict;
48 with Rident; use Rident;
49 with Rtsfind; use Rtsfind;
50 with Sinfo; use Sinfo;
51 with Sinfo.Nodes; use Sinfo.Nodes;
52 with Sinfo.Utils; use Sinfo.Utils;
53 with Sem; use Sem;
54 with Sem_Aux; use Sem_Aux;
55 with Sem_Ch3; use Sem_Ch3;
56 with Sem_Ch8; use Sem_Ch8;
57 with Sem_Ch13; use Sem_Ch13;
58 with Sem_Eval; use Sem_Eval;
59 with Sem_Res; use Sem_Res;
60 with Sem_Util; use Sem_Util;
61 with Snames; use Snames;
62 with Stand; use Stand;
63 with Stringt; use Stringt;
64 with Tbuild; use Tbuild;
65 with Ttypes; use Ttypes;
66 with Uintp; use Uintp;
67 with Validsw; use Validsw;
69 package body Exp_Ch5 is
71 procedure Build_Formal_Container_Iteration
72 (N : Node_Id;
73 Container : Entity_Id;
74 Cursor : Entity_Id;
75 Init : out Node_Id;
76 Advance : out Node_Id;
77 New_Loop : out Node_Id);
78 -- Utility to create declarations and loop statement for both forms
79 -- of formal container iterators.
81 function Convert_To_Iterable_Type
82 (Container : Entity_Id;
83 Loc : Source_Ptr) return Node_Id;
84 -- Returns New_Occurrence_Of (Container), possibly converted to an ancestor
85 -- type, if the type of Container inherited the Iterable aspect from that
86 -- ancestor.
88 function Change_Of_Representation (N : Node_Id) return Boolean;
89 -- Determine if the right-hand side of assignment N is a type conversion
90 -- which requires a change of representation. Called only for the array
91 -- and record cases.
93 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id);
94 -- N is an assignment which assigns an array value. This routine process
95 -- the various special cases and checks required for such assignments,
96 -- including change of representation. Rhs is normally simply the right-
97 -- hand side of the assignment, except that if the right-hand side is a
98 -- type conversion or a qualified expression, then the RHS is the actual
99 -- expression inside any such type conversions or qualifications.
101 function Expand_Assign_Array_Loop
102 (N : Node_Id;
103 Larray : Entity_Id;
104 Rarray : Entity_Id;
105 L_Type : Entity_Id;
106 R_Type : Entity_Id;
107 Ndim : Pos;
108 Rev : Boolean) return Node_Id;
109 -- N is an assignment statement which assigns an array value. This routine
110 -- expands the assignment into a loop (or nested loops for the case of a
111 -- multi-dimensional array) to do the assignment component by component.
112 -- Larray and Rarray are the entities of the actual arrays on the left-hand
113 -- and right-hand sides. L_Type and R_Type are the types of these arrays
114 -- (which may not be the same, due to either sliding, or to a change of
115 -- representation case). Ndim is the number of dimensions and the parameter
116 -- Rev indicates if the loops run normally (Rev = False), or reversed
117 -- (Rev = True). The value returned is the constructed loop statement.
118 -- Auxiliary declarations are inserted before node N using the standard
119 -- Insert_Actions mechanism.
121 function Expand_Assign_Array_Bitfield
122 (N : Node_Id;
123 Larray : Entity_Id;
124 Rarray : Entity_Id;
125 L_Type : Entity_Id;
126 R_Type : Entity_Id;
127 Rev : Boolean) return Node_Id;
128 -- Alternative to Expand_Assign_Array_Loop for packed bitfields. Generates
129 -- a call to System.Bitfields.Copy_Bitfield, which is more efficient than
130 -- copying component-by-component.
132 function Expand_Assign_Array_Bitfield_Fast
133 (N : Node_Id;
134 Larray : Entity_Id;
135 Rarray : Entity_Id) return Node_Id;
136 -- Alternative to Expand_Assign_Array_Bitfield. Generates a call to
137 -- System.Bitfields.Fast_Copy_Bitfield, which is more efficient than
138 -- Copy_Bitfield, but only works in restricted situations.
140 function Expand_Assign_Array_Loop_Or_Bitfield
141 (N : Node_Id;
142 Larray : Entity_Id;
143 Rarray : Entity_Id;
144 L_Type : Entity_Id;
145 R_Type : Entity_Id;
146 Ndim : Pos;
147 Rev : Boolean) return Node_Id;
148 -- Calls either Expand_Assign_Array_Loop, Expand_Assign_Array_Bitfield, or
149 -- Expand_Assign_Array_Bitfield_Fast as appropriate.
151 procedure Expand_Assign_Record (N : Node_Id);
152 -- N is an assignment of an untagged record value. This routine handles
153 -- the case where the assignment must be made component by component,
154 -- either because the target is not byte aligned, or there is a change
155 -- of representation, or when we have a tagged type with a representation
156 -- clause (this last case is required because holes in the tagged type
157 -- might be filled with components from child types).
159 procedure Expand_Assign_With_Target_Names (N : Node_Id);
160 -- (AI12-0125): N is an assignment statement whose RHS contains occurrences
161 -- of @ that designate the value of the LHS of the assignment. If the LHS
162 -- is side-effect free the target names can be replaced with a copy of the
163 -- LHS; otherwise the semantics of the assignment is described in terms of
164 -- a procedure with an in-out parameter, and expanded as such.
166 procedure Expand_Formal_Container_Loop (N : Node_Id);
167 -- Use the primitives specified in an Iterable aspect to expand a loop
168 -- over a so-called formal container, primarily for SPARK usage.
170 procedure Expand_Formal_Container_Element_Loop (N : Node_Id);
171 -- Same, for an iterator of the form " For E of C". In this case the
172 -- iterator provides the name of the element, and the cursor is generated
173 -- internally.
175 procedure Expand_Iterator_Loop (N : Node_Id);
176 -- Expand loop over arrays and containers that uses the form "for X of C"
177 -- with an optional subtype mark, or "for Y in C".
179 procedure Expand_Iterator_Loop_Over_Container
180 (N : Node_Id;
181 Isc : Node_Id;
182 I_Spec : Node_Id;
183 Container : Node_Id;
184 Container_Typ : Entity_Id);
185 -- Expand loop over containers that uses the form "for X of C" with an
186 -- optional subtype mark, or "for Y in C". Isc is the iteration scheme.
187 -- I_Spec is the iterator specification and Container is either the
188 -- Container (for OF) or the iterator (for IN).
190 procedure Expand_Predicated_Loop (N : Node_Id);
191 -- Expand for loop over predicated subtype
193 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id;
194 -- Generate the necessary code for controlled and tagged assignment, that
195 -- is to say, finalization of the target before, adjustment of the target
196 -- after and save and restore of the tag and finalization pointers which
197 -- are not 'part of the value' and must not be changed upon assignment. N
198 -- is the original Assignment node.
200 --------------------------------------
201 -- Build_Formal_Container_Iteration --
202 --------------------------------------
204 procedure Build_Formal_Container_Iteration
205 (N : Node_Id;
206 Container : Entity_Id;
207 Cursor : Entity_Id;
208 Init : out Node_Id;
209 Advance : out Node_Id;
210 New_Loop : out Node_Id)
212 Loc : constant Source_Ptr := Sloc (N);
213 Stats : constant List_Id := Statements (N);
214 Typ : constant Entity_Id := Base_Type (Etype (Container));
216 Has_Element_Op : constant Entity_Id :=
217 Get_Iterable_Type_Primitive (Typ, Name_Has_Element);
219 First_Op : Entity_Id;
220 Next_Op : Entity_Id;
222 begin
223 -- Use the proper set of primitives depending on the direction of
224 -- iteration. The legality of a reverse iteration has been checked
225 -- during analysis.
227 if Reverse_Present (Iterator_Specification (Iteration_Scheme (N))) then
228 First_Op := Get_Iterable_Type_Primitive (Typ, Name_Last);
229 Next_Op := Get_Iterable_Type_Primitive (Typ, Name_Previous);
231 else
232 First_Op := Get_Iterable_Type_Primitive (Typ, Name_First);
233 Next_Op := Get_Iterable_Type_Primitive (Typ, Name_Next);
234 end if;
236 -- Declaration for Cursor
238 Init :=
239 Make_Object_Declaration (Loc,
240 Defining_Identifier => Cursor,
241 Object_Definition => New_Occurrence_Of (Etype (First_Op), Loc),
242 Expression =>
243 Make_Function_Call (Loc,
244 Name => New_Occurrence_Of (First_Op, Loc),
245 Parameter_Associations => New_List (
246 Convert_To_Iterable_Type (Container, Loc))));
248 -- Statement that advances (in the right direction) cursor in loop
250 Advance :=
251 Make_Assignment_Statement (Loc,
252 Name => New_Occurrence_Of (Cursor, Loc),
253 Expression =>
254 Make_Function_Call (Loc,
255 Name => New_Occurrence_Of (Next_Op, Loc),
256 Parameter_Associations => New_List (
257 Convert_To_Iterable_Type (Container, Loc),
258 New_Occurrence_Of (Cursor, Loc))));
260 -- Iterator is rewritten as a while_loop
262 New_Loop :=
263 Make_Loop_Statement (Loc,
264 Iteration_Scheme =>
265 Make_Iteration_Scheme (Loc,
266 Condition =>
267 Make_Function_Call (Loc,
268 Name => New_Occurrence_Of (Has_Element_Op, Loc),
269 Parameter_Associations => New_List (
270 Convert_To_Iterable_Type (Container, Loc),
271 New_Occurrence_Of (Cursor, Loc)))),
272 Statements => Stats,
273 End_Label => Empty);
275 -- If the contruct has a specified loop name, preserve it in the new
276 -- loop, for possible use in exit statements.
278 if Present (Identifier (N))
279 and then Comes_From_Source (Identifier (N))
280 then
281 Set_Identifier (New_Loop, Identifier (N));
282 end if;
283 end Build_Formal_Container_Iteration;
285 ------------------------------
286 -- Change_Of_Representation --
287 ------------------------------
289 function Change_Of_Representation (N : Node_Id) return Boolean is
290 Rhs : constant Node_Id := Expression (N);
291 begin
292 return
293 Nkind (Rhs) = N_Type_Conversion
294 and then not Has_Compatible_Representation
295 (Target_Typ => Etype (Rhs),
296 Operand_Typ => Etype (Expression (Rhs)));
297 end Change_Of_Representation;
299 ------------------------------
300 -- Convert_To_Iterable_Type --
301 ------------------------------
303 function Convert_To_Iterable_Type
304 (Container : Entity_Id;
305 Loc : Source_Ptr) return Node_Id
307 Typ : constant Entity_Id := Base_Type (Etype (Container));
308 Aspect : constant Node_Id := Find_Aspect (Typ, Aspect_Iterable);
309 Result : Node_Id;
311 begin
312 Result := New_Occurrence_Of (Container, Loc);
314 if Entity (Aspect) /= Typ then
315 Result :=
316 Make_Type_Conversion (Loc,
317 Subtype_Mark => New_Occurrence_Of (Entity (Aspect), Loc),
318 Expression => Result);
319 end if;
321 return Result;
322 end Convert_To_Iterable_Type;
324 -------------------------
325 -- Expand_Assign_Array --
326 -------------------------
328 -- There are two issues here. First, do we let Gigi do a block move, or
329 -- do we expand out into a loop? Second, we need to set the two flags
330 -- Forwards_OK and Backwards_OK which show whether the block move (or
331 -- corresponding loops) can be legitimately done in a forwards (low to
332 -- high) or backwards (high to low) manner.
334 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id) is
335 Loc : constant Source_Ptr := Sloc (N);
337 Lhs : constant Node_Id := Name (N);
339 Act_Lhs : constant Node_Id := Get_Referenced_Object (Lhs);
340 Act_Rhs : Node_Id := Get_Referenced_Object (Rhs);
342 L_Type : constant Entity_Id :=
343 Underlying_Type (Get_Actual_Subtype (Act_Lhs));
344 R_Type : Entity_Id :=
345 Underlying_Type (Get_Actual_Subtype (Act_Rhs));
347 L_Slice : constant Boolean := Nkind (Act_Lhs) = N_Slice;
348 R_Slice : constant Boolean := Nkind (Act_Rhs) = N_Slice;
350 Crep : constant Boolean := Change_Of_Representation (N);
352 pragma Assert
353 (Crep
354 or else Is_Bit_Packed_Array (L_Type) = Is_Bit_Packed_Array (R_Type));
356 Larray : Node_Id;
357 Rarray : Node_Id;
359 Ndim : constant Pos := Number_Dimensions (L_Type);
361 Loop_Required : Boolean := False;
362 -- This switch is set to True if the array move must be done using
363 -- an explicit front end generated loop.
365 procedure Apply_Dereference (Arg : Node_Id);
366 -- If the argument is an access to an array, and the assignment is
367 -- converted into a procedure call, apply explicit dereference.
369 function Has_Address_Clause (Exp : Node_Id) return Boolean;
370 -- Test if Exp is a reference to an array whose declaration has
371 -- an address clause, or it is a slice of such an array.
373 function Is_Formal_Array (Exp : Node_Id) return Boolean;
374 -- Test if Exp is a reference to an array which is either a formal
375 -- parameter or a slice of a formal parameter. These are the cases
376 -- where hidden aliasing can occur.
378 function Is_Non_Local_Array (Exp : Node_Id) return Boolean;
379 -- Determine if Exp is a reference to an array variable which is other
380 -- than an object defined in the current scope, or a component or a
381 -- slice of such an object. Such objects can be aliased to parameters
382 -- (unlike local array references).
384 -----------------------
385 -- Apply_Dereference --
386 -----------------------
388 procedure Apply_Dereference (Arg : Node_Id) is
389 Typ : constant Entity_Id := Etype (Arg);
390 begin
391 if Is_Access_Type (Typ) then
392 Rewrite (Arg, Make_Explicit_Dereference (Loc,
393 Prefix => Relocate_Node (Arg)));
394 Analyze_And_Resolve (Arg, Designated_Type (Typ));
395 end if;
396 end Apply_Dereference;
398 ------------------------
399 -- Has_Address_Clause --
400 ------------------------
402 function Has_Address_Clause (Exp : Node_Id) return Boolean is
403 begin
404 return
405 (Is_Entity_Name (Exp) and then
406 Present (Address_Clause (Entity (Exp))))
407 or else
408 (Nkind (Exp) = N_Slice and then Has_Address_Clause (Prefix (Exp)));
409 end Has_Address_Clause;
411 ---------------------
412 -- Is_Formal_Array --
413 ---------------------
415 function Is_Formal_Array (Exp : Node_Id) return Boolean is
416 begin
417 return
418 (Is_Entity_Name (Exp) and then Is_Formal (Entity (Exp)))
419 or else
420 (Nkind (Exp) = N_Slice and then Is_Formal_Array (Prefix (Exp)));
421 end Is_Formal_Array;
423 ------------------------
424 -- Is_Non_Local_Array --
425 ------------------------
427 function Is_Non_Local_Array (Exp : Node_Id) return Boolean is
428 begin
429 case Nkind (Exp) is
430 when N_Indexed_Component
431 | N_Selected_Component
432 | N_Slice
434 return Is_Non_Local_Array (Prefix (Exp));
436 when others =>
437 return
438 not (Is_Entity_Name (Exp)
439 and then Scope (Entity (Exp)) = Current_Scope);
440 end case;
441 end Is_Non_Local_Array;
443 -- Determine if Lhs, Rhs are formal arrays or nonlocal arrays
445 Lhs_Formal : constant Boolean := Is_Formal_Array (Act_Lhs);
446 Rhs_Formal : constant Boolean := Is_Formal_Array (Act_Rhs);
448 Lhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Lhs);
449 Rhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Rhs);
451 -- Start of processing for Expand_Assign_Array
453 begin
454 -- Deal with length check. Note that the length check is done with
455 -- respect to the right-hand side as given, not a possible underlying
456 -- renamed object, since this would generate incorrect extra checks.
458 Apply_Length_Check_On_Assignment (Rhs, L_Type, Lhs);
460 -- We start by assuming that the move can be done in either direction,
461 -- i.e. that the two sides are completely disjoint.
463 Set_Forwards_OK (N, True);
464 Set_Backwards_OK (N, True);
466 -- Normally it is only the slice case that can lead to overlap, and
467 -- explicit checks for slices are made below. But there is one case
468 -- where the slice can be implicit and invisible to us: when we have a
469 -- one dimensional array, and either both operands are parameters, or
470 -- one is a parameter (which can be a slice passed by reference) and the
471 -- other is a non-local variable. In this case the parameter could be a
472 -- slice that overlaps with the other operand.
474 -- However, if the array subtype is a constrained first subtype in the
475 -- parameter case, then we don't have to worry about overlap, since
476 -- slice assignments aren't possible (other than for a slice denoting
477 -- the whole array).
479 -- Note: No overlap is possible if there is a change of representation,
480 -- so we can exclude this case.
482 if Ndim = 1
483 and then not Crep
484 and then
485 ((Lhs_Formal and Rhs_Formal)
486 or else
487 (Lhs_Formal and Rhs_Non_Local_Var)
488 or else
489 (Rhs_Formal and Lhs_Non_Local_Var))
490 and then
491 (not Is_Constrained (Etype (Lhs))
492 or else not Is_First_Subtype (Etype (Lhs)))
493 then
494 Set_Forwards_OK (N, False);
495 Set_Backwards_OK (N, False);
497 -- Note: the bit-packed case is not worrisome here, since if we have
498 -- a slice passed as a parameter, it is always aligned on a byte
499 -- boundary, and if there are no explicit slices, the assignment
500 -- can be performed directly.
501 end if;
503 -- If either operand has an address clause clear Backwards_OK and
504 -- Forwards_OK, since we cannot tell if the operands overlap. We
505 -- exclude this treatment when Rhs is an aggregate, since we know
506 -- that overlap can't occur.
508 if (Has_Address_Clause (Lhs) and then Nkind (Rhs) /= N_Aggregate)
509 or else Has_Address_Clause (Rhs)
510 then
511 Set_Forwards_OK (N, False);
512 Set_Backwards_OK (N, False);
513 end if;
515 -- We certainly must use a loop for change of representation and also
516 -- we use the operand of the conversion on the right-hand side as the
517 -- effective right-hand side (the component types must match in this
518 -- situation).
520 if Crep then
521 Act_Rhs := Get_Referenced_Object (Rhs);
522 R_Type := Get_Actual_Subtype (Act_Rhs);
523 Loop_Required := True;
525 -- We require a loop if the left side is possibly bit unaligned
527 elsif Possible_Bit_Aligned_Component (Lhs)
528 or else
529 Possible_Bit_Aligned_Component (Rhs)
530 then
531 Loop_Required := True;
533 -- Arrays with controlled components are expanded into a loop to force
534 -- calls to Adjust at the component level.
536 elsif Has_Controlled_Component (L_Type) then
537 Loop_Required := True;
539 -- If object is full access, we cannot tolerate a loop
541 elsif Is_Full_Access_Object (Act_Lhs)
542 or else
543 Is_Full_Access_Object (Act_Rhs)
544 then
545 return;
547 -- Loop is required if we have atomic components since we have to
548 -- be sure to do any accesses on an element by element basis.
550 elsif Has_Atomic_Components (L_Type)
551 or else Has_Atomic_Components (R_Type)
552 or else Is_Full_Access (Component_Type (L_Type))
553 or else Is_Full_Access (Component_Type (R_Type))
554 then
555 Loop_Required := True;
557 -- Case where no slice is involved
559 elsif not L_Slice and not R_Slice then
561 -- The following code deals with the case of unconstrained bit packed
562 -- arrays. The problem is that the template for such arrays contains
563 -- the bounds of the actual source level array, but the copy of an
564 -- entire array requires the bounds of the underlying array. It would
565 -- be nice if the back end could take care of this, but right now it
566 -- does not know how, so if we have such a type, then we expand out
567 -- into a loop, which is inefficient but works correctly. If we don't
568 -- do this, we get the wrong length computed for the array to be
569 -- moved. The two cases we need to worry about are:
571 -- Explicit dereference of an unconstrained packed array type as in
572 -- the following example:
574 -- procedure C52 is
575 -- type BITS is array(INTEGER range <>) of BOOLEAN;
576 -- pragma PACK(BITS);
577 -- type A is access BITS;
578 -- P1,P2 : A;
579 -- begin
580 -- P1 := new BITS (1 .. 65_535);
581 -- P2 := new BITS (1 .. 65_535);
582 -- P2.ALL := P1.ALL;
583 -- end C52;
585 -- A formal parameter reference with an unconstrained bit array type
586 -- is the other case we need to worry about (here we assume the same
587 -- BITS type declared above):
589 -- procedure Write_All (File : out BITS; Contents : BITS);
590 -- begin
591 -- File.Storage := Contents;
592 -- end Write_All;
594 -- We expand to a loop in either of these two cases
596 -- Question for future thought. Another potentially more efficient
597 -- approach would be to create the actual subtype, and then do an
598 -- unchecked conversion to this actual subtype ???
600 Check_Unconstrained_Bit_Packed_Array : declare
602 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean;
603 -- Function to perform required test for the first case, above
604 -- (dereference of an unconstrained bit packed array).
606 -----------------------
607 -- Is_UBPA_Reference --
608 -----------------------
610 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean is
611 Typ : constant Entity_Id := Underlying_Type (Etype (Opnd));
612 P_Type : Entity_Id;
613 Des_Type : Entity_Id;
615 begin
616 if Present (Packed_Array_Impl_Type (Typ))
617 and then Is_Array_Type (Packed_Array_Impl_Type (Typ))
618 and then not Is_Constrained (Packed_Array_Impl_Type (Typ))
619 then
620 return True;
622 elsif Nkind (Opnd) = N_Explicit_Dereference then
623 P_Type := Underlying_Type (Etype (Prefix (Opnd)));
625 if not Is_Access_Type (P_Type) then
626 return False;
628 else
629 Des_Type := Designated_Type (P_Type);
630 return
631 Is_Bit_Packed_Array (Des_Type)
632 and then not Is_Constrained (Des_Type);
633 end if;
635 else
636 return False;
637 end if;
638 end Is_UBPA_Reference;
640 -- Start of processing for Check_Unconstrained_Bit_Packed_Array
642 begin
643 if Is_UBPA_Reference (Lhs)
644 or else
645 Is_UBPA_Reference (Rhs)
646 then
647 Loop_Required := True;
649 -- Here if we do not have the case of a reference to a bit packed
650 -- unconstrained array case. In this case gigi can most certainly
651 -- handle the assignment if a forwards move is allowed.
653 -- (could it handle the backwards case also???)
655 elsif Forwards_OK (N) then
656 return;
657 end if;
658 end Check_Unconstrained_Bit_Packed_Array;
660 -- The back end can always handle the assignment if the right side is a
661 -- string literal (note that overlap is definitely impossible in this
662 -- case). If the type is packed, a string literal is always converted
663 -- into an aggregate, except in the case of a null slice, for which no
664 -- aggregate can be written. In that case, rewrite the assignment as a
665 -- null statement, a length check has already been emitted to verify
666 -- that the range of the left-hand side is empty.
668 -- Note that this code is not executed if we have an assignment of a
669 -- string literal to a non-bit aligned component of a record, a case
670 -- which cannot be handled by the backend.
672 elsif Nkind (Rhs) = N_String_Literal then
673 if String_Length (Strval (Rhs)) = 0
674 and then Is_Bit_Packed_Array (L_Type)
675 then
676 Rewrite (N, Make_Null_Statement (Loc));
677 Analyze (N);
678 end if;
680 return;
682 -- If either operand is bit packed, then we need a loop, since we can't
683 -- be sure that the slice is byte aligned. Similarly, if either operand
684 -- is a possibly unaligned slice, then we need a loop (since the back
685 -- end cannot handle unaligned slices).
687 elsif Is_Bit_Packed_Array (L_Type)
688 or else Is_Bit_Packed_Array (R_Type)
689 or else Is_Possibly_Unaligned_Slice (Lhs)
690 or else Is_Possibly_Unaligned_Slice (Rhs)
691 then
692 Loop_Required := True;
694 -- If we are not bit-packed, and we have only one slice, then no overlap
695 -- is possible except in the parameter case, so we can let the back end
696 -- handle things.
698 elsif not (L_Slice and R_Slice) then
699 if Forwards_OK (N) then
700 return;
701 end if;
702 end if;
704 -- If the right-hand side is a string literal, introduce a temporary for
705 -- it, for use in the generated loop that will follow.
707 if Nkind (Rhs) = N_String_Literal then
708 declare
709 Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Rhs);
710 Decl : Node_Id;
712 begin
713 Decl :=
714 Make_Object_Declaration (Loc,
715 Defining_Identifier => Temp,
716 Object_Definition => New_Occurrence_Of (L_Type, Loc),
717 Expression => Relocate_Node (Rhs));
719 Insert_Action (N, Decl);
720 Rewrite (Rhs, New_Occurrence_Of (Temp, Loc));
721 R_Type := Etype (Temp);
722 end;
723 end if;
725 -- Come here to complete the analysis
727 -- Loop_Required: Set to True if we know that a loop is required
728 -- regardless of overlap considerations.
730 -- Forwards_OK: Set to False if we already know that a forwards
731 -- move is not safe, else set to True.
733 -- Backwards_OK: Set to False if we already know that a backwards
734 -- move is not safe, else set to True
736 -- Our task at this stage is to complete the overlap analysis, which can
737 -- result in possibly setting Forwards_OK or Backwards_OK to False, and
738 -- then generating the final code, either by deciding that it is OK
739 -- after all to let Gigi handle it, or by generating appropriate code
740 -- in the front end.
742 declare
743 L_Index_Typ : constant Entity_Id := Etype (First_Index (L_Type));
744 R_Index_Typ : constant Entity_Id := Etype (First_Index (R_Type));
746 Left_Lo : constant Node_Id := Type_Low_Bound (L_Index_Typ);
747 Left_Hi : constant Node_Id := Type_High_Bound (L_Index_Typ);
748 Right_Lo : constant Node_Id := Type_Low_Bound (R_Index_Typ);
749 Right_Hi : constant Node_Id := Type_High_Bound (R_Index_Typ);
751 Act_L_Array : Node_Id;
752 Act_R_Array : Node_Id;
754 Cleft_Lo : Node_Id;
755 Cright_Lo : Node_Id;
756 Condition : Node_Id;
758 Cresult : Compare_Result;
760 begin
761 -- Get the expressions for the arrays. If we are dealing with a
762 -- private type, then convert to the underlying type. We can do
763 -- direct assignments to an array that is a private type, but we
764 -- cannot assign to elements of the array without this extra
765 -- unchecked conversion.
767 -- Note: We propagate Parent to the conversion nodes to generate
768 -- a well-formed subtree.
770 if Nkind (Act_Lhs) = N_Slice then
771 Larray := Prefix (Act_Lhs);
772 else
773 Larray := Act_Lhs;
775 if Is_Private_Type (Etype (Larray)) then
776 declare
777 Par : constant Node_Id := Parent (Larray);
778 begin
779 Larray :=
780 Unchecked_Convert_To
781 (Underlying_Type (Etype (Larray)), Larray);
782 Set_Parent (Larray, Par);
783 end;
784 end if;
785 end if;
787 if Nkind (Act_Rhs) = N_Slice then
788 Rarray := Prefix (Act_Rhs);
789 else
790 Rarray := Act_Rhs;
792 if Is_Private_Type (Etype (Rarray)) then
793 declare
794 Par : constant Node_Id := Parent (Rarray);
795 begin
796 Rarray :=
797 Unchecked_Convert_To
798 (Underlying_Type (Etype (Rarray)), Rarray);
799 Set_Parent (Rarray, Par);
800 end;
801 end if;
802 end if;
804 -- If both sides are slices, we must figure out whether it is safe
805 -- to do the move in one direction or the other. It is always safe
806 -- if there is a change of representation since obviously two arrays
807 -- with different representations cannot possibly overlap.
809 if (not Crep) and L_Slice and R_Slice then
810 Act_L_Array := Get_Referenced_Object (Prefix (Act_Lhs));
811 Act_R_Array := Get_Referenced_Object (Prefix (Act_Rhs));
813 -- If both left- and right-hand arrays are entity names, and refer
814 -- to different entities, then we know that the move is safe (the
815 -- two storage areas are completely disjoint).
817 if Is_Entity_Name (Act_L_Array)
818 and then Is_Entity_Name (Act_R_Array)
819 and then Entity (Act_L_Array) /= Entity (Act_R_Array)
820 then
821 null;
823 -- Otherwise, we assume the worst, which is that the two arrays
824 -- are the same array. There is no need to check if we know that
825 -- is the case, because if we don't know it, we still have to
826 -- assume it.
828 -- Generally if the same array is involved, then we have an
829 -- overlapping case. We will have to really assume the worst (i.e.
830 -- set neither of the OK flags) unless we can determine the lower
831 -- or upper bounds at compile time and compare them.
833 else
834 Cresult :=
835 Compile_Time_Compare
836 (Left_Lo, Right_Lo, Assume_Valid => True);
838 if Cresult = Unknown then
839 Cresult :=
840 Compile_Time_Compare
841 (Left_Hi, Right_Hi, Assume_Valid => True);
842 end if;
844 case Cresult is
845 when EQ | LE | LT =>
846 Set_Backwards_OK (N, False);
848 when GE | GT =>
849 Set_Forwards_OK (N, False);
851 when NE | Unknown =>
852 Set_Backwards_OK (N, False);
853 Set_Forwards_OK (N, False);
854 end case;
855 end if;
856 end if;
858 -- If after that analysis Loop_Required is False, meaning that we
859 -- have not discovered some non-overlap reason for requiring a loop,
860 -- then the outcome depends on the capabilities of the back end.
862 if not Loop_Required then
863 -- Assume the back end can deal with all cases of overlap by
864 -- falling back to memmove if it cannot use a more efficient
865 -- approach.
867 return;
868 end if;
870 -- At this stage we have to generate an explicit loop, and we have
871 -- the following cases:
873 -- Forwards_OK = True
875 -- Rnn : right_index := right_index'First;
876 -- for Lnn in left-index loop
877 -- left (Lnn) := right (Rnn);
878 -- Rnn := right_index'Succ (Rnn);
879 -- end loop;
881 -- Note: the above code MUST be analyzed with checks off, because
882 -- otherwise the Succ could overflow. But in any case this is more
883 -- efficient.
885 -- Forwards_OK = False, Backwards_OK = True
887 -- Rnn : right_index := right_index'Last;
888 -- for Lnn in reverse left-index loop
889 -- left (Lnn) := right (Rnn);
890 -- Rnn := right_index'Pred (Rnn);
891 -- end loop;
893 -- Note: the above code MUST be analyzed with checks off, because
894 -- otherwise the Pred could overflow. But in any case this is more
895 -- efficient.
897 -- Forwards_OK = Backwards_OK = False
899 -- This only happens if we have the same array on each side. It is
900 -- possible to create situations using overlays that violate this,
901 -- but we simply do not promise to get this "right" in this case.
903 -- There are two possible subcases. If the No_Implicit_Conditionals
904 -- restriction is set, then we generate the following code:
906 -- declare
907 -- T : constant <operand-type> := rhs;
908 -- begin
909 -- lhs := T;
910 -- end;
912 -- If implicit conditionals are permitted, then we generate:
914 -- if Left_Lo <= Right_Lo then
915 -- <code for Forwards_OK = True above>
916 -- else
917 -- <code for Backwards_OK = True above>
918 -- end if;
920 -- In order to detect possible aliasing, we examine the renamed
921 -- expression when the source or target is a renaming. However,
922 -- the renaming may be intended to capture an address that may be
923 -- affected by subsequent code, and therefore we must recover
924 -- the actual entity for the expansion that follows, not the
925 -- object it renames. In particular, if source or target designate
926 -- a portion of a dynamically allocated object, the pointer to it
927 -- may be reassigned but the renaming preserves the proper location.
929 if Is_Entity_Name (Rhs)
930 and then
931 Nkind (Parent (Entity (Rhs))) = N_Object_Renaming_Declaration
932 and then Nkind (Act_Rhs) = N_Slice
933 then
934 Rarray := Rhs;
935 end if;
937 if Is_Entity_Name (Lhs)
938 and then
939 Nkind (Parent (Entity (Lhs))) = N_Object_Renaming_Declaration
940 and then Nkind (Act_Lhs) = N_Slice
941 then
942 Larray := Lhs;
943 end if;
945 -- Cases where either Forwards_OK or Backwards_OK is true
947 if Forwards_OK (N) or else Backwards_OK (N) then
948 if Needs_Finalization (Component_Type (L_Type))
949 and then Base_Type (L_Type) = Base_Type (R_Type)
950 and then Ndim = 1
951 and then not No_Ctrl_Actions (N)
952 then
953 declare
954 Proc : constant Entity_Id :=
955 TSS (Base_Type (L_Type), TSS_Slice_Assign);
956 Actuals : List_Id;
958 begin
959 Apply_Dereference (Larray);
960 Apply_Dereference (Rarray);
961 Actuals := New_List (
962 Duplicate_Subexpr (Larray, Name_Req => True),
963 Duplicate_Subexpr (Rarray, Name_Req => True),
964 Duplicate_Subexpr (Left_Lo, Name_Req => True),
965 Duplicate_Subexpr (Left_Hi, Name_Req => True),
966 Duplicate_Subexpr (Right_Lo, Name_Req => True),
967 Duplicate_Subexpr (Right_Hi, Name_Req => True));
969 Append_To (Actuals,
970 New_Occurrence_Of (
971 Boolean_Literals (not Forwards_OK (N)), Loc));
973 Rewrite (N,
974 Make_Procedure_Call_Statement (Loc,
975 Name => New_Occurrence_Of (Proc, Loc),
976 Parameter_Associations => Actuals));
977 end;
979 else
980 Rewrite (N,
981 Expand_Assign_Array_Loop_Or_Bitfield
982 (N, Larray, Rarray, L_Type, R_Type, Ndim,
983 Rev => not Forwards_OK (N)));
984 end if;
986 -- Case of both are false with No_Implicit_Conditionals
988 elsif Restriction_Active (No_Implicit_Conditionals) then
989 declare
990 T : constant Entity_Id :=
991 Make_Defining_Identifier (Loc, Chars => Name_T);
993 begin
994 Rewrite (N,
995 Make_Block_Statement (Loc,
996 Declarations => New_List (
997 Make_Object_Declaration (Loc,
998 Defining_Identifier => T,
999 Constant_Present => True,
1000 Object_Definition =>
1001 New_Occurrence_Of (Etype (Rhs), Loc),
1002 Expression => Relocate_Node (Rhs))),
1004 Handled_Statement_Sequence =>
1005 Make_Handled_Sequence_Of_Statements (Loc,
1006 Statements => New_List (
1007 Make_Assignment_Statement (Loc,
1008 Name => Relocate_Node (Lhs),
1009 Expression => New_Occurrence_Of (T, Loc))))));
1010 end;
1012 -- Case of both are false with implicit conditionals allowed
1014 else
1015 -- Before we generate this code, we must ensure that the left and
1016 -- right side array types are defined. They may be itypes, and we
1017 -- cannot let them be defined inside the if, since the first use
1018 -- in the then may not be executed.
1020 Ensure_Defined (L_Type, N);
1021 Ensure_Defined (R_Type, N);
1023 -- We normally compare addresses to find out which way round to
1024 -- do the loop, since this is reliable, and handles the cases of
1025 -- parameters, conversions etc. But we can't do that in the bit
1026 -- packed case, because addresses don't work there.
1028 if not Is_Bit_Packed_Array (L_Type) then
1029 Condition :=
1030 Make_Op_Le (Loc,
1031 Left_Opnd =>
1032 Unchecked_Convert_To (RTE (RE_Integer_Address),
1033 Make_Attribute_Reference (Loc,
1034 Prefix =>
1035 Make_Indexed_Component (Loc,
1036 Prefix =>
1037 Duplicate_Subexpr_Move_Checks (Larray, True),
1038 Expressions => New_List (
1039 Make_Attribute_Reference (Loc,
1040 Prefix =>
1041 New_Occurrence_Of
1042 (L_Index_Typ, Loc),
1043 Attribute_Name => Name_First))),
1044 Attribute_Name => Name_Address)),
1046 Right_Opnd =>
1047 Unchecked_Convert_To (RTE (RE_Integer_Address),
1048 Make_Attribute_Reference (Loc,
1049 Prefix =>
1050 Make_Indexed_Component (Loc,
1051 Prefix =>
1052 Duplicate_Subexpr_Move_Checks (Rarray, True),
1053 Expressions => New_List (
1054 Make_Attribute_Reference (Loc,
1055 Prefix =>
1056 New_Occurrence_Of
1057 (R_Index_Typ, Loc),
1058 Attribute_Name => Name_First))),
1059 Attribute_Name => Name_Address)));
1061 -- For the bit packed and VM cases we use the bounds. That's OK,
1062 -- because we don't have to worry about parameters, since they
1063 -- cannot cause overlap. Perhaps we should worry about weird slice
1064 -- conversions ???
1066 else
1067 -- Copy the bounds
1069 Cleft_Lo := New_Copy_Tree (Left_Lo);
1070 Cright_Lo := New_Copy_Tree (Right_Lo);
1072 -- If the types do not match we add an implicit conversion
1073 -- here to ensure proper match
1075 if Etype (Left_Lo) /= Etype (Right_Lo) then
1076 Cright_Lo :=
1077 Unchecked_Convert_To (Etype (Left_Lo), Cright_Lo);
1078 end if;
1080 -- Reset the Analyzed flag, because the bounds of the index
1081 -- type itself may be universal, and must be reanalyzed to
1082 -- acquire the proper type for the back end.
1084 Set_Analyzed (Cleft_Lo, False);
1085 Set_Analyzed (Cright_Lo, False);
1087 Condition :=
1088 Make_Op_Le (Loc,
1089 Left_Opnd => Cleft_Lo,
1090 Right_Opnd => Cright_Lo);
1091 end if;
1093 if Needs_Finalization (Component_Type (L_Type))
1094 and then Base_Type (L_Type) = Base_Type (R_Type)
1095 and then Ndim = 1
1096 and then not No_Ctrl_Actions (N)
1097 then
1099 -- Call TSS procedure for array assignment, passing the
1100 -- explicit bounds of right- and left-hand sides.
1102 declare
1103 Proc : constant Entity_Id :=
1104 TSS (Base_Type (L_Type), TSS_Slice_Assign);
1105 Actuals : List_Id;
1107 begin
1108 Apply_Dereference (Larray);
1109 Apply_Dereference (Rarray);
1110 Actuals := New_List (
1111 Duplicate_Subexpr (Larray, Name_Req => True),
1112 Duplicate_Subexpr (Rarray, Name_Req => True),
1113 Duplicate_Subexpr (Left_Lo, Name_Req => True),
1114 Duplicate_Subexpr (Left_Hi, Name_Req => True),
1115 Duplicate_Subexpr (Right_Lo, Name_Req => True),
1116 Duplicate_Subexpr (Right_Hi, Name_Req => True));
1118 Append_To (Actuals,
1119 Make_Op_Not (Loc,
1120 Right_Opnd => Condition));
1122 Rewrite (N,
1123 Make_Procedure_Call_Statement (Loc,
1124 Name => New_Occurrence_Of (Proc, Loc),
1125 Parameter_Associations => Actuals));
1126 end;
1128 else
1129 Rewrite (N,
1130 Make_Implicit_If_Statement (N,
1131 Condition => Condition,
1133 Then_Statements => New_List (
1134 Expand_Assign_Array_Loop_Or_Bitfield
1135 (N, Larray, Rarray, L_Type, R_Type, Ndim,
1136 Rev => False)),
1138 Else_Statements => New_List (
1139 Expand_Assign_Array_Loop_Or_Bitfield
1140 (N, Larray, Rarray, L_Type, R_Type, Ndim,
1141 Rev => True))));
1142 end if;
1143 end if;
1145 Analyze (N, Suppress => All_Checks);
1146 end;
1148 exception
1149 when RE_Not_Available =>
1150 return;
1151 end Expand_Assign_Array;
1153 ------------------------------
1154 -- Expand_Assign_Array_Loop --
1155 ------------------------------
1157 -- The following is an example of the loop generated for the case of a
1158 -- two-dimensional array:
1160 -- declare
1161 -- R2b : Tm1X1 := 1;
1162 -- begin
1163 -- for L1b in 1 .. 100 loop
1164 -- declare
1165 -- R4b : Tm1X2 := 1;
1166 -- begin
1167 -- for L3b in 1 .. 100 loop
1168 -- vm1 (L1b, L3b) := vm2 (R2b, R4b);
1169 -- R4b := Tm1X2'succ(R4b);
1170 -- end loop;
1171 -- end;
1172 -- R2b := Tm1X1'succ(R2b);
1173 -- end loop;
1174 -- end;
1176 -- Here Rev is False, and Tm1Xn are the subscript types for the right-hand
1177 -- side. The declarations of R2b and R4b are inserted before the original
1178 -- assignment statement.
1180 function Expand_Assign_Array_Loop
1181 (N : Node_Id;
1182 Larray : Entity_Id;
1183 Rarray : Entity_Id;
1184 L_Type : Entity_Id;
1185 R_Type : Entity_Id;
1186 Ndim : Pos;
1187 Rev : Boolean) return Node_Id
1189 Loc : constant Source_Ptr := Sloc (N);
1191 Lnn : array (1 .. Ndim) of Entity_Id;
1192 Rnn : array (1 .. Ndim) of Entity_Id;
1193 -- Entities used as subscripts on left and right sides
1195 L_Index_Type : array (1 .. Ndim) of Entity_Id;
1196 R_Index_Type : array (1 .. Ndim) of Entity_Id;
1197 -- Left and right index types
1199 Assign : Node_Id;
1201 F_Or_L : Name_Id;
1202 S_Or_P : Name_Id;
1204 function Build_Step (J : Nat) return Node_Id;
1205 -- The increment step for the index of the right-hand side is written
1206 -- as an attribute reference (Succ or Pred). This function returns
1207 -- the corresponding node, which is placed at the end of the loop body.
1209 ----------------
1210 -- Build_Step --
1211 ----------------
1213 function Build_Step (J : Nat) return Node_Id is
1214 Step : Node_Id;
1215 Lim : Name_Id;
1217 begin
1218 if Rev then
1219 Lim := Name_First;
1220 else
1221 Lim := Name_Last;
1222 end if;
1224 Step :=
1225 Make_Assignment_Statement (Loc,
1226 Name => New_Occurrence_Of (Rnn (J), Loc),
1227 Expression =>
1228 Make_Attribute_Reference (Loc,
1229 Prefix =>
1230 New_Occurrence_Of (R_Index_Type (J), Loc),
1231 Attribute_Name => S_Or_P,
1232 Expressions => New_List (
1233 New_Occurrence_Of (Rnn (J), Loc))));
1235 -- Note that on the last iteration of the loop, the index is increased
1236 -- (or decreased) past the corresponding bound. This is consistent with
1237 -- the C semantics of the back-end, where such an off-by-one value on a
1238 -- dead index variable is OK. However, in CodePeer mode this leads to
1239 -- spurious warnings, and thus we place a guard around the attribute
1240 -- reference. For obvious reasons we only do this for CodePeer.
1242 if CodePeer_Mode then
1243 Step :=
1244 Make_If_Statement (Loc,
1245 Condition =>
1246 Make_Op_Ne (Loc,
1247 Left_Opnd => New_Occurrence_Of (Lnn (J), Loc),
1248 Right_Opnd =>
1249 Make_Attribute_Reference (Loc,
1250 Prefix => New_Occurrence_Of (L_Index_Type (J), Loc),
1251 Attribute_Name => Lim)),
1252 Then_Statements => New_List (Step));
1253 end if;
1255 return Step;
1256 end Build_Step;
1258 -- Start of processing for Expand_Assign_Array_Loop
1260 begin
1261 if Rev then
1262 F_Or_L := Name_Last;
1263 S_Or_P := Name_Pred;
1264 else
1265 F_Or_L := Name_First;
1266 S_Or_P := Name_Succ;
1267 end if;
1269 -- Setup index types and subscript entities
1271 declare
1272 L_Index : Node_Id;
1273 R_Index : Node_Id;
1275 begin
1276 L_Index := First_Index (L_Type);
1277 R_Index := First_Index (R_Type);
1279 for J in 1 .. Ndim loop
1280 Lnn (J) := Make_Temporary (Loc, 'L');
1281 Rnn (J) := Make_Temporary (Loc, 'R');
1283 L_Index_Type (J) := Etype (L_Index);
1284 R_Index_Type (J) := Etype (R_Index);
1286 Next_Index (L_Index);
1287 Next_Index (R_Index);
1288 end loop;
1289 end;
1291 -- Now construct the assignment statement
1293 declare
1294 ExprL : constant List_Id := New_List;
1295 ExprR : constant List_Id := New_List;
1297 begin
1298 for J in 1 .. Ndim loop
1299 Append_To (ExprL, New_Occurrence_Of (Lnn (J), Loc));
1300 Append_To (ExprR, New_Occurrence_Of (Rnn (J), Loc));
1301 end loop;
1303 Assign :=
1304 Make_Assignment_Statement (Loc,
1305 Name =>
1306 Make_Indexed_Component (Loc,
1307 Prefix => Duplicate_Subexpr (Larray, Name_Req => True),
1308 Expressions => ExprL),
1309 Expression =>
1310 Make_Indexed_Component (Loc,
1311 Prefix => Duplicate_Subexpr (Rarray, Name_Req => True),
1312 Expressions => ExprR));
1314 -- We set assignment OK, since there are some cases, e.g. in object
1315 -- declarations, where we are actually assigning into a constant.
1316 -- If there really is an illegality, it was caught long before now,
1317 -- and was flagged when the original assignment was analyzed.
1319 Set_Assignment_OK (Name (Assign));
1321 -- Propagate the No_Ctrl_Actions flag to individual assignments
1323 Set_No_Ctrl_Actions (Assign, No_Ctrl_Actions (N));
1324 end;
1326 -- Now construct the loop from the inside out, with the last subscript
1327 -- varying most rapidly. Note that Assign is first the raw assignment
1328 -- statement, and then subsequently the loop that wraps it up.
1330 for J in reverse 1 .. Ndim loop
1331 Assign :=
1332 Make_Block_Statement (Loc,
1333 Declarations => New_List (
1334 Make_Object_Declaration (Loc,
1335 Defining_Identifier => Rnn (J),
1336 Object_Definition =>
1337 New_Occurrence_Of (R_Index_Type (J), Loc),
1338 Expression =>
1339 Make_Attribute_Reference (Loc,
1340 Prefix => New_Occurrence_Of (R_Index_Type (J), Loc),
1341 Attribute_Name => F_Or_L))),
1343 Handled_Statement_Sequence =>
1344 Make_Handled_Sequence_Of_Statements (Loc,
1345 Statements => New_List (
1346 Make_Implicit_Loop_Statement (N,
1347 Iteration_Scheme =>
1348 Make_Iteration_Scheme (Loc,
1349 Loop_Parameter_Specification =>
1350 Make_Loop_Parameter_Specification (Loc,
1351 Defining_Identifier => Lnn (J),
1352 Reverse_Present => Rev,
1353 Discrete_Subtype_Definition =>
1354 New_Occurrence_Of (L_Index_Type (J), Loc))),
1356 Statements => New_List (Assign, Build_Step (J))))));
1357 end loop;
1359 return Assign;
1360 end Expand_Assign_Array_Loop;
1362 ----------------------------------
1363 -- Expand_Assign_Array_Bitfield --
1364 ----------------------------------
1366 function Expand_Assign_Array_Bitfield
1367 (N : Node_Id;
1368 Larray : Entity_Id;
1369 Rarray : Entity_Id;
1370 L_Type : Entity_Id;
1371 R_Type : Entity_Id;
1372 Rev : Boolean) return Node_Id
1374 pragma Assert (not Rev);
1375 -- Reverse copying is not yet supported by Copy_Bitfield.
1377 pragma Assert (not Change_Of_Representation (N));
1378 -- This won't work, for example, to copy a packed array to an unpacked
1379 -- array.
1381 Loc : constant Source_Ptr := Sloc (N);
1383 L_Index_Typ : constant Entity_Id := Etype (First_Index (L_Type));
1384 R_Index_Typ : constant Entity_Id := Etype (First_Index (R_Type));
1385 Left_Lo : constant Node_Id := Type_Low_Bound (L_Index_Typ);
1386 Right_Lo : constant Node_Id := Type_Low_Bound (R_Index_Typ);
1388 L_Addr : constant Node_Id :=
1389 Make_Attribute_Reference (Loc,
1390 Prefix =>
1391 Make_Indexed_Component (Loc,
1392 Prefix =>
1393 Duplicate_Subexpr (Larray, True),
1394 Expressions => New_List (New_Copy_Tree (Left_Lo))),
1395 Attribute_Name => Name_Address);
1397 L_Bit : constant Node_Id :=
1398 Make_Attribute_Reference (Loc,
1399 Prefix =>
1400 Make_Indexed_Component (Loc,
1401 Prefix =>
1402 Duplicate_Subexpr (Larray, True),
1403 Expressions => New_List (New_Copy_Tree (Left_Lo))),
1404 Attribute_Name => Name_Bit);
1406 R_Addr : constant Node_Id :=
1407 Make_Attribute_Reference (Loc,
1408 Prefix =>
1409 Make_Indexed_Component (Loc,
1410 Prefix =>
1411 Duplicate_Subexpr (Rarray, True),
1412 Expressions => New_List (New_Copy_Tree (Right_Lo))),
1413 Attribute_Name => Name_Address);
1415 R_Bit : constant Node_Id :=
1416 Make_Attribute_Reference (Loc,
1417 Prefix =>
1418 Make_Indexed_Component (Loc,
1419 Prefix =>
1420 Duplicate_Subexpr (Rarray, True),
1421 Expressions => New_List (New_Copy_Tree (Right_Lo))),
1422 Attribute_Name => Name_Bit);
1424 -- Compute the Size of the bitfield
1426 -- Note that the length check has already been done, so we can use the
1427 -- size of either L or R; they are equal. We can't use 'Size here,
1428 -- because sometimes bit fields get copied into a temp, and the 'Size
1429 -- ends up being the size of the temp (e.g. an 8-bit temp containing
1430 -- a 4-bit bit field).
1432 Size : constant Node_Id :=
1433 Make_Op_Multiply (Loc,
1434 Make_Attribute_Reference (Loc,
1435 Prefix =>
1436 Duplicate_Subexpr (Name (N), True),
1437 Attribute_Name => Name_Length),
1438 Make_Attribute_Reference (Loc,
1439 Prefix =>
1440 Duplicate_Subexpr (Name (N), True),
1441 Attribute_Name => Name_Component_Size));
1443 begin
1444 return Make_Procedure_Call_Statement (Loc,
1445 Name => New_Occurrence_Of (RTE (RE_Copy_Bitfield), Loc),
1446 Parameter_Associations => New_List (
1447 R_Addr, R_Bit, L_Addr, L_Bit, Size));
1448 end Expand_Assign_Array_Bitfield;
1450 ---------------------------------------
1451 -- Expand_Assign_Array_Bitfield_Fast --
1452 ---------------------------------------
1454 function Expand_Assign_Array_Bitfield_Fast
1455 (N : Node_Id;
1456 Larray : Entity_Id;
1457 Rarray : Entity_Id) return Node_Id
1459 pragma Assert (not Change_Of_Representation (N));
1460 -- This won't work, for example, to copy a packed array to an unpacked
1461 -- array.
1463 -- For L (A .. B) := R (C .. D), we generate:
1465 -- L := Fast_Copy_Bitfield (R, <offset of R(C)>, L, <offset of L(A)>,
1466 -- L (A .. B)'Length * L'Component_Size);
1468 -- with L and R suitably uncheckedly converted to/from Val_2.
1469 -- The offsets are from the start of L and R.
1471 Loc : constant Source_Ptr := Sloc (N);
1473 L_Typ : constant Entity_Id := Etype (Larray);
1474 R_Typ : constant Entity_Id := Etype (Rarray);
1475 -- The original type of the arrays
1477 L_Val : constant Node_Id :=
1478 Unchecked_Convert_To (RTE (RE_Val_2), Larray);
1479 R_Val : constant Node_Id :=
1480 Unchecked_Convert_To (RTE (RE_Val_2), Rarray);
1481 -- Converted values of left- and right-hand sides
1483 L_Small : constant Boolean :=
1484 Known_Static_RM_Size (L_Typ)
1485 and then RM_Size (L_Typ) < Standard_Long_Long_Integer_Size;
1486 R_Small : constant Boolean :=
1487 Known_Static_RM_Size (R_Typ)
1488 and then RM_Size (R_Typ) < Standard_Long_Long_Integer_Size;
1489 -- Whether the above unchecked conversions need to be padded with zeros
1491 C_Size : constant Uint := Component_Size (L_Typ);
1492 pragma Assert (C_Size >= 1);
1493 pragma Assert (C_Size = Component_Size (R_Typ));
1495 Larray_Bounds : constant Range_Values :=
1496 Get_Index_Bounds (First_Index (L_Typ));
1497 L_Bounds : constant Range_Values :=
1498 (if Nkind (Name (N)) = N_Slice
1499 then Get_Index_Bounds (Discrete_Range (Name (N)))
1500 else Larray_Bounds);
1501 -- If the left-hand side is A (First..Last), Larray_Bounds is A'Range,
1502 -- and L_Bounds is First..Last. If it's not a slice, we treat it like
1503 -- a slice starting at A'First.
1505 L_Bit : constant Node_Id :=
1506 Make_Integer_Literal
1507 (Loc, (L_Bounds.First - Larray_Bounds.First) * C_Size);
1509 Rarray_Bounds : constant Range_Values :=
1510 Get_Index_Bounds (First_Index (R_Typ));
1511 R_Bounds : constant Range_Values :=
1512 (if Nkind (Expression (N)) = N_Slice
1513 then Get_Index_Bounds (Discrete_Range (Expression (N)))
1514 else Rarray_Bounds);
1516 R_Bit : constant Node_Id :=
1517 Make_Integer_Literal
1518 (Loc, (R_Bounds.First - Rarray_Bounds.First) * C_Size);
1520 Size : constant Node_Id :=
1521 Make_Op_Multiply (Loc,
1522 Make_Attribute_Reference (Loc,
1523 Prefix =>
1524 Duplicate_Subexpr (Name (N), True),
1525 Attribute_Name => Name_Length),
1526 Make_Attribute_Reference (Loc,
1527 Prefix =>
1528 Duplicate_Subexpr (Larray, True),
1529 Attribute_Name => Name_Component_Size));
1531 L_Arg, R_Arg, Call : Node_Id;
1533 begin
1534 -- The semantics of unchecked conversion between bit-packed arrays that
1535 -- are implemented as modular types and modular types is precisely that
1536 -- of unchecked conversion between modular types. Therefore, if it needs
1537 -- to be padded with zeros, the padding must be moved to the correct end
1538 -- for memory order because System.Bitfield_Utils works in memory order.
1540 if L_Small
1541 and then (Bytes_Big_Endian xor Reverse_Storage_Order (L_Typ))
1542 then
1543 L_Arg := Make_Op_Shift_Left (Loc,
1544 Left_Opnd => L_Val,
1545 Right_Opnd => Make_Integer_Literal (Loc,
1546 Standard_Long_Long_Integer_Size - RM_Size (L_Typ)));
1547 else
1548 L_Arg := L_Val;
1549 end if;
1551 if R_Small
1552 and then (Bytes_Big_Endian xor Reverse_Storage_Order (R_Typ))
1553 then
1554 R_Arg := Make_Op_Shift_Left (Loc,
1555 Left_Opnd => R_Val,
1556 Right_Opnd => Make_Integer_Literal (Loc,
1557 Standard_Long_Long_Integer_Size - RM_Size (R_Typ)));
1558 else
1559 R_Arg := R_Val;
1560 end if;
1562 Call := Make_Function_Call (Loc,
1563 Name => New_Occurrence_Of (RTE (RE_Fast_Copy_Bitfield), Loc),
1564 Parameter_Associations => New_List (
1565 R_Arg, R_Bit, L_Arg, L_Bit, Size));
1567 -- Conversely, the final unchecked conversion must take significant bits
1569 if L_Small
1570 and then (Bytes_Big_Endian xor Reverse_Storage_Order (L_Typ))
1571 then
1572 Call := Make_Op_Shift_Right (Loc,
1573 Left_Opnd => Call,
1574 Right_Opnd => Make_Integer_Literal (Loc,
1575 Standard_Long_Long_Integer_Size - RM_Size (L_Typ)));
1576 end if;
1578 return Make_Assignment_Statement (Loc,
1579 Name => Duplicate_Subexpr (Larray, True),
1580 Expression => Unchecked_Convert_To (L_Typ, Call));
1581 end Expand_Assign_Array_Bitfield_Fast;
1583 ------------------------------------------
1584 -- Expand_Assign_Array_Loop_Or_Bitfield --
1585 ------------------------------------------
1587 function Expand_Assign_Array_Loop_Or_Bitfield
1588 (N : Node_Id;
1589 Larray : Entity_Id;
1590 Rarray : Entity_Id;
1591 L_Type : Entity_Id;
1592 R_Type : Entity_Id;
1593 Ndim : Pos;
1594 Rev : Boolean) return Node_Id
1597 L : constant Node_Id := Name (N);
1598 R : constant Node_Id := Expression (N);
1599 -- Left- and right-hand sides of the assignment statement
1601 Slices : constant Boolean :=
1602 Nkind (L) = N_Slice or else Nkind (R) = N_Slice;
1603 L_Prefix_Comp : constant Boolean :=
1604 -- True if the left-hand side is a slice of a component or slice
1605 Nkind (L) = N_Slice
1606 and then Nkind (Prefix (L)) in
1607 N_Selected_Component | N_Indexed_Component | N_Slice;
1608 R_Prefix_Comp : constant Boolean :=
1609 -- Likewise for the right-hand side
1610 Nkind (R) = N_Slice
1611 and then Nkind (Prefix (R)) in
1612 N_Selected_Component | N_Indexed_Component | N_Slice;
1614 begin
1615 -- Determine whether Copy_Bitfield or Fast_Copy_Bitfield is appropriate
1616 -- (will work, and will be more efficient than component-by-component
1617 -- copy). Copy_Bitfield doesn't work for reversed storage orders. It is
1618 -- efficient for slices of bit-packed arrays. Copy_Bitfield can read and
1619 -- write bits that are not part of the objects being copied, so we don't
1620 -- want to use it if there are volatile or independent components. If
1621 -- the Prefix of the slice is a component or slice, then it might be a
1622 -- part of an object with some other volatile or independent components,
1623 -- so we disable the optimization in that case as well. We could
1624 -- complicate this code by actually looking for such volatile and
1625 -- independent components.
1627 if Is_Bit_Packed_Array (L_Type)
1628 and then Is_Bit_Packed_Array (R_Type)
1629 and then not Reverse_Storage_Order (L_Type)
1630 and then not Reverse_Storage_Order (R_Type)
1631 and then Ndim = 1
1632 and then Slices
1633 and then not Has_Volatile_Component (L_Type)
1634 and then not Has_Volatile_Component (R_Type)
1635 and then not Has_Independent_Components (L_Type)
1636 and then not Has_Independent_Components (R_Type)
1637 and then not L_Prefix_Comp
1638 and then not R_Prefix_Comp
1639 then
1640 -- Here if Copy_Bitfield can work (except for the Rev test below).
1641 -- Determine whether to call Fast_Copy_Bitfield instead. If we
1642 -- are assigning slices, and all the relevant bounds are known at
1643 -- compile time, and the maximum object size is no greater than
1644 -- System.Bitfields.Val_Bits (i.e. Long_Long_Integer'Size / 2), and
1645 -- we don't have enumeration representation clauses, we can use
1646 -- Fast_Copy_Bitfield. The max size test is to ensure that the slices
1647 -- cannot overlap boundaries not supported by Fast_Copy_Bitfield.
1649 pragma Assert (Known_Component_Size (Base_Type (L_Type)));
1650 pragma Assert (Known_Component_Size (Base_Type (R_Type)));
1652 -- Note that L_Type and R_Type do not necessarily have the same base
1653 -- type, because of array type conversions. Hence the need to check
1654 -- various properties of both.
1656 if Compile_Time_Known_Bounds (Base_Type (L_Type))
1657 and then Compile_Time_Known_Bounds (Base_Type (R_Type))
1658 then
1659 declare
1660 Left_Base_Index : constant Entity_Id :=
1661 First_Index (Base_Type (L_Type));
1662 Left_Base_Range : constant Range_Values :=
1663 Get_Index_Bounds (Left_Base_Index);
1665 Right_Base_Index : constant Entity_Id :=
1666 First_Index (Base_Type (R_Type));
1667 Right_Base_Range : constant Range_Values :=
1668 Get_Index_Bounds (Right_Base_Index);
1670 Known_Left_Slice_Low : constant Boolean :=
1671 (if Nkind (L) = N_Slice
1672 then Compile_Time_Known_Value
1673 (Get_Index_Bounds (Discrete_Range (L)).First));
1674 Known_Right_Slice_Low : constant Boolean :=
1675 (if Nkind (R) = N_Slice
1676 then Compile_Time_Known_Value
1677 (Get_Index_Bounds (Discrete_Range (R)).Last));
1679 Val_Bits : constant Pos := Standard_Long_Long_Integer_Size / 2;
1681 begin
1682 if Left_Base_Range.Last - Left_Base_Range.First < Val_Bits
1683 and then Right_Base_Range.Last - Right_Base_Range.First <
1684 Val_Bits
1685 and then Known_Esize (L_Type)
1686 and then Known_Esize (R_Type)
1687 and then Known_Left_Slice_Low
1688 and then Known_Right_Slice_Low
1689 and then Compile_Time_Known_Value
1690 (Get_Index_Bounds (First_Index (Etype (Larray))).First)
1691 and then Compile_Time_Known_Value
1692 (Get_Index_Bounds (First_Index (Etype (Rarray))).First)
1693 and then
1694 not (Is_Enumeration_Type (Etype (Left_Base_Index))
1695 and then Has_Enumeration_Rep_Clause
1696 (Etype (Left_Base_Index)))
1697 and then RTE_Available (RE_Fast_Copy_Bitfield)
1698 then
1699 pragma Assert (Known_Esize (L_Type));
1700 pragma Assert (Known_Esize (R_Type));
1702 return Expand_Assign_Array_Bitfield_Fast (N, Larray, Rarray);
1703 end if;
1704 end;
1705 end if;
1707 -- Fast_Copy_Bitfield can work if Rev is True, because the data is
1708 -- passed and returned by copy. Copy_Bitfield cannot.
1710 if not Rev and then RTE_Available (RE_Copy_Bitfield) then
1711 return Expand_Assign_Array_Bitfield
1712 (N, Larray, Rarray, L_Type, R_Type, Rev);
1713 end if;
1714 end if;
1716 -- Here if we did not return above, with Fast_Copy_Bitfield or
1717 -- Copy_Bitfield.
1719 return Expand_Assign_Array_Loop
1720 (N, Larray, Rarray, L_Type, R_Type, Ndim, Rev);
1721 end Expand_Assign_Array_Loop_Or_Bitfield;
1723 --------------------------
1724 -- Expand_Assign_Record --
1725 --------------------------
1727 procedure Expand_Assign_Record (N : Node_Id) is
1728 Lhs : constant Node_Id := Name (N);
1729 Rhs : Node_Id := Expression (N);
1730 L_Typ : constant Entity_Id := Base_Type (Etype (Lhs));
1732 begin
1733 -- If change of representation, then extract the real right-hand side
1734 -- from the type conversion, and proceed with component-wise assignment,
1735 -- since the two types are not the same as far as the back end is
1736 -- concerned.
1738 if Change_Of_Representation (N) then
1739 Rhs := Expression (Rhs);
1741 -- If this may be a case of a large bit aligned component, then proceed
1742 -- with component-wise assignment, to avoid possible clobbering of other
1743 -- components sharing bits in the first or last byte of the component to
1744 -- be assigned.
1746 elsif Possible_Bit_Aligned_Component (Lhs)
1747 or else
1748 Possible_Bit_Aligned_Component (Rhs)
1749 then
1750 null;
1752 -- If we have a tagged type that has a complete record representation
1753 -- clause, we must do we must do component-wise assignments, since child
1754 -- types may have used gaps for their components, and we might be
1755 -- dealing with a view conversion.
1757 elsif Is_Fully_Repped_Tagged_Type (L_Typ) then
1758 null;
1760 -- If neither condition met, then nothing special to do, the back end
1761 -- can handle assignment of the entire component as a single entity.
1763 else
1764 return;
1765 end if;
1767 -- At this stage we know that we must do a component wise assignment
1769 declare
1770 Loc : constant Source_Ptr := Sloc (N);
1771 R_Typ : constant Entity_Id := Base_Type (Etype (Rhs));
1772 Decl : constant Node_Id := Declaration_Node (R_Typ);
1773 RDef : Node_Id;
1774 F : Entity_Id;
1776 function Find_Component
1777 (Typ : Entity_Id;
1778 Comp : Entity_Id) return Entity_Id;
1779 -- Find the component with the given name in the underlying record
1780 -- declaration for Typ. We need to use the actual entity because the
1781 -- type may be private and resolution by identifier alone would fail.
1783 function Make_Component_List_Assign
1784 (CL : Node_Id;
1785 U_U : Boolean := False) return List_Id;
1786 -- Returns a sequence of statements to assign the components that
1787 -- are referenced in the given component list. The flag U_U is
1788 -- used to force the usage of the inferred value of the variant
1789 -- part expression as the switch for the generated case statement.
1791 function Make_Field_Assign
1792 (C : Entity_Id;
1793 U_U : Boolean := False) return Node_Id;
1794 -- Given C, the entity for a discriminant or component, build an
1795 -- assignment for the corresponding field values. The flag U_U
1796 -- signals the presence of an Unchecked_Union and forces the usage
1797 -- of the inferred discriminant value of C as the right-hand side
1798 -- of the assignment.
1800 function Make_Field_Assigns (CI : List_Id) return List_Id;
1801 -- Given CI, a component items list, construct series of statements
1802 -- for fieldwise assignment of the corresponding components.
1804 --------------------
1805 -- Find_Component --
1806 --------------------
1808 function Find_Component
1809 (Typ : Entity_Id;
1810 Comp : Entity_Id) return Entity_Id
1812 Utyp : constant Entity_Id := Underlying_Type (Typ);
1813 C : Entity_Id;
1815 begin
1816 C := First_Entity (Utyp);
1817 while Present (C) loop
1818 if Chars (C) = Chars (Comp) then
1819 return C;
1821 -- The component may be a renamed discriminant, in
1822 -- which case check against the name of the original
1823 -- discriminant of the parent type.
1825 elsif Is_Derived_Type (Scope (Comp))
1826 and then Ekind (Comp) = E_Discriminant
1827 and then Present (Corresponding_Discriminant (Comp))
1828 and then
1829 Chars (C) = Chars (Corresponding_Discriminant (Comp))
1830 then
1831 return C;
1832 end if;
1834 Next_Entity (C);
1835 end loop;
1837 raise Program_Error;
1838 end Find_Component;
1840 --------------------------------
1841 -- Make_Component_List_Assign --
1842 --------------------------------
1844 function Make_Component_List_Assign
1845 (CL : Node_Id;
1846 U_U : Boolean := False) return List_Id
1848 CI : constant List_Id := Component_Items (CL);
1849 VP : constant Node_Id := Variant_Part (CL);
1851 Alts : List_Id;
1852 DC : Node_Id;
1853 DCH : List_Id;
1854 Expr : Node_Id;
1855 Result : List_Id;
1856 V : Node_Id;
1858 begin
1859 Result := Make_Field_Assigns (CI);
1861 if Present (VP) then
1862 V := First_Non_Pragma (Variants (VP));
1863 Alts := New_List;
1864 while Present (V) loop
1865 DCH := New_List;
1866 DC := First (Discrete_Choices (V));
1867 while Present (DC) loop
1868 Append_To (DCH, New_Copy_Tree (DC));
1869 Next (DC);
1870 end loop;
1872 Append_To (Alts,
1873 Make_Case_Statement_Alternative (Loc,
1874 Discrete_Choices => DCH,
1875 Statements =>
1876 Make_Component_List_Assign (Component_List (V))));
1877 Next_Non_Pragma (V);
1878 end loop;
1880 -- Try to find a constrained type or a derived type to extract
1881 -- discriminant values from, so that the case statement built
1882 -- below can be folded by Expand_N_Case_Statement.
1884 if U_U or else Is_Constrained (Etype (Rhs)) then
1885 Expr :=
1886 New_Copy (Get_Discriminant_Value (
1887 Entity (Name (VP)),
1888 Etype (Rhs),
1889 Discriminant_Constraint (Etype (Rhs))));
1891 elsif Is_Constrained (Etype (Expression (N))) then
1892 Expr :=
1893 New_Copy (Get_Discriminant_Value (
1894 Entity (Name (VP)),
1895 Etype (Expression (N)),
1896 Discriminant_Constraint (Etype (Expression (N)))));
1898 elsif Is_Derived_Type (Etype (Rhs))
1899 and then Present (Stored_Constraint (Etype (Rhs)))
1900 then
1901 Expr :=
1902 New_Copy (Get_Discriminant_Value (
1903 Corresponding_Record_Component (Entity (Name (VP))),
1904 Etype (Etype (Rhs)),
1905 Stored_Constraint (Etype (Rhs))));
1907 else
1908 Expr := Empty;
1909 end if;
1911 if No (Expr) or else not Compile_Time_Known_Value (Expr) then
1912 Expr :=
1913 Make_Selected_Component (Loc,
1914 Prefix => Duplicate_Subexpr (Rhs),
1915 Selector_Name =>
1916 Make_Identifier (Loc, Chars (Name (VP))));
1917 end if;
1919 Append_To (Result,
1920 Make_Case_Statement (Loc,
1921 Expression => Expr,
1922 Alternatives => Alts));
1923 end if;
1925 return Result;
1926 end Make_Component_List_Assign;
1928 -----------------------
1929 -- Make_Field_Assign --
1930 -----------------------
1932 function Make_Field_Assign
1933 (C : Entity_Id;
1934 U_U : Boolean := False) return Node_Id
1936 A : Node_Id;
1937 Disc : Entity_Id;
1938 Expr : Node_Id;
1940 begin
1941 -- The discriminant entity to be used in the retrieval below must
1942 -- be one in the corresponding type, given that the assignment may
1943 -- be between derived and parent types.
1945 if Is_Derived_Type (Etype (Rhs)) then
1946 Disc := Find_Component (R_Typ, C);
1947 else
1948 Disc := C;
1949 end if;
1951 -- In the case of an Unchecked_Union, use the discriminant
1952 -- constraint value as on the right-hand side of the assignment.
1954 if U_U then
1955 Expr :=
1956 New_Copy (Get_Discriminant_Value (C,
1957 Etype (Rhs),
1958 Discriminant_Constraint (Etype (Rhs))));
1959 else
1960 Expr :=
1961 Make_Selected_Component (Loc,
1962 Prefix => Duplicate_Subexpr (Rhs),
1963 Selector_Name => New_Occurrence_Of (Disc, Loc));
1964 end if;
1966 -- Generate the assignment statement. When the left-hand side
1967 -- is an object with an address clause present, force generated
1968 -- temporaries to be renamings so as to correctly assign to any
1969 -- overlaid objects.
1971 A :=
1972 Make_Assignment_Statement (Loc,
1973 Name =>
1974 Make_Selected_Component (Loc,
1975 Prefix =>
1976 Duplicate_Subexpr
1977 (Exp => Lhs,
1978 Name_Req => False,
1979 Renaming_Req =>
1980 Is_Entity_Name (Lhs)
1981 and then Present (Address_Clause (Entity (Lhs)))),
1982 Selector_Name =>
1983 New_Occurrence_Of (Find_Component (L_Typ, C), Loc)),
1984 Expression => Expr);
1986 -- Set Assignment_OK, so discriminants can be assigned
1988 Set_Assignment_OK (Name (A), True);
1990 if Componentwise_Assignment (N)
1991 and then Nkind (Name (A)) = N_Selected_Component
1992 and then Chars (Selector_Name (Name (A))) = Name_uParent
1993 then
1994 Set_Componentwise_Assignment (A);
1995 end if;
1997 return A;
1998 end Make_Field_Assign;
2000 ------------------------
2001 -- Make_Field_Assigns --
2002 ------------------------
2004 function Make_Field_Assigns (CI : List_Id) return List_Id is
2005 Item : Node_Id;
2006 Result : List_Id;
2008 begin
2009 Item := First (CI);
2010 Result := New_List;
2012 while Present (Item) loop
2014 -- Look for components, but exclude _tag field assignment if
2015 -- the special Componentwise_Assignment flag is set.
2017 if Nkind (Item) = N_Component_Declaration
2018 and then not (Is_Tag (Defining_Identifier (Item))
2019 and then Componentwise_Assignment (N))
2020 then
2021 Append_To
2022 (Result, Make_Field_Assign (Defining_Identifier (Item)));
2023 end if;
2025 Next (Item);
2026 end loop;
2028 return Result;
2029 end Make_Field_Assigns;
2031 -- Start of processing for Expand_Assign_Record
2033 begin
2034 -- Note that we need to use the base types for this processing in
2035 -- order to retrieve the Type_Definition. In the constrained case,
2036 -- we filter out the non relevant fields in
2037 -- Make_Component_List_Assign.
2039 -- First copy the discriminants. This is done unconditionally. It
2040 -- is required in the unconstrained left side case, and also in the
2041 -- case where this assignment was constructed during the expansion
2042 -- of a type conversion (since initialization of discriminants is
2043 -- suppressed in this case). It is unnecessary but harmless in
2044 -- other cases.
2046 -- Special case: no copy if the target has no discriminants
2048 if Has_Discriminants (L_Typ)
2049 and then Is_Unchecked_Union (Base_Type (L_Typ))
2050 then
2051 null;
2053 elsif Has_Discriminants (L_Typ) then
2054 F := First_Discriminant (R_Typ);
2055 while Present (F) loop
2057 -- If we are expanding the initialization of a derived record
2058 -- that constrains or renames discriminants of the parent, we
2059 -- must use the corresponding discriminant in the parent.
2061 declare
2062 CF : Entity_Id;
2064 begin
2065 if Inside_Init_Proc
2066 and then Present (Corresponding_Discriminant (F))
2067 then
2068 CF := Corresponding_Discriminant (F);
2069 else
2070 CF := F;
2071 end if;
2073 if Is_Unchecked_Union (R_Typ) then
2075 -- Within an initialization procedure this is the
2076 -- assignment to an unchecked union component, in which
2077 -- case there is no discriminant to initialize.
2079 if Inside_Init_Proc then
2080 null;
2082 else
2083 -- The assignment is part of a conversion from a
2084 -- derived unchecked union type with an inferable
2085 -- discriminant, to a parent type.
2087 Insert_Action (N, Make_Field_Assign (CF, True));
2088 end if;
2090 else
2091 Insert_Action (N, Make_Field_Assign (CF));
2092 end if;
2094 Next_Discriminant (F);
2095 end;
2096 end loop;
2098 -- If the derived type has a stored constraint, assign the value
2099 -- of the corresponding discriminants explicitly, skipping those
2100 -- that are renamed discriminants. We cannot just retrieve them
2101 -- from the Rhs by selected component because they are invisible
2102 -- in the type of the right-hand side.
2104 if Present (Stored_Constraint (R_Typ)) then
2105 declare
2106 Assign : Node_Id;
2107 Discr_Val : Elmt_Id;
2109 begin
2110 Discr_Val := First_Elmt (Stored_Constraint (R_Typ));
2111 F := First_Entity (R_Typ);
2112 while Present (F) loop
2113 if Ekind (F) = E_Discriminant
2114 and then Is_Completely_Hidden (F)
2115 and then Present (Corresponding_Record_Component (F))
2116 and then
2117 (not Is_Entity_Name (Node (Discr_Val))
2118 or else Ekind (Entity (Node (Discr_Val))) /=
2119 E_Discriminant)
2120 then
2121 Assign :=
2122 Make_Assignment_Statement (Loc,
2123 Name =>
2124 Make_Selected_Component (Loc,
2125 Prefix => Duplicate_Subexpr (Lhs),
2126 Selector_Name =>
2127 New_Occurrence_Of
2128 (Corresponding_Record_Component (F), Loc)),
2129 Expression => New_Copy (Node (Discr_Val)));
2131 Set_Assignment_OK (Name (Assign));
2132 Insert_Action (N, Assign);
2133 Next_Elmt (Discr_Val);
2134 end if;
2136 Next_Entity (F);
2137 end loop;
2138 end;
2139 end if;
2140 end if;
2142 -- We know the underlying type is a record, but its current view
2143 -- may be private. We must retrieve the usable record declaration.
2145 if Nkind (Decl) in N_Private_Type_Declaration
2146 | N_Private_Extension_Declaration
2147 and then Present (Full_View (R_Typ))
2148 then
2149 RDef := Type_Definition (Declaration_Node (Full_View (R_Typ)));
2150 else
2151 RDef := Type_Definition (Decl);
2152 end if;
2154 if Nkind (RDef) = N_Derived_Type_Definition then
2155 RDef := Record_Extension_Part (RDef);
2156 end if;
2158 if Nkind (RDef) = N_Record_Definition
2159 and then Present (Component_List (RDef))
2160 then
2161 if Is_Unchecked_Union (R_Typ) then
2162 Insert_Actions (N,
2163 Make_Component_List_Assign (Component_List (RDef), True));
2164 else
2165 Insert_Actions (N,
2166 Make_Component_List_Assign (Component_List (RDef)));
2167 end if;
2169 Rewrite (N, Make_Null_Statement (Loc));
2170 end if;
2171 end;
2172 end Expand_Assign_Record;
2174 -------------------------------------
2175 -- Expand_Assign_With_Target_Names --
2176 -------------------------------------
2178 procedure Expand_Assign_With_Target_Names (N : Node_Id) is
2179 LHS : constant Node_Id := Name (N);
2180 LHS_Typ : constant Entity_Id := Etype (LHS);
2181 Loc : constant Source_Ptr := Sloc (N);
2182 RHS : constant Node_Id := Expression (N);
2184 Ent : Entity_Id;
2185 -- The entity of the left-hand side
2187 function Replace_Target (N : Node_Id) return Traverse_Result;
2188 -- Replace occurrences of the target name by the proper entity: either
2189 -- the entity of the LHS in simple cases, or the formal of the
2190 -- constructed procedure otherwise.
2192 --------------------
2193 -- Replace_Target --
2194 --------------------
2196 function Replace_Target (N : Node_Id) return Traverse_Result is
2197 begin
2198 if Nkind (N) = N_Target_Name then
2199 Rewrite (N, New_Occurrence_Of (Ent, Sloc (N)));
2201 -- The expression will be reanalyzed when the enclosing assignment
2202 -- is reanalyzed, so reset the entity, which may be a temporary
2203 -- created during analysis, e.g. a loop variable for an iterated
2204 -- component association. However, if entity is callable then
2205 -- resolution has established its proper identity (including in
2206 -- rewritten prefixed calls) so we must preserve it.
2208 elsif Is_Entity_Name (N) then
2209 if Present (Entity (N))
2210 and then not Is_Overloadable (Entity (N))
2211 then
2212 Set_Entity (N, Empty);
2213 end if;
2214 end if;
2216 Set_Analyzed (N, False);
2217 return OK;
2218 end Replace_Target;
2220 procedure Replace_Target_Name is new Traverse_Proc (Replace_Target);
2222 -- Local variables
2224 New_RHS : Node_Id;
2225 Proc_Id : Entity_Id;
2227 -- Start of processing for Expand_Assign_With_Target_Names
2229 begin
2230 New_RHS := New_Copy_Tree (RHS);
2232 -- The left-hand side is a direct name
2234 if Is_Entity_Name (LHS)
2235 and then not Is_Renaming_Of_Object (Entity (LHS))
2236 then
2237 Ent := Entity (LHS);
2238 Replace_Target_Name (New_RHS);
2240 -- Generate:
2241 -- LHS := ... LHS ...;
2243 Rewrite (N,
2244 Make_Assignment_Statement (Loc,
2245 Name => Relocate_Node (LHS),
2246 Expression => New_RHS));
2248 -- The left-hand side is not a direct name, but is side-effect free.
2249 -- Capture its value in a temporary to avoid generating a procedure.
2250 -- We don't do this optimization if the target object's type may need
2251 -- finalization actions, because we don't want extra finalizations to
2252 -- be done for the temp object, and instead we use the more general
2253 -- procedure-based approach below.
2255 elsif Side_Effect_Free (LHS)
2256 and then not Needs_Finalization (Etype (LHS))
2257 then
2258 Ent := Make_Temporary (Loc, 'T');
2259 Replace_Target_Name (New_RHS);
2261 -- Generate:
2262 -- T : LHS_Typ := LHS;
2264 Insert_Before_And_Analyze (N,
2265 Make_Object_Declaration (Loc,
2266 Defining_Identifier => Ent,
2267 Object_Definition => New_Occurrence_Of (LHS_Typ, Loc),
2268 Expression => New_Copy_Tree (LHS)));
2270 -- Generate:
2271 -- LHS := ... T ...;
2273 Rewrite (N,
2274 Make_Assignment_Statement (Loc,
2275 Name => Relocate_Node (LHS),
2276 Expression => New_RHS));
2278 -- Otherwise wrap the whole assignment statement in a procedure with an
2279 -- IN OUT parameter. The original assignment then becomes a call to the
2280 -- procedure with the left-hand side as an actual.
2282 else
2283 Ent := Make_Temporary (Loc, 'T');
2284 Replace_Target_Name (New_RHS);
2286 -- Generate:
2287 -- procedure P (T : in out LHS_Typ) is
2288 -- begin
2289 -- T := ... T ...;
2290 -- end P;
2292 Proc_Id := Make_Temporary (Loc, 'P');
2294 Insert_Before_And_Analyze (N,
2295 Make_Subprogram_Body (Loc,
2296 Specification =>
2297 Make_Procedure_Specification (Loc,
2298 Defining_Unit_Name => Proc_Id,
2299 Parameter_Specifications => New_List (
2300 Make_Parameter_Specification (Loc,
2301 Defining_Identifier => Ent,
2302 In_Present => True,
2303 Out_Present => True,
2304 Parameter_Type =>
2305 New_Occurrence_Of (LHS_Typ, Loc)))),
2307 Declarations => Empty_List,
2309 Handled_Statement_Sequence =>
2310 Make_Handled_Sequence_Of_Statements (Loc,
2311 Statements => New_List (
2312 Make_Assignment_Statement (Loc,
2313 Name => New_Occurrence_Of (Ent, Loc),
2314 Expression => New_RHS)))));
2316 -- Generate:
2317 -- P (LHS);
2319 Rewrite (N,
2320 Make_Procedure_Call_Statement (Loc,
2321 Name => New_Occurrence_Of (Proc_Id, Loc),
2322 Parameter_Associations => New_List (Relocate_Node (LHS))));
2323 end if;
2325 -- Analyze rewritten node, either as assignment or procedure call
2327 Analyze (N);
2328 end Expand_Assign_With_Target_Names;
2330 -----------------------------------
2331 -- Expand_N_Assignment_Statement --
2332 -----------------------------------
2334 -- This procedure implements various cases where an assignment statement
2335 -- cannot just be passed on to the back end in untransformed state.
2337 procedure Expand_N_Assignment_Statement (N : Node_Id) is
2338 Crep : constant Boolean := Change_Of_Representation (N);
2339 Lhs : constant Node_Id := Name (N);
2340 Loc : constant Source_Ptr := Sloc (N);
2341 Rhs : constant Node_Id := Expression (N);
2342 Typ : constant Entity_Id := Underlying_Type (Etype (Lhs));
2343 Exp : Node_Id;
2345 begin
2346 -- Special case to check right away, if the Componentwise_Assignment
2347 -- flag is set, this is a reanalysis from the expansion of the primitive
2348 -- assignment procedure for a tagged type, and all we need to do is to
2349 -- expand to assignment of components, because otherwise, we would get
2350 -- infinite recursion (since this looks like a tagged assignment which
2351 -- would normally try to *call* the primitive assignment procedure).
2353 if Componentwise_Assignment (N) then
2354 Expand_Assign_Record (N);
2355 return;
2356 end if;
2358 -- Defend against invalid subscripts on left side if we are in standard
2359 -- validity checking mode. No need to do this if we are checking all
2360 -- subscripts.
2362 -- Note that we do this right away, because there are some early return
2363 -- paths in this procedure, and this is required on all paths.
2365 if Validity_Checks_On
2366 and then Validity_Check_Default
2367 and then not Validity_Check_Subscripts
2368 then
2369 Check_Valid_Lvalue_Subscripts (Lhs);
2370 end if;
2372 -- Separate expansion if RHS contain target names. Note that assignment
2373 -- may already have been expanded if RHS is aggregate.
2375 if Nkind (N) = N_Assignment_Statement and then Has_Target_Names (N) then
2376 Expand_Assign_With_Target_Names (N);
2377 return;
2378 end if;
2380 -- Ada 2005 (AI-327): Handle assignment to priority of protected object
2382 -- Rewrite an assignment to X'Priority into a run-time call
2384 -- For example: X'Priority := New_Prio_Expr;
2385 -- ...is expanded into Set_Ceiling (X._Object, New_Prio_Expr);
2387 -- Note that although X'Priority is notionally an object, it is quite
2388 -- deliberately not defined as an aliased object in the RM. This means
2389 -- that it works fine to rewrite it as a call, without having to worry
2390 -- about complications that would other arise from X'Priority'Access,
2391 -- which is illegal, because of the lack of aliasing.
2393 if Ada_Version >= Ada_2005 then
2394 declare
2395 Call : Node_Id;
2396 Conctyp : Entity_Id;
2397 Ent : Entity_Id;
2398 Subprg : Entity_Id;
2399 RT_Subprg_Name : Node_Id;
2401 begin
2402 -- Handle chains of renamings
2404 Ent := Name (N);
2405 while Nkind (Ent) in N_Has_Entity
2406 and then Present (Entity (Ent))
2407 and then Is_Object (Entity (Ent))
2408 and then Present (Renamed_Object (Entity (Ent)))
2409 loop
2410 Ent := Renamed_Object (Entity (Ent));
2411 end loop;
2413 -- The attribute Priority applied to protected objects has been
2414 -- previously expanded into a call to the Get_Ceiling run-time
2415 -- subprogram. In restricted profiles this is not available.
2417 if Is_Expanded_Priority_Attribute (Ent) then
2419 -- Look for the enclosing concurrent type
2421 Conctyp := Current_Scope;
2422 while not Is_Concurrent_Type (Conctyp) loop
2423 Conctyp := Scope (Conctyp);
2424 end loop;
2426 pragma Assert (Is_Protected_Type (Conctyp));
2428 -- Generate the first actual of the call
2430 Subprg := Current_Scope;
2431 while not Present (Protected_Body_Subprogram (Subprg)) loop
2432 Subprg := Scope (Subprg);
2433 end loop;
2435 -- Select the appropriate run-time call
2437 if Number_Entries (Conctyp) = 0 then
2438 RT_Subprg_Name :=
2439 New_Occurrence_Of (RTE (RE_Set_Ceiling), Loc);
2440 else
2441 RT_Subprg_Name :=
2442 New_Occurrence_Of (RTE (RO_PE_Set_Ceiling), Loc);
2443 end if;
2445 Call :=
2446 Make_Procedure_Call_Statement (Loc,
2447 Name => RT_Subprg_Name,
2448 Parameter_Associations => New_List (
2449 New_Copy_Tree (First (Parameter_Associations (Ent))),
2450 Relocate_Node (Expression (N))));
2452 Rewrite (N, Call);
2453 Analyze (N);
2455 return;
2456 end if;
2457 end;
2458 end if;
2460 -- Deal with assignment checks unless suppressed
2462 if not Suppress_Assignment_Checks (N) then
2464 -- First deal with generation of range check if required,
2465 -- and then predicate checks if the type carries a predicate.
2466 -- If the Rhs is an expression these tests may have been applied
2467 -- already. This is the case if the RHS is a type conversion.
2468 -- Other such redundant checks could be removed ???
2470 if Nkind (Rhs) /= N_Type_Conversion
2471 or else Entity (Subtype_Mark (Rhs)) /= Typ
2472 then
2473 if Do_Range_Check (Rhs) then
2474 Generate_Range_Check (Rhs, Typ, CE_Range_Check_Failed);
2475 end if;
2477 Apply_Predicate_Check (Rhs, Typ);
2478 end if;
2479 end if;
2481 -- Check for a special case where a high level transformation is
2482 -- required. If we have either of:
2484 -- P.field := rhs;
2485 -- P (sub) := rhs;
2487 -- where P is a reference to a bit packed array, then we have to unwind
2488 -- the assignment. The exact meaning of being a reference to a bit
2489 -- packed array is as follows:
2491 -- An indexed component whose prefix is a bit packed array is a
2492 -- reference to a bit packed array.
2494 -- An indexed component or selected component whose prefix is a
2495 -- reference to a bit packed array is itself a reference ot a
2496 -- bit packed array.
2498 -- The required transformation is
2500 -- Tnn : prefix_type := P;
2501 -- Tnn.field := rhs;
2502 -- P := Tnn;
2504 -- or
2506 -- Tnn : prefix_type := P;
2507 -- Tnn (subscr) := rhs;
2508 -- P := Tnn;
2510 -- Since P is going to be evaluated more than once, any subscripts
2511 -- in P must have their evaluation forced.
2513 if Nkind (Lhs) in N_Indexed_Component | N_Selected_Component
2514 and then Is_Ref_To_Bit_Packed_Array (Prefix (Lhs))
2515 then
2516 declare
2517 BPAR_Expr : constant Node_Id := Relocate_Node (Prefix (Lhs));
2518 BPAR_Typ : constant Entity_Id := Etype (BPAR_Expr);
2519 Tnn : constant Entity_Id :=
2520 Make_Temporary (Loc, 'T', BPAR_Expr);
2522 begin
2523 -- Insert the post assignment first, because we want to copy the
2524 -- BPAR_Expr tree before it gets analyzed in the context of the
2525 -- pre assignment. Note that we do not analyze the post assignment
2526 -- yet (we cannot till we have completed the analysis of the pre
2527 -- assignment). As usual, the analysis of this post assignment
2528 -- will happen on its own when we "run into" it after finishing
2529 -- the current assignment.
2531 Insert_After (N,
2532 Make_Assignment_Statement (Loc,
2533 Name => New_Copy_Tree (BPAR_Expr),
2534 Expression => New_Occurrence_Of (Tnn, Loc)));
2536 -- At this stage BPAR_Expr is a reference to a bit packed array
2537 -- where the reference was not expanded in the original tree,
2538 -- since it was on the left side of an assignment. But in the
2539 -- pre-assignment statement (the object definition), BPAR_Expr
2540 -- will end up on the right-hand side, and must be reexpanded. To
2541 -- achieve this, we reset the analyzed flag of all selected and
2542 -- indexed components down to the actual indexed component for
2543 -- the packed array.
2545 Exp := BPAR_Expr;
2546 loop
2547 Set_Analyzed (Exp, False);
2549 if Nkind (Exp) in N_Indexed_Component | N_Selected_Component
2550 then
2551 Exp := Prefix (Exp);
2552 else
2553 exit;
2554 end if;
2555 end loop;
2557 -- Now we can insert and analyze the pre-assignment
2559 -- If the right-hand side requires a transient scope, it has
2560 -- already been placed on the stack. However, the declaration is
2561 -- inserted in the tree outside of this scope, and must reflect
2562 -- the proper scope for its variable. This awkward bit is forced
2563 -- by the stricter scope discipline imposed by GCC 2.97.
2565 declare
2566 Uses_Transient_Scope : constant Boolean :=
2567 Scope_Is_Transient
2568 and then N = Node_To_Be_Wrapped;
2570 begin
2571 if Uses_Transient_Scope then
2572 Push_Scope (Scope (Current_Scope));
2573 end if;
2575 Insert_Before_And_Analyze (N,
2576 Make_Object_Declaration (Loc,
2577 Defining_Identifier => Tnn,
2578 Object_Definition => New_Occurrence_Of (BPAR_Typ, Loc),
2579 Expression => BPAR_Expr));
2581 if Uses_Transient_Scope then
2582 Pop_Scope;
2583 end if;
2584 end;
2586 -- Now fix up the original assignment and continue processing
2588 Rewrite (Prefix (Lhs),
2589 New_Occurrence_Of (Tnn, Loc));
2591 -- We do not need to reanalyze that assignment, and we do not need
2592 -- to worry about references to the temporary, but we do need to
2593 -- make sure that the temporary is not marked as a true constant
2594 -- since we now have a generated assignment to it.
2596 Set_Is_True_Constant (Tnn, False);
2597 end;
2598 end if;
2600 -- When we have the appropriate type of aggregate in the expression (it
2601 -- has been determined during analysis of the aggregate by setting the
2602 -- delay flag), let's perform in place assignment and thus avoid
2603 -- creating a temporary.
2605 if Is_Delayed_Aggregate (Rhs) then
2606 Convert_Aggr_In_Assignment (N);
2607 Rewrite (N, Make_Null_Statement (Loc));
2608 Analyze (N);
2610 return;
2611 end if;
2613 -- Apply discriminant check if required. If Lhs is an access type to a
2614 -- designated type with discriminants, we must always check. If the
2615 -- type has unknown discriminants, more elaborate processing below.
2617 if Has_Discriminants (Etype (Lhs))
2618 and then not Has_Unknown_Discriminants (Etype (Lhs))
2619 then
2620 -- Skip discriminant check if change of representation. Will be
2621 -- done when the change of representation is expanded out.
2623 if not Crep then
2624 Apply_Discriminant_Check (Rhs, Etype (Lhs), Lhs);
2625 end if;
2627 -- If the type is private without discriminants, and the full type
2628 -- has discriminants (necessarily with defaults) a check may still be
2629 -- necessary if the Lhs is aliased. The private discriminants must be
2630 -- visible to build the discriminant constraints.
2632 -- Only an explicit dereference that comes from source indicates
2633 -- aliasing. Access to formals of protected operations and entries
2634 -- create dereferences but are not semantic aliasings.
2636 elsif Is_Private_Type (Etype (Lhs))
2637 and then Has_Discriminants (Typ)
2638 and then Nkind (Lhs) = N_Explicit_Dereference
2639 and then Comes_From_Source (Lhs)
2640 then
2641 declare
2642 Lt : constant Entity_Id := Etype (Lhs);
2643 Ubt : Entity_Id := Base_Type (Typ);
2645 begin
2646 -- In the case of an expander-generated record subtype whose base
2647 -- type still appears private, Typ will have been set to that
2648 -- private type rather than the underlying record type (because
2649 -- Underlying type will have returned the record subtype), so it's
2650 -- necessary to apply Underlying_Type again to the base type to
2651 -- get the record type we need for the discriminant check. Such
2652 -- subtypes can be created for assignments in certain cases, such
2653 -- as within an instantiation passed this kind of private type.
2654 -- It would be good to avoid this special test, but making changes
2655 -- to prevent this odd form of record subtype seems difficult. ???
2657 if Is_Private_Type (Ubt) then
2658 Ubt := Underlying_Type (Ubt);
2659 end if;
2661 Set_Etype (Lhs, Ubt);
2662 Rewrite (Rhs, OK_Convert_To (Base_Type (Ubt), Rhs));
2663 Apply_Discriminant_Check (Rhs, Ubt, Lhs);
2664 Set_Etype (Lhs, Lt);
2665 end;
2667 -- If the Lhs has a private type with unknown discriminants, it may
2668 -- have a full view with discriminants, but those are nameable only
2669 -- in the underlying type, so convert the Rhs to it before potential
2670 -- checking. Convert Lhs as well, otherwise the actual subtype might
2671 -- not be constructible. If the discriminants have defaults the type
2672 -- is unconstrained and there is nothing to check.
2673 -- Ditto if a private type with unknown discriminants has a full view
2674 -- that is an unconstrained array, in which case a length check is
2675 -- needed.
2677 elsif Has_Unknown_Discriminants (Base_Type (Etype (Lhs))) then
2678 if Has_Discriminants (Typ)
2679 and then not Has_Defaulted_Discriminants (Typ)
2680 then
2681 Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
2682 Rewrite (Lhs, OK_Convert_To (Base_Type (Typ), Lhs));
2683 Apply_Discriminant_Check (Rhs, Typ, Lhs);
2685 elsif Is_Array_Type (Typ) and then Is_Constrained (Typ) then
2686 Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
2687 Rewrite (Lhs, OK_Convert_To (Base_Type (Typ), Lhs));
2688 Apply_Length_Check (Rhs, Typ);
2689 end if;
2691 -- In the access type case, we need the same discriminant check, and
2692 -- also range checks if we have an access to constrained array.
2694 elsif Is_Access_Type (Etype (Lhs))
2695 and then Is_Constrained (Designated_Type (Etype (Lhs)))
2696 then
2697 if Has_Discriminants (Designated_Type (Etype (Lhs))) then
2699 -- Skip discriminant check if change of representation. Will be
2700 -- done when the change of representation is expanded out.
2702 if not Crep then
2703 Apply_Discriminant_Check (Rhs, Etype (Lhs));
2704 end if;
2706 elsif Is_Array_Type (Designated_Type (Etype (Lhs))) then
2707 Apply_Range_Check (Rhs, Etype (Lhs));
2709 if Is_Constrained (Etype (Lhs)) then
2710 Apply_Length_Check (Rhs, Etype (Lhs));
2711 end if;
2712 end if;
2713 end if;
2715 -- Ada 2005 (AI-231): Generate the run-time check
2717 if Is_Access_Type (Typ)
2718 and then Can_Never_Be_Null (Etype (Lhs))
2719 and then not Can_Never_Be_Null (Etype (Rhs))
2721 -- If an actual is an out parameter of a null-excluding access
2722 -- type, there is access check on entry, so we set the flag
2723 -- Suppress_Assignment_Checks on the generated statement to
2724 -- assign the actual to the parameter block, and we do not want
2725 -- to generate an additional check at this point.
2727 and then not Suppress_Assignment_Checks (N)
2728 then
2729 Apply_Constraint_Check (Rhs, Etype (Lhs));
2730 end if;
2732 -- Ada 2012 (AI05-148): Update current accessibility level if Rhs is a
2733 -- stand-alone obj of an anonymous access type. Do not install the check
2734 -- when the Lhs denotes a container cursor and the Next function employs
2735 -- an access type, because this can never result in a dangling pointer.
2737 if Is_Access_Type (Typ)
2738 and then Is_Entity_Name (Lhs)
2739 and then Ekind (Entity (Lhs)) /= E_Loop_Parameter
2740 and then Present (Effective_Extra_Accessibility (Entity (Lhs)))
2741 then
2742 declare
2743 function Lhs_Entity return Entity_Id;
2744 -- Look through renames to find the underlying entity.
2745 -- For assignment to a rename, we don't care about the
2746 -- Enclosing_Dynamic_Scope of the rename declaration.
2748 ----------------
2749 -- Lhs_Entity --
2750 ----------------
2752 function Lhs_Entity return Entity_Id is
2753 Result : Entity_Id := Entity (Lhs);
2755 begin
2756 while Present (Renamed_Object (Result)) loop
2758 -- Renamed_Object must return an Entity_Name here
2759 -- because of preceding "Present (E_E_A (...))" test.
2761 Result := Entity (Renamed_Object (Result));
2762 end loop;
2764 return Result;
2765 end Lhs_Entity;
2767 -- Local Declarations
2769 Access_Check : constant Node_Id :=
2770 Make_Raise_Program_Error (Loc,
2771 Condition =>
2772 Make_Op_Gt (Loc,
2773 Left_Opnd =>
2774 Accessibility_Level (Rhs, Dynamic_Level),
2775 Right_Opnd =>
2776 Make_Integer_Literal (Loc,
2777 Intval =>
2778 Scope_Depth
2779 (Enclosing_Dynamic_Scope
2780 (Lhs_Entity)))),
2781 Reason => PE_Accessibility_Check_Failed);
2783 Access_Level_Update : constant Node_Id :=
2784 Make_Assignment_Statement (Loc,
2785 Name =>
2786 New_Occurrence_Of
2787 (Effective_Extra_Accessibility
2788 (Entity (Lhs)), Loc),
2789 Expression =>
2790 Accessibility_Level
2791 (Expr => Rhs,
2792 Level => Dynamic_Level,
2793 Allow_Alt_Model => False));
2795 begin
2796 if not Accessibility_Checks_Suppressed (Entity (Lhs)) then
2797 Insert_Action (N, Access_Check);
2798 end if;
2800 Insert_Action (N, Access_Level_Update);
2801 end;
2802 end if;
2804 -- Case of assignment to a bit packed array element. If there is a
2805 -- change of representation this must be expanded into components,
2806 -- otherwise this is a bit-field assignment.
2808 if Nkind (Lhs) = N_Indexed_Component
2809 and then Is_Bit_Packed_Array (Etype (Prefix (Lhs)))
2810 then
2811 -- Normal case, no change of representation
2813 if not Crep then
2814 Expand_Bit_Packed_Element_Set (N);
2815 return;
2817 -- Change of representation case
2819 else
2820 -- Generate the following, to force component-by-component
2821 -- assignments in an efficient way. Otherwise each component
2822 -- will require a temporary and two bit-field manipulations.
2824 -- T1 : Elmt_Type;
2825 -- T1 := RhS;
2826 -- Lhs := T1;
2828 declare
2829 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T');
2830 Stats : List_Id;
2832 begin
2833 Stats :=
2834 New_List (
2835 Make_Object_Declaration (Loc,
2836 Defining_Identifier => Tnn,
2837 Object_Definition =>
2838 New_Occurrence_Of (Etype (Lhs), Loc)),
2839 Make_Assignment_Statement (Loc,
2840 Name => New_Occurrence_Of (Tnn, Loc),
2841 Expression => Relocate_Node (Rhs)),
2842 Make_Assignment_Statement (Loc,
2843 Name => Relocate_Node (Lhs),
2844 Expression => New_Occurrence_Of (Tnn, Loc)));
2846 Insert_Actions (N, Stats);
2847 Rewrite (N, Make_Null_Statement (Loc));
2848 Analyze (N);
2849 end;
2850 end if;
2852 -- Build-in-place function call case. This is for assignment statements
2853 -- that come from aggregate component associations or from init procs.
2854 -- User-written assignment statements with b-i-p calls are handled
2855 -- elsewhere.
2857 elsif Is_Build_In_Place_Function_Call (Rhs) then
2858 pragma Assert (not Comes_From_Source (N));
2859 Make_Build_In_Place_Call_In_Assignment (N, Rhs);
2861 elsif Is_Tagged_Type (Typ)
2862 or else (Needs_Finalization (Typ) and then not Is_Array_Type (Typ))
2863 then
2864 Tagged_Case : declare
2865 L : List_Id := No_List;
2866 Expand_Ctrl_Actions : constant Boolean := not No_Ctrl_Actions (N);
2868 begin
2869 -- In the controlled case, we ensure that function calls are
2870 -- evaluated before finalizing the target. In all cases, it makes
2871 -- the expansion easier if the side effects are removed first.
2873 Remove_Side_Effects (Lhs);
2874 Remove_Side_Effects (Rhs);
2876 -- Avoid recursion in the mechanism
2878 Set_Analyzed (N);
2880 -- If dispatching assignment, we need to dispatch to _assign
2882 if Is_Class_Wide_Type (Typ)
2884 -- If the type is tagged, we may as well use the predefined
2885 -- primitive assignment. This avoids inlining a lot of code
2886 -- and in the class-wide case, the assignment is replaced
2887 -- by a dispatching call to _assign. It is suppressed in the
2888 -- case of assignments created by the expander that correspond
2889 -- to initializations, where we do want to copy the tag
2890 -- (Expand_Ctrl_Actions flag is set False in this case). It is
2891 -- also suppressed if restriction No_Dispatching_Calls is in
2892 -- force because in that case predefined primitives are not
2893 -- generated.
2895 or else (Is_Tagged_Type (Typ)
2896 and then Chars (Current_Scope) /= Name_uAssign
2897 and then Expand_Ctrl_Actions
2898 and then
2899 not Restriction_Active (No_Dispatching_Calls))
2900 then
2901 -- We should normally not encounter any limited type here,
2902 -- except in the corner case where an assignment was not
2903 -- intended like the pathological case of a raise expression
2904 -- within a return statement.
2906 if Is_Limited_Type (Typ) then
2907 pragma Assert (not Comes_From_Source (N));
2908 return;
2909 end if;
2911 -- Fetch the primitive op _assign and proper type to call it.
2912 -- Because of possible conflicts between private and full view,
2913 -- fetch the proper type directly from the operation profile.
2915 declare
2916 Op : constant Entity_Id :=
2917 Find_Prim_Op (Typ, Name_uAssign);
2918 F_Typ : Entity_Id := Etype (First_Formal (Op));
2920 begin
2921 -- If the assignment is dispatching, make sure to use the
2922 -- proper type.
2924 if Is_Class_Wide_Type (Typ) then
2925 F_Typ := Class_Wide_Type (F_Typ);
2926 end if;
2928 L := New_List;
2930 -- In case of assignment to a class-wide tagged type, before
2931 -- the assignment we generate run-time check to ensure that
2932 -- the tags of source and target match.
2934 if not Tag_Checks_Suppressed (Typ)
2935 and then Is_Class_Wide_Type (Typ)
2936 and then Is_Tagged_Type (Typ)
2937 and then Is_Tagged_Type (Underlying_Type (Etype (Rhs)))
2938 then
2939 declare
2940 Lhs_Tag : Node_Id;
2941 Rhs_Tag : Node_Id;
2943 begin
2944 if not Is_Interface (Typ) then
2945 Lhs_Tag :=
2946 Make_Selected_Component (Loc,
2947 Prefix => Duplicate_Subexpr (Lhs),
2948 Selector_Name =>
2949 Make_Identifier (Loc, Name_uTag));
2950 Rhs_Tag :=
2951 Make_Selected_Component (Loc,
2952 Prefix => Duplicate_Subexpr (Rhs),
2953 Selector_Name =>
2954 Make_Identifier (Loc, Name_uTag));
2955 else
2956 -- Displace the pointer to the base of the objects
2957 -- applying 'Address, which is later expanded into
2958 -- a call to RE_Base_Address.
2960 Lhs_Tag :=
2961 Make_Explicit_Dereference (Loc,
2962 Prefix =>
2963 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
2964 Make_Attribute_Reference (Loc,
2965 Prefix => Duplicate_Subexpr (Lhs),
2966 Attribute_Name => Name_Address)));
2967 Rhs_Tag :=
2968 Make_Explicit_Dereference (Loc,
2969 Prefix =>
2970 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
2971 Make_Attribute_Reference (Loc,
2972 Prefix => Duplicate_Subexpr (Rhs),
2973 Attribute_Name => Name_Address)));
2974 end if;
2976 Append_To (L,
2977 Make_Raise_Constraint_Error (Loc,
2978 Condition =>
2979 Make_Op_Ne (Loc,
2980 Left_Opnd => Lhs_Tag,
2981 Right_Opnd => Rhs_Tag),
2982 Reason => CE_Tag_Check_Failed));
2983 end;
2984 end if;
2986 declare
2987 Left_N : Node_Id := Duplicate_Subexpr (Lhs);
2988 Right_N : Node_Id := Duplicate_Subexpr (Rhs);
2990 begin
2991 -- In order to dispatch the call to _assign the type of
2992 -- the actuals must match. Add conversion (if required).
2994 if Etype (Lhs) /= F_Typ then
2995 Left_N := Unchecked_Convert_To (F_Typ, Left_N);
2996 end if;
2998 if Etype (Rhs) /= F_Typ then
2999 Right_N := Unchecked_Convert_To (F_Typ, Right_N);
3000 end if;
3002 Append_To (L,
3003 Make_Procedure_Call_Statement (Loc,
3004 Name => New_Occurrence_Of (Op, Loc),
3005 Parameter_Associations => New_List (
3006 Node1 => Left_N,
3007 Node2 => Right_N)));
3008 end;
3009 end;
3011 else
3012 L := Make_Tag_Ctrl_Assignment (N);
3014 -- We can't afford to have destructive Finalization Actions in
3015 -- the Self assignment case, so if the target and the source
3016 -- are not obviously different, code is generated to avoid the
3017 -- self assignment case:
3019 -- if lhs'address /= rhs'address then
3020 -- <code for controlled and/or tagged assignment>
3021 -- end if;
3023 -- Skip this if Restriction (No_Finalization) is active
3025 if not Statically_Different (Lhs, Rhs)
3026 and then Expand_Ctrl_Actions
3027 and then not Restriction_Active (No_Finalization)
3028 then
3029 L := New_List (
3030 Make_Implicit_If_Statement (N,
3031 Condition =>
3032 Make_Op_Ne (Loc,
3033 Left_Opnd =>
3034 Make_Attribute_Reference (Loc,
3035 Prefix => Duplicate_Subexpr (Lhs),
3036 Attribute_Name => Name_Address),
3038 Right_Opnd =>
3039 Make_Attribute_Reference (Loc,
3040 Prefix => Duplicate_Subexpr (Rhs),
3041 Attribute_Name => Name_Address)),
3043 Then_Statements => L));
3044 end if;
3046 -- We need to set up an exception handler for implementing
3047 -- 7.6.1(18). The remaining adjustments are tackled by the
3048 -- implementation of adjust for record_controllers (see
3049 -- s-finimp.adb).
3051 -- This is skipped if we have no finalization
3053 if Expand_Ctrl_Actions
3054 and then not Restriction_Active (No_Finalization)
3055 then
3056 L := New_List (
3057 Make_Block_Statement (Loc,
3058 Handled_Statement_Sequence =>
3059 Make_Handled_Sequence_Of_Statements (Loc,
3060 Statements => L,
3061 Exception_Handlers => New_List (
3062 Make_Handler_For_Ctrl_Operation (Loc)))));
3063 end if;
3064 end if;
3066 Rewrite (N,
3067 Make_Block_Statement (Loc,
3068 Handled_Statement_Sequence =>
3069 Make_Handled_Sequence_Of_Statements (Loc, Statements => L)));
3071 -- If no restrictions on aborts, protect the whole assignment
3072 -- for controlled objects as per 9.8(11).
3074 if Needs_Finalization (Typ)
3075 and then Expand_Ctrl_Actions
3076 and then Abort_Allowed
3077 then
3078 declare
3079 Blk : constant Entity_Id :=
3080 New_Internal_Entity
3081 (E_Block, Current_Scope, Sloc (N), 'B');
3082 AUD : constant Entity_Id := RTE (RE_Abort_Undefer_Direct);
3084 begin
3085 Set_Is_Abort_Block (N);
3087 Set_Scope (Blk, Current_Scope);
3088 Set_Etype (Blk, Standard_Void_Type);
3089 Set_Identifier (N, New_Occurrence_Of (Blk, Sloc (N)));
3091 Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
3092 Set_At_End_Proc (Handled_Statement_Sequence (N),
3093 New_Occurrence_Of (AUD, Loc));
3095 -- Present the Abort_Undefer_Direct function to the backend
3096 -- so that it can inline the call to the function.
3098 Add_Inlined_Body (AUD, N);
3100 Expand_At_End_Handler
3101 (Handled_Statement_Sequence (N), Blk);
3102 end;
3103 end if;
3105 -- N has been rewritten to a block statement for which it is
3106 -- known by construction that no checks are necessary: analyze
3107 -- it with all checks suppressed.
3109 Analyze (N, Suppress => All_Checks);
3110 return;
3111 end Tagged_Case;
3113 -- Array types
3115 elsif Is_Array_Type (Typ) then
3116 declare
3117 Actual_Rhs : Node_Id := Rhs;
3119 begin
3120 while Nkind (Actual_Rhs) in
3121 N_Type_Conversion | N_Qualified_Expression
3122 loop
3123 Actual_Rhs := Expression (Actual_Rhs);
3124 end loop;
3126 Expand_Assign_Array (N, Actual_Rhs);
3127 return;
3128 end;
3130 -- Record types
3132 elsif Is_Record_Type (Typ) then
3133 Expand_Assign_Record (N);
3134 return;
3136 -- Scalar types. This is where we perform the processing related to the
3137 -- requirements of (RM 13.9.1(9-11)) concerning the handling of invalid
3138 -- scalar values.
3140 elsif Is_Scalar_Type (Typ) then
3142 -- Case where right side is known valid
3144 if Expr_Known_Valid (Rhs) then
3146 -- Here the right side is valid, so it is fine. The case to deal
3147 -- with is when the left side is a local variable reference whose
3148 -- value is not currently known to be valid. If this is the case,
3149 -- and the assignment appears in an unconditional context, then
3150 -- we can mark the left side as now being valid if one of these
3151 -- conditions holds:
3153 -- The expression of the right side has Do_Range_Check set so
3154 -- that we know a range check will be performed. Note that it
3155 -- can be the case that a range check is omitted because we
3156 -- make the assumption that we can assume validity for operands
3157 -- appearing in the right side in determining whether a range
3158 -- check is required
3160 -- The subtype of the right side matches the subtype of the
3161 -- left side. In this case, even though we have not checked
3162 -- the range of the right side, we know it is in range of its
3163 -- subtype if the expression is valid.
3165 if Is_Local_Variable_Reference (Lhs)
3166 and then not Is_Known_Valid (Entity (Lhs))
3167 and then In_Unconditional_Context (N)
3168 then
3169 if Do_Range_Check (Rhs)
3170 or else Etype (Lhs) = Etype (Rhs)
3171 then
3172 Set_Is_Known_Valid (Entity (Lhs), True);
3173 end if;
3174 end if;
3176 -- Case where right side may be invalid in the sense of the RM
3177 -- reference above. The RM does not require that we check for the
3178 -- validity on an assignment, but it does require that the assignment
3179 -- of an invalid value not cause erroneous behavior.
3181 -- The general approach in GNAT is to use the Is_Known_Valid flag
3182 -- to avoid the need for validity checking on assignments. However
3183 -- in some cases, we have to do validity checking in order to make
3184 -- sure that the setting of this flag is correct.
3186 else
3187 -- Validate right side if we are validating copies
3189 if Validity_Checks_On
3190 and then Validity_Check_Copies
3191 then
3192 -- Skip this if left-hand side is an array or record component
3193 -- and elementary component validity checks are suppressed.
3195 if Nkind (Lhs) in N_Selected_Component | N_Indexed_Component
3196 and then not Validity_Check_Components
3197 then
3198 null;
3199 else
3200 Ensure_Valid (Rhs);
3201 end if;
3203 -- We can propagate this to the left side where appropriate
3205 if Is_Local_Variable_Reference (Lhs)
3206 and then not Is_Known_Valid (Entity (Lhs))
3207 and then In_Unconditional_Context (N)
3208 then
3209 Set_Is_Known_Valid (Entity (Lhs), True);
3210 end if;
3212 -- Otherwise check to see what should be done
3214 -- If left side is a local variable, then we just set its flag to
3215 -- indicate that its value may no longer be valid, since we are
3216 -- copying a potentially invalid value.
3218 elsif Is_Local_Variable_Reference (Lhs) then
3219 Set_Is_Known_Valid (Entity (Lhs), False);
3221 -- Check for case of a nonlocal variable on the left side which
3222 -- is currently known to be valid. In this case, we simply ensure
3223 -- that the right side is valid. We only play the game of copying
3224 -- validity status for local variables, since we are doing this
3225 -- statically, not by tracing the full flow graph.
3227 elsif Is_Entity_Name (Lhs)
3228 and then Is_Known_Valid (Entity (Lhs))
3229 then
3230 -- Note: If Validity_Checking mode is set to none, we ignore
3231 -- the Ensure_Valid call so don't worry about that case here.
3233 Ensure_Valid (Rhs);
3235 -- In all other cases, we can safely copy an invalid value without
3236 -- worrying about the status of the left side. Since it is not a
3237 -- variable reference it will not be considered
3238 -- as being known to be valid in any case.
3240 else
3241 null;
3242 end if;
3243 end if;
3244 end if;
3246 exception
3247 when RE_Not_Available =>
3248 return;
3249 end Expand_N_Assignment_Statement;
3251 ------------------------------
3252 -- Expand_N_Block_Statement --
3253 ------------------------------
3255 -- Encode entity names defined in block statement
3257 procedure Expand_N_Block_Statement (N : Node_Id) is
3258 begin
3259 Qualify_Entity_Names (N);
3260 end Expand_N_Block_Statement;
3262 -----------------------------
3263 -- Expand_N_Case_Statement --
3264 -----------------------------
3266 procedure Expand_N_Case_Statement (N : Node_Id) is
3267 Loc : constant Source_Ptr := Sloc (N);
3268 Expr : constant Node_Id := Expression (N);
3269 From_Cond_Expr : constant Boolean := From_Conditional_Expression (N);
3270 Alt : Node_Id;
3271 Len : Nat;
3272 Cond : Node_Id;
3273 Choice : Node_Id;
3274 Chlist : List_Id;
3276 function Expand_General_Case_Statement return Node_Id;
3277 -- Expand a case statement whose selecting expression is not discrete
3279 -----------------------------------
3280 -- Expand_General_Case_Statement --
3281 -----------------------------------
3283 function Expand_General_Case_Statement return Node_Id is
3284 -- expand into a block statement
3286 Selector : constant Entity_Id :=
3287 Make_Temporary (Loc, 'J');
3289 function Selector_Subtype_Mark return Node_Id is
3290 (New_Occurrence_Of (Etype (Expr), Loc));
3292 Renamed_Name : constant Node_Id :=
3293 (if Is_Name_Reference (Expr)
3294 then Expr
3295 else Make_Qualified_Expression (Loc,
3296 Subtype_Mark => Selector_Subtype_Mark,
3297 Expression => Expr));
3299 Selector_Decl : constant Node_Id :=
3300 Make_Object_Renaming_Declaration (Loc,
3301 Defining_Identifier => Selector,
3302 Subtype_Mark => Selector_Subtype_Mark,
3303 Name => Renamed_Name);
3305 First_Alt : constant Node_Id := First (Alternatives (N));
3307 function Choice_Index_Decl_If_Needed return Node_Id;
3308 -- If we are going to need a choice index object (that is, if
3309 -- Multidefined_Bindings is true for at least one of the case
3310 -- alternatives), then create and return that object's declaration.
3311 -- Otherwise, return Empty; no need for a decl in that case because
3312 -- it would never be referenced.
3314 ---------------------------------
3315 -- Choice_Index_Decl_If_Needed --
3316 ---------------------------------
3318 function Choice_Index_Decl_If_Needed return Node_Id is
3319 Alt : Node_Id := First_Alt;
3320 begin
3321 while Present (Alt) loop
3322 if Multidefined_Bindings (Alt) then
3323 return Make_Object_Declaration
3324 (Sloc => Loc,
3325 Defining_Identifier =>
3326 Make_Temporary (Loc, 'K'),
3327 Object_Definition =>
3328 New_Occurrence_Of (Standard_Positive, Loc));
3329 end if;
3331 Next (Alt);
3332 end loop;
3333 return Empty; -- decl not needed
3334 end Choice_Index_Decl_If_Needed;
3336 Choice_Index_Decl : constant Node_Id := Choice_Index_Decl_If_Needed;
3338 function Pattern_Match
3339 (Pattern : Node_Id;
3340 Object : Node_Id;
3341 Choice_Index : Natural;
3342 Alt : Node_Id;
3343 Suppress_Choice_Index_Update : Boolean := False) return Node_Id;
3344 -- Returns a Boolean-valued expression indicating a pattern match
3345 -- for a given pattern and object. If Choice_Index is nonzero,
3346 -- then Choice_Index is assigned to Choice_Index_Decl (unless
3347 -- Suppress_Choice_Index_Update is specified, which should only
3348 -- be the case for a recursive call where the caller has already
3349 -- taken care of the update). Pattern occurs as a choice (or as a
3350 -- subexpression of a choice) of the case statement alternative Alt.
3352 function Top_Level_Pattern_Match_Condition
3353 (Alt : Node_Id) return Node_Id;
3354 -- Returns a Boolean-valued expression indicating a pattern match
3355 -- for the given alternative's list of choices.
3357 -------------------
3358 -- Pattern_Match --
3359 -------------------
3361 function Pattern_Match
3362 (Pattern : Node_Id;
3363 Object : Node_Id;
3364 Choice_Index : Natural;
3365 Alt : Node_Id;
3366 Suppress_Choice_Index_Update : Boolean := False) return Node_Id
3368 procedure Finish_Binding_Object_Declaration
3369 (Component_Assoc : Node_Id; Subobject : Node_Id);
3370 -- Finish the work that was started during analysis to
3371 -- declare a binding object. If we are generating a copy,
3372 -- then initialize it. If we are generating a renaming, then
3373 -- initialize the access value designating the renamed object.
3375 function Update_Choice_Index return Node_Id is (
3376 Make_Assignment_Statement (Loc,
3377 Name =>
3378 New_Occurrence_Of
3379 (Defining_Identifier (Choice_Index_Decl), Loc),
3380 Expression => Make_Integer_Literal (Loc, Pos (Choice_Index))));
3382 function PM
3383 (Pattern : Node_Id;
3384 Object : Node_Id;
3385 Choice_Index : Natural := Pattern_Match.Choice_Index;
3386 Alt : Node_Id := Pattern_Match.Alt;
3387 Suppress_Choice_Index_Update : Boolean :=
3388 Pattern_Match.Suppress_Choice_Index_Update) return Node_Id
3389 renames Pattern_Match;
3390 -- convenient rename for recursive calls
3392 function Indexed_Element (Idx : Pos) return Node_Id;
3393 -- Returns the Nth (well, ok, the Idxth) element of Object
3395 ---------------------------------------
3396 -- Finish_Binding_Object_Declaration --
3397 ---------------------------------------
3399 procedure Finish_Binding_Object_Declaration
3400 (Component_Assoc : Node_Id; Subobject : Node_Id)
3402 Decl_Chars : constant Name_Id :=
3403 Binding_Chars (Component_Assoc);
3405 Block_Stmt : constant Node_Id := First (Statements (Alt));
3406 pragma Assert (Nkind (Block_Stmt) = N_Block_Statement);
3407 pragma Assert (No (Next (Block_Stmt)));
3409 Decl : Node_Id := First (Declarations (Block_Stmt));
3410 Def_Id : Node_Id := Empty;
3412 function Declare_Copy (Decl : Node_Id) return Boolean is
3413 (Nkind (Decl) = N_Object_Declaration);
3414 -- Declare_Copy indicates which of the two approaches
3415 -- was chosen during analysis: declare (and initialize)
3416 -- a new variable, or use access values to declare a renaming
3417 -- of the appropriate subcomponent of the selector value.
3419 function Make_Conditional (Stmt : Node_Id) return Node_Id;
3420 -- If there is only one choice for this alternative, then
3421 -- simply return the argument. If there is more than one
3422 -- choice, then wrap an if-statement around the argument
3423 -- so that it is only executed if the current choice matches.
3425 ----------------------
3426 -- Make_Conditional --
3427 ----------------------
3429 function Make_Conditional (Stmt : Node_Id) return Node_Id
3431 Condition : Node_Id;
3432 begin
3433 if Present (Choice_Index_Decl) then
3434 Condition :=
3435 Make_Op_Eq (Loc,
3436 New_Occurrence_Of
3437 (Defining_Identifier (Choice_Index_Decl), Loc),
3438 Make_Integer_Literal (Loc, Int (Choice_Index)));
3440 return Make_If_Statement (Loc,
3441 Condition => Condition,
3442 Then_Statements => New_List (Stmt));
3443 else
3444 -- execute Stmt unconditionally
3445 return Stmt;
3446 end if;
3447 end Make_Conditional;
3449 begin
3450 -- find the variable to be modified (and its declaration)
3451 loop
3452 if Nkind (Decl) in N_Object_Declaration
3453 | N_Object_Renaming_Declaration
3454 then
3455 Def_Id := Defining_Identifier (Decl);
3456 exit when Chars (Def_Id) = Decl_Chars;
3457 end if;
3458 Next (Decl);
3459 pragma Assert (Present (Decl));
3460 end loop;
3462 -- For a binding object, we sometimes make a copy and
3463 -- sometimes introduce a renaming. That decision is made
3464 -- elsewhere. The renaming case involves dereferencing an
3465 -- access value because of the possibility of multiple
3466 -- choices (with multiple binding definitions) for a single
3467 -- alternative. In the copy case, we initialize the copy
3468 -- here (conditionally if there are multiple choices); in the
3469 -- renaming case, we initialize (again, maybe conditionally)
3470 -- the access value.
3472 if Declare_Copy (Decl) then
3473 declare
3474 Assign_Value : constant Node_Id :=
3475 Make_Assignment_Statement (Loc,
3476 Name => New_Occurrence_Of (Def_Id, Loc),
3477 Expression => Subobject);
3479 HSS : constant Node_Id :=
3480 Handled_Statement_Sequence (Block_Stmt);
3481 begin
3482 Prepend (Make_Conditional (Assign_Value),
3483 Statements (HSS));
3484 Set_Analyzed (HSS, False);
3485 end;
3486 else
3487 pragma Assert (Nkind (Name (Decl)) = N_Explicit_Dereference);
3489 declare
3490 Ptr_Obj : constant Entity_Id :=
3491 Entity (Prefix (Name (Decl)));
3492 Ptr_Decl : constant Node_Id := Parent (Ptr_Obj);
3494 Assign_Reference : constant Node_Id :=
3495 Make_Assignment_Statement (Loc,
3496 Name => New_Occurrence_Of (Ptr_Obj, Loc),
3497 Expression =>
3498 Make_Attribute_Reference (Loc,
3499 Prefix => Subobject,
3500 Attribute_Name => Name_Unrestricted_Access));
3501 begin
3502 Insert_After
3503 (After => Ptr_Decl,
3504 Node => Make_Conditional (Assign_Reference));
3506 if Present (Expression (Ptr_Decl)) then
3507 -- Delete bogus initial value built during analysis.
3508 -- Look for "5432" in sem_case.adb.
3509 pragma Assert (Nkind (Expression (Ptr_Decl)) =
3510 N_Unchecked_Type_Conversion);
3511 Set_Expression (Ptr_Decl, Empty);
3512 end if;
3513 end;
3514 end if;
3516 Set_Analyzed (Block_Stmt, False);
3517 end Finish_Binding_Object_Declaration;
3519 ---------------------
3520 -- Indexed_Element --
3521 ---------------------
3523 function Indexed_Element (Idx : Pos) return Node_Id is
3524 Obj_Index : constant Node_Id :=
3525 Make_Op_Add (Loc,
3526 Left_Opnd =>
3527 Make_Attribute_Reference (Loc,
3528 Attribute_Name => Name_First,
3529 Prefix => New_Copy_Tree (Object)),
3530 Right_Opnd =>
3531 Make_Integer_Literal (Loc, Idx - 1));
3532 begin
3533 return Make_Indexed_Component (Loc,
3534 Prefix => New_Copy_Tree (Object),
3535 Expressions => New_List (Obj_Index));
3536 end Indexed_Element;
3538 -- Start of processing for Pattern_Match
3540 begin
3541 if Choice_Index /= 0 and not Suppress_Choice_Index_Update then
3542 pragma Assert (Present (Choice_Index_Decl));
3544 -- Add Choice_Index update as a side effect of evaluating
3545 -- this condition and try again, this time suppressing
3546 -- Choice_Index update.
3548 return Make_Expression_With_Actions (Loc,
3549 Actions => New_List (Update_Choice_Index),
3550 Expression =>
3551 PM (Pattern, Object,
3552 Suppress_Choice_Index_Update => True));
3553 end if;
3555 if Nkind (Pattern) in N_Has_Etype
3556 and then Is_Discrete_Type (Etype (Pattern))
3557 and then Compile_Time_Known_Value (Pattern)
3558 then
3559 declare
3560 Val : Node_Id;
3561 begin
3562 if Is_Enumeration_Type (Etype (Pattern)) then
3563 Val := Get_Enum_Lit_From_Pos
3564 (Etype (Pattern), Expr_Value (Pattern), Loc);
3565 else
3566 Val := Make_Integer_Literal (Loc, Expr_Value (Pattern));
3567 end if;
3568 return Make_Op_Eq (Loc, Object, Val);
3569 end;
3570 end if;
3572 case Nkind (Pattern) is
3573 when N_Aggregate =>
3574 declare
3575 Result : Node_Id;
3576 begin
3577 if Is_Array_Type (Etype (Pattern)) then
3579 -- Nonpositional aggregates currently unimplemented.
3580 -- We flag that case during analysis, so an assertion
3581 -- is ok here.
3583 pragma Assert
3584 (Is_Empty_List (Component_Associations (Pattern)));
3586 declare
3587 Agg_Length : constant Node_Id :=
3588 Make_Integer_Literal (Loc,
3589 List_Length (Expressions (Pattern)));
3591 Obj_Length : constant Node_Id :=
3592 Make_Attribute_Reference (Loc,
3593 Attribute_Name => Name_Length,
3594 Prefix => New_Copy_Tree (Object));
3595 begin
3596 Result := Make_Op_Eq (Loc,
3597 Left_Opnd => Obj_Length,
3598 Right_Opnd => Agg_Length);
3599 end;
3601 declare
3602 Expr : Node_Id := First (Expressions (Pattern));
3603 Idx : Pos := 1;
3604 begin
3605 while Present (Expr) loop
3606 Result :=
3607 Make_And_Then (Loc,
3608 Left_Opnd => Result,
3609 Right_Opnd =>
3610 PM (Pattern => Expr,
3611 Object => Indexed_Element (Idx)));
3612 Next (Expr);
3613 Idx := Idx + 1;
3614 end loop;
3615 end;
3617 return Result;
3618 end if;
3620 -- positional notation should have been normalized
3621 pragma Assert (No (Expressions (Pattern)));
3623 declare
3624 Component_Assoc : Node_Id
3625 := First (Component_Associations (Pattern));
3626 Choice : Node_Id;
3628 function Subobject return Node_Id is
3629 (Make_Selected_Component (Loc,
3630 Prefix => New_Copy_Tree (Object),
3631 Selector_Name => New_Occurrence_Of
3632 (Entity (Choice), Loc)));
3633 begin
3634 Result := New_Occurrence_Of (Standard_True, Loc);
3636 while Present (Component_Assoc) loop
3637 Choice := First (Choices (Component_Assoc));
3638 while Present (Choice) loop
3639 pragma Assert
3640 (Is_Entity_Name (Choice)
3641 and then Ekind (Entity (Choice))
3642 in E_Discriminant | E_Component);
3644 if Box_Present (Component_Assoc) then
3645 -- Box matches anything
3647 pragma Assert
3648 (No (Expression (Component_Assoc)));
3649 else
3650 Result := Make_And_Then (Loc,
3651 Left_Opnd => Result,
3652 Right_Opnd =>
3653 PM (Pattern =>
3654 Expression
3655 (Component_Assoc),
3656 Object => Subobject));
3657 end if;
3659 -- If this component association defines
3660 -- (in the case where the pattern matches)
3661 -- the value of a binding object, then
3662 -- prepend to the statement list for this
3663 -- alternative an assignment to the binding
3664 -- object. This assignment will be conditional
3665 -- if there is more than one choice.
3667 if Binding_Chars (Component_Assoc) /= No_Name
3668 then
3669 Finish_Binding_Object_Declaration
3670 (Component_Assoc => Component_Assoc,
3671 Subobject => Subobject);
3672 end if;
3674 Next (Choice);
3675 end loop;
3677 Next (Component_Assoc);
3678 end loop;
3679 end;
3680 return Result;
3681 end;
3683 when N_String_Literal =>
3684 return Result : Node_Id do
3685 declare
3686 Char_Type : constant Entity_Id :=
3687 Root_Type (Component_Type (Etype (Pattern)));
3689 -- If the component type is not a standard character
3690 -- type then this string lit should have already been
3691 -- transformed into an aggregate in
3692 -- Resolve_String_Literal.
3694 pragma Assert (Is_Standard_Character_Type (Char_Type));
3696 Str : constant String_Id := Strval (Pattern);
3697 Strlen : constant Nat := String_Length (Str);
3699 Lit_Length : constant Node_Id :=
3700 Make_Integer_Literal (Loc, Strlen);
3702 Obj_Length : constant Node_Id :=
3703 Make_Attribute_Reference (Loc,
3704 Attribute_Name => Name_Length,
3705 Prefix => New_Copy_Tree (Object));
3706 begin
3707 Result := Make_Op_Eq (Loc,
3708 Left_Opnd => Obj_Length,
3709 Right_Opnd => Lit_Length);
3711 for Idx in 1 .. Strlen loop
3712 declare
3713 C : constant Char_Code :=
3714 Get_String_Char (Str, Idx);
3715 Obj_Element : constant Node_Id :=
3716 Indexed_Element (Idx);
3717 Char_Lit : Node_Id;
3718 begin
3719 Set_Character_Literal_Name (C);
3720 Char_Lit :=
3721 Make_Character_Literal (Loc,
3722 Chars => Name_Find,
3723 Char_Literal_Value => UI_From_CC (C));
3725 Result :=
3726 Make_And_Then (Loc,
3727 Left_Opnd => Result,
3728 Right_Opnd =>
3729 Make_Op_Eq (Loc,
3730 Left_Opnd => Obj_Element,
3731 Right_Opnd => Char_Lit));
3732 end;
3733 end loop;
3734 end;
3735 end return;
3737 when N_Qualified_Expression =>
3738 return Make_And_Then (Loc,
3739 Left_Opnd => Make_In (Loc,
3740 Left_Opnd => New_Copy_Tree (Object),
3741 Right_Opnd => New_Copy_Tree (Subtype_Mark (Pattern))),
3742 Right_Opnd =>
3743 PM (Pattern => Expression (Pattern),
3744 Object => New_Copy_Tree (Object)));
3746 when N_Identifier | N_Expanded_Name =>
3747 if Is_Type (Entity (Pattern)) then
3748 return Make_In (Loc,
3749 Left_Opnd => New_Copy_Tree (Object),
3750 Right_Opnd => New_Occurrence_Of
3751 (Entity (Pattern), Loc));
3752 elsif Ekind (Entity (Pattern)) = E_Constant then
3753 return PM (Pattern =>
3754 Expression (Parent (Entity (Pattern))),
3755 Object => Object);
3756 end if;
3758 when N_Others_Choice =>
3759 return New_Occurrence_Of (Standard_True, Loc);
3761 when N_Type_Conversion =>
3762 -- aggregate expansion sometimes introduces conversions
3763 if not Comes_From_Source (Pattern)
3764 and then Base_Type (Etype (Pattern))
3765 = Base_Type (Etype (Expression (Pattern)))
3766 then
3767 return PM (Expression (Pattern), Object);
3768 end if;
3770 when others =>
3771 null;
3772 end case;
3774 -- Avoid cascading errors
3775 pragma Assert (Serious_Errors_Detected > 0);
3776 return New_Occurrence_Of (Standard_True, Loc);
3777 end Pattern_Match;
3779 ---------------------------------------
3780 -- Top_Level_Pattern_Match_Condition --
3781 ---------------------------------------
3783 function Top_Level_Pattern_Match_Condition
3784 (Alt : Node_Id) return Node_Id
3786 Top_Level_Object : constant Node_Id :=
3787 New_Occurrence_Of (Selector, Loc);
3789 Choices : constant List_Id := Discrete_Choices (Alt);
3791 First_Choice : constant Node_Id := First (Choices);
3792 Subsequent : Node_Id := Next (First_Choice);
3794 Choice_Index : Natural := 0;
3795 begin
3796 if Multidefined_Bindings (Alt) then
3797 Choice_Index := 1;
3798 end if;
3800 return Result : Node_Id :=
3801 Pattern_Match (Pattern => First_Choice,
3802 Object => Top_Level_Object,
3803 Choice_Index => Choice_Index,
3804 Alt => Alt)
3806 while Present (Subsequent) loop
3807 if Choice_Index /= 0 then
3808 Choice_Index := Choice_Index + 1;
3809 end if;
3811 Result := Make_Or_Else (Loc,
3812 Left_Opnd => Result,
3813 Right_Opnd => Pattern_Match
3814 (Pattern => Subsequent,
3815 Object => Top_Level_Object,
3816 Choice_Index => Choice_Index,
3817 Alt => Alt));
3818 Subsequent := Next (Subsequent);
3819 end loop;
3820 end return;
3821 end Top_Level_Pattern_Match_Condition;
3823 function Elsif_Parts return List_Id;
3824 -- Process subsequent alternatives
3826 -----------------
3827 -- Elsif_Parts --
3828 -----------------
3830 function Elsif_Parts return List_Id is
3831 Alt : Node_Id := First_Alt;
3832 Result : constant List_Id := New_List;
3833 begin
3834 loop
3835 Alt := Next (Alt);
3836 exit when No (Alt);
3838 Append (Make_Elsif_Part (Loc,
3839 Condition => Top_Level_Pattern_Match_Condition (Alt),
3840 Then_Statements => Statements (Alt)),
3841 Result);
3842 end loop;
3843 return Result;
3844 end Elsif_Parts;
3846 function Else_Statements return List_Id;
3847 -- Returns a "raise Constraint_Error" statement if
3848 -- exception propagate is permitted and No_List otherwise.
3850 ---------------------
3851 -- Else_Statements --
3852 ---------------------
3854 function Else_Statements return List_Id is
3855 begin
3856 if Restriction_Active (No_Exception_Propagation) then
3857 return No_List;
3858 else
3859 return New_List (Make_Raise_Constraint_Error (Loc,
3860 Reason => CE_Invalid_Data));
3861 end if;
3862 end Else_Statements;
3864 -- Local constants
3866 If_Stmt : constant Node_Id :=
3867 Make_If_Statement (Loc,
3868 Condition => Top_Level_Pattern_Match_Condition (First_Alt),
3869 Then_Statements => Statements (First_Alt),
3870 Elsif_Parts => Elsif_Parts,
3871 Else_Statements => Else_Statements);
3873 Declarations : constant List_Id := New_List (Selector_Decl);
3875 -- Start of processing for Expand_General_Case_Statment
3877 begin
3878 if Present (Choice_Index_Decl) then
3879 Append_To (Declarations, Choice_Index_Decl);
3880 end if;
3882 return Make_Block_Statement (Loc,
3883 Declarations => Declarations,
3884 Handled_Statement_Sequence =>
3885 Make_Handled_Sequence_Of_Statements (Loc,
3886 Statements => New_List (If_Stmt)));
3887 end Expand_General_Case_Statement;
3889 -- Start of processing for Expand_N_Case_Statement
3891 begin
3892 if Extensions_Allowed and then not Is_Discrete_Type (Etype (Expr)) then
3893 Rewrite (N, Expand_General_Case_Statement);
3894 Analyze (N);
3895 return;
3896 end if;
3898 -- Check for the situation where we know at compile time which branch
3899 -- will be taken.
3901 -- If the value is static but its subtype is predicated and the value
3902 -- does not obey the predicate, the value is marked non-static, and
3903 -- there can be no corresponding static alternative. In that case we
3904 -- replace the case statement with an exception, regardless of whether
3905 -- assertions are enabled or not, unless predicates are ignored.
3907 if Compile_Time_Known_Value (Expr)
3908 and then Has_Predicates (Etype (Expr))
3909 and then not Predicates_Ignored (Etype (Expr))
3910 and then not Is_OK_Static_Expression (Expr)
3911 then
3912 Rewrite (N,
3913 Make_Raise_Constraint_Error (Loc, Reason => CE_Invalid_Data));
3914 Analyze (N);
3915 return;
3917 elsif Compile_Time_Known_Value (Expr)
3918 and then (not Has_Predicates (Etype (Expr))
3919 or else Is_Static_Expression (Expr))
3920 then
3921 Alt := Find_Static_Alternative (N);
3923 -- Do not consider controlled objects found in a case statement which
3924 -- actually models a case expression because their early finalization
3925 -- will affect the result of the expression.
3927 if not From_Conditional_Expression (N) then
3928 Process_Statements_For_Controlled_Objects (Alt);
3929 end if;
3931 -- Move statements from this alternative after the case statement.
3932 -- They are already analyzed, so will be skipped by the analyzer.
3934 Insert_List_After (N, Statements (Alt));
3936 -- That leaves the case statement as a shell. So now we can kill all
3937 -- other alternatives in the case statement.
3939 Kill_Dead_Code (Expression (N));
3941 declare
3942 Dead_Alt : Node_Id;
3944 begin
3945 -- Loop through case alternatives, skipping pragmas, and skipping
3946 -- the one alternative that we select (and therefore retain).
3948 Dead_Alt := First (Alternatives (N));
3949 while Present (Dead_Alt) loop
3950 if Dead_Alt /= Alt
3951 and then Nkind (Dead_Alt) = N_Case_Statement_Alternative
3952 then
3953 Kill_Dead_Code (Statements (Dead_Alt), Warn_On_Deleted_Code);
3954 end if;
3956 Next (Dead_Alt);
3957 end loop;
3958 end;
3960 Rewrite (N, Make_Null_Statement (Loc));
3961 return;
3962 end if;
3964 -- Here if the choice is not determined at compile time
3966 declare
3967 Last_Alt : constant Node_Id := Last (Alternatives (N));
3969 Others_Present : Boolean;
3970 Others_Node : Node_Id;
3972 Then_Stms : List_Id;
3973 Else_Stms : List_Id;
3975 begin
3976 if Nkind (First (Discrete_Choices (Last_Alt))) = N_Others_Choice then
3977 Others_Present := True;
3978 Others_Node := Last_Alt;
3979 else
3980 Others_Present := False;
3981 end if;
3983 -- First step is to worry about possible invalid argument. The RM
3984 -- requires (RM 5.4(13)) that if the result is invalid (e.g. it is
3985 -- outside the base range), then Constraint_Error must be raised.
3987 -- Case of validity check required (validity checks are on, the
3988 -- expression is not known to be valid, and the case statement
3989 -- comes from source -- no need to validity check internally
3990 -- generated case statements).
3992 if Validity_Check_Default
3993 and then not Predicates_Ignored (Etype (Expr))
3994 then
3995 -- Recognize the simple case where Expr is an object reference
3996 -- and the case statement is directly preceded by an
3997 -- "if Obj'Valid then": in this case, do not emit another validity
3998 -- check.
4000 declare
4001 Check_Validity : Boolean := True;
4002 Attr : Node_Id;
4003 begin
4004 if Nkind (Expr) = N_Identifier
4005 and then Nkind (Parent (N)) = N_If_Statement
4006 and then Nkind (Original_Node (Condition (Parent (N))))
4007 = N_Attribute_Reference
4008 and then No (Prev (N))
4009 then
4010 Attr := Original_Node (Condition (Parent (N)));
4012 if Attribute_Name (Attr) = Name_Valid
4013 and then Nkind (Prefix (Attr)) = N_Identifier
4014 and then Entity (Prefix (Attr)) = Entity (Expr)
4015 then
4016 Check_Validity := False;
4017 end if;
4018 end if;
4020 if Check_Validity then
4021 Ensure_Valid (Expr);
4022 end if;
4023 end;
4024 end if;
4026 -- If there is only a single alternative, just replace it with the
4027 -- sequence of statements since obviously that is what is going to
4028 -- be executed in all cases.
4030 Len := List_Length (Alternatives (N));
4032 if Len = 1 then
4034 -- We still need to evaluate the expression if it has any side
4035 -- effects.
4037 Remove_Side_Effects (Expression (N));
4038 Alt := First (Alternatives (N));
4040 -- Do not consider controlled objects found in a case statement
4041 -- which actually models a case expression because their early
4042 -- finalization will affect the result of the expression.
4044 if not From_Conditional_Expression (N) then
4045 Process_Statements_For_Controlled_Objects (Alt);
4046 end if;
4048 Insert_List_After (N, Statements (Alt));
4050 -- That leaves the case statement as a shell. The alternative that
4051 -- will be executed is reset to a null list. So now we can kill
4052 -- the entire case statement.
4054 Kill_Dead_Code (Expression (N));
4055 Rewrite (N, Make_Null_Statement (Loc));
4056 return;
4058 -- An optimization. If there are only two alternatives, and only
4059 -- a single choice, then rewrite the whole case statement as an
4060 -- if statement, since this can result in subsequent optimizations.
4061 -- This helps not only with case statements in the source of a
4062 -- simple form, but also with generated code (discriminant check
4063 -- functions in particular).
4065 -- Note: it is OK to do this before expanding out choices for any
4066 -- static predicates, since the if statement processing will handle
4067 -- the static predicate case fine.
4069 elsif Len = 2 then
4070 Chlist := Discrete_Choices (First (Alternatives (N)));
4072 if List_Length (Chlist) = 1 then
4073 Choice := First (Chlist);
4075 Then_Stms := Statements (First (Alternatives (N)));
4076 Else_Stms := Statements (Last (Alternatives (N)));
4078 -- For TRUE, generate "expression", not expression = true
4080 if Nkind (Choice) = N_Identifier
4081 and then Entity (Choice) = Standard_True
4082 then
4083 Cond := Expression (N);
4085 -- For FALSE, generate "expression" and switch then/else
4087 elsif Nkind (Choice) = N_Identifier
4088 and then Entity (Choice) = Standard_False
4089 then
4090 Cond := Expression (N);
4091 Else_Stms := Statements (First (Alternatives (N)));
4092 Then_Stms := Statements (Last (Alternatives (N)));
4094 -- For a range, generate "expression in range"
4096 elsif Nkind (Choice) = N_Range
4097 or else (Nkind (Choice) = N_Attribute_Reference
4098 and then Attribute_Name (Choice) = Name_Range)
4099 or else (Is_Entity_Name (Choice)
4100 and then Is_Type (Entity (Choice)))
4101 then
4102 Cond :=
4103 Make_In (Loc,
4104 Left_Opnd => Expression (N),
4105 Right_Opnd => Relocate_Node (Choice));
4107 -- A subtype indication is not a legal operator in a membership
4108 -- test, so retrieve its range.
4110 elsif Nkind (Choice) = N_Subtype_Indication then
4111 Cond :=
4112 Make_In (Loc,
4113 Left_Opnd => Expression (N),
4114 Right_Opnd =>
4115 Relocate_Node
4116 (Range_Expression (Constraint (Choice))));
4118 -- For any other subexpression "expression = value"
4120 else
4121 Cond :=
4122 Make_Op_Eq (Loc,
4123 Left_Opnd => Expression (N),
4124 Right_Opnd => Relocate_Node (Choice));
4125 end if;
4127 -- Now rewrite the case as an IF
4129 Rewrite (N,
4130 Make_If_Statement (Loc,
4131 Condition => Cond,
4132 Then_Statements => Then_Stms,
4133 Else_Statements => Else_Stms));
4135 -- The rewritten if statement needs to inherit whether the
4136 -- case statement was expanded from a conditional expression,
4137 -- for proper handling of nested controlled objects.
4139 Set_From_Conditional_Expression (N, From_Cond_Expr);
4141 Analyze (N);
4143 return;
4144 end if;
4145 end if;
4147 -- If the last alternative is not an Others choice, replace it with
4148 -- an N_Others_Choice. Note that we do not bother to call Analyze on
4149 -- the modified case statement, since it's only effect would be to
4150 -- compute the contents of the Others_Discrete_Choices which is not
4151 -- needed by the back end anyway.
4153 -- The reason for this is that the back end always needs some default
4154 -- for a switch, so if we have not supplied one in the processing
4155 -- above for validity checking, then we need to supply one here.
4157 if not Others_Present then
4158 Others_Node := Make_Others_Choice (Sloc (Last_Alt));
4160 -- If Predicates_Ignored is true the value does not satisfy the
4161 -- predicate, and there is no Others choice, Constraint_Error
4162 -- must be raised (4.5.7 (21/3)).
4164 if Predicates_Ignored (Etype (Expr)) then
4165 declare
4166 Except : constant Node_Id :=
4167 Make_Raise_Constraint_Error (Loc,
4168 Reason => CE_Invalid_Data);
4169 New_Alt : constant Node_Id :=
4170 Make_Case_Statement_Alternative (Loc,
4171 Discrete_Choices => New_List (
4172 Make_Others_Choice (Loc)),
4173 Statements => New_List (Except));
4175 begin
4176 Append (New_Alt, Alternatives (N));
4177 Analyze_And_Resolve (Except);
4178 end;
4180 else
4181 Set_Others_Discrete_Choices
4182 (Others_Node, Discrete_Choices (Last_Alt));
4183 Set_Discrete_Choices (Last_Alt, New_List (Others_Node));
4184 end if;
4186 end if;
4188 -- Deal with possible declarations of controlled objects, and also
4189 -- with rewriting choice sequences for static predicate references.
4191 Alt := First_Non_Pragma (Alternatives (N));
4192 while Present (Alt) loop
4194 -- Do not consider controlled objects found in a case statement
4195 -- which actually models a case expression because their early
4196 -- finalization will affect the result of the expression.
4198 if not From_Conditional_Expression (N) then
4199 Process_Statements_For_Controlled_Objects (Alt);
4200 end if;
4202 if Has_SP_Choice (Alt) then
4203 Expand_Static_Predicates_In_Choices (Alt);
4204 end if;
4206 Next_Non_Pragma (Alt);
4207 end loop;
4208 end;
4209 end Expand_N_Case_Statement;
4211 -----------------------------
4212 -- Expand_N_Exit_Statement --
4213 -----------------------------
4215 -- The only processing required is to deal with a possible C/Fortran
4216 -- boolean value used as the condition for the exit statement.
4218 procedure Expand_N_Exit_Statement (N : Node_Id) is
4219 begin
4220 Adjust_Condition (Condition (N));
4221 end Expand_N_Exit_Statement;
4223 ----------------------------------
4224 -- Expand_Formal_Container_Loop --
4225 ----------------------------------
4227 procedure Expand_Formal_Container_Loop (N : Node_Id) is
4228 Loc : constant Source_Ptr := Sloc (N);
4229 Isc : constant Node_Id := Iteration_Scheme (N);
4230 I_Spec : constant Node_Id := Iterator_Specification (Isc);
4231 Cursor : constant Entity_Id := Defining_Identifier (I_Spec);
4232 Container : constant Node_Id := Entity (Name (I_Spec));
4233 Stats : constant List_Id := Statements (N);
4235 Advance : Node_Id;
4236 Init_Decl : Node_Id;
4237 Init_Name : Entity_Id;
4238 New_Loop : Node_Id;
4240 begin
4241 -- The expansion of a formal container loop resembles the one for Ada
4242 -- containers. The only difference is that the primitives mention the
4243 -- domain of iteration explicitly, and function First applied to the
4244 -- container yields a cursor directly.
4246 -- Cursor : Cursor_type := First (Container);
4247 -- while Has_Element (Cursor, Container) loop
4248 -- <original loop statements>
4249 -- Cursor := Next (Container, Cursor);
4250 -- end loop;
4252 Build_Formal_Container_Iteration
4253 (N, Container, Cursor, Init_Decl, Advance, New_Loop);
4255 Append_To (Stats, Advance);
4257 -- Build a block to capture declaration of the cursor
4259 Rewrite (N,
4260 Make_Block_Statement (Loc,
4261 Declarations => New_List (Init_Decl),
4262 Handled_Statement_Sequence =>
4263 Make_Handled_Sequence_Of_Statements (Loc,
4264 Statements => New_List (New_Loop))));
4266 -- The loop parameter is declared by an object declaration, but within
4267 -- the loop we must prevent user assignments to it, so we analyze the
4268 -- declaration and reset the entity kind, before analyzing the rest of
4269 -- the loop.
4271 Analyze (Init_Decl);
4272 Init_Name := Defining_Identifier (Init_Decl);
4273 Mutate_Ekind (Init_Name, E_Loop_Parameter);
4275 -- The cursor was marked as a loop parameter to prevent user assignments
4276 -- to it, however this renders the advancement step illegal as it is not
4277 -- possible to change the value of a constant. Flag the advancement step
4278 -- as a legal form of assignment to remedy this side effect.
4280 Set_Assignment_OK (Name (Advance));
4281 Analyze (N);
4283 -- Because we have to analyze the initial declaration of the loop
4284 -- parameter multiple times its scope is incorrectly set at this point
4285 -- to the one surrounding the block statement - so set the scope
4286 -- manually to be the actual block statement, and indicate that it is
4287 -- not visible after the block has been analyzed.
4289 Set_Scope (Init_Name, Entity (Identifier (N)));
4290 Set_Is_Immediately_Visible (Init_Name, False);
4291 end Expand_Formal_Container_Loop;
4293 ------------------------------------------
4294 -- Expand_Formal_Container_Element_Loop --
4295 ------------------------------------------
4297 procedure Expand_Formal_Container_Element_Loop (N : Node_Id) is
4298 Loc : constant Source_Ptr := Sloc (N);
4299 Isc : constant Node_Id := Iteration_Scheme (N);
4300 I_Spec : constant Node_Id := Iterator_Specification (Isc);
4301 Element : constant Entity_Id := Defining_Identifier (I_Spec);
4302 Container : constant Node_Id := Entity (Name (I_Spec));
4303 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
4304 Stats : constant List_Id := Statements (N);
4306 Cursor : constant Entity_Id :=
4307 Make_Defining_Identifier (Loc,
4308 Chars => New_External_Name (Chars (Element), 'C'));
4309 Elmt_Decl : Node_Id;
4311 Element_Op : constant Entity_Id :=
4312 Get_Iterable_Type_Primitive (Container_Typ, Name_Element);
4314 Advance : Node_Id;
4315 Init : Node_Id;
4316 New_Loop : Node_Id;
4318 begin
4319 -- For an element iterator, the Element aspect must be present,
4320 -- (this is checked during analysis).
4322 -- We create a block to hold a variable declaration initialized with
4323 -- a call to Element, and generate:
4325 -- Cursor : Cursor_Type := First (Container);
4326 -- while Has_Element (Cursor, Container) loop
4327 -- declare
4328 -- Elmt : Element_Type := Element (Container, Cursor);
4329 -- begin
4330 -- <original loop statements>
4331 -- Cursor := Next (Container, Cursor);
4332 -- end;
4333 -- end loop;
4335 Build_Formal_Container_Iteration
4336 (N, Container, Cursor, Init, Advance, New_Loop);
4337 Append_To (Stats, Advance);
4339 Mutate_Ekind (Cursor, E_Variable);
4340 Insert_Action (N, Init);
4342 -- The loop parameter is declared by an object declaration, but within
4343 -- the loop we must prevent user assignments to it; the following flag
4344 -- accomplishes that.
4346 Set_Is_Loop_Parameter (Element);
4348 -- Declaration for Element
4350 Elmt_Decl :=
4351 Make_Object_Declaration (Loc,
4352 Defining_Identifier => Element,
4353 Object_Definition => New_Occurrence_Of (Etype (Element_Op), Loc));
4355 Set_Expression (Elmt_Decl,
4356 Make_Function_Call (Loc,
4357 Name => New_Occurrence_Of (Element_Op, Loc),
4358 Parameter_Associations => New_List (
4359 Convert_To_Iterable_Type (Container, Loc),
4360 New_Occurrence_Of (Cursor, Loc))));
4362 Set_Statements (New_Loop,
4363 New_List
4364 (Make_Block_Statement (Loc,
4365 Declarations => New_List (Elmt_Decl),
4366 Handled_Statement_Sequence =>
4367 Make_Handled_Sequence_Of_Statements (Loc,
4368 Statements => Stats))));
4370 -- The element is only modified in expanded code, so it appears as
4371 -- unassigned to the warning machinery. We must suppress this spurious
4372 -- warning explicitly.
4374 Set_Warnings_Off (Element);
4376 Rewrite (N, New_Loop);
4377 Analyze (N);
4378 end Expand_Formal_Container_Element_Loop;
4380 ----------------------------------
4381 -- Expand_N_Goto_When_Statement --
4382 ----------------------------------
4384 procedure Expand_N_Goto_When_Statement (N : Node_Id) is
4385 Loc : constant Source_Ptr := Sloc (N);
4386 begin
4387 Rewrite (N,
4388 Make_If_Statement (Loc,
4389 Condition => Condition (N),
4390 Then_Statements => New_List (
4391 Make_Goto_Statement (Loc,
4392 Name => Name (N)))));
4394 Analyze (N);
4395 end Expand_N_Goto_When_Statement;
4397 ---------------------------
4398 -- Expand_N_If_Statement --
4399 ---------------------------
4401 -- First we deal with the case of C and Fortran convention boolean values,
4402 -- with zero/nonzero semantics.
4404 -- Second, we deal with the obvious rewriting for the cases where the
4405 -- condition of the IF is known at compile time to be True or False.
4407 -- Third, we remove elsif parts which have non-empty Condition_Actions and
4408 -- rewrite as independent if statements. For example:
4410 -- if x then xs
4411 -- elsif y then ys
4412 -- ...
4413 -- end if;
4415 -- becomes
4417 -- if x then xs
4418 -- else
4419 -- <<condition actions of y>>
4420 -- if y then ys
4421 -- ...
4422 -- end if;
4423 -- end if;
4425 -- This rewriting is needed if at least one elsif part has a non-empty
4426 -- Condition_Actions list. We also do the same processing if there is a
4427 -- constant condition in an elsif part (in conjunction with the first
4428 -- processing step mentioned above, for the recursive call made to deal
4429 -- with the created inner if, this deals with properly optimizing the
4430 -- cases of constant elsif conditions).
4432 procedure Expand_N_If_Statement (N : Node_Id) is
4433 Loc : constant Source_Ptr := Sloc (N);
4434 Hed : Node_Id;
4435 E : Node_Id;
4436 New_If : Node_Id;
4438 Warn_If_Deleted : constant Boolean :=
4439 Warn_On_Deleted_Code and then Comes_From_Source (N);
4440 -- Indicates whether we want warnings when we delete branches of the
4441 -- if statement based on constant condition analysis. We never want
4442 -- these warnings for expander generated code.
4444 begin
4445 -- Do not consider controlled objects found in an if statement which
4446 -- actually models an if expression because their early finalization
4447 -- will affect the result of the expression.
4449 if not From_Conditional_Expression (N) then
4450 Process_Statements_For_Controlled_Objects (N);
4451 end if;
4453 Adjust_Condition (Condition (N));
4455 -- The following loop deals with constant conditions for the IF. We
4456 -- need a loop because as we eliminate False conditions, we grab the
4457 -- first elsif condition and use it as the primary condition.
4459 while Compile_Time_Known_Value (Condition (N)) loop
4461 -- If condition is True, we can simply rewrite the if statement now
4462 -- by replacing it by the series of then statements.
4464 if Is_True (Expr_Value (Condition (N))) then
4466 -- All the else parts can be killed
4468 Kill_Dead_Code (Elsif_Parts (N), Warn_If_Deleted);
4469 Kill_Dead_Code (Else_Statements (N), Warn_If_Deleted);
4471 Hed := Remove_Head (Then_Statements (N));
4472 Insert_List_After (N, Then_Statements (N));
4473 Rewrite (N, Hed);
4474 return;
4476 -- If condition is False, then we can delete the condition and
4477 -- the Then statements
4479 else
4480 -- We do not delete the condition if constant condition warnings
4481 -- are enabled, since otherwise we end up deleting the desired
4482 -- warning. Of course the backend will get rid of this True/False
4483 -- test anyway, so nothing is lost here.
4485 if not Constant_Condition_Warnings then
4486 Kill_Dead_Code (Condition (N));
4487 end if;
4489 Kill_Dead_Code (Then_Statements (N), Warn_If_Deleted);
4491 -- If there are no elsif statements, then we simply replace the
4492 -- entire if statement by the sequence of else statements.
4494 if No (Elsif_Parts (N)) then
4495 if Is_Empty_List (Else_Statements (N)) then
4496 Rewrite (N,
4497 Make_Null_Statement (Sloc (N)));
4498 else
4499 Hed := Remove_Head (Else_Statements (N));
4500 Insert_List_After (N, Else_Statements (N));
4501 Rewrite (N, Hed);
4502 end if;
4504 return;
4506 -- If there are elsif statements, the first of them becomes the
4507 -- if/then section of the rebuilt if statement This is the case
4508 -- where we loop to reprocess this copied condition.
4510 else
4511 Hed := Remove_Head (Elsif_Parts (N));
4512 Insert_Actions (N, Condition_Actions (Hed));
4513 Set_Condition (N, Condition (Hed));
4514 Set_Then_Statements (N, Then_Statements (Hed));
4516 -- Hed might have been captured as the condition determining
4517 -- the current value for an entity. Now it is detached from
4518 -- the tree, so a Current_Value pointer in the condition might
4519 -- need to be updated.
4521 Set_Current_Value_Condition (N);
4523 if Is_Empty_List (Elsif_Parts (N)) then
4524 Set_Elsif_Parts (N, No_List);
4525 end if;
4526 end if;
4527 end if;
4528 end loop;
4530 -- Loop through elsif parts, dealing with constant conditions and
4531 -- possible condition actions that are present.
4533 E := First (Elsif_Parts (N));
4534 while Present (E) loop
4536 -- Do not consider controlled objects found in an if statement which
4537 -- actually models an if expression because their early finalization
4538 -- will affect the result of the expression.
4540 if not From_Conditional_Expression (N) then
4541 Process_Statements_For_Controlled_Objects (E);
4542 end if;
4544 Adjust_Condition (Condition (E));
4546 -- If there are condition actions, then rewrite the if statement as
4547 -- indicated above. We also do the same rewrite for a True or False
4548 -- condition. The further processing of this constant condition is
4549 -- then done by the recursive call to expand the newly created if
4550 -- statement
4552 if Present (Condition_Actions (E))
4553 or else Compile_Time_Known_Value (Condition (E))
4554 then
4555 New_If :=
4556 Make_If_Statement (Sloc (E),
4557 Condition => Condition (E),
4558 Then_Statements => Then_Statements (E),
4559 Elsif_Parts => No_List,
4560 Else_Statements => Else_Statements (N));
4562 -- Elsif parts for new if come from remaining elsif's of parent
4564 while Present (Next (E)) loop
4565 if No (Elsif_Parts (New_If)) then
4566 Set_Elsif_Parts (New_If, New_List);
4567 end if;
4569 Append (Remove_Next (E), Elsif_Parts (New_If));
4570 end loop;
4572 Set_Else_Statements (N, New_List (New_If));
4574 Insert_List_Before (New_If, Condition_Actions (E));
4576 Remove (E);
4578 if Is_Empty_List (Elsif_Parts (N)) then
4579 Set_Elsif_Parts (N, No_List);
4580 end if;
4582 Analyze (New_If);
4584 -- Note this is not an implicit if statement, since it is part of
4585 -- an explicit if statement in the source (or of an implicit if
4586 -- statement that has already been tested). We set the flag after
4587 -- calling Analyze to avoid generating extra warnings specific to
4588 -- pure if statements, however (see Sem_Ch5.Analyze_If_Statement).
4590 Preserve_Comes_From_Source (New_If, N);
4591 return;
4593 -- No special processing for that elsif part, move to next
4595 else
4596 Next (E);
4597 end if;
4598 end loop;
4600 -- Some more optimizations applicable if we still have an IF statement
4602 if Nkind (N) /= N_If_Statement then
4603 return;
4604 end if;
4606 -- Another optimization, special cases that can be simplified
4608 -- if expression then
4609 -- return [standard.]true;
4610 -- else
4611 -- return [standard.]false;
4612 -- end if;
4614 -- can be changed to:
4616 -- return expression;
4618 -- and
4620 -- if expression then
4621 -- return [standard.]false;
4622 -- else
4623 -- return [standard.]true;
4624 -- end if;
4626 -- can be changed to:
4628 -- return not (expression);
4630 -- Do these optimizations only for internally generated code and only
4631 -- when -fpreserve-control-flow isn't set, to preserve the original
4632 -- source control flow.
4634 if not Comes_From_Source (N)
4635 and then not Opt.Suppress_Control_Flow_Optimizations
4636 and then Nkind (N) = N_If_Statement
4637 and then No (Elsif_Parts (N))
4638 and then Present (Else_Statements (N))
4639 and then List_Length (Then_Statements (N)) = 1
4640 and then List_Length (Else_Statements (N)) = 1
4641 then
4642 declare
4643 Then_Stm : constant Node_Id := First (Then_Statements (N));
4644 Else_Stm : constant Node_Id := First (Else_Statements (N));
4646 Then_Expr : Node_Id;
4647 Else_Expr : Node_Id;
4649 begin
4650 if Nkind (Then_Stm) = N_Simple_Return_Statement
4651 and then
4652 Nkind (Else_Stm) = N_Simple_Return_Statement
4653 then
4654 Then_Expr := Expression (Then_Stm);
4655 Else_Expr := Expression (Else_Stm);
4657 if Nkind (Then_Expr) in N_Expanded_Name | N_Identifier
4658 and then
4659 Nkind (Else_Expr) in N_Expanded_Name | N_Identifier
4660 then
4661 if Entity (Then_Expr) = Standard_True
4662 and then Entity (Else_Expr) = Standard_False
4663 then
4664 Rewrite (N,
4665 Make_Simple_Return_Statement (Loc,
4666 Expression => Relocate_Node (Condition (N))));
4667 Analyze (N);
4669 elsif Entity (Then_Expr) = Standard_False
4670 and then Entity (Else_Expr) = Standard_True
4671 then
4672 Rewrite (N,
4673 Make_Simple_Return_Statement (Loc,
4674 Expression =>
4675 Make_Op_Not (Loc,
4676 Right_Opnd => Relocate_Node (Condition (N)))));
4677 Analyze (N);
4678 end if;
4679 end if;
4680 end if;
4681 end;
4682 end if;
4683 end Expand_N_If_Statement;
4685 --------------------------
4686 -- Expand_Iterator_Loop --
4687 --------------------------
4689 procedure Expand_Iterator_Loop (N : Node_Id) is
4690 Isc : constant Node_Id := Iteration_Scheme (N);
4691 I_Spec : constant Node_Id := Iterator_Specification (Isc);
4693 Container : constant Node_Id := Name (I_Spec);
4694 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
4696 begin
4697 -- Processing for arrays
4699 if Is_Array_Type (Container_Typ) then
4700 pragma Assert (Of_Present (I_Spec));
4701 Expand_Iterator_Loop_Over_Array (N);
4703 elsif Has_Aspect (Container_Typ, Aspect_Iterable) then
4704 if Of_Present (I_Spec) then
4705 Expand_Formal_Container_Element_Loop (N);
4706 else
4707 Expand_Formal_Container_Loop (N);
4708 end if;
4710 -- Processing for containers
4712 else
4713 Expand_Iterator_Loop_Over_Container
4714 (N, Isc, I_Spec, Container, Container_Typ);
4715 end if;
4716 end Expand_Iterator_Loop;
4718 -------------------------------------
4719 -- Expand_Iterator_Loop_Over_Array --
4720 -------------------------------------
4722 procedure Expand_Iterator_Loop_Over_Array (N : Node_Id) is
4723 Isc : constant Node_Id := Iteration_Scheme (N);
4724 I_Spec : constant Node_Id := Iterator_Specification (Isc);
4725 Array_Node : constant Node_Id := Name (I_Spec);
4726 Array_Typ : constant Entity_Id := Base_Type (Etype (Array_Node));
4727 Array_Dim : constant Pos := Number_Dimensions (Array_Typ);
4728 Id : constant Entity_Id := Defining_Identifier (I_Spec);
4729 Loc : constant Source_Ptr := Sloc (Isc);
4730 Stats : List_Id := Statements (N);
4731 Core_Loop : Node_Id;
4732 Dim1 : Int;
4733 Ind_Comp : Node_Id;
4734 Iterator : Entity_Id;
4736 begin
4737 if Present (Iterator_Filter (I_Spec)) then
4738 pragma Assert (Ada_Version >= Ada_2022);
4739 Stats := New_List (Make_If_Statement (Loc,
4740 Condition => Iterator_Filter (I_Spec),
4741 Then_Statements => Stats));
4742 end if;
4744 -- for Element of Array loop
4746 -- It requires an internally generated cursor to iterate over the array
4748 pragma Assert (Of_Present (I_Spec));
4750 Iterator := Make_Temporary (Loc, 'C');
4752 -- Generate:
4753 -- Element : Component_Type renames Array (Iterator);
4754 -- Iterator is the index value, or a list of index values
4755 -- in the case of a multidimensional array.
4757 Ind_Comp :=
4758 Make_Indexed_Component (Loc,
4759 Prefix => New_Copy_Tree (Array_Node),
4760 Expressions => New_List (New_Occurrence_Of (Iterator, Loc)));
4762 -- Propagate the original node to the copy since the analysis of the
4763 -- following object renaming declaration relies on the original node.
4765 Set_Original_Node (Prefix (Ind_Comp), Original_Node (Array_Node));
4767 Prepend_To (Stats,
4768 Make_Object_Renaming_Declaration (Loc,
4769 Defining_Identifier => Id,
4770 Subtype_Mark =>
4771 New_Occurrence_Of (Component_Type (Array_Typ), Loc),
4772 Name => Ind_Comp));
4774 -- Mark the loop variable as needing debug info, so that expansion
4775 -- of the renaming will result in Materialize_Entity getting set via
4776 -- Debug_Renaming_Declaration. (This setting is needed here because
4777 -- the setting in Freeze_Entity comes after the expansion, which is
4778 -- too late. ???)
4780 Set_Debug_Info_Needed (Id);
4782 -- Generate:
4784 -- for Iterator in [reverse] Array'Range (Array_Dim) loop
4785 -- Element : Component_Type renames Array (Iterator);
4786 -- <original loop statements>
4787 -- end loop;
4789 -- If this is an iteration over a multidimensional array, the
4790 -- innermost loop is over the last dimension in Ada, and over
4791 -- the first dimension in Fortran.
4793 if Convention (Array_Typ) = Convention_Fortran then
4794 Dim1 := 1;
4795 else
4796 Dim1 := Array_Dim;
4797 end if;
4799 Core_Loop :=
4800 Make_Loop_Statement (Sloc (N),
4801 Iteration_Scheme =>
4802 Make_Iteration_Scheme (Loc,
4803 Loop_Parameter_Specification =>
4804 Make_Loop_Parameter_Specification (Loc,
4805 Defining_Identifier => Iterator,
4806 Discrete_Subtype_Definition =>
4807 Make_Attribute_Reference (Loc,
4808 Prefix => New_Copy_Tree (Array_Node),
4809 Attribute_Name => Name_Range,
4810 Expressions => New_List (
4811 Make_Integer_Literal (Loc, Dim1))),
4812 Reverse_Present => Reverse_Present (I_Spec))),
4813 Statements => Stats,
4814 End_Label => Empty);
4816 -- Processing for multidimensional array. The body of each loop is
4817 -- a loop over a previous dimension, going in decreasing order in Ada
4818 -- and in increasing order in Fortran.
4820 if Array_Dim > 1 then
4821 for Dim in 1 .. Array_Dim - 1 loop
4822 if Convention (Array_Typ) = Convention_Fortran then
4823 Dim1 := Dim + 1;
4824 else
4825 Dim1 := Array_Dim - Dim;
4826 end if;
4828 Iterator := Make_Temporary (Loc, 'C');
4830 -- Generate the dimension loops starting from the innermost one
4832 -- for Iterator in [reverse] Array'Range (Array_Dim - Dim) loop
4833 -- <core loop>
4834 -- end loop;
4836 Core_Loop :=
4837 Make_Loop_Statement (Sloc (N),
4838 Iteration_Scheme =>
4839 Make_Iteration_Scheme (Loc,
4840 Loop_Parameter_Specification =>
4841 Make_Loop_Parameter_Specification (Loc,
4842 Defining_Identifier => Iterator,
4843 Discrete_Subtype_Definition =>
4844 Make_Attribute_Reference (Loc,
4845 Prefix => New_Copy_Tree (Array_Node),
4846 Attribute_Name => Name_Range,
4847 Expressions => New_List (
4848 Make_Integer_Literal (Loc, Dim1))),
4849 Reverse_Present => Reverse_Present (I_Spec))),
4850 Statements => New_List (Core_Loop),
4851 End_Label => Empty);
4853 -- Update the previously created object renaming declaration with
4854 -- the new iterator, by adding the index of the next loop to the
4855 -- indexed component, in the order that corresponds to the
4856 -- convention.
4858 if Convention (Array_Typ) = Convention_Fortran then
4859 Append_To (Expressions (Ind_Comp),
4860 New_Occurrence_Of (Iterator, Loc));
4861 else
4862 Prepend_To (Expressions (Ind_Comp),
4863 New_Occurrence_Of (Iterator, Loc));
4864 end if;
4865 end loop;
4866 end if;
4868 -- Inherit the loop identifier from the original loop. This ensures that
4869 -- the scope stack is consistent after the rewriting.
4871 if Present (Identifier (N)) then
4872 Set_Identifier (Core_Loop, Relocate_Node (Identifier (N)));
4873 end if;
4875 Rewrite (N, Core_Loop);
4876 Analyze (N);
4877 end Expand_Iterator_Loop_Over_Array;
4879 -----------------------------------------
4880 -- Expand_Iterator_Loop_Over_Container --
4881 -----------------------------------------
4883 -- For a 'for ... in' loop, such as:
4885 -- for Cursor in Iterator_Function (...) loop
4886 -- ...
4887 -- end loop;
4889 -- we generate:
4891 -- Iter : Iterator_Type := Iterator_Function (...);
4892 -- Cursor : Cursor_type := First (Iter); -- or Last for "reverse"
4893 -- while Has_Element (Cursor) loop
4894 -- ...
4896 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
4897 -- end loop;
4899 -- For a 'for ... of' loop, such as:
4901 -- for X of Container loop
4902 -- ...
4903 -- end loop;
4905 -- the RM implies the generation of:
4907 -- Iter : Iterator_Type := Container.Iterate; -- the Default_Iterator
4908 -- Cursor : Cursor_Type := First (Iter); -- or Last for "reverse"
4909 -- while Has_Element (Cursor) loop
4910 -- declare
4911 -- X : Element_Type renames Element (Cursor).Element.all;
4912 -- -- or Constant_Element
4913 -- begin
4914 -- ...
4915 -- end;
4916 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
4917 -- end loop;
4919 -- In the general case, we do what the RM says. However, the operations
4920 -- Element and Iter.Next are slow, which is bad inside a loop, because they
4921 -- involve dispatching via interfaces, secondary stack manipulation,
4922 -- Busy/Lock incr/decr, and adjust/finalization/at-end handling. So for the
4923 -- predefined containers, we use an equivalent but optimized expansion.
4925 -- In the optimized case, we make use of these:
4927 -- procedure Next (Position : in out Cursor); -- instead of Iter.Next
4929 -- function Pseudo_Reference
4930 -- (Container : aliased Vector'Class) return Reference_Control_Type;
4932 -- type Element_Access is access all Element_Type;
4934 -- function Get_Element_Access
4935 -- (Position : Cursor) return not null Element_Access;
4937 -- Next is declared in the visible part of the container packages.
4938 -- The other three are added in the private part. (We're not supposed to
4939 -- pollute the namespace for clients. The compiler has no trouble breaking
4940 -- privacy to call things in the private part of an instance.)
4942 -- Source:
4944 -- for X of My_Vector loop
4945 -- X.Count := X.Count + 1;
4946 -- ...
4947 -- end loop;
4949 -- The compiler will generate:
4951 -- Iter : Reversible_Iterator'Class := Iterate (My_Vector);
4952 -- -- Reversible_Iterator is an interface. Iterate is the
4953 -- -- Default_Iterator aspect of Vector. This increments Lock,
4954 -- -- disallowing tampering with cursors. Unfortunately, it does not
4955 -- -- increment Busy. The result of Iterate is Limited_Controlled;
4956 -- -- finalization will decrement Lock. This is a build-in-place
4957 -- -- dispatching call to Iterate.
4959 -- Cur : Cursor := First (Iter); -- or Last
4960 -- -- Dispatching call via interface.
4962 -- Control : Reference_Control_Type := Pseudo_Reference (My_Vector);
4963 -- -- Pseudo_Reference increments Busy, to detect tampering with
4964 -- -- elements, as required by RM. Also redundantly increment
4965 -- -- Lock. Finalization of Control will decrement both Busy and
4966 -- -- Lock. Pseudo_Reference returns a record containing a pointer to
4967 -- -- My_Vector, used by Finalize.
4968 -- --
4969 -- -- Control is not used below, except to finalize it -- it's purely
4970 -- -- an RAII thing. This is needed because we are eliminating the
4971 -- -- call to Reference within the loop.
4973 -- while Has_Element (Cur) loop
4974 -- declare
4975 -- X : My_Element renames Get_Element_Access (Cur).all;
4976 -- -- Get_Element_Access returns a pointer to the element
4977 -- -- designated by Cur. No dispatching here, and no horsing
4978 -- -- around with access discriminants. This is instead of the
4979 -- -- existing
4980 -- --
4981 -- -- X : My_Element renames Reference (Cur).Element.all;
4982 -- --
4983 -- -- which creates a controlled object.
4984 -- begin
4985 -- -- Any attempt to tamper with My_Vector here in the loop
4986 -- -- will correctly raise Program_Error, because of the
4987 -- -- Control.
4989 -- X.Count := X.Count + 1;
4990 -- ...
4992 -- Next (Cur); -- or Prev
4993 -- -- This is instead of "Cur := Next (Iter, Cur);"
4994 -- end;
4995 -- -- No finalization here
4996 -- end loop;
4997 -- Finalize Iter and Control here, decrementing Lock twice and Busy
4998 -- once.
5000 -- This optimization makes "for ... of" loops over 30 times faster in cases
5001 -- measured.
5003 procedure Expand_Iterator_Loop_Over_Container
5004 (N : Node_Id;
5005 Isc : Node_Id;
5006 I_Spec : Node_Id;
5007 Container : Node_Id;
5008 Container_Typ : Entity_Id)
5010 Id : constant Entity_Id := Defining_Identifier (I_Spec);
5011 Elem_Typ : constant Entity_Id := Etype (Id);
5012 Id_Kind : constant Entity_Kind := Ekind (Id);
5013 Loc : constant Source_Ptr := Sloc (N);
5015 Stats : List_Id := Statements (N);
5016 -- Maybe wrapped in a conditional if a filter is present
5018 Cursor : Entity_Id;
5019 Decl : Node_Id;
5020 Iter_Type : Entity_Id;
5021 Iterator : Entity_Id;
5022 Name_Init : Name_Id;
5023 Name_Step : Name_Id;
5024 New_Loop : Node_Id;
5026 Fast_Element_Access_Op : Entity_Id := Empty;
5027 Fast_Step_Op : Entity_Id := Empty;
5028 -- Only for optimized version of "for ... of"
5030 Iter_Pack : Entity_Id;
5031 -- The package in which the iterator interface is instantiated. This is
5032 -- typically an instance within the container package.
5034 Pack : Entity_Id;
5035 -- The package in which the container type is declared
5037 begin
5038 if Present (Iterator_Filter (I_Spec)) then
5039 pragma Assert (Ada_Version >= Ada_2022);
5040 Stats := New_List (Make_If_Statement (Loc,
5041 Condition => Iterator_Filter (I_Spec),
5042 Then_Statements => Stats));
5043 end if;
5045 -- Determine the advancement and initialization steps for the cursor.
5046 -- Analysis of the expanded loop will verify that the container has a
5047 -- reverse iterator.
5049 if Reverse_Present (I_Spec) then
5050 Name_Init := Name_Last;
5051 Name_Step := Name_Previous;
5052 else
5053 Name_Init := Name_First;
5054 Name_Step := Name_Next;
5055 end if;
5057 -- The type of the iterator is the return type of the Iterate function
5058 -- used. For the "of" form this is the default iterator for the type,
5059 -- otherwise it is the type of the explicit function used in the
5060 -- iterator specification. The most common case will be an Iterate
5061 -- function in the container package.
5063 -- The Iterator type is declared in an instance within the container
5064 -- package itself, for example:
5066 -- package Vector_Iterator_Interfaces is new
5067 -- Ada.Iterator_Interfaces (Cursor, Has_Element);
5069 -- If the container type is a derived type, the cursor type is found in
5070 -- the package of the ultimate ancestor type.
5072 if Is_Derived_Type (Container_Typ) then
5073 Pack := Scope (Root_Type (Container_Typ));
5074 else
5075 Pack := Scope (Container_Typ);
5076 end if;
5078 if Of_Present (I_Spec) then
5079 Handle_Of : declare
5080 Container_Arg : Node_Id;
5082 function Get_Default_Iterator
5083 (T : Entity_Id) return Entity_Id;
5084 -- Return the default iterator for a specific type. If the type is
5085 -- derived, we return the inherited or overridden one if
5086 -- appropriate.
5088 --------------------------
5089 -- Get_Default_Iterator --
5090 --------------------------
5092 function Get_Default_Iterator
5093 (T : Entity_Id) return Entity_Id
5095 Iter : constant Entity_Id :=
5096 Entity (Find_Value_Of_Aspect (T, Aspect_Default_Iterator));
5097 Prim : Elmt_Id;
5098 Op : Entity_Id;
5100 begin
5101 Container_Arg := New_Copy_Tree (Container);
5103 -- A previous version of GNAT allowed indexing aspects to be
5104 -- redefined on derived container types, while the default
5105 -- iterator was inherited from the parent type. This
5106 -- nonstandard extension is preserved for use by the
5107 -- modeling project under debug flag -gnatd.X.
5109 if Debug_Flag_Dot_XX then
5110 if Base_Type (Etype (Container)) /=
5111 Base_Type (Etype (First_Formal (Iter)))
5112 then
5113 Container_Arg :=
5114 Make_Type_Conversion (Loc,
5115 Subtype_Mark =>
5116 New_Occurrence_Of
5117 (Etype (First_Formal (Iter)), Loc),
5118 Expression => Container_Arg);
5119 end if;
5121 return Iter;
5123 elsif Is_Derived_Type (T) then
5125 -- The default iterator must be a primitive operation of the
5126 -- type, at the same dispatch slot position. The DT position
5127 -- may not be established if type is not frozen yet.
5129 Prim := First_Elmt (Primitive_Operations (T));
5130 while Present (Prim) loop
5131 Op := Node (Prim);
5133 if Alias (Op) = Iter
5134 or else
5135 (Chars (Op) = Chars (Iter)
5136 and then Present (DTC_Entity (Op))
5137 and then DT_Position (Op) = DT_Position (Iter))
5138 then
5139 return Op;
5140 end if;
5142 Next_Elmt (Prim);
5143 end loop;
5145 -- If we didn't find it, then our parent type is not
5146 -- iterable, so we return the Default_Iterator aspect of
5147 -- this type.
5149 return Iter;
5151 -- Otherwise not a derived type
5153 else
5154 return Iter;
5155 end if;
5156 end Get_Default_Iterator;
5158 -- Local variables
5160 Default_Iter : Entity_Id;
5161 Ent : Entity_Id;
5163 Reference_Control_Type : Entity_Id := Empty;
5164 Pseudo_Reference : Entity_Id := Empty;
5166 -- Start of processing for Handle_Of
5168 begin
5169 if Is_Class_Wide_Type (Container_Typ) then
5170 Default_Iter :=
5171 Get_Default_Iterator (Etype (Base_Type (Container_Typ)));
5172 else
5173 Default_Iter := Get_Default_Iterator (Etype (Container));
5174 end if;
5176 Cursor := Make_Temporary (Loc, 'C');
5178 -- For a container element iterator, the iterator type is obtained
5179 -- from the corresponding aspect, whose return type is descended
5180 -- from the corresponding interface type in some instance of
5181 -- Ada.Iterator_Interfaces. The actuals of that instantiation
5182 -- are Cursor and Has_Element.
5184 Iter_Type := Etype (Default_Iter);
5186 -- The iterator type, which is a class-wide type, may itself be
5187 -- derived locally, so the desired instantiation is the scope of
5188 -- the root type of the iterator type.
5190 Iter_Pack := Scope (Root_Type (Etype (Iter_Type)));
5192 -- Find declarations needed for "for ... of" optimization
5193 -- These declarations come from GNAT sources or sources
5194 -- derived from them. User code may include additional
5195 -- overloadings with similar names, and we need to perforn
5196 -- some reasonable resolution to find the needed primitives.
5197 -- It is unclear whether this mechanism is fragile if a user
5198 -- makes arbitrary changes to the private part of a package
5199 -- that supports iterators.
5201 Ent := First_Entity (Pack);
5202 while Present (Ent) loop
5203 -- Get_Element_Access function with one parameter called
5204 -- Position.
5206 if Chars (Ent) = Name_Get_Element_Access
5207 and then Ekind (Ent) = E_Function
5208 and then Present (First_Formal (Ent))
5209 and then Chars (First_Formal (Ent)) = Name_Position
5210 and then No (Next_Formal (First_Formal (Ent)))
5211 then
5212 pragma Assert (No (Fast_Element_Access_Op));
5213 Fast_Element_Access_Op := Ent;
5215 -- Next or Prev procedure with one parameter called
5216 -- Position.
5218 elsif Chars (Ent) = Name_Step
5219 and then Ekind (Ent) = E_Procedure
5220 and then Present (First_Formal (Ent))
5221 and then Chars (First_Formal (Ent)) = Name_Position
5222 and then No (Next_Formal (First_Formal (Ent)))
5223 then
5224 pragma Assert (No (Fast_Step_Op));
5225 Fast_Step_Op := Ent;
5227 elsif Chars (Ent) = Name_Reference_Control_Type then
5228 pragma Assert (No (Reference_Control_Type));
5229 Reference_Control_Type := Ent;
5231 elsif Chars (Ent) = Name_Pseudo_Reference then
5232 pragma Assert (No (Pseudo_Reference));
5233 Pseudo_Reference := Ent;
5234 end if;
5236 Next_Entity (Ent);
5237 end loop;
5239 if Present (Reference_Control_Type)
5240 and then Present (Pseudo_Reference)
5241 then
5242 Insert_Action (N,
5243 Make_Object_Declaration (Loc,
5244 Defining_Identifier => Make_Temporary (Loc, 'D'),
5245 Object_Definition =>
5246 New_Occurrence_Of (Reference_Control_Type, Loc),
5247 Expression =>
5248 Make_Function_Call (Loc,
5249 Name =>
5250 New_Occurrence_Of (Pseudo_Reference, Loc),
5251 Parameter_Associations =>
5252 New_List (New_Copy_Tree (Container_Arg)))));
5253 end if;
5255 -- Rewrite domain of iteration as a call to the default iterator
5256 -- for the container type. The formal may be an access parameter
5257 -- in which case we must build a reference to the container.
5259 declare
5260 Arg : Node_Id;
5261 begin
5262 if Is_Access_Type (Etype (First_Entity (Default_Iter))) then
5263 Arg :=
5264 Make_Attribute_Reference (Loc,
5265 Prefix => Container_Arg,
5266 Attribute_Name => Name_Unrestricted_Access);
5267 else
5268 Arg := Container_Arg;
5269 end if;
5271 Rewrite (Name (I_Spec),
5272 Make_Function_Call (Loc,
5273 Name =>
5274 New_Occurrence_Of (Default_Iter, Loc),
5275 Parameter_Associations => New_List (Arg)));
5276 end;
5278 Analyze_And_Resolve (Name (I_Spec));
5280 -- Find cursor type in proper iterator package, which is an
5281 -- instantiation of Iterator_Interfaces.
5283 Ent := First_Entity (Iter_Pack);
5284 while Present (Ent) loop
5285 if Chars (Ent) = Name_Cursor then
5286 Set_Etype (Cursor, Etype (Ent));
5287 exit;
5288 end if;
5290 Next_Entity (Ent);
5291 end loop;
5293 if Present (Fast_Element_Access_Op) then
5294 Decl :=
5295 Make_Object_Renaming_Declaration (Loc,
5296 Defining_Identifier => Id,
5297 Subtype_Mark =>
5298 New_Occurrence_Of (Elem_Typ, Loc),
5299 Name =>
5300 Make_Explicit_Dereference (Loc,
5301 Prefix =>
5302 Make_Function_Call (Loc,
5303 Name =>
5304 New_Occurrence_Of (Fast_Element_Access_Op, Loc),
5305 Parameter_Associations =>
5306 New_List (New_Occurrence_Of (Cursor, Loc)))));
5308 else
5309 Decl :=
5310 Make_Object_Renaming_Declaration (Loc,
5311 Defining_Identifier => Id,
5312 Subtype_Mark =>
5313 New_Occurrence_Of (Elem_Typ, Loc),
5314 Name =>
5315 Make_Indexed_Component (Loc,
5316 Prefix => Relocate_Node (Container_Arg),
5317 Expressions =>
5318 New_List (New_Occurrence_Of (Cursor, Loc))));
5319 end if;
5321 -- The defining identifier in the iterator is user-visible and
5322 -- must be visible in the debugger.
5324 Set_Debug_Info_Needed (Id);
5326 -- If the container does not have a variable indexing aspect,
5327 -- the element is a constant in the loop. The container itself
5328 -- may be constant, in which case the element is a constant as
5329 -- well. The container has been rewritten as a call to Iterate,
5330 -- so examine original node.
5332 if No (Find_Value_Of_Aspect
5333 (Container_Typ, Aspect_Variable_Indexing))
5334 or else not Is_Variable (Original_Node (Container))
5335 then
5336 Mutate_Ekind (Id, E_Constant);
5337 end if;
5339 Prepend_To (Stats, Decl);
5340 end Handle_Of;
5342 -- X in Iterate (S) : type of iterator is type of explicitly given
5343 -- Iterate function, and the loop variable is the cursor. It will be
5344 -- assigned in the loop and must be a variable.
5346 else
5347 Iter_Type := Etype (Name (I_Spec));
5349 -- The iterator type, which is a class-wide type, may itself be
5350 -- derived locally, so the desired instantiation is the scope of
5351 -- the root type of the iterator type, as in the "of" case.
5353 Iter_Pack := Scope (Root_Type (Etype (Iter_Type)));
5354 Cursor := Id;
5355 end if;
5357 Iterator := Make_Temporary (Loc, 'I');
5359 -- For both iterator forms, add a call to the step operation to advance
5360 -- the cursor. Generate:
5362 -- Cursor := Iterator.Next (Cursor);
5364 -- or else
5366 -- Cursor := Next (Cursor);
5368 if Present (Fast_Element_Access_Op) and then Present (Fast_Step_Op) then
5369 declare
5370 Curs_Name : constant Node_Id := New_Occurrence_Of (Cursor, Loc);
5371 Step_Call : Node_Id;
5373 begin
5374 Step_Call :=
5375 Make_Procedure_Call_Statement (Loc,
5376 Name =>
5377 New_Occurrence_Of (Fast_Step_Op, Loc),
5378 Parameter_Associations => New_List (Curs_Name));
5380 Append_To (Stats, Step_Call);
5381 Set_Assignment_OK (Curs_Name);
5382 end;
5384 else
5385 declare
5386 Rhs : Node_Id;
5388 begin
5389 Rhs :=
5390 Make_Function_Call (Loc,
5391 Name =>
5392 Make_Selected_Component (Loc,
5393 Prefix => New_Occurrence_Of (Iterator, Loc),
5394 Selector_Name => Make_Identifier (Loc, Name_Step)),
5395 Parameter_Associations => New_List (
5396 New_Occurrence_Of (Cursor, Loc)));
5398 Append_To (Stats,
5399 Make_Assignment_Statement (Loc,
5400 Name => New_Occurrence_Of (Cursor, Loc),
5401 Expression => Rhs));
5402 Set_Assignment_OK (Name (Last (Stats)));
5403 end;
5404 end if;
5406 -- Generate:
5407 -- while Has_Element (Cursor) loop
5408 -- <Stats>
5409 -- end loop;
5411 -- Has_Element is the second actual in the iterator package
5413 New_Loop :=
5414 Make_Loop_Statement (Loc,
5415 Iteration_Scheme =>
5416 Make_Iteration_Scheme (Loc,
5417 Condition =>
5418 Make_Function_Call (Loc,
5419 Name =>
5420 New_Occurrence_Of
5421 (Next_Entity (First_Entity (Iter_Pack)), Loc),
5422 Parameter_Associations => New_List (
5423 New_Occurrence_Of (Cursor, Loc)))),
5425 Statements => Stats,
5426 End_Label => Empty);
5428 -- If present, preserve identifier of loop, which can be used in an exit
5429 -- statement in the body.
5431 if Present (Identifier (N)) then
5432 Set_Identifier (New_Loop, Relocate_Node (Identifier (N)));
5433 end if;
5435 -- Create the declarations for Iterator and cursor and insert them
5436 -- before the source loop. Given that the domain of iteration is already
5437 -- an entity, the iterator is just a renaming of that entity. Possible
5438 -- optimization ???
5440 Insert_Action (N,
5441 Make_Object_Renaming_Declaration (Loc,
5442 Defining_Identifier => Iterator,
5443 Subtype_Mark => New_Occurrence_Of (Iter_Type, Loc),
5444 Name => Relocate_Node (Name (I_Spec))));
5446 -- Create declaration for cursor
5448 declare
5449 Cursor_Decl : constant Node_Id :=
5450 Make_Object_Declaration (Loc,
5451 Defining_Identifier => Cursor,
5452 Object_Definition =>
5453 New_Occurrence_Of (Etype (Cursor), Loc),
5454 Expression =>
5455 Make_Selected_Component (Loc,
5456 Prefix =>
5457 New_Occurrence_Of (Iterator, Loc),
5458 Selector_Name =>
5459 Make_Identifier (Loc, Name_Init)));
5461 begin
5462 -- The cursor is only modified in expanded code, so it appears
5463 -- as unassigned to the warning machinery. We must suppress this
5464 -- spurious warning explicitly. The cursor's kind is that of the
5465 -- original loop parameter (it is a constant if the domain of
5466 -- iteration is constant).
5468 Set_Warnings_Off (Cursor);
5469 Set_Assignment_OK (Cursor_Decl);
5471 Insert_Action (N, Cursor_Decl);
5472 Mutate_Ekind (Cursor, Id_Kind);
5473 end;
5475 -- If the range of iteration is given by a function call that returns
5476 -- a container, the finalization actions have been saved in the
5477 -- Condition_Actions of the iterator. Insert them now at the head of
5478 -- the loop.
5480 Insert_List_Before (N, Condition_Actions (Isc));
5482 Rewrite (N, New_Loop);
5483 Analyze (N);
5484 end Expand_Iterator_Loop_Over_Container;
5486 -----------------------------
5487 -- Expand_N_Loop_Statement --
5488 -----------------------------
5490 -- 1. Remove null loop entirely
5491 -- 2. Deal with while condition for C/Fortran boolean
5492 -- 3. Deal with loops with a non-standard enumeration type range
5493 -- 4. Deal with while loops where Condition_Actions is set
5494 -- 5. Deal with loops over predicated subtypes
5495 -- 6. Deal with loops with iterators over arrays and containers
5497 procedure Expand_N_Loop_Statement (N : Node_Id) is
5498 Loc : constant Source_Ptr := Sloc (N);
5499 Scheme : constant Node_Id := Iteration_Scheme (N);
5500 Stmt : Node_Id;
5502 begin
5503 -- Delete null loop
5505 if Is_Null_Loop (N) then
5506 Rewrite (N, Make_Null_Statement (Loc));
5507 return;
5508 end if;
5510 -- Deal with condition for C/Fortran Boolean
5512 if Present (Scheme) then
5513 Adjust_Condition (Condition (Scheme));
5514 end if;
5516 -- Nothing more to do for plain loop with no iteration scheme
5518 if No (Scheme) then
5519 null;
5521 -- Case of for loop (Loop_Parameter_Specification present)
5523 -- Note: we do not have to worry about validity checking of the for loop
5524 -- range bounds here, since they were frozen with constant declarations
5525 -- and it is during that process that the validity checking is done.
5527 elsif Present (Loop_Parameter_Specification (Scheme)) then
5528 declare
5529 LPS : constant Node_Id :=
5530 Loop_Parameter_Specification (Scheme);
5531 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
5532 Ltype : constant Entity_Id := Etype (Loop_Id);
5533 Btype : constant Entity_Id := Base_Type (Ltype);
5534 Stats : constant List_Id := Statements (N);
5535 Expr : Node_Id;
5536 Decls : List_Id;
5537 New_Id : Entity_Id;
5539 begin
5540 -- If Discrete_Subtype_Definition has been rewritten as an
5541 -- N_Raise_xxx_Error, rewrite the whole loop as a raise node to
5542 -- avoid confusing the code generator down the line.
5544 if Nkind (Discrete_Subtype_Definition (LPS)) in N_Raise_xxx_Error
5545 then
5546 Rewrite (N, Discrete_Subtype_Definition (LPS));
5547 return;
5548 end if;
5550 if Present (Iterator_Filter (LPS)) then
5551 pragma Assert (Ada_Version >= Ada_2022);
5552 Set_Statements (N,
5553 New_List (Make_If_Statement (Loc,
5554 Condition => Iterator_Filter (LPS),
5555 Then_Statements => Stats)));
5556 end if;
5558 -- Deal with loop over predicates
5560 if Is_Discrete_Type (Ltype)
5561 and then Present (Predicate_Function (Ltype))
5562 then
5563 Expand_Predicated_Loop (N);
5565 -- Handle the case where we have a for loop with the range type
5566 -- being an enumeration type with non-standard representation.
5567 -- In this case we expand:
5569 -- for x in [reverse] a .. b loop
5570 -- ...
5571 -- end loop;
5573 -- to
5575 -- for xP in [reverse] integer
5576 -- range etype'Pos (a) .. etype'Pos (b)
5577 -- loop
5578 -- declare
5579 -- x : constant etype := Pos_To_Rep (xP);
5580 -- begin
5581 -- ...
5582 -- end;
5583 -- end loop;
5585 elsif Is_Enumeration_Type (Btype)
5586 and then Present (Enum_Pos_To_Rep (Btype))
5587 then
5588 New_Id :=
5589 Make_Defining_Identifier (Loc,
5590 Chars => New_External_Name (Chars (Loop_Id), 'P'));
5592 -- If the type has a contiguous representation, successive
5593 -- values can be generated as offsets from the first literal.
5595 if Has_Contiguous_Rep (Btype) then
5596 Expr :=
5597 Unchecked_Convert_To (Btype,
5598 Make_Op_Add (Loc,
5599 Left_Opnd =>
5600 Make_Integer_Literal (Loc,
5601 Enumeration_Rep (First_Literal (Btype))),
5602 Right_Opnd => New_Occurrence_Of (New_Id, Loc)));
5603 else
5604 -- Use the constructed array Enum_Pos_To_Rep
5606 Expr :=
5607 Make_Indexed_Component (Loc,
5608 Prefix =>
5609 New_Occurrence_Of (Enum_Pos_To_Rep (Btype), Loc),
5610 Expressions =>
5611 New_List (New_Occurrence_Of (New_Id, Loc)));
5612 end if;
5614 -- Build declaration for loop identifier
5616 Decls :=
5617 New_List (
5618 Make_Object_Declaration (Loc,
5619 Defining_Identifier => Loop_Id,
5620 Constant_Present => True,
5621 Object_Definition => New_Occurrence_Of (Ltype, Loc),
5622 Expression => Expr));
5624 Rewrite (N,
5625 Make_Loop_Statement (Loc,
5626 Identifier => Identifier (N),
5628 Iteration_Scheme =>
5629 Make_Iteration_Scheme (Loc,
5630 Loop_Parameter_Specification =>
5631 Make_Loop_Parameter_Specification (Loc,
5632 Defining_Identifier => New_Id,
5633 Reverse_Present => Reverse_Present (LPS),
5635 Discrete_Subtype_Definition =>
5636 Make_Subtype_Indication (Loc,
5638 Subtype_Mark =>
5639 New_Occurrence_Of (Standard_Natural, Loc),
5641 Constraint =>
5642 Make_Range_Constraint (Loc,
5643 Range_Expression =>
5644 Make_Range (Loc,
5646 Low_Bound =>
5647 Make_Attribute_Reference (Loc,
5648 Prefix =>
5649 New_Occurrence_Of (Btype, Loc),
5651 Attribute_Name => Name_Pos,
5653 Expressions => New_List (
5654 Relocate_Node
5655 (Type_Low_Bound (Ltype)))),
5657 High_Bound =>
5658 Make_Attribute_Reference (Loc,
5659 Prefix =>
5660 New_Occurrence_Of (Btype, Loc),
5662 Attribute_Name => Name_Pos,
5664 Expressions => New_List (
5665 Relocate_Node
5666 (Type_High_Bound
5667 (Ltype))))))))),
5669 Statements => New_List (
5670 Make_Block_Statement (Loc,
5671 Declarations => Decls,
5672 Handled_Statement_Sequence =>
5673 Make_Handled_Sequence_Of_Statements (Loc,
5674 Statements => Stats))),
5676 End_Label => End_Label (N)));
5678 -- The loop parameter's entity must be removed from the loop
5679 -- scope's entity list and rendered invisible, since it will
5680 -- now be located in the new block scope. Any other entities
5681 -- already associated with the loop scope, such as the loop
5682 -- parameter's subtype, will remain there.
5684 -- In an element loop, the loop will contain a declaration for
5685 -- a cursor variable; otherwise the loop id is the first entity
5686 -- in the scope constructed for the loop.
5688 if Comes_From_Source (Loop_Id) then
5689 pragma Assert (First_Entity (Scope (Loop_Id)) = Loop_Id);
5690 null;
5691 end if;
5693 Set_First_Entity (Scope (Loop_Id), Next_Entity (Loop_Id));
5694 Remove_Homonym (Loop_Id);
5696 if Last_Entity (Scope (Loop_Id)) = Loop_Id then
5697 Set_Last_Entity (Scope (Loop_Id), Empty);
5698 end if;
5700 Analyze (N);
5702 -- Nothing to do with other cases of for loops
5704 else
5705 null;
5706 end if;
5707 end;
5709 -- Second case, if we have a while loop with Condition_Actions set, then
5710 -- we change it into a plain loop:
5712 -- while C loop
5713 -- ...
5714 -- end loop;
5716 -- changed to:
5718 -- loop
5719 -- <<condition actions>>
5720 -- exit when not C;
5721 -- ...
5722 -- end loop
5724 elsif Present (Scheme)
5725 and then Present (Condition_Actions (Scheme))
5726 and then Present (Condition (Scheme))
5727 then
5728 declare
5729 ES : Node_Id;
5731 begin
5732 ES :=
5733 Make_Exit_Statement (Sloc (Condition (Scheme)),
5734 Condition =>
5735 Make_Op_Not (Sloc (Condition (Scheme)),
5736 Right_Opnd => Condition (Scheme)));
5738 Prepend (ES, Statements (N));
5739 Insert_List_Before (ES, Condition_Actions (Scheme));
5741 -- This is not an implicit loop, since it is generated in response
5742 -- to the loop statement being processed. If this is itself
5743 -- implicit, the restriction has already been checked. If not,
5744 -- it is an explicit loop.
5746 Rewrite (N,
5747 Make_Loop_Statement (Sloc (N),
5748 Identifier => Identifier (N),
5749 Statements => Statements (N),
5750 End_Label => End_Label (N)));
5752 Analyze (N);
5753 end;
5755 -- Here to deal with iterator case
5757 elsif Present (Scheme)
5758 and then Present (Iterator_Specification (Scheme))
5759 then
5760 Expand_Iterator_Loop (N);
5762 -- An iterator loop may generate renaming declarations for elements
5763 -- that require debug information. This is the case in particular
5764 -- with element iterators, where debug information must be generated
5765 -- for the temporary that holds the element value. These temporaries
5766 -- are created within a transient block whose local declarations are
5767 -- transferred to the loop, which now has nontrivial local objects.
5769 if Nkind (N) = N_Loop_Statement
5770 and then Present (Identifier (N))
5771 then
5772 Qualify_Entity_Names (N);
5773 end if;
5774 end if;
5776 -- When the iteration scheme mentions attribute 'Loop_Entry, the loop
5777 -- is transformed into a conditional block where the original loop is
5778 -- the sole statement. Inspect the statements of the nested loop for
5779 -- controlled objects.
5781 Stmt := N;
5783 if Subject_To_Loop_Entry_Attributes (Stmt) then
5784 Stmt := Find_Loop_In_Conditional_Block (Stmt);
5785 end if;
5787 Process_Statements_For_Controlled_Objects (Stmt);
5788 end Expand_N_Loop_Statement;
5790 ----------------------------
5791 -- Expand_Predicated_Loop --
5792 ----------------------------
5794 -- Note: the expander can handle generation of loops over predicated
5795 -- subtypes for both the dynamic and static cases. Depending on what
5796 -- we decide is allowed in Ada 2012 mode and/or extensions allowed
5797 -- mode, the semantic analyzer may disallow one or both forms.
5799 procedure Expand_Predicated_Loop (N : Node_Id) is
5800 Orig_Loop_Id : Node_Id := Empty;
5801 Loc : constant Source_Ptr := Sloc (N);
5802 Isc : constant Node_Id := Iteration_Scheme (N);
5803 LPS : constant Node_Id := Loop_Parameter_Specification (Isc);
5804 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
5805 Ltype : constant Entity_Id := Etype (Loop_Id);
5806 Stat : constant List_Id := Static_Discrete_Predicate (Ltype);
5807 Stmts : constant List_Id := Statements (N);
5809 begin
5810 -- Case of iteration over non-static predicate, should not be possible
5811 -- since this is not allowed by the semantics and should have been
5812 -- caught during analysis of the loop statement.
5814 if No (Stat) then
5815 raise Program_Error;
5817 -- If the predicate list is empty, that corresponds to a predicate of
5818 -- False, in which case the loop won't run at all, and we rewrite the
5819 -- entire loop as a null statement.
5821 elsif Is_Empty_List (Stat) then
5822 Rewrite (N, Make_Null_Statement (Loc));
5823 Analyze (N);
5825 -- For expansion over a static predicate we generate the following
5827 -- declare
5828 -- J : Ltype := min-val;
5829 -- begin
5830 -- loop
5831 -- body
5832 -- case J is
5833 -- when endpoint => J := startpoint;
5834 -- when endpoint => J := startpoint;
5835 -- ...
5836 -- when max-val => exit;
5837 -- when others => J := Lval'Succ (J);
5838 -- end case;
5839 -- end loop;
5840 -- end;
5842 -- with min-val replaced by max-val and Succ replaced by Pred if the
5843 -- loop parameter specification carries a Reverse indicator.
5845 -- To make this a little clearer, let's take a specific example:
5847 -- type Int is range 1 .. 10;
5848 -- subtype StaticP is Int with
5849 -- predicate => StaticP in 3 | 10 | 5 .. 7;
5850 -- ...
5851 -- for L in StaticP loop
5852 -- Put_Line ("static:" & J'Img);
5853 -- end loop;
5855 -- In this case, the loop is transformed into
5857 -- begin
5858 -- J : L := 3;
5859 -- loop
5860 -- body
5861 -- case J is
5862 -- when 3 => J := 5;
5863 -- when 7 => J := 10;
5864 -- when 10 => exit;
5865 -- when others => J := L'Succ (J);
5866 -- end case;
5867 -- end loop;
5868 -- end;
5870 -- In addition, if the loop specification is given by a subtype
5871 -- indication that constrains a predicated type, the bounds of
5872 -- iteration are given by those of the subtype indication.
5874 else
5875 Static_Predicate : declare
5876 S : Node_Id;
5877 D : Node_Id;
5878 P : Node_Id;
5879 Alts : List_Id;
5880 Cstm : Node_Id;
5882 -- If the domain is an itype, note the bounds of its range.
5884 L_Hi : Node_Id := Empty;
5885 L_Lo : Node_Id := Empty;
5887 function Lo_Val (N : Node_Id) return Node_Id;
5888 -- Given static expression or static range, returns an identifier
5889 -- whose value is the low bound of the expression value or range.
5891 function Hi_Val (N : Node_Id) return Node_Id;
5892 -- Given static expression or static range, returns an identifier
5893 -- whose value is the high bound of the expression value or range.
5895 ------------
5896 -- Hi_Val --
5897 ------------
5899 function Hi_Val (N : Node_Id) return Node_Id is
5900 begin
5901 if Is_OK_Static_Expression (N) then
5902 return New_Copy (N);
5903 else
5904 pragma Assert (Nkind (N) = N_Range);
5905 return New_Copy (High_Bound (N));
5906 end if;
5907 end Hi_Val;
5909 ------------
5910 -- Lo_Val --
5911 ------------
5913 function Lo_Val (N : Node_Id) return Node_Id is
5914 begin
5915 if Is_OK_Static_Expression (N) then
5916 return New_Copy (N);
5917 else
5918 pragma Assert (Nkind (N) = N_Range);
5919 return New_Copy (Low_Bound (N));
5920 end if;
5921 end Lo_Val;
5923 -- Start of processing for Static_Predicate
5925 begin
5926 -- Convert loop identifier to normal variable and reanalyze it so
5927 -- that this conversion works. We have to use the same defining
5928 -- identifier, since there may be references in the loop body.
5930 Set_Analyzed (Loop_Id, False);
5931 Mutate_Ekind (Loop_Id, E_Variable);
5933 -- In most loops the loop variable is assigned in various
5934 -- alternatives in the body. However, in the rare case when
5935 -- the range specifies a single element, the loop variable
5936 -- may trigger a spurious warning that is could be constant.
5937 -- This warning might as well be suppressed.
5939 Set_Warnings_Off (Loop_Id);
5941 if Is_Itype (Ltype) then
5942 L_Hi := High_Bound (Scalar_Range (Ltype));
5943 L_Lo := Low_Bound (Scalar_Range (Ltype));
5944 end if;
5946 -- Loop to create branches of case statement
5948 Alts := New_List;
5950 if Reverse_Present (LPS) then
5952 -- Initial value is largest value in predicate.
5954 if Is_Itype (Ltype) then
5955 D :=
5956 Make_Object_Declaration (Loc,
5957 Defining_Identifier => Loop_Id,
5958 Object_Definition => New_Occurrence_Of (Ltype, Loc),
5959 Expression => L_Hi);
5961 else
5962 D :=
5963 Make_Object_Declaration (Loc,
5964 Defining_Identifier => Loop_Id,
5965 Object_Definition => New_Occurrence_Of (Ltype, Loc),
5966 Expression => Hi_Val (Last (Stat)));
5967 end if;
5969 P := Last (Stat);
5970 while Present (P) loop
5971 if No (Prev (P)) then
5972 S := Make_Exit_Statement (Loc);
5973 else
5974 S :=
5975 Make_Assignment_Statement (Loc,
5976 Name => New_Occurrence_Of (Loop_Id, Loc),
5977 Expression => Hi_Val (Prev (P)));
5978 Set_Suppress_Assignment_Checks (S);
5979 end if;
5981 Append_To (Alts,
5982 Make_Case_Statement_Alternative (Loc,
5983 Statements => New_List (S),
5984 Discrete_Choices => New_List (Lo_Val (P))));
5986 Prev (P);
5987 end loop;
5989 if Is_Itype (Ltype)
5990 and then Is_OK_Static_Expression (L_Lo)
5991 and then
5992 Expr_Value (L_Lo) /= Expr_Value (Lo_Val (First (Stat)))
5993 then
5994 Append_To (Alts,
5995 Make_Case_Statement_Alternative (Loc,
5996 Statements => New_List (Make_Exit_Statement (Loc)),
5997 Discrete_Choices => New_List (L_Lo)));
5998 end if;
6000 else
6001 -- Initial value is smallest value in predicate
6003 if Is_Itype (Ltype) then
6004 D :=
6005 Make_Object_Declaration (Loc,
6006 Defining_Identifier => Loop_Id,
6007 Object_Definition => New_Occurrence_Of (Ltype, Loc),
6008 Expression => L_Lo);
6009 else
6010 D :=
6011 Make_Object_Declaration (Loc,
6012 Defining_Identifier => Loop_Id,
6013 Object_Definition => New_Occurrence_Of (Ltype, Loc),
6014 Expression => Lo_Val (First (Stat)));
6015 end if;
6017 P := First (Stat);
6018 while Present (P) loop
6019 if No (Next (P)) then
6020 S := Make_Exit_Statement (Loc);
6021 else
6022 S :=
6023 Make_Assignment_Statement (Loc,
6024 Name => New_Occurrence_Of (Loop_Id, Loc),
6025 Expression => Lo_Val (Next (P)));
6026 Set_Suppress_Assignment_Checks (S);
6027 end if;
6029 Append_To (Alts,
6030 Make_Case_Statement_Alternative (Loc,
6031 Statements => New_List (S),
6032 Discrete_Choices => New_List (Hi_Val (P))));
6034 Next (P);
6035 end loop;
6037 if Is_Itype (Ltype)
6038 and then Is_OK_Static_Expression (L_Hi)
6039 and then
6040 Expr_Value (L_Hi) /= Expr_Value (Lo_Val (Last (Stat)))
6041 then
6042 Append_To (Alts,
6043 Make_Case_Statement_Alternative (Loc,
6044 Statements => New_List (Make_Exit_Statement (Loc)),
6045 Discrete_Choices => New_List (L_Hi)));
6046 end if;
6047 end if;
6049 -- Add others choice
6051 declare
6052 Name_Next : Name_Id;
6054 begin
6055 if Reverse_Present (LPS) then
6056 Name_Next := Name_Pred;
6057 else
6058 Name_Next := Name_Succ;
6059 end if;
6061 S :=
6062 Make_Assignment_Statement (Loc,
6063 Name => New_Occurrence_Of (Loop_Id, Loc),
6064 Expression =>
6065 Make_Attribute_Reference (Loc,
6066 Prefix => New_Occurrence_Of (Ltype, Loc),
6067 Attribute_Name => Name_Next,
6068 Expressions => New_List (
6069 New_Occurrence_Of (Loop_Id, Loc))));
6070 Set_Suppress_Assignment_Checks (S);
6071 end;
6073 Append_To (Alts,
6074 Make_Case_Statement_Alternative (Loc,
6075 Discrete_Choices => New_List (Make_Others_Choice (Loc)),
6076 Statements => New_List (S)));
6078 -- Construct case statement and append to body statements
6080 Cstm :=
6081 Make_Case_Statement (Loc,
6082 Expression => New_Occurrence_Of (Loop_Id, Loc),
6083 Alternatives => Alts);
6084 Append_To (Stmts, Cstm);
6086 -- Rewrite the loop preserving the loop identifier in case there
6087 -- are exit statements referencing it.
6089 if Present (Identifier (N)) then
6090 Orig_Loop_Id := New_Occurrence_Of
6091 (Entity (Identifier (N)), Loc);
6092 end if;
6094 Set_Suppress_Assignment_Checks (D);
6096 Rewrite (N,
6097 Make_Block_Statement (Loc,
6098 Declarations => New_List (D),
6099 Handled_Statement_Sequence =>
6100 Make_Handled_Sequence_Of_Statements (Loc,
6101 Statements => New_List (
6102 Make_Loop_Statement (Loc,
6103 Statements => Stmts,
6104 Identifier => Orig_Loop_Id,
6105 End_Label => Empty)))));
6107 Analyze (N);
6108 end Static_Predicate;
6109 end if;
6110 end Expand_Predicated_Loop;
6112 ------------------------------
6113 -- Make_Tag_Ctrl_Assignment --
6114 ------------------------------
6116 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
6117 Asn : constant Node_Id := Relocate_Node (N);
6118 L : constant Node_Id := Name (N);
6119 Loc : constant Source_Ptr := Sloc (N);
6120 Res : constant List_Id := New_List;
6121 T : constant Entity_Id := Underlying_Type (Etype (L));
6123 Comp_Asn : constant Boolean := Is_Fully_Repped_Tagged_Type (T);
6124 Ctrl_Act : constant Boolean := Needs_Finalization (T)
6125 and then not No_Ctrl_Actions (N);
6126 Save_Tag : constant Boolean := Is_Tagged_Type (T)
6127 and then not Comp_Asn
6128 and then not No_Ctrl_Actions (N)
6129 and then Tagged_Type_Expansion;
6130 Adj_Call : Node_Id;
6131 Fin_Call : Node_Id;
6132 Tag_Id : Entity_Id;
6134 begin
6135 -- Finalize the target of the assignment when controlled
6137 -- We have two exceptions here:
6139 -- 1. If we are in an init proc since it is an initialization more
6140 -- than an assignment.
6142 -- 2. If the left-hand side is a temporary that was not initialized
6143 -- (or the parent part of a temporary since it is the case in
6144 -- extension aggregates). Such a temporary does not come from
6145 -- source. We must examine the original node for the prefix, because
6146 -- it may be a component of an entry formal, in which case it has
6147 -- been rewritten and does not appear to come from source either.
6149 -- Case of init proc
6151 if not Ctrl_Act then
6152 null;
6154 -- The left-hand side is an uninitialized temporary object
6156 elsif Nkind (L) = N_Type_Conversion
6157 and then Is_Entity_Name (Expression (L))
6158 and then Nkind (Parent (Entity (Expression (L)))) =
6159 N_Object_Declaration
6160 and then No_Initialization (Parent (Entity (Expression (L))))
6161 then
6162 null;
6164 else
6165 Fin_Call :=
6166 Make_Final_Call
6167 (Obj_Ref => Duplicate_Subexpr_No_Checks (L),
6168 Typ => Etype (L));
6170 if Present (Fin_Call) then
6171 Append_To (Res, Fin_Call);
6172 end if;
6173 end if;
6175 -- Save the Tag in a local variable Tag_Id
6177 if Save_Tag then
6178 Tag_Id := Make_Temporary (Loc, 'A');
6180 Append_To (Res,
6181 Make_Object_Declaration (Loc,
6182 Defining_Identifier => Tag_Id,
6183 Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc),
6184 Expression =>
6185 Make_Selected_Component (Loc,
6186 Prefix => Duplicate_Subexpr_No_Checks (L),
6187 Selector_Name =>
6188 New_Occurrence_Of (First_Tag_Component (T), Loc))));
6190 -- Otherwise Tag_Id is not used
6192 else
6193 Tag_Id := Empty;
6194 end if;
6196 -- If the tagged type has a full rep clause, expand the assignment into
6197 -- component-wise assignments. Mark the node as unanalyzed in order to
6198 -- generate the proper code and propagate this scenario by setting a
6199 -- flag to avoid infinite recursion.
6201 if Comp_Asn then
6202 Set_Analyzed (Asn, False);
6203 Set_Componentwise_Assignment (Asn, True);
6204 end if;
6206 Append_To (Res, Asn);
6208 -- Restore the tag
6210 if Save_Tag then
6211 Append_To (Res,
6212 Make_Assignment_Statement (Loc,
6213 Name =>
6214 Make_Selected_Component (Loc,
6215 Prefix => Duplicate_Subexpr_No_Checks (L),
6216 Selector_Name =>
6217 New_Occurrence_Of (First_Tag_Component (T), Loc)),
6218 Expression => New_Occurrence_Of (Tag_Id, Loc)));
6219 end if;
6221 -- Adjust the target after the assignment when controlled (not in the
6222 -- init proc since it is an initialization more than an assignment).
6224 if Ctrl_Act then
6225 Adj_Call :=
6226 Make_Adjust_Call
6227 (Obj_Ref => Duplicate_Subexpr_Move_Checks (L),
6228 Typ => Etype (L));
6230 if Present (Adj_Call) then
6231 Append_To (Res, Adj_Call);
6232 end if;
6233 end if;
6235 return Res;
6237 exception
6239 -- Could use comment here ???
6241 when RE_Not_Available =>
6242 return Empty_List;
6243 end Make_Tag_Ctrl_Assignment;
6245 end Exp_Ch5;