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