OSDN Git Service

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