OSDN Git Service

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