OSDN Git Service

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