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