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