Debian Codegraph @

gcc/ada/exp_ch5.adb

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