OSDN Git Service

2007-08-31 Hristian Kirtchev <kirtchev@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             Subprg         : Entity_Id;
1416             RT_Subprg_Name : Node_Id;
1417
1418          begin
1419             --  Handle chains of renamings
1420
1421             Ent := Name (N);
1422             while Nkind (Ent) in N_Has_Entity
1423               and then Present (Entity (Ent))
1424               and then Present (Renamed_Object (Entity (Ent)))
1425             loop
1426                Ent := Renamed_Object (Entity (Ent));
1427             end loop;
1428
1429             --  The attribute Priority applied to protected objects has been
1430             --  previously expanded into a call to the Get_Ceiling run-time
1431             --  subprogram.
1432
1433             if Nkind (Ent) = N_Function_Call
1434               and then (Entity (Name (Ent)) = RTE (RE_Get_Ceiling)
1435                           or else
1436                         Entity (Name (Ent)) = RTE (RO_PE_Get_Ceiling))
1437             then
1438                --  Look for the enclosing concurrent type
1439
1440                Conctyp := Current_Scope;
1441                while not Is_Concurrent_Type (Conctyp) loop
1442                   Conctyp := Scope (Conctyp);
1443                end loop;
1444
1445                pragma Assert (Is_Protected_Type (Conctyp));
1446
1447                --  Generate the first actual of the call
1448
1449                Subprg := Current_Scope;
1450                while not Present (Protected_Body_Subprogram (Subprg)) loop
1451                   Subprg := Scope (Subprg);
1452                end loop;
1453
1454                --  Select the appropriate run-time call
1455
1456                if Number_Entries (Conctyp) = 0 then
1457                   RT_Subprg_Name :=
1458                     New_Reference_To (RTE (RE_Set_Ceiling), Loc);
1459                else
1460                   RT_Subprg_Name :=
1461                     New_Reference_To (RTE (RO_PE_Set_Ceiling), Loc);
1462                end if;
1463
1464                Call :=
1465                  Make_Procedure_Call_Statement (Loc,
1466                    Name => RT_Subprg_Name,
1467                    Parameter_Associations => New_List (
1468                      New_Copy_Tree (First (Parameter_Associations (Ent))),
1469                      Relocate_Node (Expression (N))));
1470
1471                Rewrite (N, Call);
1472                Analyze (N);
1473                return;
1474             end if;
1475          end;
1476       end if;
1477
1478       --  First deal with generation of range check if required. For now we do
1479       --  this only for discrete types.
1480
1481       if Do_Range_Check (Rhs)
1482         and then Is_Discrete_Type (Typ)
1483       then
1484          Set_Do_Range_Check (Rhs, False);
1485          Generate_Range_Check (Rhs, Typ, CE_Range_Check_Failed);
1486       end if;
1487
1488       --  Check for a special case where a high level transformation is
1489       --  required. If we have either of:
1490
1491       --    P.field := rhs;
1492       --    P (sub) := rhs;
1493
1494       --  where P is a reference to a bit packed array, then we have to unwind
1495       --  the assignment. The exact meaning of being a reference to a bit
1496       --  packed array is as follows:
1497
1498       --    An indexed component whose prefix is a bit packed array is a
1499       --    reference to a bit packed array.
1500
1501       --    An indexed component or selected component whose prefix is a
1502       --    reference to a bit packed array is itself a reference ot a
1503       --    bit packed array.
1504
1505       --  The required transformation is
1506
1507       --     Tnn : prefix_type := P;
1508       --     Tnn.field := rhs;
1509       --     P := Tnn;
1510
1511       --  or
1512
1513       --     Tnn : prefix_type := P;
1514       --     Tnn (subscr) := rhs;
1515       --     P := Tnn;
1516
1517       --  Since P is going to be evaluated more than once, any subscripts
1518       --  in P must have their evaluation forced.
1519
1520       if (Nkind (Lhs) = N_Indexed_Component
1521            or else
1522           Nkind (Lhs) = N_Selected_Component)
1523         and then Is_Ref_To_Bit_Packed_Array (Prefix (Lhs))
1524       then
1525          declare
1526             BPAR_Expr : constant Node_Id   := Relocate_Node (Prefix (Lhs));
1527             BPAR_Typ  : constant Entity_Id := Etype (BPAR_Expr);
1528             Tnn       : constant Entity_Id :=
1529                           Make_Defining_Identifier (Loc,
1530                             Chars => New_Internal_Name ('T'));
1531
1532          begin
1533             --  Insert the post assignment first, because we want to copy the
1534             --  BPAR_Expr tree before it gets analyzed in the context of the
1535             --  pre assignment. Note that we do not analyze the post assignment
1536             --  yet (we cannot till we have completed the analysis of the pre
1537             --  assignment). As usual, the analysis of this post assignment
1538             --  will happen on its own when we "run into" it after finishing
1539             --  the current assignment.
1540
1541             Insert_After (N,
1542               Make_Assignment_Statement (Loc,
1543                 Name       => New_Copy_Tree (BPAR_Expr),
1544                 Expression => New_Occurrence_Of (Tnn, Loc)));
1545
1546             --  At this stage BPAR_Expr is a reference to a bit packed array
1547             --  where the reference was not expanded in the original tree,
1548             --  since it was on the left side of an assignment. But in the
1549             --  pre-assignment statement (the object definition), BPAR_Expr
1550             --  will end up on the right hand side, and must be reexpanded. To
1551             --  achieve this, we reset the analyzed flag of all selected and
1552             --  indexed components down to the actual indexed component for
1553             --  the packed array.
1554
1555             Exp := BPAR_Expr;
1556             loop
1557                Set_Analyzed (Exp, False);
1558
1559                if Nkind (Exp) = N_Selected_Component
1560                     or else
1561                   Nkind (Exp) = N_Indexed_Component
1562                then
1563                   Exp := Prefix (Exp);
1564                else
1565                   exit;
1566                end if;
1567             end loop;
1568
1569             --  Now we can insert and analyze the pre-assignment
1570
1571             --  If the right-hand side requires a transient scope, it has
1572             --  already been placed on the stack. However, the declaration is
1573             --  inserted in the tree outside of this scope, and must reflect
1574             --  the proper scope for its variable. This awkward bit is forced
1575             --  by the stricter scope discipline imposed by GCC 2.97.
1576
1577             declare
1578                Uses_Transient_Scope : constant Boolean :=
1579                                         Scope_Is_Transient
1580                                           and then N = Node_To_Be_Wrapped;
1581
1582             begin
1583                if Uses_Transient_Scope then
1584                   Push_Scope (Scope (Current_Scope));
1585                end if;
1586
1587                Insert_Before_And_Analyze (N,
1588                  Make_Object_Declaration (Loc,
1589                    Defining_Identifier => Tnn,
1590                    Object_Definition   => New_Occurrence_Of (BPAR_Typ, Loc),
1591                    Expression          => BPAR_Expr));
1592
1593                if Uses_Transient_Scope then
1594                   Pop_Scope;
1595                end if;
1596             end;
1597
1598             --  Now fix up the original assignment and continue processing
1599
1600             Rewrite (Prefix (Lhs),
1601               New_Occurrence_Of (Tnn, Loc));
1602
1603             --  We do not need to reanalyze that assignment, and we do not need
1604             --  to worry about references to the temporary, but we do need to
1605             --  make sure that the temporary is not marked as a true constant
1606             --  since we now have a generated assignment to it!
1607
1608             Set_Is_True_Constant (Tnn, False);
1609          end;
1610       end if;
1611
1612       --  When we have the appropriate type of aggregate in the expression (it
1613       --  has been determined during analysis of the aggregate by setting the
1614       --  delay flag), let's perform in place assignment and thus avoid
1615       --  creating a temporary.
1616
1617       if Is_Delayed_Aggregate (Rhs) then
1618          Convert_Aggr_In_Assignment (N);
1619          Rewrite (N, Make_Null_Statement (Loc));
1620          Analyze (N);
1621          return;
1622       end if;
1623
1624       --  Apply discriminant check if required. If Lhs is an access type to a
1625       --  designated type with discriminants, we must always check.
1626
1627       if Has_Discriminants (Etype (Lhs)) then
1628
1629          --  Skip discriminant check if change of representation. Will be
1630          --  done when the change of representation is expanded out.
1631
1632          if not Change_Of_Representation (N) then
1633             Apply_Discriminant_Check (Rhs, Etype (Lhs), Lhs);
1634          end if;
1635
1636       --  If the type is private without discriminants, and the full type
1637       --  has discriminants (necessarily with defaults) a check may still be
1638       --  necessary if the Lhs is aliased. The private determinants must be
1639       --  visible to build the discriminant constraints.
1640
1641       --  Only an explicit dereference that comes from source indicates
1642       --  aliasing. Access to formals of protected operations and entries
1643       --  create dereferences but are not semantic aliasings.
1644
1645       elsif Is_Private_Type (Etype (Lhs))
1646         and then Has_Discriminants (Typ)
1647         and then Nkind (Lhs) = N_Explicit_Dereference
1648         and then Comes_From_Source (Lhs)
1649       then
1650          declare
1651             Lt : constant Entity_Id := Etype (Lhs);
1652          begin
1653             Set_Etype (Lhs, Typ);
1654             Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
1655             Apply_Discriminant_Check (Rhs, Typ, Lhs);
1656             Set_Etype (Lhs, Lt);
1657          end;
1658
1659          --  If the Lhs has a private type with unknown discriminants, it
1660          --  may have a full view with discriminants, but those are nameable
1661          --  only in the underlying type, so convert the Rhs to it before
1662          --  potential checking.
1663
1664       elsif Has_Unknown_Discriminants (Base_Type (Etype (Lhs)))
1665         and then Has_Discriminants (Typ)
1666       then
1667          Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
1668          Apply_Discriminant_Check (Rhs, Typ, Lhs);
1669
1670       --  In the access type case, we need the same discriminant check, and
1671       --  also range checks if we have an access to constrained array.
1672
1673       elsif Is_Access_Type (Etype (Lhs))
1674         and then Is_Constrained (Designated_Type (Etype (Lhs)))
1675       then
1676          if Has_Discriminants (Designated_Type (Etype (Lhs))) then
1677
1678             --  Skip discriminant check if change of representation. Will be
1679             --  done when the change of representation is expanded out.
1680
1681             if not Change_Of_Representation (N) then
1682                Apply_Discriminant_Check (Rhs, Etype (Lhs));
1683             end if;
1684
1685          elsif Is_Array_Type (Designated_Type (Etype (Lhs))) then
1686             Apply_Range_Check (Rhs, Etype (Lhs));
1687
1688             if Is_Constrained (Etype (Lhs)) then
1689                Apply_Length_Check (Rhs, Etype (Lhs));
1690             end if;
1691
1692             if Nkind (Rhs) = N_Allocator then
1693                declare
1694                   Target_Typ : constant Entity_Id := Etype (Expression (Rhs));
1695                   C_Es       : Check_Result;
1696
1697                begin
1698                   C_Es :=
1699                     Get_Range_Checks
1700                       (Lhs,
1701                        Target_Typ,
1702                        Etype (Designated_Type (Etype (Lhs))));
1703
1704                   Insert_Range_Checks
1705                     (C_Es,
1706                      N,
1707                      Target_Typ,
1708                      Sloc (Lhs),
1709                      Lhs);
1710                end;
1711             end if;
1712          end if;
1713
1714       --  Apply range check for access type case
1715
1716       elsif Is_Access_Type (Etype (Lhs))
1717         and then Nkind (Rhs) = N_Allocator
1718         and then Nkind (Expression (Rhs)) = N_Qualified_Expression
1719       then
1720          Analyze_And_Resolve (Expression (Rhs));
1721          Apply_Range_Check
1722            (Expression (Rhs), Designated_Type (Etype (Lhs)));
1723       end if;
1724
1725       --  Ada 2005 (AI-231): Generate the run-time check
1726
1727       if Is_Access_Type (Typ)
1728         and then Can_Never_Be_Null (Etype (Lhs))
1729         and then not Can_Never_Be_Null (Etype (Rhs))
1730       then
1731          Apply_Constraint_Check (Rhs, Etype (Lhs));
1732       end if;
1733
1734       --  Case of assignment to a bit packed array element
1735
1736       if Nkind (Lhs) = N_Indexed_Component
1737         and then Is_Bit_Packed_Array (Etype (Prefix (Lhs)))
1738       then
1739          Expand_Bit_Packed_Element_Set (N);
1740          return;
1741
1742       --  Build-in-place function call case. Note that we're not yet doing
1743       --  build-in-place for user-written assignment statements (the assignment
1744       --  here came from an aggregate.)
1745
1746       elsif Ada_Version >= Ada_05
1747         and then Is_Build_In_Place_Function_Call (Rhs)
1748       then
1749          Make_Build_In_Place_Call_In_Assignment (N, Rhs);
1750
1751       elsif Is_Tagged_Type (Typ) and then Is_Value_Type (Etype (Lhs)) then
1752
1753          --  Nothing to do for valuetypes
1754          --  ??? Set_Scope_Is_Transient (False);
1755
1756          return;
1757
1758       elsif Is_Tagged_Type (Typ)
1759         or else (Controlled_Type (Typ) and then not Is_Array_Type (Typ))
1760       then
1761          Tagged_Case : declare
1762             L                   : List_Id := No_List;
1763             Expand_Ctrl_Actions : constant Boolean := not No_Ctrl_Actions (N);
1764
1765          begin
1766             --  In the controlled case, we need to make sure that function
1767             --  calls are evaluated before finalizing the target. In all cases,
1768             --  it makes the expansion easier if the side-effects are removed
1769             --  first.
1770
1771             Remove_Side_Effects (Lhs);
1772             Remove_Side_Effects (Rhs);
1773
1774             --  Avoid recursion in the mechanism
1775
1776             Set_Analyzed (N);
1777
1778             --  If dispatching assignment, we need to dispatch to _assign
1779
1780             if Is_Class_Wide_Type (Typ)
1781
1782                --  If the type is tagged, we may as well use the predefined
1783                --  primitive assignment. This avoids inlining a lot of code
1784                --  and in the class-wide case, the assignment is replaced by
1785                --  dispatch call to _assign. Note that this cannot be done when
1786                --  discriminant checks are locally suppressed (as in extension
1787                --  aggregate expansions) because otherwise the discriminant
1788                --  check will be performed within the _assign call. It is also
1789                --  suppressed for assignmments created by the expander that
1790                --  correspond to initializations, where we do want to copy the
1791                --  tag (No_Ctrl_Actions flag set True). by the expander and we
1792                --  do not need to mess with tags ever (Expand_Ctrl_Actions flag
1793                --  is set True in this case).
1794
1795                or else (Is_Tagged_Type (Typ)
1796                           and then not Is_Value_Type (Etype (Lhs))
1797                           and then Chars (Current_Scope) /= Name_uAssign
1798                           and then Expand_Ctrl_Actions
1799                           and then not Discriminant_Checks_Suppressed (Empty))
1800             then
1801                --  Fetch the primitive op _assign and proper type to call it.
1802                --  Because of possible conflits between private and full view
1803                --  the proper type is fetched directly from the operation
1804                --  profile.
1805
1806                declare
1807                   Op    : constant Entity_Id :=
1808                             Find_Prim_Op (Typ, Name_uAssign);
1809                   F_Typ : Entity_Id := Etype (First_Formal (Op));
1810
1811                begin
1812                   --  If the assignment is dispatching, make sure to use the
1813                   --  proper type.
1814
1815                   if Is_Class_Wide_Type (Typ) then
1816                      F_Typ := Class_Wide_Type (F_Typ);
1817                   end if;
1818
1819                   L := New_List;
1820
1821                   --  In case of assignment to a class-wide tagged type, before
1822                   --  the assignment we generate run-time check to ensure that
1823                   --  the tags of source and target match.
1824
1825                   if Is_Class_Wide_Type (Typ)
1826                     and then Is_Tagged_Type (Typ)
1827                     and then Is_Tagged_Type (Underlying_Type (Etype (Rhs)))
1828                   then
1829                      Append_To (L,
1830                        Make_Raise_Constraint_Error (Loc,
1831                          Condition =>
1832                              Make_Op_Ne (Loc,
1833                                Left_Opnd =>
1834                                  Make_Selected_Component (Loc,
1835                                    Prefix        => Duplicate_Subexpr (Lhs),
1836                                    Selector_Name =>
1837                                      Make_Identifier (Loc,
1838                                        Chars => Name_uTag)),
1839                                Right_Opnd =>
1840                                  Make_Selected_Component (Loc,
1841                                    Prefix        => Duplicate_Subexpr (Rhs),
1842                                    Selector_Name =>
1843                                      Make_Identifier (Loc,
1844                                        Chars => Name_uTag))),
1845                          Reason => CE_Tag_Check_Failed));
1846                   end if;
1847
1848                   Append_To (L,
1849                     Make_Procedure_Call_Statement (Loc,
1850                       Name => New_Reference_To (Op, Loc),
1851                       Parameter_Associations => New_List (
1852                         Unchecked_Convert_To (F_Typ,
1853                           Duplicate_Subexpr (Lhs)),
1854                         Unchecked_Convert_To (F_Typ,
1855                           Duplicate_Subexpr (Rhs)))));
1856                end;
1857
1858             else
1859                L := Make_Tag_Ctrl_Assignment (N);
1860
1861                --  We can't afford to have destructive Finalization Actions in
1862                --  the Self assignment case, so if the target and the source
1863                --  are not obviously different, code is generated to avoid the
1864                --  self assignment case:
1865
1866                --    if lhs'address /= rhs'address then
1867                --       <code for controlled and/or tagged assignment>
1868                --    end if;
1869
1870                if not Statically_Different (Lhs, Rhs)
1871                  and then Expand_Ctrl_Actions
1872                then
1873                   L := New_List (
1874                     Make_Implicit_If_Statement (N,
1875                       Condition =>
1876                         Make_Op_Ne (Loc,
1877                           Left_Opnd =>
1878                             Make_Attribute_Reference (Loc,
1879                               Prefix         => Duplicate_Subexpr (Lhs),
1880                               Attribute_Name => Name_Address),
1881
1882                            Right_Opnd =>
1883                             Make_Attribute_Reference (Loc,
1884                               Prefix         => Duplicate_Subexpr (Rhs),
1885                               Attribute_Name => Name_Address)),
1886
1887                       Then_Statements => L));
1888                end if;
1889
1890                --  We need to set up an exception handler for implementing
1891                --  7.6.1(18). The remaining adjustments are tackled by the
1892                --  implementation of adjust for record_controllers (see
1893                --  s-finimp.adb).
1894
1895                --  This is skipped if we have no finalization
1896
1897                if Expand_Ctrl_Actions
1898                  and then not Restriction_Active (No_Finalization)
1899                then
1900                   L := New_List (
1901                     Make_Block_Statement (Loc,
1902                       Handled_Statement_Sequence =>
1903                         Make_Handled_Sequence_Of_Statements (Loc,
1904                           Statements => L,
1905                           Exception_Handlers => New_List (
1906                             Make_Handler_For_Ctrl_Operation (Loc)))));
1907                end if;
1908             end if;
1909
1910             Rewrite (N,
1911               Make_Block_Statement (Loc,
1912                 Handled_Statement_Sequence =>
1913                   Make_Handled_Sequence_Of_Statements (Loc, Statements => L)));
1914
1915             --  If no restrictions on aborts, protect the whole assignement
1916             --  for controlled objects as per 9.8(11).
1917
1918             if Controlled_Type (Typ)
1919               and then Expand_Ctrl_Actions
1920               and then Abort_Allowed
1921             then
1922                declare
1923                   Blk : constant Entity_Id :=
1924                           New_Internal_Entity
1925                             (E_Block, Current_Scope, Sloc (N), 'B');
1926
1927                begin
1928                   Set_Scope (Blk, Current_Scope);
1929                   Set_Etype (Blk, Standard_Void_Type);
1930                   Set_Identifier (N, New_Occurrence_Of (Blk, Sloc (N)));
1931
1932                   Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
1933                   Set_At_End_Proc (Handled_Statement_Sequence (N),
1934                     New_Occurrence_Of (RTE (RE_Abort_Undefer_Direct), Loc));
1935                   Expand_At_End_Handler
1936                     (Handled_Statement_Sequence (N), Blk);
1937                end;
1938             end if;
1939
1940             --  N has been rewritten to a block statement for which it is
1941             --  known by construction that no checks are necessary: analyze
1942             --  it with all checks suppressed.
1943
1944             Analyze (N, Suppress => All_Checks);
1945             return;
1946          end Tagged_Case;
1947
1948       --  Array types
1949
1950       elsif Is_Array_Type (Typ) then
1951          declare
1952             Actual_Rhs : Node_Id := Rhs;
1953
1954          begin
1955             while Nkind (Actual_Rhs) = N_Type_Conversion
1956               or else
1957                   Nkind (Actual_Rhs) = N_Qualified_Expression
1958             loop
1959                Actual_Rhs := Expression (Actual_Rhs);
1960             end loop;
1961
1962             Expand_Assign_Array (N, Actual_Rhs);
1963             return;
1964          end;
1965
1966       --  Record types
1967
1968       elsif Is_Record_Type (Typ) then
1969          Expand_Assign_Record (N);
1970          return;
1971
1972       --  Scalar types. This is where we perform the processing related to the
1973       --  requirements of (RM 13.9.1(9-11)) concerning the handling of invalid
1974       --  scalar values.
1975
1976       elsif Is_Scalar_Type (Typ) then
1977
1978          --  Case where right side is known valid
1979
1980          if Expr_Known_Valid (Rhs) then
1981
1982             --  Here the right side is valid, so it is fine. The case to deal
1983             --  with is when the left side is a local variable reference whose
1984             --  value is not currently known to be valid. If this is the case,
1985             --  and the assignment appears in an unconditional context, then we
1986             --  can mark the left side as now being valid.
1987
1988             if Is_Local_Variable_Reference (Lhs)
1989               and then not Is_Known_Valid (Entity (Lhs))
1990               and then In_Unconditional_Context (N)
1991             then
1992                Set_Is_Known_Valid (Entity (Lhs), True);
1993             end if;
1994
1995          --  Case where right side may be invalid in the sense of the RM
1996          --  reference above. The RM does not require that we check for the
1997          --  validity on an assignment, but it does require that the assignment
1998          --  of an invalid value not cause erroneous behavior.
1999
2000          --  The general approach in GNAT is to use the Is_Known_Valid flag
2001          --  to avoid the need for validity checking on assignments. However
2002          --  in some cases, we have to do validity checking in order to make
2003          --  sure that the setting of this flag is correct.
2004
2005          else
2006             --  Validate right side if we are validating copies
2007
2008             if Validity_Checks_On
2009               and then Validity_Check_Copies
2010             then
2011                --  Skip this if left hand side is an array or record component
2012                --  and elementary component validity checks are suppressed.
2013
2014                if (Nkind (Lhs) = N_Selected_Component
2015                     or else
2016                    Nkind (Lhs) = N_Indexed_Component)
2017                  and then not Validity_Check_Components
2018                then
2019                   null;
2020                else
2021                   Ensure_Valid (Rhs);
2022                end if;
2023
2024                --  We can propagate this to the left side where appropriate
2025
2026                if Is_Local_Variable_Reference (Lhs)
2027                  and then not Is_Known_Valid (Entity (Lhs))
2028                  and then In_Unconditional_Context (N)
2029                then
2030                   Set_Is_Known_Valid (Entity (Lhs), True);
2031                end if;
2032
2033             --  Otherwise check to see what should be done
2034
2035             --  If left side is a local variable, then we just set its flag to
2036             --  indicate that its value may no longer be valid, since we are
2037             --  copying a potentially invalid value.
2038
2039             elsif Is_Local_Variable_Reference (Lhs) then
2040                Set_Is_Known_Valid (Entity (Lhs), False);
2041
2042             --  Check for case of a nonlocal variable on the left side which
2043             --  is currently known to be valid. In this case, we simply ensure
2044             --  that the right side is valid. We only play the game of copying
2045             --  validity status for local variables, since we are doing this
2046             --  statically, not by tracing the full flow graph.
2047
2048             elsif Is_Entity_Name (Lhs)
2049               and then Is_Known_Valid (Entity (Lhs))
2050             then
2051                --  Note: If Validity_Checking mode is set to none, we ignore
2052                --  the Ensure_Valid call so don't worry about that case here.
2053
2054                Ensure_Valid (Rhs);
2055
2056             --  In all other cases, we can safely copy an invalid value without
2057             --  worrying about the status of the left side. Since it is not a
2058             --  variable reference it will not be considered
2059             --  as being known to be valid in any case.
2060
2061             else
2062                null;
2063             end if;
2064          end if;
2065       end if;
2066
2067       --  Defend against invalid subscripts on left side if we are in standard
2068       --  validity checking mode. No need to do this if we are checking all
2069       --  subscripts.
2070
2071       if Validity_Checks_On
2072         and then Validity_Check_Default
2073         and then not Validity_Check_Subscripts
2074       then
2075          Check_Valid_Lvalue_Subscripts (Lhs);
2076       end if;
2077
2078    exception
2079       when RE_Not_Available =>
2080          return;
2081    end Expand_N_Assignment_Statement;
2082
2083    ------------------------------
2084    -- Expand_N_Block_Statement --
2085    ------------------------------
2086
2087    --  Encode entity names defined in block statement
2088
2089    procedure Expand_N_Block_Statement (N : Node_Id) is
2090    begin
2091       Qualify_Entity_Names (N);
2092    end Expand_N_Block_Statement;
2093
2094    -----------------------------
2095    -- Expand_N_Case_Statement --
2096    -----------------------------
2097
2098    procedure Expand_N_Case_Statement (N : Node_Id) is
2099       Loc    : constant Source_Ptr := Sloc (N);
2100       Expr   : constant Node_Id    := Expression (N);
2101       Alt    : Node_Id;
2102       Len    : Nat;
2103       Cond   : Node_Id;
2104       Choice : Node_Id;
2105       Chlist : List_Id;
2106
2107    begin
2108       --  Check for the situation where we know at compile time which branch
2109       --  will be taken
2110
2111       if Compile_Time_Known_Value (Expr) then
2112          Alt := Find_Static_Alternative (N);
2113
2114          --  Move statements from this alternative after the case statement.
2115          --  They are already analyzed, so will be skipped by the analyzer.
2116
2117          Insert_List_After (N, Statements (Alt));
2118
2119          --  That leaves the case statement as a shell. So now we can kill all
2120          --  other alternatives in the case statement.
2121
2122          Kill_Dead_Code (Expression (N));
2123
2124          declare
2125             A : Node_Id;
2126
2127          begin
2128             --  Loop through case alternatives, skipping pragmas, and skipping
2129             --  the one alternative that we select (and therefore retain).
2130
2131             A := First (Alternatives (N));
2132             while Present (A) loop
2133                if A /= Alt
2134                  and then Nkind (A) = N_Case_Statement_Alternative
2135                then
2136                   Kill_Dead_Code (Statements (A), Warn_On_Deleted_Code);
2137                end if;
2138
2139                Next (A);
2140             end loop;
2141          end;
2142
2143          Rewrite (N, Make_Null_Statement (Loc));
2144          return;
2145       end if;
2146
2147       --  Here if the choice is not determined at compile time
2148
2149       declare
2150          Last_Alt : constant Node_Id := Last (Alternatives (N));
2151
2152          Others_Present : Boolean;
2153          Others_Node    : Node_Id;
2154
2155          Then_Stms : List_Id;
2156          Else_Stms : List_Id;
2157
2158       begin
2159          if Nkind (First (Discrete_Choices (Last_Alt))) = N_Others_Choice then
2160             Others_Present := True;
2161             Others_Node    := Last_Alt;
2162          else
2163             Others_Present := False;
2164          end if;
2165
2166          --  First step is to worry about possible invalid argument. The RM
2167          --  requires (RM 5.4(13)) that if the result is invalid (e.g. it is
2168          --  outside the base range), then Constraint_Error must be raised.
2169
2170          --  Case of validity check required (validity checks are on, the
2171          --  expression is not known to be valid, and the case statement
2172          --  comes from source -- no need to validity check internally
2173          --  generated case statements).
2174
2175          if Validity_Check_Default then
2176             Ensure_Valid (Expr);
2177          end if;
2178
2179          --  If there is only a single alternative, just replace it with the
2180          --  sequence of statements since obviously that is what is going to
2181          --  be executed in all cases.
2182
2183          Len := List_Length (Alternatives (N));
2184
2185          if Len = 1 then
2186             --  We still need to evaluate the expression if it has any
2187             --  side effects.
2188
2189             Remove_Side_Effects (Expression (N));
2190
2191             Insert_List_After (N, Statements (First (Alternatives (N))));
2192
2193             --  That leaves the case statement as a shell. The alternative that
2194             --  will be executed is reset to a null list. So now we can kill
2195             --  the entire case statement.
2196
2197             Kill_Dead_Code (Expression (N));
2198             Rewrite (N, Make_Null_Statement (Loc));
2199             return;
2200          end if;
2201
2202          --  An optimization. If there are only two alternatives, and only
2203          --  a single choice, then rewrite the whole case statement as an
2204          --  if statement, since this can result in susbequent optimizations.
2205          --  This helps not only with case statements in the source of a
2206          --  simple form, but also with generated code (discriminant check
2207          --  functions in particular)
2208
2209          if Len = 2 then
2210             Chlist := Discrete_Choices (First (Alternatives (N)));
2211
2212             if List_Length (Chlist) = 1 then
2213                Choice := First (Chlist);
2214
2215                Then_Stms := Statements (First (Alternatives (N)));
2216                Else_Stms := Statements (Last  (Alternatives (N)));
2217
2218                --  For TRUE, generate "expression", not expression = true
2219
2220                if Nkind (Choice) = N_Identifier
2221                  and then Entity (Choice) = Standard_True
2222                then
2223                   Cond := Expression (N);
2224
2225                --  For FALSE, generate "expression" and switch then/else
2226
2227                elsif Nkind (Choice) = N_Identifier
2228                  and then Entity (Choice) = Standard_False
2229                then
2230                   Cond := Expression (N);
2231                   Else_Stms := Statements (First (Alternatives (N)));
2232                   Then_Stms := Statements (Last  (Alternatives (N)));
2233
2234                --  For a range, generate "expression in range"
2235
2236                elsif Nkind (Choice) = N_Range
2237                  or else (Nkind (Choice) = N_Attribute_Reference
2238                            and then Attribute_Name (Choice) = Name_Range)
2239                  or else (Is_Entity_Name (Choice)
2240                            and then Is_Type (Entity (Choice)))
2241                  or else Nkind (Choice) = N_Subtype_Indication
2242                then
2243                   Cond :=
2244                     Make_In (Loc,
2245                       Left_Opnd  => Expression (N),
2246                       Right_Opnd => Relocate_Node (Choice));
2247
2248                --  For any other subexpression "expression = value"
2249
2250                else
2251                   Cond :=
2252                     Make_Op_Eq (Loc,
2253                       Left_Opnd  => Expression (N),
2254                       Right_Opnd => Relocate_Node (Choice));
2255                end if;
2256
2257                --  Now rewrite the case as an IF
2258
2259                Rewrite (N,
2260                  Make_If_Statement (Loc,
2261                    Condition => Cond,
2262                    Then_Statements => Then_Stms,
2263                    Else_Statements => Else_Stms));
2264                Analyze (N);
2265                return;
2266             end if;
2267          end if;
2268
2269          --  If the last alternative is not an Others choice, replace it with
2270          --  an N_Others_Choice. Note that we do not bother to call Analyze on
2271          --  the modified case statement, since it's only effect would be to
2272          --  compute the contents of the Others_Discrete_Choices which is not
2273          --  needed by the back end anyway.
2274
2275          --  The reason we do this is that the back end always needs some
2276          --  default for a switch, so if we have not supplied one in the
2277          --  processing above for validity checking, then we need to supply
2278          --  one here.
2279
2280          if not Others_Present then
2281             Others_Node := Make_Others_Choice (Sloc (Last_Alt));
2282             Set_Others_Discrete_Choices
2283               (Others_Node, Discrete_Choices (Last_Alt));
2284             Set_Discrete_Choices (Last_Alt, New_List (Others_Node));
2285          end if;
2286       end;
2287    end Expand_N_Case_Statement;
2288
2289    -----------------------------
2290    -- Expand_N_Exit_Statement --
2291    -----------------------------
2292
2293    --  The only processing required is to deal with a possible C/Fortran
2294    --  boolean value used as the condition for the exit statement.
2295
2296    procedure Expand_N_Exit_Statement (N : Node_Id) is
2297    begin
2298       Adjust_Condition (Condition (N));
2299    end Expand_N_Exit_Statement;
2300
2301    ----------------------------------------
2302    -- Expand_N_Extended_Return_Statement --
2303    ----------------------------------------
2304
2305    --  If there is a Handled_Statement_Sequence, we rewrite this:
2306
2307    --     return Result : T := <expression> do
2308    --        <handled_seq_of_stms>
2309    --     end return;
2310
2311    --  to be:
2312
2313    --     declare
2314    --        Result : T := <expression>;
2315    --     begin
2316    --        <handled_seq_of_stms>
2317    --        return Result;
2318    --     end;
2319
2320    --  Otherwise (no Handled_Statement_Sequence), we rewrite this:
2321
2322    --     return Result : T := <expression>;
2323
2324    --  to be:
2325
2326    --     return <expression>;
2327
2328    --  unless it's build-in-place or there's no <expression>, in which case
2329    --  we generate:
2330
2331    --     declare
2332    --        Result : T := <expression>;
2333    --     begin
2334    --        return Result;
2335    --     end;
2336
2337    --  Note that this case could have been written by the user as an extended
2338    --  return statement, or could have been transformed to this from a simple
2339    --  return statement.
2340
2341    --  That is, we need to have a reified return object if there are statements
2342    --  (which might refer to it) or if we're doing build-in-place (so we can
2343    --  set its address to the final resting place or if there is no expression
2344    --  (in which case default initial values might need to be set).
2345
2346    procedure Expand_N_Extended_Return_Statement (N : Node_Id) is
2347       Loc : constant Source_Ptr := Sloc (N);
2348
2349       Return_Object_Entity : constant Entity_Id :=
2350                                First_Entity (Return_Statement_Entity (N));
2351       Return_Object_Decl   : constant Node_Id :=
2352                                Parent (Return_Object_Entity);
2353       Parent_Function      : constant Entity_Id :=
2354                                Return_Applies_To (Return_Statement_Entity (N));
2355       Is_Build_In_Place    : constant Boolean :=
2356                                Is_Build_In_Place_Function (Parent_Function);
2357
2358       Return_Stm      : Node_Id;
2359       Statements      : List_Id;
2360       Handled_Stm_Seq : Node_Id;
2361       Result          : Node_Id;
2362       Exp             : Node_Id;
2363
2364       function Move_Activation_Chain return Node_Id;
2365       --  Construct a call to System.Tasking.Stages.Move_Activation_Chain
2366       --  with parameters:
2367       --    From         current activation chain
2368       --    To           activation chain passed in by the caller
2369       --    New_Master   master passed in by the caller
2370
2371       function Move_Final_List return Node_Id;
2372       --  Construct call to System.Finalization_Implementation.Move_Final_List
2373       --  with parameters:
2374       --
2375       --    From         finalization list of the return statement
2376       --    To           finalization list passed in by the caller
2377
2378       ---------------------------
2379       -- Move_Activation_Chain --
2380       ---------------------------
2381
2382       function Move_Activation_Chain return Node_Id is
2383          Activation_Chain_Formal : constant Entity_Id :=
2384                                      Build_In_Place_Formal
2385                                        (Parent_Function, BIP_Activation_Chain);
2386          To                      : constant Node_Id :=
2387                                      New_Reference_To
2388                                        (Activation_Chain_Formal, Loc);
2389          Master_Formal           : constant Entity_Id :=
2390                                      Build_In_Place_Formal
2391                                        (Parent_Function, BIP_Master);
2392          New_Master              : constant Node_Id :=
2393                                      New_Reference_To (Master_Formal, Loc);
2394
2395          Chain_Entity : Entity_Id;
2396          From         : Node_Id;
2397
2398       begin
2399          Chain_Entity := First_Entity (Return_Statement_Entity (N));
2400          while Chars (Chain_Entity) /= Name_uChain loop
2401             Chain_Entity := Next_Entity (Chain_Entity);
2402          end loop;
2403
2404          From :=
2405            Make_Attribute_Reference (Loc,
2406              Prefix         => New_Reference_To (Chain_Entity, Loc),
2407              Attribute_Name => Name_Unrestricted_Access);
2408          --  ??? Not clear why "Make_Identifier (Loc, Name_uChain)" doesn't
2409          --  work, instead of "New_Reference_To (Chain_Entity, Loc)" above.
2410
2411          return
2412            Make_Procedure_Call_Statement (Loc,
2413              Name => New_Reference_To (RTE (RE_Move_Activation_Chain), Loc),
2414              Parameter_Associations => New_List (From, To, New_Master));
2415       end Move_Activation_Chain;
2416
2417       ---------------------
2418       -- Move_Final_List --
2419       ---------------------
2420
2421       function Move_Final_List return Node_Id is
2422          Flist : constant Entity_Id  :=
2423                    Finalization_Chain_Entity (Return_Statement_Entity (N));
2424
2425          From : constant Node_Id := New_Reference_To (Flist, Loc);
2426
2427          Caller_Final_List : constant Entity_Id :=
2428                                Build_In_Place_Formal
2429                                  (Parent_Function, BIP_Final_List);
2430
2431          To : constant Node_Id := New_Reference_To (Caller_Final_List, Loc);
2432
2433       begin
2434          --  Catch cases where a finalization chain entity has not been
2435          --  associated with the return statement entity.
2436
2437          pragma Assert (Present (Flist));
2438
2439          --  Build required call
2440
2441          return
2442            Make_If_Statement (Loc,
2443              Condition =>
2444                Make_Op_Ne (Loc,
2445                  Left_Opnd  => New_Copy (From),
2446                  Right_Opnd => New_Node (N_Null, Loc)),
2447              Then_Statements =>
2448                New_List (
2449                  Make_Procedure_Call_Statement (Loc,
2450                    Name => New_Reference_To (RTE (RE_Move_Final_List), Loc),
2451                    Parameter_Associations => New_List (From, To))));
2452       end Move_Final_List;
2453
2454    --  Start of processing for Expand_N_Extended_Return_Statement
2455
2456    begin
2457       if Nkind (Return_Object_Decl) = N_Object_Declaration then
2458          Exp := Expression (Return_Object_Decl);
2459       else
2460          Exp := Empty;
2461       end if;
2462
2463       Handled_Stm_Seq := Handled_Statement_Sequence (N);
2464
2465       --  Build a simple_return_statement that returns the return object when
2466       --  there is a statement sequence, or no expression, or the result will
2467       --  be built in place. Note however that we currently do this for all
2468       --  composite cases, even though nonlimited composite results are not yet
2469       --  built in place (though we plan to do so eventually).
2470
2471       if Present (Handled_Stm_Seq)
2472         or else Is_Composite_Type (Etype (Parent_Function))
2473         or else No (Exp)
2474       then
2475          if No (Handled_Stm_Seq) then
2476             Statements := New_List;
2477
2478          --  If the extended return has a handled statement sequence, then wrap
2479          --  it in a block and use the block as the first statement.
2480
2481          else
2482             Statements :=
2483               New_List (Make_Block_Statement (Loc,
2484                           Declarations => New_List,
2485                           Handled_Statement_Sequence => Handled_Stm_Seq));
2486          end if;
2487
2488          --  If control gets past the above Statements, we have successfully
2489          --  completed the return statement. If the result type has controlled
2490          --  parts and the return is for a build-in-place function, then we
2491          --  call Move_Final_List to transfer responsibility for finalization
2492          --  of the return object to the caller. An alternative would be to
2493          --  declare a Success flag in the function, initialize it to False,
2494          --  and set it to True here. Then move the Move_Final_List call into
2495          --  the cleanup code, and check Success. If Success then make a call
2496          --  to Move_Final_List else do finalization. Then we can remove the
2497          --  abort-deferral and the nulling-out of the From parameter from
2498          --  Move_Final_List. Note that the current method is not quite correct
2499          --  in the rather obscure case of a select-then-abort statement whose
2500          --  abortable part contains the return statement.
2501
2502          --  We test the type of the expression as well as the return type
2503          --  of the function, because the latter may be a class-wide type
2504          --  which is always treated as controlled, while the expression itself
2505          --  has to have a definite type. The expression may be absent if a
2506          --  constrained aggregate has been expanded into component assignments
2507          --  so we have to check for this as well.
2508
2509          if Is_Build_In_Place
2510            and then Controlled_Type (Etype (Parent_Function))
2511          then
2512             if not Is_Class_Wide_Type (Etype (Parent_Function))
2513               or else
2514                (Present (Exp)
2515                  and then Controlled_Type (Etype (Exp)))
2516             then
2517                Append_To (Statements, Move_Final_List);
2518             end if;
2519          end if;
2520
2521          --  Similarly to the above Move_Final_List, if the result type
2522          --  contains tasks, we call Move_Activation_Chain. Later, the cleanup
2523          --  code will call Complete_Master, which will terminate any
2524          --  unactivated tasks belonging to the return statement master. But
2525          --  Move_Activation_Chain updates their master to be that of the
2526          --  caller, so they will not be terminated unless the return statement
2527          --  completes unsuccessfully due to exception, abort, goto, or exit.
2528          --  As a formality, we test whether the function requires the result
2529          --  to be built in place, though that's necessarily true for the case
2530          --  of result types with task parts.
2531
2532          if Is_Build_In_Place and Has_Task (Etype (Parent_Function)) then
2533             Append_To (Statements, Move_Activation_Chain);
2534          end if;
2535
2536          --  Build a simple_return_statement that returns the return object
2537
2538          Return_Stm :=
2539            Make_Simple_Return_Statement (Loc,
2540              Expression => New_Occurrence_Of (Return_Object_Entity, Loc));
2541          Append_To (Statements, Return_Stm);
2542
2543          Handled_Stm_Seq :=
2544            Make_Handled_Sequence_Of_Statements (Loc, Statements);
2545       end if;
2546
2547       --  Case where we build a block
2548
2549       if Present (Handled_Stm_Seq) then
2550          Result :=
2551            Make_Block_Statement (Loc,
2552              Declarations => Return_Object_Declarations (N),
2553              Handled_Statement_Sequence => Handled_Stm_Seq);
2554
2555          --  We set the entity of the new block statement to be that of the
2556          --  return statement. This is necessary so that various fields, such
2557          --  as Finalization_Chain_Entity carry over from the return statement
2558          --  to the block. Note that this block is unusual, in that its entity
2559          --  is an E_Return_Statement rather than an E_Block.
2560
2561          Set_Identifier
2562            (Result, New_Occurrence_Of (Return_Statement_Entity (N), Loc));
2563
2564          --  If the object decl was already rewritten as a renaming, then
2565          --  we don't want to do the object allocation and transformation of
2566          --  of the return object declaration to a renaming. This case occurs
2567          --  when the return object is initialized by a call to another
2568          --  build-in-place function, and that function is responsible for the
2569          --  allocation of the return object.
2570
2571          if Is_Build_In_Place
2572            and then
2573              Nkind (Return_Object_Decl) = N_Object_Renaming_Declaration
2574          then
2575             Set_By_Ref (Return_Stm);  -- Return build-in-place results by ref
2576
2577          elsif Is_Build_In_Place then
2578
2579             --  Locate the implicit access parameter associated with the
2580             --  caller-supplied return object and convert the return
2581             --  statement's return object declaration to a renaming of a
2582             --  dereference of the access parameter. If the return object's
2583             --  declaration includes an expression that has not already been
2584             --  expanded as separate assignments, then add an assignment
2585             --  statement to ensure the return object gets initialized.
2586
2587             --  declare
2588             --     Result : T [:= <expression>];
2589             --  begin
2590             --     ...
2591
2592             --  is converted to
2593
2594             --  declare
2595             --     Result : T renames FuncRA.all;
2596             --     [Result := <expression;]
2597             --  begin
2598             --     ...
2599
2600             declare
2601                Return_Obj_Id    : constant Entity_Id :=
2602                                     Defining_Identifier (Return_Object_Decl);
2603                Return_Obj_Typ   : constant Entity_Id := Etype (Return_Obj_Id);
2604                Return_Obj_Expr  : constant Node_Id :=
2605                                     Expression (Return_Object_Decl);
2606                Result_Subt      : constant Entity_Id :=
2607                                     Etype (Parent_Function);
2608                Constr_Result    : constant Boolean :=
2609                                     Is_Constrained (Result_Subt);
2610                Obj_Alloc_Formal : Entity_Id;
2611                Object_Access    : Entity_Id;
2612                Obj_Acc_Deref    : Node_Id;
2613                Init_Assignment  : Node_Id := Empty;
2614
2615             begin
2616                --  Build-in-place results must be returned by reference
2617
2618                Set_By_Ref (Return_Stm);
2619
2620                --  Retrieve the implicit access parameter passed by the caller
2621
2622                Object_Access :=
2623                  Build_In_Place_Formal (Parent_Function, BIP_Object_Access);
2624
2625                --  If the return object's declaration includes an expression
2626                --  and the declaration isn't marked as No_Initialization, then
2627                --  we need to generate an assignment to the object and insert
2628                --  it after the declaration before rewriting it as a renaming
2629                --  (otherwise we'll lose the initialization).
2630
2631                if Present (Return_Obj_Expr)
2632                  and then not No_Initialization (Return_Object_Decl)
2633                then
2634                   Init_Assignment :=
2635                     Make_Assignment_Statement (Loc,
2636                       Name       => New_Reference_To (Return_Obj_Id, Loc),
2637                       Expression => Relocate_Node (Return_Obj_Expr));
2638                   Set_Etype (Name (Init_Assignment), Etype (Return_Obj_Id));
2639                   Set_Assignment_OK (Name (Init_Assignment));
2640                   Set_No_Ctrl_Actions (Init_Assignment);
2641
2642                   Set_Parent (Name (Init_Assignment), Init_Assignment);
2643                   Set_Parent (Expression (Init_Assignment), Init_Assignment);
2644
2645                   Set_Expression (Return_Object_Decl, Empty);
2646
2647                   if Is_Class_Wide_Type (Etype (Return_Obj_Id))
2648                     and then not Is_Class_Wide_Type
2649                                    (Etype (Expression (Init_Assignment)))
2650                   then
2651                      Rewrite (Expression (Init_Assignment),
2652                        Make_Type_Conversion (Loc,
2653                          Subtype_Mark =>
2654                            New_Occurrence_Of
2655                              (Etype (Return_Obj_Id), Loc),
2656                          Expression =>
2657                            Relocate_Node (Expression (Init_Assignment))));
2658                   end if;
2659
2660                   --  In the case of functions where the calling context can
2661                   --  determine the form of allocation needed, initialization
2662                   --  is done with each part of the if statement that handles
2663                   --  the different forms of allocation (this is true for
2664                   --  unconstrained and tagged result subtypes).
2665
2666                   if Constr_Result
2667                     and then not Is_Tagged_Type (Underlying_Type (Result_Subt))
2668                   then
2669                      Insert_After (Return_Object_Decl, Init_Assignment);
2670                   end if;
2671                end if;
2672
2673                --  When the function's subtype is unconstrained, a run-time
2674                --  test is needed to determine the form of allocation to use
2675                --  for the return object. The function has an implicit formal
2676                --  parameter indicating this. If the BIP_Alloc_Form formal has
2677                --  the value one, then the caller has passed access to an
2678                --  existing object for use as the return object. If the value
2679                --  is two, then the return object must be allocated on the
2680                --  secondary stack. Otherwise, the object must be allocated in
2681                --  a storage pool (currently only supported for the global
2682                --  heap, user-defined storage pools TBD ???). We generate an
2683                --  if statement to test the implicit allocation formal and
2684                --  initialize a local access value appropriately, creating
2685                --  allocators in the secondary stack and global heap cases.
2686                --  The special formal also exists and must be tested when the
2687                --  function has a tagged result, even when the result subtype
2688                --  is constrained, because in general such functions can be
2689                --  called in dispatching contexts and must be handled similarly
2690                --  to functions with a class-wide result.
2691
2692                if not Constr_Result
2693                  or else Is_Tagged_Type (Underlying_Type (Result_Subt))
2694                then
2695                   Obj_Alloc_Formal :=
2696                     Build_In_Place_Formal (Parent_Function, BIP_Alloc_Form);
2697
2698                   declare
2699                      Ref_Type       : Entity_Id;
2700                      Ptr_Type_Decl  : Node_Id;
2701                      Alloc_Obj_Id   : Entity_Id;
2702                      Alloc_Obj_Decl : Node_Id;
2703                      Alloc_If_Stmt  : Node_Id;
2704                      SS_Allocator   : Node_Id;
2705                      Heap_Allocator : Node_Id;
2706
2707                   begin
2708                      --  Reuse the itype created for the function's implicit
2709                      --  access formal. This avoids the need to create a new
2710                      --  access type here, plus it allows assigning the access
2711                      --  formal directly without applying a conversion.
2712
2713                      --  Ref_Type := Etype (Object_Access);
2714
2715                      --  Create an access type designating the function's
2716                      --  result subtype.
2717
2718                      Ref_Type :=
2719                        Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
2720
2721                      Ptr_Type_Decl :=
2722                        Make_Full_Type_Declaration (Loc,
2723                          Defining_Identifier => Ref_Type,
2724                          Type_Definition =>
2725                            Make_Access_To_Object_Definition (Loc,
2726                              All_Present => True,
2727                              Subtype_Indication =>
2728                                New_Reference_To (Return_Obj_Typ, Loc)));
2729
2730                      Insert_Before (Return_Object_Decl, Ptr_Type_Decl);
2731
2732                      --  Create an access object that will be initialized to an
2733                      --  access value denoting the return object, either coming
2734                      --  from an implicit access value passed in by the caller
2735                      --  or from the result of an allocator.
2736
2737                      Alloc_Obj_Id :=
2738                        Make_Defining_Identifier (Loc,
2739                          Chars => New_Internal_Name ('R'));
2740                      Set_Etype (Alloc_Obj_Id, Ref_Type);
2741
2742                      Alloc_Obj_Decl :=
2743                        Make_Object_Declaration (Loc,
2744                          Defining_Identifier => Alloc_Obj_Id,
2745                          Object_Definition   => New_Reference_To
2746                                                   (Ref_Type, Loc));
2747
2748                      Insert_Before (Return_Object_Decl, Alloc_Obj_Decl);
2749
2750                      --  Create allocators for both the secondary stack and
2751                      --  global heap. If there's an initialization expression,
2752                      --  then create these as initialized allocators.
2753
2754                      if Present (Return_Obj_Expr)
2755                        and then not No_Initialization (Return_Object_Decl)
2756                      then
2757                         Heap_Allocator :=
2758                           Make_Allocator (Loc,
2759                             Expression =>
2760                               Make_Qualified_Expression (Loc,
2761                                 Subtype_Mark =>
2762                                   New_Reference_To (Return_Obj_Typ, Loc),
2763                                 Expression =>
2764                                   New_Copy_Tree (Return_Obj_Expr)));
2765
2766                         SS_Allocator := New_Copy_Tree (Heap_Allocator);
2767
2768                      else
2769                         --  If the function returns a class-wide type we cannot
2770                         --  use the return type for the allocator. Instead we
2771                         --  use the type of the expression, which must be an
2772                         --  aggregate of a definite type.
2773
2774                         if Is_Class_Wide_Type (Return_Obj_Typ) then
2775                            Heap_Allocator :=
2776                              Make_Allocator (Loc,
2777                                New_Reference_To
2778                                  (Etype (Return_Obj_Expr), Loc));
2779                         else
2780                            Heap_Allocator :=
2781                              Make_Allocator (Loc,
2782                                New_Reference_To (Return_Obj_Typ, Loc));
2783                         end if;
2784
2785                         --  If the object requires default initialization then
2786                         --  that will happen later following the elaboration of
2787                         --  the object renaming. If we don't turn it off here
2788                         --  then the object will be default initialized twice.
2789
2790                         Set_No_Initialization (Heap_Allocator);
2791
2792                         SS_Allocator := New_Copy_Tree (Heap_Allocator);
2793                      end if;
2794
2795                      Set_Storage_Pool
2796                        (SS_Allocator, RTE (RE_SS_Pool));
2797                      Set_Procedure_To_Call
2798                        (SS_Allocator, RTE (RE_SS_Allocate));
2799
2800                      --  The allocator is returned on the secondary stack,
2801                      --  so indicate that the function return, as well as
2802                      --  the block that encloses the allocator, must not
2803                      --  release it. The flags must be set now because the
2804                      --  decision to use the secondary stack is done very
2805                      --  late in the course of expanding the return statement,
2806                      --  past the point where these flags are normally set.
2807
2808                      Set_Sec_Stack_Needed_For_Return (Parent_Function);
2809                      Set_Sec_Stack_Needed_For_Return
2810                        (Return_Statement_Entity (N));
2811                      Set_Uses_Sec_Stack (Parent_Function);
2812                      Set_Uses_Sec_Stack (Return_Statement_Entity (N));
2813
2814                      --  Create an if statement to test the BIP_Alloc_Form
2815                      --  formal and initialize the access object to either the
2816                      --  BIP_Object_Access formal (BIP_Alloc_Form = 0), the
2817                      --  result of allocating the object in the secondary stack
2818                      --  (BIP_Alloc_Form = 1), or else an allocator to create
2819                      --  the return object in the heap (BIP_Alloc_Form = 2).
2820
2821                      --  ??? An unchecked type conversion must be made in the
2822                      --  case of assigning the access object formal to the
2823                      --  local access object, because a normal conversion would
2824                      --  be illegal in some cases (such as converting access-
2825                      --  to-unconstrained to access-to-constrained), but the
2826                      --  the unchecked conversion will presumably fail to work
2827                      --  right in just such cases. It's not clear at all how to
2828                      --  handle this. ???
2829
2830                      Alloc_If_Stmt :=
2831                        Make_If_Statement (Loc,
2832                          Condition       =>
2833                            Make_Op_Eq (Loc,
2834                              Left_Opnd =>
2835                                New_Reference_To (Obj_Alloc_Formal, Loc),
2836                              Right_Opnd =>
2837                                Make_Integer_Literal (Loc,
2838                                  UI_From_Int (BIP_Allocation_Form'Pos
2839                                                 (Caller_Allocation)))),
2840                          Then_Statements =>
2841                            New_List (Make_Assignment_Statement (Loc,
2842                                        Name       =>
2843                                          New_Reference_To
2844                                            (Alloc_Obj_Id, Loc),
2845                                        Expression =>
2846                                          Make_Unchecked_Type_Conversion (Loc,
2847                                            Subtype_Mark =>
2848                                              New_Reference_To (Ref_Type, Loc),
2849                                            Expression =>
2850                                              New_Reference_To
2851                                                (Object_Access, Loc)))),
2852                          Elsif_Parts     =>
2853                            New_List (Make_Elsif_Part (Loc,
2854                                        Condition       =>
2855                                          Make_Op_Eq (Loc,
2856                                            Left_Opnd =>
2857                                              New_Reference_To
2858                                                (Obj_Alloc_Formal, Loc),
2859                                            Right_Opnd =>
2860                                              Make_Integer_Literal (Loc,
2861                                                UI_From_Int (
2862                                                  BIP_Allocation_Form'Pos
2863                                                     (Secondary_Stack)))),
2864                                        Then_Statements =>
2865                                           New_List
2866                                             (Make_Assignment_Statement (Loc,
2867                                                Name       =>
2868                                                  New_Reference_To
2869                                                    (Alloc_Obj_Id, Loc),
2870                                                Expression =>
2871                                                  SS_Allocator)))),
2872                          Else_Statements =>
2873                            New_List (Make_Assignment_Statement (Loc,
2874                                         Name       =>
2875                                           New_Reference_To
2876                                             (Alloc_Obj_Id, Loc),
2877                                         Expression =>
2878                                           Heap_Allocator)));
2879
2880                      --  If a separate initialization assignment was created
2881                      --  earlier, append that following the assignment of the
2882                      --  implicit access formal to the access object, to ensure
2883                      --  that the return object is initialized in that case.
2884                      --  In this situation, the target of the assignment must
2885                      --  be rewritten to denote a derference of the access to
2886                      --  the return object passed in by the caller.
2887
2888                      if Present (Init_Assignment) then
2889                         Rewrite (Name (Init_Assignment),
2890                           Make_Explicit_Dereference (Loc,
2891                             Prefix => New_Reference_To (Alloc_Obj_Id, Loc)));
2892                         Set_Etype
2893                           (Name (Init_Assignment), Etype (Return_Obj_Id));
2894
2895                         Append_To
2896                           (Then_Statements (Alloc_If_Stmt),
2897                            Init_Assignment);
2898                      end if;
2899
2900                      Insert_Before (Return_Object_Decl, Alloc_If_Stmt);
2901
2902                      --  Remember the local access object for use in the
2903                      --  dereference of the renaming created below.
2904
2905                      Object_Access := Alloc_Obj_Id;
2906                   end;
2907                end if;
2908
2909                --  Replace the return object declaration with a renaming of a
2910                --  dereference of the access value designating the return
2911                --  object.
2912
2913                Obj_Acc_Deref :=
2914                  Make_Explicit_Dereference (Loc,
2915                    Prefix => New_Reference_To (Object_Access, Loc));
2916
2917                Rewrite (Return_Object_Decl,
2918                  Make_Object_Renaming_Declaration (Loc,
2919                    Defining_Identifier => Return_Obj_Id,
2920                    Access_Definition   => Empty,
2921                    Subtype_Mark        => New_Occurrence_Of
2922                                             (Return_Obj_Typ, Loc),
2923                    Name                => Obj_Acc_Deref));
2924
2925                Set_Renamed_Object (Return_Obj_Id, Obj_Acc_Deref);
2926             end;
2927          end if;
2928
2929       --  Case where we do not build a block
2930
2931       else
2932          --  We're about to drop Return_Object_Declarations on the floor, so
2933          --  we need to insert it, in case it got expanded into useful code.
2934
2935          Insert_List_Before (N, Return_Object_Declarations (N));
2936
2937          --  Build simple_return_statement that returns the expression directly
2938
2939          Return_Stm := Make_Simple_Return_Statement (Loc, Expression => Exp);
2940
2941          Result := Return_Stm;
2942       end if;
2943
2944       --  Set the flag to prevent infinite recursion
2945
2946       Set_Comes_From_Extended_Return_Statement (Return_Stm);
2947
2948       Rewrite (N, Result);
2949       Analyze (N);
2950    end Expand_N_Extended_Return_Statement;
2951
2952    -----------------------------
2953    -- Expand_N_Goto_Statement --
2954    -----------------------------
2955
2956    --  Add poll before goto if polling active
2957
2958    procedure Expand_N_Goto_Statement (N : Node_Id) is
2959    begin
2960       Generate_Poll_Call (N);
2961    end Expand_N_Goto_Statement;
2962
2963    ---------------------------
2964    -- Expand_N_If_Statement --
2965    ---------------------------
2966
2967    --  First we deal with the case of C and Fortran convention boolean values,
2968    --  with zero/non-zero semantics.
2969
2970    --  Second, we deal with the obvious rewriting for the cases where the
2971    --  condition of the IF is known at compile time to be True or False.
2972
2973    --  Third, we remove elsif parts which have non-empty Condition_Actions
2974    --  and rewrite as independent if statements. For example:
2975
2976    --     if x then xs
2977    --     elsif y then ys
2978    --     ...
2979    --     end if;
2980
2981    --  becomes
2982    --
2983    --     if x then xs
2984    --     else
2985    --        <<condition actions of y>>
2986    --        if y then ys
2987    --        ...
2988    --        end if;
2989    --     end if;
2990
2991    --  This rewriting is needed if at least one elsif part has a non-empty
2992    --  Condition_Actions list. We also do the same processing if there is a
2993    --  constant condition in an elsif part (in conjunction with the first
2994    --  processing step mentioned above, for the recursive call made to deal
2995    --  with the created inner if, this deals with properly optimizing the
2996    --  cases of constant elsif conditions).
2997
2998    procedure Expand_N_If_Statement (N : Node_Id) is
2999       Loc    : constant Source_Ptr := Sloc (N);
3000       Hed    : Node_Id;
3001       E      : Node_Id;
3002       New_If : Node_Id;
3003
3004       Warn_If_Deleted : constant Boolean :=
3005                           Warn_On_Deleted_Code and then Comes_From_Source (N);
3006       --  Indicates whether we want warnings when we delete branches of the
3007       --  if statement based on constant condition analysis. We never want
3008       --  these warnings for expander generated code.
3009
3010    begin
3011       Adjust_Condition (Condition (N));
3012
3013       --  The following loop deals with constant conditions for the IF. We
3014       --  need a loop because as we eliminate False conditions, we grab the
3015       --  first elsif condition and use it as the primary condition.
3016
3017       while Compile_Time_Known_Value (Condition (N)) loop
3018
3019          --  If condition is True, we can simply rewrite the if statement now
3020          --  by replacing it by the series of then statements.
3021
3022          if Is_True (Expr_Value (Condition (N))) then
3023
3024             --  All the else parts can be killed
3025
3026             Kill_Dead_Code (Elsif_Parts (N), Warn_If_Deleted);
3027             Kill_Dead_Code (Else_Statements (N), Warn_If_Deleted);
3028
3029             Hed := Remove_Head (Then_Statements (N));
3030             Insert_List_After (N, Then_Statements (N));
3031             Rewrite (N, Hed);
3032             return;
3033
3034          --  If condition is False, then we can delete the condition and
3035          --  the Then statements
3036
3037          else
3038             --  We do not delete the condition if constant condition warnings
3039             --  are enabled, since otherwise we end up deleting the desired
3040             --  warning. Of course the backend will get rid of this True/False
3041             --  test anyway, so nothing is lost here.
3042
3043             if not Constant_Condition_Warnings then
3044                Kill_Dead_Code (Condition (N));
3045             end if;
3046
3047             Kill_Dead_Code (Then_Statements (N), Warn_If_Deleted);
3048
3049             --  If there are no elsif statements, then we simply replace the
3050             --  entire if statement by the sequence of else statements.
3051
3052             if No (Elsif_Parts (N)) then
3053                if No (Else_Statements (N))
3054                  or else Is_Empty_List (Else_Statements (N))
3055                then
3056                   Rewrite (N,
3057                     Make_Null_Statement (Sloc (N)));
3058                else
3059                   Hed := Remove_Head (Else_Statements (N));
3060                   Insert_List_After (N, Else_Statements (N));
3061                   Rewrite (N, Hed);
3062                end if;
3063
3064                return;
3065
3066             --  If there are elsif statements, the first of them becomes the
3067             --  if/then section of the rebuilt if statement This is the case
3068             --  where we loop to reprocess this copied condition.
3069
3070             else
3071                Hed := Remove_Head (Elsif_Parts (N));
3072                Insert_Actions      (N, Condition_Actions (Hed));
3073                Set_Condition       (N, Condition (Hed));
3074                Set_Then_Statements (N, Then_Statements (Hed));
3075
3076                --  Hed might have been captured as the condition determining
3077                --  the current value for an entity. Now it is detached from
3078                --  the tree, so a Current_Value pointer in the condition might
3079                --  need to be updated.
3080
3081                Set_Current_Value_Condition (N);
3082
3083                if Is_Empty_List (Elsif_Parts (N)) then
3084                   Set_Elsif_Parts (N, No_List);
3085                end if;
3086             end if;
3087          end if;
3088       end loop;
3089
3090       --  Loop through elsif parts, dealing with constant conditions and
3091       --  possible expression actions that are present.
3092
3093       if Present (Elsif_Parts (N)) then
3094          E := First (Elsif_Parts (N));
3095          while Present (E) loop
3096             Adjust_Condition (Condition (E));
3097
3098             --  If there are condition actions, then rewrite the if statement
3099             --  as indicated above. We also do the same rewrite for a True or
3100             --  False condition. The further processing of this constant
3101             --  condition is then done by the recursive call to expand the
3102             --  newly created if statement
3103
3104             if Present (Condition_Actions (E))
3105               or else Compile_Time_Known_Value (Condition (E))
3106             then
3107                --  Note this is not an implicit if statement, since it is part
3108                --  of an explicit if statement in the source (or of an implicit
3109                --  if statement that has already been tested).
3110
3111                New_If :=
3112                  Make_If_Statement (Sloc (E),
3113                    Condition       => Condition (E),
3114                    Then_Statements => Then_Statements (E),
3115                    Elsif_Parts     => No_List,
3116                    Else_Statements => Else_Statements (N));
3117
3118                --  Elsif parts for new if come from remaining elsif's of parent
3119
3120                while Present (Next (E)) loop
3121                   if No (Elsif_Parts (New_If)) then
3122                      Set_Elsif_Parts (New_If, New_List);
3123                   end if;
3124
3125                   Append (Remove_Next (E), Elsif_Parts (New_If));
3126                end loop;
3127
3128                Set_Else_Statements (N, New_List (New_If));
3129
3130                if Present (Condition_Actions (E)) then
3131                   Insert_List_Before (New_If, Condition_Actions (E));
3132                end if;
3133
3134                Remove (E);
3135
3136                if Is_Empty_List (Elsif_Parts (N)) then
3137                   Set_Elsif_Parts (N, No_List);
3138                end if;
3139
3140                Analyze (New_If);
3141                return;
3142
3143             --  No special processing for that elsif part, move to next
3144
3145             else
3146                Next (E);
3147             end if;
3148          end loop;
3149       end if;
3150
3151       --  Some more optimizations applicable if we still have an IF statement
3152
3153       if Nkind (N) /= N_If_Statement then
3154          return;
3155       end if;
3156
3157       --  Another optimization, special cases that can be simplified
3158
3159       --     if expression then
3160       --        return true;
3161       --     else
3162       --        return false;
3163       --     end if;
3164
3165       --  can be changed to:
3166
3167       --     return expression;
3168
3169       --  and
3170
3171       --     if expression then
3172       --        return false;
3173       --     else
3174       --        return true;
3175       --     end if;
3176
3177       --  can be changed to:
3178
3179       --     return not (expression);
3180
3181       if Nkind (N) = N_If_Statement
3182          and then No (Elsif_Parts (N))
3183          and then Present (Else_Statements (N))
3184          and then List_Length (Then_Statements (N)) = 1
3185          and then List_Length (Else_Statements (N)) = 1
3186       then
3187          declare
3188             Then_Stm : constant Node_Id := First (Then_Statements (N));
3189             Else_Stm : constant Node_Id := First (Else_Statements (N));
3190
3191          begin
3192             if Nkind (Then_Stm) = N_Simple_Return_Statement
3193                  and then
3194                Nkind (Else_Stm) = N_Simple_Return_Statement
3195             then
3196                declare
3197                   Then_Expr : constant Node_Id := Expression (Then_Stm);
3198                   Else_Expr : constant Node_Id := Expression (Else_Stm);
3199
3200                begin
3201                   if Nkind (Then_Expr) = N_Identifier
3202                        and then
3203                      Nkind (Else_Expr) = N_Identifier
3204                   then
3205                      if Entity (Then_Expr) = Standard_True
3206                        and then Entity (Else_Expr) = Standard_False
3207                      then
3208                         Rewrite (N,
3209                           Make_Simple_Return_Statement (Loc,
3210                             Expression => Relocate_Node (Condition (N))));
3211                         Analyze (N);
3212                         return;
3213
3214                      elsif Entity (Then_Expr) = Standard_False
3215                        and then Entity (Else_Expr) = Standard_True
3216                      then
3217                         Rewrite (N,
3218                           Make_Simple_Return_Statement (Loc,
3219                             Expression =>
3220                               Make_Op_Not (Loc,
3221                                 Right_Opnd => Relocate_Node (Condition (N)))));
3222                         Analyze (N);
3223                         return;
3224                      end if;
3225                   end if;
3226                end;
3227             end if;
3228          end;
3229       end if;
3230    end Expand_N_If_Statement;
3231
3232    -----------------------------
3233    -- Expand_N_Loop_Statement --
3234    -----------------------------
3235
3236    --  1. Deal with while condition for C/Fortran boolean
3237    --  2. Deal with loops with a non-standard enumeration type range
3238    --  3. Deal with while loops where Condition_Actions is set
3239    --  4. Insert polling call if required
3240
3241    procedure Expand_N_Loop_Statement (N : Node_Id) is
3242       Loc  : constant Source_Ptr := Sloc (N);
3243       Isc  : constant Node_Id    := Iteration_Scheme (N);
3244
3245    begin
3246       if Present (Isc) then
3247          Adjust_Condition (Condition (Isc));
3248       end if;
3249
3250       if Is_Non_Empty_List (Statements (N)) then
3251          Generate_Poll_Call (First (Statements (N)));
3252       end if;
3253
3254       --  Nothing more to do for plain loop with no iteration scheme
3255
3256       if No (Isc) then
3257          return;
3258       end if;
3259
3260       --  Note: we do not have to worry about validity chekcing of the for loop
3261       --  range bounds here, since they were frozen with constant declarations
3262       --  and it is during that process that the validity checking is done.
3263
3264       --  Handle the case where we have a for loop with the range type being an
3265       --  enumeration type with non-standard representation. In this case we
3266       --  expand:
3267
3268       --    for x in [reverse] a .. b loop
3269       --       ...
3270       --    end loop;
3271
3272       --  to
3273
3274       --    for xP in [reverse] integer
3275       --                          range etype'Pos (a) .. etype'Pos (b) loop
3276       --       declare
3277       --          x : constant etype := Pos_To_Rep (xP);
3278       --       begin
3279       --          ...
3280       --       end;
3281       --    end loop;
3282
3283       if Present (Loop_Parameter_Specification (Isc)) then
3284          declare
3285             LPS     : constant Node_Id   := Loop_Parameter_Specification (Isc);
3286             Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
3287             Ltype   : constant Entity_Id := Etype (Loop_Id);
3288             Btype   : constant Entity_Id := Base_Type (Ltype);
3289             Expr    : Node_Id;
3290             New_Id  : Entity_Id;
3291
3292          begin
3293             if not Is_Enumeration_Type (Btype)
3294               or else No (Enum_Pos_To_Rep (Btype))
3295             then
3296                return;
3297             end if;
3298
3299             New_Id :=
3300               Make_Defining_Identifier (Loc,
3301                 Chars => New_External_Name (Chars (Loop_Id), 'P'));
3302
3303             --  If the type has a contiguous representation, successive values
3304             --  can be generated as offsets from the first literal.
3305
3306             if Has_Contiguous_Rep (Btype) then
3307                Expr :=
3308                   Unchecked_Convert_To (Btype,
3309                     Make_Op_Add (Loc,
3310                       Left_Opnd =>
3311                          Make_Integer_Literal (Loc,
3312                            Enumeration_Rep (First_Literal (Btype))),
3313                       Right_Opnd => New_Reference_To (New_Id, Loc)));
3314             else
3315                --  Use the constructed array Enum_Pos_To_Rep
3316
3317                Expr :=
3318                  Make_Indexed_Component (Loc,
3319                    Prefix => New_Reference_To (Enum_Pos_To_Rep (Btype), Loc),
3320                    Expressions => New_List (New_Reference_To (New_Id, Loc)));
3321             end if;
3322
3323             Rewrite (N,
3324               Make_Loop_Statement (Loc,
3325                 Identifier => Identifier (N),
3326
3327                 Iteration_Scheme =>
3328                   Make_Iteration_Scheme (Loc,
3329                     Loop_Parameter_Specification =>
3330                       Make_Loop_Parameter_Specification (Loc,
3331                         Defining_Identifier => New_Id,
3332                         Reverse_Present => Reverse_Present (LPS),
3333
3334                         Discrete_Subtype_Definition =>
3335                           Make_Subtype_Indication (Loc,
3336
3337                             Subtype_Mark =>
3338                               New_Reference_To (Standard_Natural, Loc),
3339
3340                             Constraint =>
3341                               Make_Range_Constraint (Loc,
3342                                 Range_Expression =>
3343                                   Make_Range (Loc,
3344
3345                                     Low_Bound =>
3346                                       Make_Attribute_Reference (Loc,
3347                                         Prefix =>
3348                                           New_Reference_To (Btype, Loc),
3349
3350                                         Attribute_Name => Name_Pos,
3351
3352                                         Expressions => New_List (
3353                                           Relocate_Node
3354                                             (Type_Low_Bound (Ltype)))),
3355
3356                                     High_Bound =>
3357                                       Make_Attribute_Reference (Loc,
3358                                         Prefix =>
3359                                           New_Reference_To (Btype, Loc),
3360
3361                                         Attribute_Name => Name_Pos,
3362
3363                                         Expressions => New_List (
3364                                           Relocate_Node
3365                                             (Type_High_Bound (Ltype))))))))),
3366
3367                 Statements => New_List (
3368                   Make_Block_Statement (Loc,
3369                     Declarations => New_List (
3370                       Make_Object_Declaration (Loc,
3371                         Defining_Identifier => Loop_Id,
3372                         Constant_Present    => True,
3373                         Object_Definition   => New_Reference_To (Ltype, Loc),
3374                         Expression          => Expr)),
3375
3376                     Handled_Statement_Sequence =>
3377                       Make_Handled_Sequence_Of_Statements (Loc,
3378                         Statements => Statements (N)))),
3379
3380                 End_Label => End_Label (N)));
3381             Analyze (N);
3382          end;
3383
3384       --  Second case, if we have a while loop with Condition_Actions set, then
3385       --  we change it into a plain loop:
3386
3387       --    while C loop
3388       --       ...
3389       --    end loop;
3390
3391       --  changed to:
3392
3393       --    loop
3394       --       <<condition actions>>
3395       --       exit when not C;
3396       --       ...
3397       --    end loop
3398
3399       elsif Present (Isc)
3400         and then Present (Condition_Actions (Isc))
3401       then
3402          declare
3403             ES : Node_Id;
3404
3405          begin
3406             ES :=
3407               Make_Exit_Statement (Sloc (Condition (Isc)),
3408                 Condition =>
3409                   Make_Op_Not (Sloc (Condition (Isc)),
3410                     Right_Opnd => Condition (Isc)));
3411
3412             Prepend (ES, Statements (N));
3413             Insert_List_Before (ES, Condition_Actions (Isc));
3414
3415             --  This is not an implicit loop, since it is generated in response
3416             --  to the loop statement being processed. If this is itself
3417             --  implicit, the restriction has already been checked. If not,
3418             --  it is an explicit loop.
3419
3420             Rewrite (N,
3421               Make_Loop_Statement (Sloc (N),
3422                 Identifier => Identifier (N),
3423                 Statements => Statements (N),
3424                 End_Label  => End_Label  (N)));
3425
3426             Analyze (N);
3427          end;
3428       end if;
3429    end Expand_N_Loop_Statement;
3430
3431    --------------------------------------
3432    -- Expand_N_Simple_Return_Statement --
3433    --------------------------------------
3434
3435    procedure Expand_N_Simple_Return_Statement (N : Node_Id) is
3436    begin
3437       --  Distinguish the function and non-function cases:
3438
3439       case Ekind (Return_Applies_To (Return_Statement_Entity (N))) is
3440
3441          when E_Function          |
3442               E_Generic_Function  =>
3443             Expand_Simple_Function_Return (N);
3444
3445          when E_Procedure         |
3446               E_Generic_Procedure |
3447               E_Entry             |
3448               E_Entry_Family      |
3449               E_Return_Statement =>
3450             Expand_Non_Function_Return (N);
3451
3452          when others =>
3453             raise Program_Error;
3454       end case;
3455
3456    exception
3457       when RE_Not_Available =>
3458          return;
3459    end Expand_N_Simple_Return_Statement;
3460
3461    --------------------------------
3462    -- Expand_Non_Function_Return --
3463    --------------------------------
3464
3465    procedure Expand_Non_Function_Return (N : Node_Id) is
3466       pragma Assert (No (Expression (N)));
3467
3468       Loc         : constant Source_Ptr := Sloc (N);
3469       Scope_Id    : Entity_Id :=
3470                       Return_Applies_To (Return_Statement_Entity (N));
3471       Kind        : constant Entity_Kind := Ekind (Scope_Id);
3472       Call        : Node_Id;
3473       Acc_Stat    : Node_Id;
3474       Goto_Stat   : Node_Id;
3475       Lab_Node    : Node_Id;
3476
3477    begin
3478       --  If it is a return from a procedure do no extra steps
3479
3480       if Kind = E_Procedure or else Kind = E_Generic_Procedure then
3481          return;
3482
3483       --  If it is a nested return within an extended one, replace it with a
3484       --  return of the previously declared return object.
3485
3486       elsif Kind = E_Return_Statement then
3487          Rewrite (N,
3488            Make_Simple_Return_Statement (Loc,
3489              Expression =>
3490                New_Occurrence_Of (First_Entity (Scope_Id), Loc)));
3491          Set_Comes_From_Extended_Return_Statement (N);
3492          Set_Return_Statement_Entity (N, Scope_Id);
3493          Expand_Simple_Function_Return (N);
3494          return;
3495       end if;
3496
3497       pragma Assert (Is_Entry (Scope_Id));
3498
3499       --  Look at the enclosing block to see whether the return is from an
3500       --  accept statement or an entry body.
3501
3502       for J in reverse 0 .. Scope_Stack.Last loop
3503          Scope_Id := Scope_Stack.Table (J).Entity;
3504          exit when Is_Concurrent_Type (Scope_Id);
3505       end loop;
3506
3507       --  If it is a return from accept statement it is expanded as call to
3508       --  RTS Complete_Rendezvous and a goto to the end of the accept body.
3509
3510       --  (cf : Expand_N_Accept_Statement, Expand_N_Selective_Accept,
3511       --  Expand_N_Accept_Alternative in exp_ch9.adb)
3512
3513       if Is_Task_Type (Scope_Id) then
3514
3515          Call :=
3516            Make_Procedure_Call_Statement (Loc,
3517              Name => New_Reference_To
3518                        (RTE (RE_Complete_Rendezvous), Loc));
3519          Insert_Before (N, Call);
3520          --  why not insert actions here???
3521          Analyze (Call);
3522
3523          Acc_Stat := Parent (N);
3524          while Nkind (Acc_Stat) /= N_Accept_Statement loop
3525             Acc_Stat := Parent (Acc_Stat);
3526          end loop;
3527
3528          Lab_Node := Last (Statements
3529            (Handled_Statement_Sequence (Acc_Stat)));
3530
3531          Goto_Stat := Make_Goto_Statement (Loc,
3532            Name => New_Occurrence_Of
3533              (Entity (Identifier (Lab_Node)), Loc));
3534
3535          Set_Analyzed (Goto_Stat);
3536
3537          Rewrite (N, Goto_Stat);
3538          Analyze (N);
3539
3540       --  If it is a return from an entry body, put a Complete_Entry_Body call
3541       --  in front of the return.
3542
3543       elsif Is_Protected_Type (Scope_Id) then
3544          Call :=
3545            Make_Procedure_Call_Statement (Loc,
3546              Name => New_Reference_To
3547                (RTE (RE_Complete_Entry_Body), Loc),
3548              Parameter_Associations => New_List
3549                (Make_Attribute_Reference (Loc,
3550                  Prefix =>
3551                    New_Reference_To
3552                      (Object_Ref
3553                         (Corresponding_Body (Parent (Scope_Id))),
3554                      Loc),
3555                  Attribute_Name => Name_Unchecked_Access)));
3556
3557          Insert_Before (N, Call);
3558          Analyze (Call);
3559       end if;
3560    end Expand_Non_Function_Return;
3561
3562    -----------------------------------
3563    -- Expand_Simple_Function_Return --
3564    -----------------------------------
3565
3566    --  The "simple" comes from the syntax rule simple_return_statement.
3567    --  The semantics are not at all simple!
3568
3569    procedure Expand_Simple_Function_Return (N : Node_Id) is
3570       Loc : constant Source_Ptr := Sloc (N);
3571
3572       Scope_Id : constant Entity_Id :=
3573                    Return_Applies_To (Return_Statement_Entity (N));
3574       --  The function we are returning from
3575
3576       R_Type : constant Entity_Id := Etype (Scope_Id);
3577       --  The result type of the function
3578
3579       Utyp : constant Entity_Id := Underlying_Type (R_Type);
3580
3581       Exp : constant Node_Id := Expression (N);
3582       pragma Assert (Present (Exp));
3583
3584       Exptyp : constant Entity_Id := Etype (Exp);
3585       --  The type of the expression (not necessarily the same as R_Type)
3586
3587    begin
3588       --  We rewrite "return <expression>;" to be:
3589
3590       --    return _anon_ : <return_subtype> := <expression>
3591
3592       --  The expansion produced by Expand_N_Extended_Return_Statement will
3593       --  contain simple return statements (for example, a block containing
3594       --  simple return of the return object), which brings us back here with
3595       --  Comes_From_Extended_Return_Statement set. To avoid infinite
3596       --  recursion, we do not transform into an extended return if
3597       --  Comes_From_Extended_Return_Statement is True.
3598
3599       --  The reason for this design is that for Ada 2005 limited returns, we
3600       --  need to reify the return object, so we can build it "in place", and
3601       --  we need a block statement to hang finalization and tasking stuff.
3602
3603       --  ??? In order to avoid disruption, we avoid translating to extended
3604       --  return except in the cases where we really need to (Ada 2005
3605       --  inherently limited). We would prefer eventually to do this
3606       --  translation in all cases except perhaps for the case of Ada 95
3607       --  inherently limited, in order to fully exercise the code in
3608       --  Expand_N_Extended_Return_Statement, and in order to do
3609       --  build-in-place for efficiency when it is not required.
3610
3611       --  As before, we check the type of the return expression rather than the
3612       --  return type of the function, because the latter may be a limited
3613       --  class-wide interface type, which is not a limited type, even though
3614       --  the type of the expression may be.
3615
3616       if not Comes_From_Extended_Return_Statement (N)
3617         and then Is_Inherently_Limited_Type (Etype (Expression (N)))
3618         and then Ada_Version >= Ada_05 --  ???
3619         and then not Debug_Flag_Dot_L
3620       then
3621          declare
3622             Return_Object_Entity : constant Entity_Id :=
3623                                      Make_Defining_Identifier (Loc,
3624                                        New_Internal_Name ('R'));
3625
3626             Subtype_Ind : constant Node_Id := New_Occurrence_Of (R_Type, Loc);
3627
3628             Obj_Decl : constant Node_Id :=
3629                          Make_Object_Declaration (Loc,
3630                            Defining_Identifier => Return_Object_Entity,
3631                            Object_Definition   => Subtype_Ind,
3632                            Expression          => Exp);
3633
3634             Ext : constant Node_Id := Make_Extended_Return_Statement (Loc,
3635                     Return_Object_Declarations => New_List (Obj_Decl));
3636
3637          begin
3638             Rewrite (N, Ext);
3639             Analyze (N);
3640             return;
3641          end;
3642       end if;
3643
3644       --  Here we have a simple return statement that is part of the expansion
3645       --  of an extended return statement (either written by the user, or
3646       --  generated by the above code).
3647
3648       --  Always normalize C/Fortran boolean result. This is not always needed,
3649       --  but it seems a good idea to minimize the passing around of non-
3650       --  normalized values, and in any case this handles the processing of
3651       --  barrier functions for protected types, which turn the condition into
3652       --  a return statement.
3653
3654       if Is_Boolean_Type (Exptyp)
3655         and then Nonzero_Is_True (Exptyp)
3656       then
3657          Adjust_Condition (Exp);
3658          Adjust_Result_Type (Exp, Exptyp);
3659       end if;
3660
3661       --  Do validity check if enabled for returns
3662
3663       if Validity_Checks_On
3664         and then Validity_Check_Returns
3665       then
3666          Ensure_Valid (Exp);
3667       end if;
3668
3669       --  Check the result expression of a scalar function against the subtype
3670       --  of the function by inserting a conversion. This conversion must
3671       --  eventually be performed for other classes of types, but for now it's
3672       --  only done for scalars.
3673       --  ???
3674
3675       if Is_Scalar_Type (Exptyp) then
3676          Rewrite (Exp, Convert_To (R_Type, Exp));
3677          Analyze (Exp);
3678       end if;
3679
3680       --  Deal with returning variable length objects and controlled types
3681
3682       --  Nothing to do if we are returning by reference, or this is not a
3683       --  type that requires special processing (indicated by the fact that
3684       --  it requires a cleanup scope for the secondary stack case).
3685
3686       if Is_Inherently_Limited_Type (Exptyp)
3687         or else Is_Limited_Interface (Exptyp)
3688       then
3689          null;
3690
3691       elsif not Requires_Transient_Scope (R_Type) then
3692
3693          --  Mutable records with no variable length components are not
3694          --  returned on the sec-stack, so we need to make sure that the
3695          --  backend will only copy back the size of the actual value, and not
3696          --  the maximum size. We create an actual subtype for this purpose.
3697
3698          declare
3699             Ubt  : constant Entity_Id := Underlying_Type (Base_Type (Exptyp));
3700             Decl : Node_Id;
3701             Ent  : Entity_Id;
3702          begin
3703             if Has_Discriminants (Ubt)
3704               and then not Is_Constrained (Ubt)
3705               and then not Has_Unchecked_Union (Ubt)
3706             then
3707                Decl := Build_Actual_Subtype (Ubt, Exp);
3708                Ent := Defining_Identifier (Decl);
3709                Insert_Action (Exp, Decl);
3710                Rewrite (Exp, Unchecked_Convert_To (Ent, Exp));
3711                Analyze_And_Resolve (Exp);
3712             end if;
3713          end;
3714
3715       --  Here if secondary stack is used
3716
3717       else
3718          --  Make sure that no surrounding block will reclaim the secondary
3719          --  stack on which we are going to put the result. Not only may this
3720          --  introduce secondary stack leaks but worse, if the reclamation is
3721          --  done too early, then the result we are returning may get
3722          --  clobbered.
3723
3724          declare
3725             S : Entity_Id;
3726          begin
3727             S := Current_Scope;
3728             while Ekind (S) = E_Block or else Ekind (S) = E_Loop loop
3729                Set_Sec_Stack_Needed_For_Return (S, True);
3730                S := Enclosing_Dynamic_Scope (S);
3731             end loop;
3732          end;
3733
3734          --  Optimize the case where the result is a function call. In this
3735          --  case either the result is already on the secondary stack, or is
3736          --  already being returned with the stack pointer depressed and no
3737          --  further processing is required except to set the By_Ref flag to
3738          --  ensure that gigi does not attempt an extra unnecessary copy.
3739          --  (actually not just unnecessary but harmfully wrong in the case
3740          --  of a controlled type, where gigi does not know how to do a copy).
3741          --  To make up for a gcc 2.8.1 deficiency (???), we perform
3742          --  the copy for array types if the constrained status of the
3743          --  target type is different from that of the expression.
3744
3745          if Requires_Transient_Scope (Exptyp)
3746            and then
3747               (not Is_Array_Type (Exptyp)
3748                 or else Is_Constrained (Exptyp) = Is_Constrained (R_Type)
3749                 or else CW_Or_Controlled_Type (Utyp))
3750            and then Nkind (Exp) = N_Function_Call
3751          then
3752             Set_By_Ref (N);
3753
3754             --  Remove side effects from the expression now so that other parts
3755             --  of the expander do not have to reanalyze this node without this
3756             --  optimization
3757
3758             Rewrite (Exp, Duplicate_Subexpr_No_Checks (Exp));
3759
3760          --  For controlled types, do the allocation on the secondary stack
3761          --  manually in order to call adjust at the right time:
3762
3763          --    type Anon1 is access R_Type;
3764          --    for Anon1'Storage_pool use ss_pool;
3765          --    Anon2 : anon1 := new R_Type'(expr);
3766          --    return Anon2.all;
3767
3768          --  We do the same for classwide types that are not potentially
3769          --  controlled (by the virtue of restriction No_Finalization) because
3770          --  gigi is not able to properly allocate class-wide types.
3771
3772          elsif CW_Or_Controlled_Type (Utyp) then
3773             declare
3774                Loc        : constant Source_Ptr := Sloc (N);
3775                Temp       : constant Entity_Id :=
3776                               Make_Defining_Identifier (Loc,
3777                                 Chars => New_Internal_Name ('R'));
3778                Acc_Typ    : constant Entity_Id :=
3779                               Make_Defining_Identifier (Loc,
3780                                 Chars => New_Internal_Name ('A'));
3781                Alloc_Node : Node_Id;
3782
3783             begin
3784                Set_Ekind (Acc_Typ, E_Access_Type);
3785
3786                Set_Associated_Storage_Pool (Acc_Typ, RTE (RE_SS_Pool));
3787
3788                Alloc_Node :=
3789                  Make_Allocator (Loc,
3790                    Expression =>
3791                      Make_Qualified_Expression (Loc,
3792                        Subtype_Mark => New_Reference_To (Etype (Exp), Loc),
3793                        Expression => Relocate_Node (Exp)));
3794
3795                Insert_List_Before_And_Analyze (N, New_List (
3796                  Make_Full_Type_Declaration (Loc,
3797                    Defining_Identifier => Acc_Typ,
3798                    Type_Definition     =>
3799                      Make_Access_To_Object_Definition (Loc,
3800                        Subtype_Indication =>
3801                           New_Reference_To (R_Type, Loc))),
3802
3803                  Make_Object_Declaration (Loc,
3804                    Defining_Identifier => Temp,
3805                    Object_Definition   => New_Reference_To (Acc_Typ, Loc),
3806                    Expression          => Alloc_Node)));
3807
3808                Rewrite (Exp,
3809                  Make_Explicit_Dereference (Loc,
3810                  Prefix => New_Reference_To (Temp, Loc)));
3811
3812                Analyze_And_Resolve (Exp, R_Type);
3813             end;
3814
3815          --  Otherwise use the gigi mechanism to allocate result on the
3816          --  secondary stack.
3817
3818          else
3819             Set_Storage_Pool      (N, RTE (RE_SS_Pool));
3820
3821             --  If we are generating code for the VM do not use
3822             --  SS_Allocate since everything is heap-allocated anyway.
3823
3824             if VM_Target = No_VM then
3825                Set_Procedure_To_Call (N, RTE (RE_SS_Allocate));
3826             end if;
3827          end if;
3828       end if;
3829
3830       --  Implement the rules of 6.5(8-10), which require a tag check in the
3831       --  case of a limited tagged return type, and tag reassignment for
3832       --  nonlimited tagged results. These actions are needed when the return
3833       --  type is a specific tagged type and the result expression is a
3834       --  conversion or a formal parameter, because in that case the tag of the
3835       --  expression might differ from the tag of the specific result type.
3836
3837       if Is_Tagged_Type (Utyp)
3838         and then not Is_Class_Wide_Type (Utyp)
3839         and then (Nkind (Exp) = N_Type_Conversion
3840                     or else Nkind (Exp) = N_Unchecked_Type_Conversion
3841                     or else (Is_Entity_Name (Exp)
3842                                and then Ekind (Entity (Exp)) in Formal_Kind))
3843       then
3844          --  When the return type is limited, perform a check that the
3845          --  tag of the result is the same as the tag of the return type.
3846
3847          if Is_Limited_Type (R_Type) then
3848             Insert_Action (Exp,
3849               Make_Raise_Constraint_Error (Loc,
3850                 Condition =>
3851                   Make_Op_Ne (Loc,
3852                     Left_Opnd =>
3853                       Make_Selected_Component (Loc,
3854                         Prefix => Duplicate_Subexpr (Exp),
3855                         Selector_Name =>
3856                           New_Reference_To (First_Tag_Component (Utyp), Loc)),
3857                     Right_Opnd =>
3858                       Unchecked_Convert_To (RTE (RE_Tag),
3859                         New_Reference_To
3860                           (Node (First_Elmt
3861                                   (Access_Disp_Table (Base_Type (Utyp)))),
3862                            Loc))),
3863                 Reason => CE_Tag_Check_Failed));
3864
3865          --  If the result type is a specific nonlimited tagged type, then we
3866          --  have to ensure that the tag of the result is that of the result
3867          --  type. This is handled by making a copy of the expression in the
3868          --  case where it might have a different tag, namely when the
3869          --  expression is a conversion or a formal parameter. We create a new
3870          --  object of the result type and initialize it from the expression,
3871          --  which will implicitly force the tag to be set appropriately.
3872
3873          else
3874             declare
3875                Result_Id  : constant Entity_Id :=
3876                               Make_Defining_Identifier (Loc,
3877                                 Chars => New_Internal_Name ('R'));
3878                Result_Exp : constant Node_Id :=
3879                               New_Reference_To (Result_Id, Loc);
3880                Result_Obj : constant Node_Id :=
3881                               Make_Object_Declaration (Loc,
3882                                 Defining_Identifier => Result_Id,
3883                                 Object_Definition   =>
3884                                   New_Reference_To (R_Type, Loc),
3885                                 Constant_Present    => True,
3886                                 Expression          => Relocate_Node (Exp));
3887
3888             begin
3889                Set_Assignment_OK (Result_Obj);
3890                Insert_Action (Exp, Result_Obj);
3891
3892                Rewrite (Exp, Result_Exp);
3893                Analyze_And_Resolve (Exp, R_Type);
3894             end;
3895          end if;
3896
3897       --  Ada 2005 (AI-344): If the result type is class-wide, then insert
3898       --  a check that the level of the return expression's underlying type
3899       --  is not deeper than the level of the master enclosing the function.
3900       --  Always generate the check when the type of the return expression
3901       --  is class-wide, when it's a type conversion, or when it's a formal
3902       --  parameter. Otherwise, suppress the check in the case where the
3903       --  return expression has a specific type whose level is known not to
3904       --  be statically deeper than the function's result type.
3905
3906       --  Note: accessibility check is skipped in the VM case, since there
3907       --  does not seem to be any practical way to implement this check.
3908
3909       elsif Ada_Version >= Ada_05
3910         and then VM_Target = No_VM
3911         and then Is_Class_Wide_Type (R_Type)
3912         and then not Scope_Suppress (Accessibility_Check)
3913         and then
3914           (Is_Class_Wide_Type (Etype (Exp))
3915             or else Nkind (Exp) = N_Type_Conversion
3916             or else Nkind (Exp) = N_Unchecked_Type_Conversion
3917             or else (Is_Entity_Name (Exp)
3918                        and then Ekind (Entity (Exp)) in Formal_Kind)
3919             or else Scope_Depth (Enclosing_Dynamic_Scope (Etype (Exp))) >
3920                       Scope_Depth (Enclosing_Dynamic_Scope (Scope_Id)))
3921       then
3922          declare
3923             Tag_Node : Node_Id;
3924
3925          begin
3926             --  Ada 2005 (AI-251): In class-wide interface objects we displace
3927             --  "this" to reference the base of the object --- required to get
3928             --  access to the TSD of the object.
3929
3930             if Is_Class_Wide_Type (Etype (Exp))
3931               and then Is_Interface (Etype (Exp))
3932               and then Nkind (Exp) = N_Explicit_Dereference
3933             then
3934                Tag_Node :=
3935                  Make_Explicit_Dereference (Loc,
3936                    Unchecked_Convert_To (RTE (RE_Tag_Ptr),
3937                      Make_Function_Call (Loc,
3938                        Name => New_Reference_To (RTE (RE_Base_Address), Loc),
3939                        Parameter_Associations => New_List (
3940                          Unchecked_Convert_To (RTE (RE_Address),
3941                            Duplicate_Subexpr (Prefix (Exp)))))));
3942             else
3943                Tag_Node :=
3944                  Make_Attribute_Reference (Loc,
3945                    Prefix => Duplicate_Subexpr (Exp),
3946                    Attribute_Name => Name_Tag);
3947             end if;
3948
3949             Insert_Action (Exp,
3950               Make_Raise_Program_Error (Loc,
3951                 Condition =>
3952                   Make_Op_Gt (Loc,
3953                     Left_Opnd =>
3954                       Build_Get_Access_Level (Loc, Tag_Node),
3955                     Right_Opnd =>
3956                       Make_Integer_Literal (Loc,
3957                         Scope_Depth (Enclosing_Dynamic_Scope (Scope_Id)))),
3958                 Reason => PE_Accessibility_Check_Failed));
3959          end;
3960       end if;
3961    end Expand_Simple_Function_Return;
3962
3963    ------------------------------
3964    -- Make_Tag_Ctrl_Assignment --
3965    ------------------------------
3966
3967    function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
3968       Loc : constant Source_Ptr := Sloc (N);
3969       L   : constant Node_Id    := Name (N);
3970       T   : constant Entity_Id  := Underlying_Type (Etype (L));
3971
3972       Ctrl_Act : constant Boolean := Controlled_Type (T)
3973                                        and then not No_Ctrl_Actions (N);
3974
3975       Save_Tag : constant Boolean := Is_Tagged_Type (T)
3976                                        and then not No_Ctrl_Actions (N)
3977                                        and then VM_Target = No_VM;
3978       --  Tags are not saved and restored when VM_Target because VM tags are
3979       --  represented implicitly in objects.
3980
3981       Res      : List_Id;
3982       Tag_Tmp  : Entity_Id;
3983
3984       Prev_Tmp : Entity_Id;
3985       Next_Tmp : Entity_Id;
3986       Ctrl_Ref : Node_Id;
3987
3988    begin
3989       Res := New_List;
3990
3991       --  Finalize the target of the assignment when controlled.
3992       --  We have two exceptions here:
3993
3994       --   1. If we are in an init proc since it is an initialization
3995       --      more than an assignment
3996
3997       --   2. If the left-hand side is a temporary that was not initialized
3998       --      (or the parent part of a temporary since it is the case in
3999       --      extension aggregates). Such a temporary does not come from
4000       --      source. We must examine the original node for the prefix, because
4001       --      it may be a component of an entry formal, in which case it has
4002       --      been rewritten and does not appear to come from source either.
4003
4004       --  Case of init proc
4005
4006       if not Ctrl_Act then
4007          null;
4008
4009       --  The left hand side is an uninitialized temporary
4010
4011       elsif Nkind (L) = N_Type_Conversion
4012         and then Is_Entity_Name (Expression (L))
4013         and then No_Initialization (Parent (Entity (Expression (L))))
4014       then
4015          null;
4016       else
4017          Append_List_To (Res,
4018            Make_Final_Call (
4019              Ref         => Duplicate_Subexpr_No_Checks (L),
4020              Typ         => Etype (L),
4021              With_Detach => New_Reference_To (Standard_False, Loc)));
4022       end if;
4023
4024       --  Save the Tag in a local variable Tag_Tmp
4025
4026       if Save_Tag then
4027          Tag_Tmp :=
4028            Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
4029
4030          Append_To (Res,
4031            Make_Object_Declaration (Loc,
4032              Defining_Identifier => Tag_Tmp,
4033              Object_Definition => New_Reference_To (RTE (RE_Tag), Loc),
4034              Expression =>
4035                Make_Selected_Component (Loc,
4036                  Prefix        => Duplicate_Subexpr_No_Checks (L),
4037                  Selector_Name => New_Reference_To (First_Tag_Component (T),
4038                                                     Loc))));
4039
4040       --  Otherwise Tag_Tmp not used
4041
4042       else
4043          Tag_Tmp := Empty;
4044       end if;
4045
4046       if Ctrl_Act then
4047          if VM_Target /= No_VM then
4048
4049             --  Cannot assign part of the object in a VM context, so instead
4050             --  fallback to the previous mechanism, even though it is not
4051             --  completely correct ???
4052
4053             --  Save the Finalization Pointers in local variables Prev_Tmp and
4054             --  Next_Tmp. For objects with Has_Controlled_Component set, these
4055             --  pointers are in the Record_Controller
4056
4057             Ctrl_Ref := Duplicate_Subexpr (L);
4058
4059             if Has_Controlled_Component (T) then
4060                Ctrl_Ref :=
4061                  Make_Selected_Component (Loc,
4062                    Prefix => Ctrl_Ref,
4063                    Selector_Name =>
4064                      New_Reference_To (Controller_Component (T), Loc));
4065             end if;
4066
4067             Prev_Tmp :=
4068               Make_Defining_Identifier (Loc, New_Internal_Name ('B'));
4069
4070             Append_To (Res,
4071               Make_Object_Declaration (Loc,
4072                 Defining_Identifier => Prev_Tmp,
4073
4074                 Object_Definition =>
4075                   New_Reference_To (RTE (RE_Finalizable_Ptr), Loc),
4076
4077                 Expression =>
4078                   Make_Selected_Component (Loc,
4079                     Prefix =>
4080                       Unchecked_Convert_To (RTE (RE_Finalizable), Ctrl_Ref),
4081                     Selector_Name => Make_Identifier (Loc, Name_Prev))));
4082
4083             Next_Tmp :=
4084               Make_Defining_Identifier (Loc,
4085                 Chars => New_Internal_Name ('C'));
4086
4087             Append_To (Res,
4088               Make_Object_Declaration (Loc,
4089                 Defining_Identifier => Next_Tmp,
4090
4091                 Object_Definition   =>
4092                   New_Reference_To (RTE (RE_Finalizable_Ptr), Loc),
4093
4094                 Expression          =>
4095                   Make_Selected_Component (Loc,
4096                     Prefix =>
4097                       Unchecked_Convert_To (RTE (RE_Finalizable),
4098                         New_Copy_Tree (Ctrl_Ref)),
4099                     Selector_Name => Make_Identifier (Loc, Name_Next))));
4100
4101             --  Do the Assignment
4102
4103             Append_To (Res, Relocate_Node (N));
4104
4105          else
4106             --  Regular (non VM) processing for controlled types and types with
4107             --  controlled components
4108
4109             --  Variables of such types contain pointers used to chain them in
4110             --  finalization lists, in addition to user data. These pointers
4111             --  are specific to each object of the type, not to the value being
4112             --  assigned.
4113
4114             --  Thus they need to be left intact during the assignment. We
4115             --  achieve this by constructing a Storage_Array subtype, and by
4116             --  overlaying objects of this type on the source and target of the
4117             --  assignment. The assignment is then rewritten to assignments of
4118             --  slices of these arrays, copying the user data, and leaving the
4119             --  pointers untouched.
4120
4121             Controlled_Actions : declare
4122                Prev_Ref : Node_Id;
4123                --  A reference to the Prev component of the record controller
4124
4125                First_After_Root : Node_Id := Empty;
4126                --  Index of first byte to be copied (used to skip
4127                --  Root_Controlled in controlled objects).
4128
4129                Last_Before_Hole : Node_Id := Empty;
4130                --  Index of last byte to be copied before outermost record
4131                --  controller data.
4132
4133                Hole_Length : Node_Id := Empty;
4134                --  Length of record controller data (Prev and Next pointers)
4135
4136                First_After_Hole : Node_Id := Empty;
4137                --  Index of first byte to be copied after outermost record
4138                --  controller data.
4139
4140                Expr, Source_Size     : Node_Id;
4141                Source_Actual_Subtype : Entity_Id;
4142                --  Used for computation of the size of the data to be copied
4143
4144                Range_Type  : Entity_Id;
4145                Opaque_Type : Entity_Id;
4146
4147                function Build_Slice
4148                  (Rec : Entity_Id;
4149                   Lo  : Node_Id;
4150                   Hi  : Node_Id) return Node_Id;
4151                --  Build and return a slice of an array of type S overlaid on
4152                --  object Rec, with bounds specified by Lo and Hi. If either
4153                --  bound is empty, a default of S'First (respectively S'Last)
4154                --  is used.
4155
4156                -----------------
4157                -- Build_Slice --
4158                -----------------
4159
4160                function Build_Slice
4161                  (Rec : Node_Id;
4162                   Lo  : Node_Id;
4163                   Hi  : Node_Id) return Node_Id
4164                is
4165                   Lo_Bound : Node_Id;
4166                   Hi_Bound : Node_Id;
4167
4168                   Opaque : constant Node_Id :=
4169                              Unchecked_Convert_To (Opaque_Type,
4170                                Make_Attribute_Reference (Loc,
4171                                  Prefix         => Rec,
4172                                  Attribute_Name => Name_Address));
4173                   --  Access value designating an opaque storage array of type
4174                   --  S overlaid on record Rec.
4175
4176                begin
4177                   --  Compute slice bounds using S'First (1) and S'Last as
4178                   --  default values when not specified by the caller.
4179
4180                   if No (Lo) then
4181                      Lo_Bound := Make_Integer_Literal (Loc, 1);
4182                   else
4183                      Lo_Bound := Lo;
4184                   end if;
4185
4186                   if No (Hi) then
4187                      Hi_Bound := Make_Attribute_Reference (Loc,
4188                        Prefix => New_Occurrence_Of (Range_Type, Loc),
4189                        Attribute_Name => Name_Last);
4190                   else
4191                      Hi_Bound := Hi;
4192                   end if;
4193
4194                   return Make_Slice (Loc,
4195                     Prefix =>
4196                       Opaque,
4197                     Discrete_Range => Make_Range (Loc,
4198                       Lo_Bound, Hi_Bound));
4199                end Build_Slice;
4200
4201             --  Start of processing for Controlled_Actions
4202
4203             begin
4204                --  Create a constrained subtype of Storage_Array whose size
4205                --  corresponds to the value being assigned.
4206
4207                --  subtype G is Storage_Offset range
4208                --    1 .. (Expr'Size + Storage_Unit - 1) / Storage_Unit
4209
4210                Expr := Duplicate_Subexpr_No_Checks (Expression (N));
4211
4212                if Nkind (Expr) = N_Qualified_Expression then
4213                   Expr := Expression (Expr);
4214                end if;
4215
4216                Source_Actual_Subtype := Etype (Expr);
4217
4218                if Has_Discriminants (Source_Actual_Subtype)
4219                  and then not Is_Constrained (Source_Actual_Subtype)
4220                then
4221                   Append_To (Res,
4222                     Build_Actual_Subtype (Source_Actual_Subtype, Expr));
4223                   Source_Actual_Subtype := Defining_Identifier (Last (Res));
4224                end if;
4225
4226                Source_Size :=
4227                  Make_Op_Add (Loc,
4228                    Left_Opnd =>
4229                      Make_Attribute_Reference (Loc,
4230                        Prefix =>
4231                          New_Occurrence_Of (Source_Actual_Subtype, Loc),
4232                      Attribute_Name => Name_Size),
4233                    Right_Opnd =>
4234                      Make_Integer_Literal (Loc,
4235                        Intval => System_Storage_Unit - 1));
4236
4237                Source_Size :=
4238                  Make_Op_Divide (Loc,
4239                    Left_Opnd => Source_Size,
4240                    Right_Opnd =>
4241                      Make_Integer_Literal (Loc,
4242                        Intval => System_Storage_Unit));
4243
4244                Range_Type :=
4245                  Make_Defining_Identifier (Loc,
4246                    New_Internal_Name ('G'));
4247
4248                Append_To (Res,
4249                  Make_Subtype_Declaration (Loc,
4250                    Defining_Identifier => Range_Type,
4251                    Subtype_Indication =>
4252                      Make_Subtype_Indication (Loc,
4253                        Subtype_Mark =>
4254                          New_Reference_To (RTE (RE_Storage_Offset), Loc),
4255                        Constraint   => Make_Range_Constraint (Loc,
4256                          Range_Expression =>
4257                            Make_Range (Loc,
4258                              Low_Bound  => Make_Integer_Literal (Loc, 1),
4259                              High_Bound => Source_Size)))));
4260
4261                --  subtype S is Storage_Array (G)
4262
4263                Append_To (Res,
4264                  Make_Subtype_Declaration (Loc,
4265                    Defining_Identifier =>
4266                      Make_Defining_Identifier (Loc,
4267                        New_Internal_Name ('S')),
4268                    Subtype_Indication  =>
4269                      Make_Subtype_Indication (Loc,
4270                        Subtype_Mark =>
4271                          New_Reference_To (RTE (RE_Storage_Array), Loc),
4272                        Constraint =>
4273                          Make_Index_Or_Discriminant_Constraint (Loc,
4274                            Constraints =>
4275                              New_List (New_Reference_To (Range_Type, Loc))))));
4276
4277                --  type A is access S
4278
4279                Opaque_Type :=
4280                  Make_Defining_Identifier (Loc,
4281                    Chars => New_Internal_Name ('A'));
4282
4283                Append_To (Res,
4284                  Make_Full_Type_Declaration (Loc,
4285                    Defining_Identifier => Opaque_Type,
4286                    Type_Definition     =>
4287                      Make_Access_To_Object_Definition (Loc,
4288                        Subtype_Indication =>
4289                          New_Occurrence_Of (
4290                            Defining_Identifier (Last (Res)), Loc))));
4291
4292                --  Generate appropriate slice assignments
4293
4294                First_After_Root := Make_Integer_Literal (Loc, 1);
4295
4296                --  For the case of a controlled object, skip the
4297                --  Root_Controlled part.
4298
4299                if Is_Controlled (T) then
4300                   First_After_Root :=
4301                     Make_Op_Add (Loc,
4302                       First_After_Root,
4303                       Make_Op_Divide (Loc,
4304                         Make_Attribute_Reference (Loc,
4305                           Prefix =>
4306                             New_Occurrence_Of (RTE (RE_Root_Controlled), Loc),
4307                           Attribute_Name => Name_Size),
4308                         Make_Integer_Literal (Loc, System_Storage_Unit)));
4309                end if;
4310
4311                --  For the case of a record with controlled components, skip
4312                --  the Prev and Next components of the record controller.
4313                --  These components constitute a 'hole' in the middle of the
4314                --  data to be copied.
4315
4316                if Has_Controlled_Component (T) then
4317                   Prev_Ref :=
4318                     Make_Selected_Component (Loc,
4319                       Prefix =>
4320                         Make_Selected_Component (Loc,
4321                           Prefix => Duplicate_Subexpr_No_Checks (L),
4322                           Selector_Name =>
4323                             New_Reference_To (Controller_Component (T), Loc)),
4324                       Selector_Name =>  Make_Identifier (Loc, Name_Prev));
4325
4326                   --  Last index before hole: determined by position of
4327                   --  the _Controller.Prev component.
4328
4329                   Last_Before_Hole :=
4330                     Make_Defining_Identifier (Loc,
4331                       New_Internal_Name ('L'));
4332
4333                   Append_To (Res,
4334                     Make_Object_Declaration (Loc,
4335                       Defining_Identifier => Last_Before_Hole,
4336                       Object_Definition   => New_Occurrence_Of (
4337                         RTE (RE_Storage_Offset), Loc),
4338                       Constant_Present    => True,
4339                       Expression          => Make_Op_Add (Loc,
4340                           Make_Attribute_Reference (Loc,
4341                             Prefix => Prev_Ref,
4342                             Attribute_Name => Name_Position),
4343                           Make_Attribute_Reference (Loc,
4344                             Prefix => New_Copy_Tree (Prefix (Prev_Ref)),
4345                             Attribute_Name => Name_Position))));
4346
4347                   --  Hole length: size of the Prev and Next components
4348
4349                   Hole_Length :=
4350                     Make_Op_Multiply (Loc,
4351                       Left_Opnd  => Make_Integer_Literal (Loc, Uint_2),
4352                       Right_Opnd =>
4353                         Make_Op_Divide (Loc,
4354                           Left_Opnd =>
4355                             Make_Attribute_Reference (Loc,
4356                               Prefix         => New_Copy_Tree (Prev_Ref),
4357                               Attribute_Name => Name_Size),
4358                           Right_Opnd =>
4359                             Make_Integer_Literal (Loc,
4360                               Intval => System_Storage_Unit)));
4361
4362                   --  First index after hole
4363
4364                   First_After_Hole :=
4365                     Make_Defining_Identifier (Loc,
4366                       New_Internal_Name ('F'));
4367
4368                   Append_To (Res,
4369                     Make_Object_Declaration (Loc,
4370                       Defining_Identifier => First_After_Hole,
4371                       Object_Definition   => New_Occurrence_Of (
4372                         RTE (RE_Storage_Offset), Loc),
4373                       Constant_Present    => True,
4374                       Expression          =>
4375                         Make_Op_Add (Loc,
4376                           Left_Opnd  =>
4377                             Make_Op_Add (Loc,
4378                               Left_Opnd  =>
4379                                 New_Occurrence_Of (Last_Before_Hole, Loc),
4380                               Right_Opnd => Hole_Length),
4381                           Right_Opnd => Make_Integer_Literal (Loc, 1))));
4382
4383                   Last_Before_Hole :=
4384                     New_Occurrence_Of (Last_Before_Hole, Loc);
4385                   First_After_Hole :=
4386                     New_Occurrence_Of (First_After_Hole, Loc);
4387                end if;
4388
4389                --  Assign the first slice (possibly skipping Root_Controlled,
4390                --  up to the beginning of the record controller if present,
4391                --  up to the end of the object if not).
4392
4393                Append_To (Res, Make_Assignment_Statement (Loc,
4394                  Name       => Build_Slice (
4395                    Rec => Duplicate_Subexpr_No_Checks (L),
4396                    Lo  => First_After_Root,
4397                    Hi  => Last_Before_Hole),
4398
4399                  Expression => Build_Slice (
4400                    Rec => Expression (N),
4401                    Lo  => First_After_Root,
4402                    Hi  => New_Copy_Tree (Last_Before_Hole))));
4403
4404                if Present (First_After_Hole) then
4405
4406                   --  If a record controller is present, copy the second slice,
4407                   --  from right after the _Controller.Next component up to the
4408                   --  end of the object.
4409
4410                   Append_To (Res, Make_Assignment_Statement (Loc,
4411                     Name       => Build_Slice (
4412                       Rec => Duplicate_Subexpr_No_Checks (L),
4413                       Lo  => First_After_Hole,
4414                       Hi  => Empty),
4415                     Expression => Build_Slice (
4416                       Rec => Duplicate_Subexpr_No_Checks (Expression (N)),
4417                       Lo  => New_Copy_Tree (First_After_Hole),
4418                       Hi  => Empty)));
4419                end if;
4420             end Controlled_Actions;
4421          end if;
4422
4423       else
4424          Append_To (Res, Relocate_Node (N));
4425       end if;
4426
4427       --  Restore the tag
4428
4429       if Save_Tag then
4430          Append_To (Res,
4431            Make_Assignment_Statement (Loc,
4432              Name =>
4433                Make_Selected_Component (Loc,
4434                  Prefix        => Duplicate_Subexpr_No_Checks (L),
4435                  Selector_Name => New_Reference_To (First_Tag_Component (T),
4436                                                     Loc)),
4437              Expression => New_Reference_To (Tag_Tmp, Loc)));
4438       end if;
4439
4440       if Ctrl_Act then
4441          if VM_Target /= No_VM then
4442             --  Restore the finalization pointers
4443
4444             Append_To (Res,
4445               Make_Assignment_Statement (Loc,
4446                 Name =>
4447                   Make_Selected_Component (Loc,
4448                     Prefix =>
4449                       Unchecked_Convert_To (RTE (RE_Finalizable),
4450                         New_Copy_Tree (Ctrl_Ref)),
4451                     Selector_Name => Make_Identifier (Loc, Name_Prev)),
4452                 Expression => New_Reference_To (Prev_Tmp, Loc)));
4453
4454             Append_To (Res,
4455               Make_Assignment_Statement (Loc,
4456                 Name =>
4457                   Make_Selected_Component (Loc,
4458                     Prefix =>
4459                       Unchecked_Convert_To (RTE (RE_Finalizable),
4460                         New_Copy_Tree (Ctrl_Ref)),
4461                     Selector_Name => Make_Identifier (Loc, Name_Next)),
4462                 Expression => New_Reference_To (Next_Tmp, Loc)));
4463          end if;
4464
4465          --  Adjust the target after the assignment when controlled (not in the
4466          --  init proc since it is an initialization more than an assignment).
4467
4468          Append_List_To (Res,
4469            Make_Adjust_Call (
4470              Ref         => Duplicate_Subexpr_Move_Checks (L),
4471              Typ         => Etype (L),
4472              Flist_Ref   => New_Reference_To (RTE (RE_Global_Final_List), Loc),
4473              With_Attach => Make_Integer_Literal (Loc, 0)));
4474       end if;
4475
4476       return Res;
4477
4478    exception
4479       --  Could use comment here ???
4480
4481       when RE_Not_Available =>
4482          return Empty_List;
4483    end Make_Tag_Ctrl_Assignment;
4484
4485 end Exp_Ch5;