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