OSDN Git Service

2005-03-08 Javier Miranda <miranda@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_ch5.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              E X P _ C H 5                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2005, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 2,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT;  see file COPYING.  If not, write --
19 -- to  the Free Software Foundation,  59 Temple Place - Suite 330,  Boston, --
20 -- MA 02111-1307, USA.                                                      --
21 --                                                                          --
22 -- GNAT was originally developed  by the GNAT team at  New York University. --
23 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
24 --                                                                          --
25 ------------------------------------------------------------------------------
26
27 with Atree;    use Atree;
28 with Checks;   use Checks;
29 with Einfo;    use Einfo;
30 with Elists;   use Elists;
31 with Exp_Aggr; use Exp_Aggr;
32 with Exp_Ch7;  use Exp_Ch7;
33 with Exp_Ch11; use Exp_Ch11;
34 with Exp_Dbug; use Exp_Dbug;
35 with Exp_Pakd; use Exp_Pakd;
36 with Exp_Tss;  use Exp_Tss;
37 with Exp_Util; use Exp_Util;
38 with Hostparm; use Hostparm;
39 with Nlists;   use Nlists;
40 with Nmake;    use Nmake;
41 with Opt;      use Opt;
42 with Restrict; use Restrict;
43 with Rident;   use Rident;
44 with Rtsfind;  use Rtsfind;
45 with Sinfo;    use Sinfo;
46 with Sem;      use Sem;
47 with Sem_Ch3;  use Sem_Ch3;
48 with Sem_Ch8;  use Sem_Ch8;
49 with Sem_Ch13; use Sem_Ch13;
50 with Sem_Eval; use Sem_Eval;
51 with Sem_Res;  use Sem_Res;
52 with Sem_Util; use Sem_Util;
53 with Snames;   use Snames;
54 with Stand;    use Stand;
55 with Stringt;  use Stringt;
56 with Tbuild;   use Tbuild;
57 with Ttypes;   use Ttypes;
58 with Uintp;    use Uintp;
59 with Validsw;  use Validsw;
60
61 package body Exp_Ch5 is
62
63    function Change_Of_Representation (N : Node_Id) return Boolean;
64    --  Determine if the right hand side of the assignment N is a type
65    --  conversion which requires a change of representation. Called
66    --  only for the array and record cases.
67
68    procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id);
69    --  N is an assignment which assigns an array value. This routine process
70    --  the various special cases and checks required for such assignments,
71    --  including change of representation. Rhs is normally simply the right
72    --  hand side of the assignment, except that if the right hand side is
73    --  a type conversion or a qualified expression, then the Rhs is the
74    --  actual expression inside any such type conversions or qualifications.
75
76    function Expand_Assign_Array_Loop
77      (N      : Node_Id;
78       Larray : Entity_Id;
79       Rarray : Entity_Id;
80       L_Type : Entity_Id;
81       R_Type : Entity_Id;
82       Ndim   : Pos;
83       Rev    : Boolean) return Node_Id;
84    --  N is an assignment statement which assigns an array value. This routine
85    --  expands the assignment into a loop (or nested loops for the case of a
86    --  multi-dimensional array) to do the assignment component by component.
87    --  Larray and Rarray are the entities of the actual arrays on the left
88    --  hand and right hand sides. L_Type and R_Type are the types of these
89    --  arrays (which may not be the same, due to either sliding, or to a
90    --  change of representation case). Ndim is the number of dimensions and
91    --  the parameter Rev indicates if the loops run normally (Rev = False),
92    --  or reversed (Rev = True). The value returned is the constructed
93    --  loop statement. Auxiliary declarations are inserted before node N
94    --  using the standard Insert_Actions mechanism.
95
96    procedure Expand_Assign_Record (N : Node_Id);
97    --  N is an assignment of a non-tagged record value. This routine handles
98    --  the case where the assignment must be made component by component,
99    --  either because the target is not byte aligned, or there is a change
100    --  of representation.
101
102    function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id;
103    --  Generate the necessary code for controlled and tagged assignment,
104    --  that is to say, finalization of the target before, adjustement of
105    --  the target after and save and restore of the tag and finalization
106    --  pointers which are not 'part of the value' and must not be changed
107    --  upon assignment. N is the original Assignment node.
108
109    function Possible_Bit_Aligned_Component (N : Node_Id) return Boolean;
110    --  This function is used in processing the assignment of a record or
111    --  indexed component. The argument N is either the left hand or right
112    --  hand side of an assignment, and this function determines if there
113    --  is a record component reference where the record may be bit aligned
114    --  in a manner that causes trouble for the back end (see description
115    --  of Exp_Util.Component_May_Be_Bit_Aligned for further details).
116
117    ------------------------------
118    -- Change_Of_Representation --
119    ------------------------------
120
121    function Change_Of_Representation (N : Node_Id) return Boolean is
122       Rhs : constant Node_Id := Expression (N);
123    begin
124       return
125         Nkind (Rhs) = N_Type_Conversion
126           and then
127             not Same_Representation (Etype (Rhs), Etype (Expression (Rhs)));
128    end Change_Of_Representation;
129
130    -------------------------
131    -- Expand_Assign_Array --
132    -------------------------
133
134    --  There are two issues here. First, do we let Gigi do a block move, or
135    --  do we expand out into a loop? Second, we need to set the two flags
136    --  Forwards_OK and Backwards_OK which show whether the block move (or
137    --  corresponding loops) can be legitimately done in a forwards (low to
138    --  high) or backwards (high to low) manner.
139
140    procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id) is
141       Loc : constant Source_Ptr := Sloc (N);
142
143       Lhs : constant Node_Id := Name (N);
144
145       Act_Lhs : constant Node_Id := Get_Referenced_Object (Lhs);
146       Act_Rhs : Node_Id          := Get_Referenced_Object (Rhs);
147
148       L_Type : constant Entity_Id :=
149                  Underlying_Type (Get_Actual_Subtype (Act_Lhs));
150       R_Type : Entity_Id :=
151                  Underlying_Type (Get_Actual_Subtype (Act_Rhs));
152
153       L_Slice : constant Boolean := Nkind (Act_Lhs) = N_Slice;
154       R_Slice : constant Boolean := Nkind (Act_Rhs) = N_Slice;
155
156       Crep : constant Boolean := Change_Of_Representation (N);
157
158       Larray  : Node_Id;
159       Rarray  : Node_Id;
160
161       Ndim : constant Pos := Number_Dimensions (L_Type);
162
163       Loop_Required : Boolean := False;
164       --  This switch is set to True if the array move must be done using
165       --  an explicit front end generated loop.
166
167       procedure Apply_Dereference (Arg : in out Node_Id);
168       --  If the argument is an access to an array, and the assignment is
169       --  converted into a procedure call, apply explicit dereference.
170
171       function Has_Address_Clause (Exp : Node_Id) return Boolean;
172       --  Test if Exp is a reference to an array whose declaration has
173       --  an address clause, or it is a slice of such an array.
174
175       function Is_Formal_Array (Exp : Node_Id) return Boolean;
176       --  Test if Exp is a reference to an array which is either a formal
177       --  parameter or a slice of a formal parameter. These are the cases
178       --  where hidden aliasing can occur.
179
180       function Is_Non_Local_Array (Exp : Node_Id) return Boolean;
181       --  Determine if Exp is a reference to an array variable which is other
182       --  than an object defined in the current scope, or a slice of such
183       --  an object. Such objects can be aliased to parameters (unlike local
184       --  array references).
185
186       -----------------------
187       -- Apply_Dereference --
188       -----------------------
189
190       procedure Apply_Dereference (Arg : in out Node_Id) is
191          Typ : constant Entity_Id := Etype (Arg);
192       begin
193          if Is_Access_Type (Typ) then
194             Rewrite (Arg, Make_Explicit_Dereference (Loc,
195               Prefix => Relocate_Node (Arg)));
196             Analyze_And_Resolve (Arg, Designated_Type (Typ));
197          end if;
198       end Apply_Dereference;
199
200       ------------------------
201       -- Has_Address_Clause --
202       ------------------------
203
204       function Has_Address_Clause (Exp : Node_Id) return Boolean is
205       begin
206          return
207            (Is_Entity_Name (Exp) and then
208                               Present (Address_Clause (Entity (Exp))))
209              or else
210            (Nkind (Exp) = N_Slice and then Has_Address_Clause (Prefix (Exp)));
211       end Has_Address_Clause;
212
213       ---------------------
214       -- Is_Formal_Array --
215       ---------------------
216
217       function Is_Formal_Array (Exp : Node_Id) return Boolean is
218       begin
219          return
220            (Is_Entity_Name (Exp) and then Is_Formal (Entity (Exp)))
221              or else
222            (Nkind (Exp) = N_Slice and then Is_Formal_Array (Prefix (Exp)));
223       end Is_Formal_Array;
224
225       ------------------------
226       -- Is_Non_Local_Array --
227       ------------------------
228
229       function Is_Non_Local_Array (Exp : Node_Id) return Boolean is
230       begin
231          return (Is_Entity_Name (Exp)
232                    and then Scope (Entity (Exp)) /= Current_Scope)
233             or else (Nkind (Exp) = N_Slice
234                        and then Is_Non_Local_Array (Prefix (Exp)));
235       end Is_Non_Local_Array;
236
237       --  Determine if Lhs, Rhs are formal arrays or nonlocal arrays
238
239       Lhs_Formal : constant Boolean := Is_Formal_Array (Act_Lhs);
240       Rhs_Formal : constant Boolean := Is_Formal_Array (Act_Rhs);
241
242       Lhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Lhs);
243       Rhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Rhs);
244
245    --  Start of processing for Expand_Assign_Array
246
247    begin
248       --  Deal with length check, note that the length check is done with
249       --  respect to the right hand side as given, not a possible underlying
250       --  renamed object, since this would generate incorrect extra checks.
251
252       Apply_Length_Check (Rhs, L_Type);
253
254       --  We start by assuming that the move can be done in either
255       --  direction, i.e. that the two sides are completely disjoint.
256
257       Set_Forwards_OK  (N, True);
258       Set_Backwards_OK (N, True);
259
260       --  Normally it is only the slice case that can lead to overlap,
261       --  and explicit checks for slices are made below. But there is
262       --  one case where the slice can be implicit and invisible to us
263       --  and that is the case where we have a one dimensional array,
264       --  and either both operands are parameters, or one is a parameter
265       --  and the other is a global variable. In this case the parameter
266       --  could be a slice that overlaps with the other parameter.
267
268       --  Check for the case of slices requiring an explicit loop. Normally
269       --  it is only the explicit slice cases that bother us, but in the
270       --  case of one dimensional arrays, parameters can be slices that
271       --  are passed by reference, so we can have aliasing for assignments
272       --  from one parameter to another, or assignments between parameters
273       --  and nonlocal variables. However, if the array subtype is a
274       --  constrained first subtype in the parameter case, then we don't
275       --  have to worry about overlap, since slice assignments aren't
276       --  possible (other than for a slice denoting the whole array).
277
278       --  Note: overlap is never possible if there is a change of
279       --  representation, so we can exclude this case.
280
281       if Ndim = 1
282         and then not Crep
283         and then
284            ((Lhs_Formal and Rhs_Formal)
285               or else
286             (Lhs_Formal and Rhs_Non_Local_Var)
287               or else
288             (Rhs_Formal and Lhs_Non_Local_Var))
289         and then
290            (not Is_Constrained (Etype (Lhs))
291              or else not Is_First_Subtype (Etype (Lhs)))
292
293          --  In the case of compiling for the Java Virtual Machine,
294          --  slices are always passed by making a copy, so we don't
295          --  have to worry about overlap. We also want to prevent
296          --  generation of "<" comparisons for array addresses,
297          --  since that's a meaningless operation on the JVM.
298
299         and then not Java_VM
300       then
301          Set_Forwards_OK  (N, False);
302          Set_Backwards_OK (N, False);
303
304          --  Note: the bit-packed case is not worrisome here, since if
305          --  we have a slice passed as a parameter, it is always aligned
306          --  on a byte boundary, and if there are no explicit slices, the
307          --  assignment can be performed directly.
308       end if;
309
310       --  We certainly must use a loop for change of representation
311       --  and also we use the operand of the conversion on the right
312       --  hand side as the effective right hand side (the component
313       --  types must match in this situation).
314
315       if Crep then
316          Act_Rhs := Get_Referenced_Object (Rhs);
317          R_Type  := Get_Actual_Subtype (Act_Rhs);
318          Loop_Required := True;
319
320       --  We require a loop if the left side is possibly bit unaligned
321
322       elsif Possible_Bit_Aligned_Component (Lhs)
323               or else
324             Possible_Bit_Aligned_Component (Rhs)
325       then
326          Loop_Required := True;
327
328       --  Arrays with controlled components are expanded into a loop
329       --  to force calls to adjust at the component level.
330
331       elsif Has_Controlled_Component (L_Type) then
332          Loop_Required := True;
333
334          --  If object is atomic, we cannot tolerate a loop
335
336       elsif Is_Atomic_Object (Act_Lhs)
337               or else
338             Is_Atomic_Object (Act_Rhs)
339       then
340          return;
341
342       --  Loop is required if we have atomic components since we have to
343       --  be sure to do any accesses on an element by element basis.
344
345       elsif Has_Atomic_Components (L_Type)
346         or else Has_Atomic_Components (R_Type)
347         or else Is_Atomic (Component_Type (L_Type))
348         or else Is_Atomic (Component_Type (R_Type))
349       then
350          Loop_Required := True;
351
352       --  Case where no slice is involved
353
354       elsif not L_Slice and not R_Slice then
355
356          --  The following code deals with the case of unconstrained bit
357          --  packed arrays. The problem is that the template for such
358          --  arrays contains the bounds of the actual source level array,
359
360          --  But the copy of an entire array requires the bounds of the
361          --  underlying array. It would be nice if the back end could take
362          --  care of this, but right now it does not know how, so if we
363          --  have such a type, then we expand out into a loop, which is
364          --  inefficient but works correctly. If we don't do this, we
365          --  get the wrong length computed for the array to be moved.
366          --  The two cases we need to worry about are:
367
368          --  Explicit deference of an unconstrained packed array type as
369          --  in the following example:
370
371          --    procedure C52 is
372          --       type BITS is array(INTEGER range <>) of BOOLEAN;
373          --       pragma PACK(BITS);
374          --       type A is access BITS;
375          --       P1,P2 : A;
376          --    begin
377          --       P1 := new BITS (1 .. 65_535);
378          --       P2 := new BITS (1 .. 65_535);
379          --       P2.ALL := P1.ALL;
380          --    end C52;
381
382          --  A formal parameter reference with an unconstrained bit
383          --  array type is the other case we need to worry about (here
384          --  we assume the same BITS type declared above:
385
386          --    procedure Write_All (File : out BITS; Contents : in  BITS);
387          --    begin
388          --       File.Storage := Contents;
389          --    end Write_All;
390
391          --  We expand to a loop in either of these two cases
392
393          --  Question for future thought. Another potentially more efficient
394          --  approach would be to create the actual subtype, and then do an
395          --  unchecked conversion to this actual subtype ???
396
397          Check_Unconstrained_Bit_Packed_Array : declare
398
399             function Is_UBPA_Reference (Opnd : Node_Id) return Boolean;
400             --  Function to perform required test for the first case,
401             --  above (dereference of an unconstrained bit packed array)
402
403             -----------------------
404             -- Is_UBPA_Reference --
405             -----------------------
406
407             function Is_UBPA_Reference (Opnd : Node_Id) return Boolean is
408                Typ      : constant Entity_Id := Underlying_Type (Etype (Opnd));
409                P_Type   : Entity_Id;
410                Des_Type : Entity_Id;
411
412             begin
413                if Present (Packed_Array_Type (Typ))
414                  and then Is_Array_Type (Packed_Array_Type (Typ))
415                  and then not Is_Constrained (Packed_Array_Type (Typ))
416                then
417                   return True;
418
419                elsif Nkind (Opnd) = N_Explicit_Dereference then
420                   P_Type := Underlying_Type (Etype (Prefix (Opnd)));
421
422                   if not Is_Access_Type (P_Type) then
423                      return False;
424
425                   else
426                      Des_Type := Designated_Type (P_Type);
427                      return
428                        Is_Bit_Packed_Array (Des_Type)
429                          and then not Is_Constrained (Des_Type);
430                   end if;
431
432                else
433                   return False;
434                end if;
435             end Is_UBPA_Reference;
436
437          --  Start of processing for Check_Unconstrained_Bit_Packed_Array
438
439          begin
440             if Is_UBPA_Reference (Lhs)
441                  or else
442                Is_UBPA_Reference (Rhs)
443             then
444                Loop_Required := True;
445
446             --  Here if we do not have the case of a reference to a bit
447             --  packed unconstrained array case. In this case gigi can
448             --  most certainly handle the assignment if a forwards move
449             --  is allowed.
450
451             --  (could it handle the backwards case also???)
452
453             elsif Forwards_OK (N) then
454                return;
455             end if;
456          end Check_Unconstrained_Bit_Packed_Array;
457
458       --  The back end can always handle the assignment if the right side is a
459       --  string literal (note that overlap is definitely impossible in this
460       --  case). If the type is packed, a string literal is always converted
461       --  into aggregate, except in the case of a null slice, for which no
462       --  aggregate can be written. In that case, rewrite the assignment as a
463       --  null statement, a length check has already been emitted to verify
464       --  that the range of the left-hand side is empty.
465
466       --  Note that this code is not executed if we had an assignment of
467       --  a string literal to a non-bit aligned component of a record, a
468       --  case which cannot be handled by the backend
469
470       elsif Nkind (Rhs) = N_String_Literal then
471          if String_Length (Strval (Rhs)) = 0
472            and then Is_Bit_Packed_Array (L_Type)
473          then
474             Rewrite (N, Make_Null_Statement (Loc));
475             Analyze (N);
476          end if;
477
478          return;
479
480       --  If either operand is bit packed, then we need a loop, since we
481       --  can't be sure that the slice is byte aligned. Similarly, if either
482       --  operand is a possibly unaligned slice, then we need a loop (since
483       --  the back end cannot handle unaligned slices).
484
485       elsif Is_Bit_Packed_Array (L_Type)
486         or else Is_Bit_Packed_Array (R_Type)
487         or else Is_Possibly_Unaligned_Slice (Lhs)
488         or else Is_Possibly_Unaligned_Slice (Rhs)
489       then
490          Loop_Required := True;
491
492       --  If we are not bit-packed, and we have only one slice, then no
493       --  overlap is possible except in the parameter case, so we can let
494       --  the back end handle things.
495
496       elsif not (L_Slice and R_Slice) then
497          if Forwards_OK (N) then
498             return;
499          end if;
500       end if;
501
502       --  If the right-hand side is a string literal, introduce a temporary
503       --  for it, for use in the generated loop that will follow.
504
505       if Nkind (Rhs) = N_String_Literal then
506          declare
507             Temp : constant Entity_Id :=
508                      Make_Defining_Identifier (Loc, Name_T);
509             Decl : Node_Id;
510
511          begin
512             Decl :=
513               Make_Object_Declaration (Loc,
514                  Defining_Identifier => Temp,
515                  Object_Definition => New_Occurrence_Of (L_Type, Loc),
516                  Expression => Relocate_Node (Rhs));
517
518             Insert_Action (N, Decl);
519             Rewrite (Rhs, New_Occurrence_Of (Temp, Loc));
520             R_Type := Etype (Temp);
521          end;
522       end if;
523
524       --  Come here to complete the analysis
525
526       --    Loop_Required: Set to True if we know that a loop is required
527       --                   regardless of overlap considerations.
528
529       --    Forwards_OK:   Set to False if we already know that a forwards
530       --                   move is not safe, else set to True.
531
532       --    Backwards_OK:  Set to False if we already know that a backwards
533       --                   move is not safe, else set to True
534
535       --  Our task at this stage is to complete the overlap analysis, which
536       --  can result in possibly setting Forwards_OK or Backwards_OK to
537       --  False, and then generating the final code, either by deciding
538       --  that it is OK after all to let Gigi handle it, or by generating
539       --  appropriate code in the front end.
540
541       declare
542          L_Index_Typ : constant Node_Id := Etype (First_Index (L_Type));
543          R_Index_Typ : constant Node_Id := Etype (First_Index (R_Type));
544
545          Left_Lo  : constant Node_Id := Type_Low_Bound  (L_Index_Typ);
546          Left_Hi  : constant Node_Id := Type_High_Bound (L_Index_Typ);
547          Right_Lo : constant Node_Id := Type_Low_Bound  (R_Index_Typ);
548          Right_Hi : constant Node_Id := Type_High_Bound (R_Index_Typ);
549
550          Act_L_Array : Node_Id;
551          Act_R_Array : Node_Id;
552
553          Cleft_Lo  : Node_Id;
554          Cright_Lo : Node_Id;
555          Condition : Node_Id;
556
557          Cresult : Compare_Result;
558
559       begin
560          --  Get the expressions for the arrays. If we are dealing with a
561          --  private type, then convert to the underlying type. We can do
562          --  direct assignments to an array that is a private type, but
563          --  we cannot assign to elements of the array without this extra
564          --  unchecked conversion.
565
566          if Nkind (Act_Lhs) = N_Slice then
567             Larray := Prefix (Act_Lhs);
568          else
569             Larray := Act_Lhs;
570
571             if Is_Private_Type (Etype (Larray)) then
572                Larray :=
573                  Unchecked_Convert_To
574                    (Underlying_Type (Etype (Larray)), Larray);
575             end if;
576          end if;
577
578          if Nkind (Act_Rhs) = N_Slice then
579             Rarray := Prefix (Act_Rhs);
580          else
581             Rarray := Act_Rhs;
582
583             if Is_Private_Type (Etype (Rarray)) then
584                Rarray :=
585                  Unchecked_Convert_To
586                    (Underlying_Type (Etype (Rarray)), Rarray);
587             end if;
588          end if;
589
590          --  If both sides are slices, we must figure out whether
591          --  it is safe to do the move in one direction or the other
592          --  It is always safe if there is a change of representation
593          --  since obviously two arrays with different representations
594          --  cannot possibly overlap.
595
596          if (not Crep) and L_Slice and R_Slice then
597             Act_L_Array := Get_Referenced_Object (Prefix (Act_Lhs));
598             Act_R_Array := Get_Referenced_Object (Prefix (Act_Rhs));
599
600             --  If both left and right hand arrays are entity names, and
601             --  refer to different entities, then we know that the move
602             --  is safe (the two storage areas are completely disjoint).
603
604             if Is_Entity_Name (Act_L_Array)
605               and then Is_Entity_Name (Act_R_Array)
606               and then Entity (Act_L_Array) /= Entity (Act_R_Array)
607             then
608                null;
609
610             --  Otherwise, we assume the worst, which is that the two
611             --  arrays are the same array. There is no need to check if
612             --  we know that is the case, because if we don't know it,
613             --  we still have to assume it!
614
615             --  Generally if the same array is involved, then we have
616             --  an overlapping case. We will have to really assume the
617             --  worst (i.e. set neither of the OK flags) unless we can
618             --  determine the lower or upper bounds at compile time and
619             --  compare them.
620
621             else
622                Cresult := Compile_Time_Compare (Left_Lo, Right_Lo);
623
624                if Cresult = Unknown then
625                   Cresult := Compile_Time_Compare (Left_Hi, Right_Hi);
626                end if;
627
628                case Cresult is
629                   when LT | LE | EQ => Set_Backwards_OK (N, False);
630                   when GT | GE      => Set_Forwards_OK  (N, False);
631                   when NE | Unknown => Set_Backwards_OK (N, False);
632                                        Set_Forwards_OK  (N, False);
633                end case;
634             end if;
635          end if;
636
637          --  If after that analysis, Forwards_OK is still True, and
638          --  Loop_Required is False, meaning that we have not discovered
639          --  some non-overlap reason for requiring a loop, then we can
640          --  still let gigi handle it.
641
642          if not Loop_Required then
643             if Forwards_OK (N) then
644                return;
645             else
646                null;
647                --  Here is where a memmove would be appropriate ???
648             end if;
649          end if;
650
651          --  At this stage we have to generate an explicit loop, and
652          --  we have the following cases:
653
654          --  Forwards_OK = True
655
656          --    Rnn : right_index := right_index'First;
657          --    for Lnn in left-index loop
658          --       left (Lnn) := right (Rnn);
659          --       Rnn := right_index'Succ (Rnn);
660          --    end loop;
661
662          --    Note: the above code MUST be analyzed with checks off,
663          --    because otherwise the Succ could overflow. But in any
664          --    case this is more efficient!
665
666          --  Forwards_OK = False, Backwards_OK = True
667
668          --    Rnn : right_index := right_index'Last;
669          --    for Lnn in reverse left-index loop
670          --       left (Lnn) := right (Rnn);
671          --       Rnn := right_index'Pred (Rnn);
672          --    end loop;
673
674          --    Note: the above code MUST be analyzed with checks off,
675          --    because otherwise the Pred could overflow. But in any
676          --    case this is more efficient!
677
678          --  Forwards_OK = Backwards_OK = False
679
680          --    This only happens if we have the same array on each side. It is
681          --    possible to create situations using overlays that violate this,
682          --    but we simply do not promise to get this "right" in this case.
683
684          --    There are two possible subcases. If the No_Implicit_Conditionals
685          --    restriction is set, then we generate the following code:
686
687          --      declare
688          --        T : constant <operand-type> := rhs;
689          --      begin
690          --        lhs := T;
691          --      end;
692
693          --    If implicit conditionals are permitted, then we generate:
694
695          --      if Left_Lo <= Right_Lo then
696          --         <code for Forwards_OK = True above>
697          --      else
698          --         <code for Backwards_OK = True above>
699          --      end if;
700
701          --  Cases where either Forwards_OK or Backwards_OK is true
702
703          if Forwards_OK (N) or else Backwards_OK (N) then
704             if Controlled_Type (Component_Type (L_Type))
705               and then Base_Type (L_Type) = Base_Type (R_Type)
706               and then Ndim = 1
707               and then not No_Ctrl_Actions (N)
708             then
709                declare
710                   Proc : constant Entity_Id :=
711                            TSS (Base_Type (L_Type), TSS_Slice_Assign);
712                   Actuals : List_Id;
713
714                begin
715                   Apply_Dereference (Larray);
716                   Apply_Dereference (Rarray);
717                   Actuals := New_List (
718                     Duplicate_Subexpr (Larray,   Name_Req => True),
719                     Duplicate_Subexpr (Rarray,   Name_Req => True),
720                     Duplicate_Subexpr (Left_Lo,  Name_Req => True),
721                     Duplicate_Subexpr (Left_Hi,  Name_Req => True),
722                     Duplicate_Subexpr (Right_Lo, Name_Req => True),
723                     Duplicate_Subexpr (Right_Hi, Name_Req => True));
724
725                   Append_To (Actuals,
726                     New_Occurrence_Of (
727                       Boolean_Literals (not Forwards_OK (N)), Loc));
728
729                   Rewrite (N,
730                     Make_Procedure_Call_Statement (Loc,
731                       Name => New_Reference_To (Proc, Loc),
732                       Parameter_Associations => Actuals));
733                end;
734
735             else
736                Rewrite (N,
737                  Expand_Assign_Array_Loop
738                    (N, Larray, Rarray, L_Type, R_Type, Ndim,
739                     Rev => not Forwards_OK (N)));
740             end if;
741
742          --  Case of both are false with No_Implicit_Conditionals
743
744          elsif Restriction_Active (No_Implicit_Conditionals) then
745             declare
746                   T : constant Entity_Id :=
747                         Make_Defining_Identifier (Loc, Chars => Name_T);
748
749             begin
750                Rewrite (N,
751                  Make_Block_Statement (Loc,
752                   Declarations => New_List (
753                     Make_Object_Declaration (Loc,
754                       Defining_Identifier => T,
755                       Constant_Present  => True,
756                       Object_Definition =>
757                         New_Occurrence_Of (Etype (Rhs), Loc),
758                       Expression        => Relocate_Node (Rhs))),
759
760                     Handled_Statement_Sequence =>
761                       Make_Handled_Sequence_Of_Statements (Loc,
762                         Statements => New_List (
763                           Make_Assignment_Statement (Loc,
764                             Name       => Relocate_Node (Lhs),
765                             Expression => New_Occurrence_Of (T, Loc))))));
766             end;
767
768          --  Case of both are false with implicit conditionals allowed
769
770          else
771             --  Before we generate this code, we must ensure that the
772             --  left and right side array types are defined. They may
773             --  be itypes, and we cannot let them be defined inside the
774             --  if, since the first use in the then may not be executed.
775
776             Ensure_Defined (L_Type, N);
777             Ensure_Defined (R_Type, N);
778
779             --  We normally compare addresses to find out which way round
780             --  to do the loop, since this is realiable, and handles the
781             --  cases of parameters, conversions etc. But we can't do that
782             --  in the bit packed case or the Java VM case, because addresses
783             --  don't work there.
784
785             if not Is_Bit_Packed_Array (L_Type) and then not Java_VM then
786                Condition :=
787                  Make_Op_Le (Loc,
788                    Left_Opnd =>
789                      Unchecked_Convert_To (RTE (RE_Integer_Address),
790                        Make_Attribute_Reference (Loc,
791                          Prefix =>
792                            Make_Indexed_Component (Loc,
793                              Prefix =>
794                                Duplicate_Subexpr_Move_Checks (Larray, True),
795                              Expressions => New_List (
796                                Make_Attribute_Reference (Loc,
797                                  Prefix =>
798                                    New_Reference_To
799                                      (L_Index_Typ, Loc),
800                                  Attribute_Name => Name_First))),
801                          Attribute_Name => Name_Address)),
802
803                    Right_Opnd =>
804                      Unchecked_Convert_To (RTE (RE_Integer_Address),
805                        Make_Attribute_Reference (Loc,
806                          Prefix =>
807                            Make_Indexed_Component (Loc,
808                              Prefix =>
809                                Duplicate_Subexpr_Move_Checks (Rarray, True),
810                              Expressions => New_List (
811                                Make_Attribute_Reference (Loc,
812                                  Prefix =>
813                                    New_Reference_To
814                                      (R_Index_Typ, Loc),
815                                  Attribute_Name => Name_First))),
816                          Attribute_Name => Name_Address)));
817
818             --  For the bit packed and Java VM cases we use the bounds.
819             --  That's OK, because we don't have to worry about parameters,
820             --  since they cannot cause overlap. Perhaps we should worry
821             --  about weird slice conversions ???
822
823             else
824                --  Copy the bounds and reset the Analyzed flag, because the
825                --  bounds of the index type itself may be universal, and must
826                --  must be reaanalyzed to acquire the proper type for Gigi.
827
828                Cleft_Lo  := New_Copy_Tree (Left_Lo);
829                Cright_Lo := New_Copy_Tree (Right_Lo);
830                Set_Analyzed (Cleft_Lo, False);
831                Set_Analyzed (Cright_Lo, False);
832
833                Condition :=
834                  Make_Op_Le (Loc,
835                    Left_Opnd  => Cleft_Lo,
836                    Right_Opnd => Cright_Lo);
837             end if;
838
839             if Controlled_Type (Component_Type (L_Type))
840               and then Base_Type (L_Type) = Base_Type (R_Type)
841               and then Ndim = 1
842               and then not No_Ctrl_Actions (N)
843             then
844
845                --  Call TSS procedure for array assignment, passing the
846                --  the explicit bounds of right and left hand sides.
847
848                declare
849                   Proc    : constant Node_Id :=
850                               TSS (Base_Type (L_Type), TSS_Slice_Assign);
851                   Actuals : List_Id;
852
853                begin
854                   Apply_Dereference (Larray);
855                   Apply_Dereference (Rarray);
856                   Actuals := New_List (
857                     Duplicate_Subexpr (Larray,   Name_Req => True),
858                     Duplicate_Subexpr (Rarray,   Name_Req => True),
859                     Duplicate_Subexpr (Left_Lo,  Name_Req => True),
860                     Duplicate_Subexpr (Left_Hi,  Name_Req => True),
861                     Duplicate_Subexpr (Right_Lo, Name_Req => True),
862                     Duplicate_Subexpr (Right_Hi, Name_Req => True));
863
864                   Append_To (Actuals,
865                      Make_Op_Not (Loc,
866                        Right_Opnd => Condition));
867
868                   Rewrite (N,
869                     Make_Procedure_Call_Statement (Loc,
870                       Name => New_Reference_To (Proc, Loc),
871                       Parameter_Associations => Actuals));
872                end;
873
874             else
875                Rewrite (N,
876                  Make_Implicit_If_Statement (N,
877                    Condition => Condition,
878
879                    Then_Statements => New_List (
880                      Expand_Assign_Array_Loop
881                       (N, Larray, Rarray, L_Type, R_Type, Ndim,
882                        Rev => False)),
883
884                    Else_Statements => New_List (
885                      Expand_Assign_Array_Loop
886                       (N, Larray, Rarray, L_Type, R_Type, Ndim,
887                        Rev => True))));
888             end if;
889          end if;
890
891          Analyze (N, Suppress => All_Checks);
892       end;
893
894    exception
895       when RE_Not_Available =>
896          return;
897    end Expand_Assign_Array;
898
899    ------------------------------
900    -- Expand_Assign_Array_Loop --
901    ------------------------------
902
903    --  The following is an example of the loop generated for the case of
904    --  a two-dimensional array:
905
906    --    declare
907    --       R2b : Tm1X1 := 1;
908    --    begin
909    --       for L1b in 1 .. 100 loop
910    --          declare
911    --             R4b : Tm1X2 := 1;
912    --          begin
913    --             for L3b in 1 .. 100 loop
914    --                vm1 (L1b, L3b) := vm2 (R2b, R4b);
915    --                R4b := Tm1X2'succ(R4b);
916    --             end loop;
917    --          end;
918    --          R2b := Tm1X1'succ(R2b);
919    --       end loop;
920    --    end;
921
922    --  Here Rev is False, and Tm1Xn are the subscript types for the right
923    --  hand side. The declarations of R2b and R4b are inserted before the
924    --  original assignment statement.
925
926    function Expand_Assign_Array_Loop
927      (N      : Node_Id;
928       Larray : Entity_Id;
929       Rarray : Entity_Id;
930       L_Type : Entity_Id;
931       R_Type : Entity_Id;
932       Ndim   : Pos;
933       Rev    : Boolean) return Node_Id
934    is
935       Loc  : constant Source_Ptr := Sloc (N);
936
937       Lnn : array (1 .. Ndim) of Entity_Id;
938       Rnn : array (1 .. Ndim) of Entity_Id;
939       --  Entities used as subscripts on left and right sides
940
941       L_Index_Type : array (1 .. Ndim) of Entity_Id;
942       R_Index_Type : array (1 .. Ndim) of Entity_Id;
943       --  Left and right index types
944
945       Assign : Node_Id;
946
947       F_Or_L : Name_Id;
948       S_Or_P : Name_Id;
949
950    begin
951       if Rev then
952          F_Or_L := Name_Last;
953          S_Or_P := Name_Pred;
954       else
955          F_Or_L := Name_First;
956          S_Or_P := Name_Succ;
957       end if;
958
959       --  Setup index types and subscript entities
960
961       declare
962          L_Index : Node_Id;
963          R_Index : Node_Id;
964
965       begin
966          L_Index := First_Index (L_Type);
967          R_Index := First_Index (R_Type);
968
969          for J in 1 .. Ndim loop
970             Lnn (J) :=
971               Make_Defining_Identifier (Loc,
972                 Chars => New_Internal_Name ('L'));
973
974             Rnn (J) :=
975               Make_Defining_Identifier (Loc,
976                 Chars => New_Internal_Name ('R'));
977
978             L_Index_Type (J) := Etype (L_Index);
979             R_Index_Type (J) := Etype (R_Index);
980
981             Next_Index (L_Index);
982             Next_Index (R_Index);
983          end loop;
984       end;
985
986       --  Now construct the assignment statement
987
988       declare
989          ExprL : constant List_Id := New_List;
990          ExprR : constant List_Id := New_List;
991
992       begin
993          for J in 1 .. Ndim loop
994             Append_To (ExprL, New_Occurrence_Of (Lnn (J), Loc));
995             Append_To (ExprR, New_Occurrence_Of (Rnn (J), Loc));
996          end loop;
997
998          Assign :=
999            Make_Assignment_Statement (Loc,
1000              Name =>
1001                Make_Indexed_Component (Loc,
1002                  Prefix      => Duplicate_Subexpr (Larray, Name_Req => True),
1003                  Expressions => ExprL),
1004              Expression =>
1005                Make_Indexed_Component (Loc,
1006                  Prefix      => Duplicate_Subexpr (Rarray, Name_Req => True),
1007                  Expressions => ExprR));
1008
1009          --  We set assignment OK, since there are some cases, e.g. in object
1010          --  declarations, where we are actually assigning into a constant.
1011          --  If there really is an illegality, it was caught long before now,
1012          --  and was flagged when the original assignment was analyzed.
1013
1014          Set_Assignment_OK (Name (Assign));
1015
1016          --  Propagate the No_Ctrl_Actions flag to individual assignments
1017
1018          Set_No_Ctrl_Actions (Assign, No_Ctrl_Actions (N));
1019       end;
1020
1021       --  Now construct the loop from the inside out, with the last subscript
1022       --  varying most rapidly. Note that Assign is first the raw assignment
1023       --  statement, and then subsequently the loop that wraps it up.
1024
1025       for J in reverse 1 .. Ndim loop
1026          Assign :=
1027            Make_Block_Statement (Loc,
1028              Declarations => New_List (
1029               Make_Object_Declaration (Loc,
1030                 Defining_Identifier => Rnn (J),
1031                 Object_Definition =>
1032                   New_Occurrence_Of (R_Index_Type (J), Loc),
1033                 Expression =>
1034                   Make_Attribute_Reference (Loc,
1035                     Prefix => New_Occurrence_Of (R_Index_Type (J), Loc),
1036                     Attribute_Name => F_Or_L))),
1037
1038            Handled_Statement_Sequence =>
1039              Make_Handled_Sequence_Of_Statements (Loc,
1040                Statements => New_List (
1041                  Make_Implicit_Loop_Statement (N,
1042                    Iteration_Scheme =>
1043                      Make_Iteration_Scheme (Loc,
1044                        Loop_Parameter_Specification =>
1045                          Make_Loop_Parameter_Specification (Loc,
1046                            Defining_Identifier => Lnn (J),
1047                            Reverse_Present => Rev,
1048                            Discrete_Subtype_Definition =>
1049                              New_Reference_To (L_Index_Type (J), Loc))),
1050
1051                    Statements => New_List (
1052                      Assign,
1053
1054                      Make_Assignment_Statement (Loc,
1055                        Name => New_Occurrence_Of (Rnn (J), Loc),
1056                        Expression =>
1057                          Make_Attribute_Reference (Loc,
1058                            Prefix =>
1059                              New_Occurrence_Of (R_Index_Type (J), Loc),
1060                            Attribute_Name => S_Or_P,
1061                            Expressions => New_List (
1062                              New_Occurrence_Of (Rnn (J), Loc)))))))));
1063       end loop;
1064
1065       return Assign;
1066    end Expand_Assign_Array_Loop;
1067
1068    --------------------------
1069    -- Expand_Assign_Record --
1070    --------------------------
1071
1072    --  The only processing required is in the change of representation
1073    --  case, where we must expand the assignment to a series of field
1074    --  by field assignments.
1075
1076    procedure Expand_Assign_Record (N : Node_Id) is
1077       Lhs : constant Node_Id := Name (N);
1078       Rhs : Node_Id          := Expression (N);
1079
1080    begin
1081       --  If change of representation, then extract the real right hand
1082       --  side from the type conversion, and proceed with component-wise
1083       --  assignment, since the two types are not the same as far as the
1084       --  back end is concerned.
1085
1086       if Change_Of_Representation (N) then
1087          Rhs := Expression (Rhs);
1088
1089       --  If this may be a case of a large bit aligned component, then
1090       --  proceed with component-wise assignment, to avoid possible
1091       --  clobbering of other components sharing bits in the first or
1092       --  last byte of the component to be assigned.
1093
1094       elsif Possible_Bit_Aligned_Component (Lhs)
1095               or
1096             Possible_Bit_Aligned_Component (Rhs)
1097       then
1098          null;
1099
1100       --  If neither condition met, then nothing special to do, the back end
1101       --  can handle assignment of the entire component as a single entity.
1102
1103       else
1104          return;
1105       end if;
1106
1107       --  At this stage we know that we must do a component wise assignment
1108
1109       declare
1110          Loc   : constant Source_Ptr := Sloc (N);
1111          R_Typ : constant Entity_Id  := Base_Type (Etype (Rhs));
1112          L_Typ : constant Entity_Id  := Base_Type (Etype (Lhs));
1113          Decl  : constant Node_Id    := Declaration_Node (R_Typ);
1114          RDef  : Node_Id;
1115          F     : Entity_Id;
1116
1117          function Find_Component
1118            (Typ  : Entity_Id;
1119             Comp : Entity_Id) return Entity_Id;
1120          --  Find the component with the given name in the underlying record
1121          --  declaration for Typ. We need to use the actual entity because
1122          --  the type may be private and resolution by identifier alone would
1123          --  fail.
1124
1125          function Make_Component_List_Assign
1126            (CL  : Node_Id;
1127             U_U : Boolean := False) return List_Id;
1128          --  Returns a sequence of statements to assign the components that
1129          --  are referenced in the given component list. The flag U_U is
1130          --  used to force the usage of the inferred value of the variant
1131          --  part expression as the switch for the generated case statement.
1132
1133          function Make_Field_Assign
1134            (C : Entity_Id;
1135             U_U : Boolean := False) return Node_Id;
1136          --  Given C, the entity for a discriminant or component, build an
1137          --  assignment for the corresponding field values. The flag U_U
1138          --  signals the presence of an Unchecked_Union and forces the usage
1139          --  of the inferred discriminant value of C as the right hand side
1140          --  of the assignment.
1141
1142          function Make_Field_Assigns (CI : List_Id) return List_Id;
1143          --  Given CI, a component items list, construct series of statements
1144          --  for fieldwise assignment of the corresponding components.
1145
1146          --------------------
1147          -- Find_Component --
1148          --------------------
1149
1150          function Find_Component
1151            (Typ  : Entity_Id;
1152             Comp : Entity_Id) return Entity_Id
1153          is
1154             Utyp : constant Entity_Id := Underlying_Type (Typ);
1155             C    : Entity_Id;
1156
1157          begin
1158             C := First_Entity (Utyp);
1159
1160             while Present (C) loop
1161                if Chars (C) = Chars (Comp) then
1162                   return C;
1163                end if;
1164                Next_Entity (C);
1165             end loop;
1166
1167             raise Program_Error;
1168          end Find_Component;
1169
1170          --------------------------------
1171          -- Make_Component_List_Assign --
1172          --------------------------------
1173
1174          function Make_Component_List_Assign
1175            (CL  : Node_Id;
1176             U_U : Boolean := False) return List_Id
1177          is
1178             CI : constant List_Id := Component_Items (CL);
1179             VP : constant Node_Id := Variant_Part (CL);
1180
1181             Alts   : List_Id;
1182             DC     : Node_Id;
1183             DCH    : List_Id;
1184             Expr   : Node_Id;
1185             Result : List_Id;
1186             V      : Node_Id;
1187
1188          begin
1189             Result := Make_Field_Assigns (CI);
1190
1191             if Present (VP) then
1192
1193                V := First_Non_Pragma (Variants (VP));
1194                Alts := New_List;
1195                while Present (V) loop
1196
1197                   DCH := New_List;
1198                   DC := First (Discrete_Choices (V));
1199                   while Present (DC) loop
1200                      Append_To (DCH, New_Copy_Tree (DC));
1201                      Next (DC);
1202                   end loop;
1203
1204                   Append_To (Alts,
1205                     Make_Case_Statement_Alternative (Loc,
1206                       Discrete_Choices => DCH,
1207                       Statements =>
1208                         Make_Component_List_Assign (Component_List (V))));
1209                   Next_Non_Pragma (V);
1210                end loop;
1211
1212                --  If we have an Unchecked_Union, use the value of the inferred
1213                --  discriminant of the variant part expression as the switch
1214                --  for the case statement. The case statement may later be
1215                --  folded.
1216
1217                if U_U then
1218                   Expr :=
1219                     New_Copy (Get_Discriminant_Value (
1220                       Entity (Name (VP)),
1221                       Etype (Rhs),
1222                       Discriminant_Constraint (Etype (Rhs))));
1223                else
1224                   Expr :=
1225                     Make_Selected_Component (Loc,
1226                       Prefix => Duplicate_Subexpr (Rhs),
1227                       Selector_Name =>
1228                         Make_Identifier (Loc, Chars (Name (VP))));
1229                end if;
1230
1231                Append_To (Result,
1232                  Make_Case_Statement (Loc,
1233                    Expression => Expr,
1234                    Alternatives => Alts));
1235             end if;
1236
1237             return Result;
1238          end Make_Component_List_Assign;
1239
1240          -----------------------
1241          -- Make_Field_Assign --
1242          -----------------------
1243
1244          function Make_Field_Assign
1245            (C : Entity_Id;
1246             U_U : Boolean := False) return Node_Id
1247          is
1248             A    : Node_Id;
1249             Expr : Node_Id;
1250
1251          begin
1252             --  In the case of an Unchecked_Union, use the discriminant
1253             --  constraint value as on the right hand side of the assignment.
1254
1255             if U_U then
1256                Expr :=
1257                  New_Copy (Get_Discriminant_Value (C,
1258                    Etype (Rhs),
1259                    Discriminant_Constraint (Etype (Rhs))));
1260             else
1261                Expr :=
1262                  Make_Selected_Component (Loc,
1263                    Prefix => Duplicate_Subexpr (Rhs),
1264                    Selector_Name => New_Occurrence_Of (C, Loc));
1265             end if;
1266
1267             A :=
1268               Make_Assignment_Statement (Loc,
1269                 Name =>
1270                   Make_Selected_Component (Loc,
1271                     Prefix => Duplicate_Subexpr (Lhs),
1272                     Selector_Name =>
1273                       New_Occurrence_Of (Find_Component (L_Typ, C), Loc)),
1274                 Expression => Expr);
1275
1276             --  Set Assignment_OK, so discriminants can be assigned
1277
1278             Set_Assignment_OK (Name (A), True);
1279             return A;
1280          end Make_Field_Assign;
1281
1282          ------------------------
1283          -- Make_Field_Assigns --
1284          ------------------------
1285
1286          function Make_Field_Assigns (CI : List_Id) return List_Id is
1287             Item   : Node_Id;
1288             Result : List_Id;
1289
1290          begin
1291             Item := First (CI);
1292             Result := New_List;
1293             while Present (Item) loop
1294                if Nkind (Item) = N_Component_Declaration then
1295                   Append_To
1296                     (Result, Make_Field_Assign (Defining_Identifier (Item)));
1297                end if;
1298
1299                Next (Item);
1300             end loop;
1301
1302             return Result;
1303          end Make_Field_Assigns;
1304
1305       --  Start of processing for Expand_Assign_Record
1306
1307       begin
1308          --  Note that we use the base types for this processing. This results
1309          --  in some extra work in the constrained case, but the change of
1310          --  representation case is so unusual that it is not worth the effort.
1311
1312          --  First copy the discriminants. This is done unconditionally. It
1313          --  is required in the unconstrained left side case, and also in the
1314          --  case where this assignment was constructed during the expansion
1315          --  of a type conversion (since initialization of discriminants is
1316          --  suppressed in this case). It is unnecessary but harmless in
1317          --  other cases.
1318
1319          if Has_Discriminants (L_Typ) then
1320             F := First_Discriminant (R_Typ);
1321             while Present (F) loop
1322
1323                if Is_Unchecked_Union (Base_Type (R_Typ)) then
1324                   Insert_Action (N, Make_Field_Assign (F, True));
1325                else
1326                   Insert_Action (N, Make_Field_Assign (F));
1327                end if;
1328
1329                Next_Discriminant (F);
1330             end loop;
1331          end if;
1332
1333          --  We know the underlying type is a record, but its current view
1334          --  may be private. We must retrieve the usable record declaration.
1335
1336          if Nkind (Decl) = N_Private_Type_Declaration
1337            and then Present (Full_View (R_Typ))
1338          then
1339             RDef := Type_Definition (Declaration_Node (Full_View (R_Typ)));
1340          else
1341             RDef := Type_Definition (Decl);
1342          end if;
1343
1344          if Nkind (RDef) = N_Record_Definition
1345            and then Present (Component_List (RDef))
1346          then
1347
1348             if Is_Unchecked_Union (R_Typ) then
1349                Insert_Actions (N,
1350                  Make_Component_List_Assign (Component_List (RDef), True));
1351             else
1352                Insert_Actions
1353                  (N, Make_Component_List_Assign (Component_List (RDef)));
1354             end if;
1355
1356             Rewrite (N, Make_Null_Statement (Loc));
1357          end if;
1358
1359       end;
1360    end Expand_Assign_Record;
1361
1362    -----------------------------------
1363    -- Expand_N_Assignment_Statement --
1364    -----------------------------------
1365
1366    --  This procedure implements various cases where an assignment statement
1367    --  cannot just be passed on to the back end in untransformed state.
1368
1369    procedure Expand_N_Assignment_Statement (N : Node_Id) is
1370       Loc  : constant Source_Ptr := Sloc (N);
1371       Lhs  : constant Node_Id    := Name (N);
1372       Rhs  : constant Node_Id    := Expression (N);
1373       Typ  : constant Entity_Id  := Underlying_Type (Etype (Lhs));
1374       Exp  : Node_Id;
1375
1376    begin
1377       --  First deal with generation of range check if required. For now
1378       --  we do this only for discrete types.
1379
1380       if Do_Range_Check (Rhs)
1381         and then Is_Discrete_Type (Typ)
1382       then
1383          Set_Do_Range_Check (Rhs, False);
1384          Generate_Range_Check (Rhs, Typ, CE_Range_Check_Failed);
1385       end if;
1386
1387       --  Check for a special case where a high level transformation is
1388       --  required. If we have either of:
1389
1390       --    P.field := rhs;
1391       --    P (sub) := rhs;
1392
1393       --  where P is a reference to a bit packed array, then we have to unwind
1394       --  the assignment. The exact meaning of being a reference to a bit
1395       --  packed array is as follows:
1396
1397       --    An indexed component whose prefix is a bit packed array is a
1398       --     reference to a bit packed array.
1399
1400       --    An indexed component or selected component whose prefix is a
1401       --     reference to a bit packed array is itself a reference ot a
1402       --     bit packed array.
1403
1404       --  The required transformation is
1405
1406       --     Tnn : prefix_type := P;
1407       --     Tnn.field := rhs;
1408       --     P := Tnn;
1409
1410       --  or
1411
1412       --     Tnn : prefix_type := P;
1413       --     Tnn (subscr) := rhs;
1414       --     P := Tnn;
1415
1416       --  Since P is going to be evaluated more than once, any subscripts
1417       --  in P must have their evaluation forced.
1418
1419       if (Nkind (Lhs) = N_Indexed_Component
1420            or else
1421           Nkind (Lhs) = N_Selected_Component)
1422         and then Is_Ref_To_Bit_Packed_Array (Prefix (Lhs))
1423       then
1424          declare
1425             BPAR_Expr : constant Node_Id   := Relocate_Node (Prefix (Lhs));
1426             BPAR_Typ  : constant Entity_Id := Etype (BPAR_Expr);
1427             Tnn       : constant Entity_Id :=
1428                           Make_Defining_Identifier (Loc,
1429                             Chars => New_Internal_Name ('T'));
1430
1431          begin
1432             --  Insert the post assignment first, because we want to copy
1433             --  the BPAR_Expr tree before it gets analyzed in the context
1434             --  of the pre assignment. Note that we do not analyze the
1435             --  post assignment yet (we cannot till we have completed the
1436             --  analysis of the pre assignment). As usual, the analysis
1437             --  of this post assignment will happen on its own when we
1438             --  "run into" it after finishing the current assignment.
1439
1440             Insert_After (N,
1441               Make_Assignment_Statement (Loc,
1442                 Name       => New_Copy_Tree (BPAR_Expr),
1443                 Expression => New_Occurrence_Of (Tnn, Loc)));
1444
1445             --  At this stage BPAR_Expr is a reference to a bit packed
1446             --  array where the reference was not expanded in the original
1447             --  tree, since it was on the left side of an assignment. But
1448             --  in the pre-assignment statement (the object definition),
1449             --  BPAR_Expr will end up on the right hand side, and must be
1450             --  reexpanded. To achieve this, we reset the analyzed flag
1451             --  of all selected and indexed components down to the actual
1452             --  indexed component for the packed array.
1453
1454             Exp := BPAR_Expr;
1455             loop
1456                Set_Analyzed (Exp, False);
1457
1458                if Nkind (Exp) = N_Selected_Component
1459                     or else
1460                   Nkind (Exp) = N_Indexed_Component
1461                then
1462                   Exp := Prefix (Exp);
1463                else
1464                   exit;
1465                end if;
1466             end loop;
1467
1468             --  Now we can insert and analyze the pre-assignment
1469
1470             --  If the right-hand side requires a transient scope, it has
1471             --  already been placed on the stack. However, the declaration is
1472             --  inserted in the tree outside of this scope, and must reflect
1473             --  the proper scope for its variable. This awkward bit is forced
1474             --  by the stricter scope discipline imposed by GCC 2.97.
1475
1476             declare
1477                Uses_Transient_Scope : constant Boolean :=
1478                                         Scope_Is_Transient
1479                                           and then N = Node_To_Be_Wrapped;
1480
1481             begin
1482                if Uses_Transient_Scope then
1483                   New_Scope (Scope (Current_Scope));
1484                end if;
1485
1486                Insert_Before_And_Analyze (N,
1487                  Make_Object_Declaration (Loc,
1488                    Defining_Identifier => Tnn,
1489                    Object_Definition   => New_Occurrence_Of (BPAR_Typ, Loc),
1490                    Expression          => BPAR_Expr));
1491
1492                if Uses_Transient_Scope then
1493                   Pop_Scope;
1494                end if;
1495             end;
1496
1497             --  Now fix up the original assignment and continue processing
1498
1499             Rewrite (Prefix (Lhs),
1500               New_Occurrence_Of (Tnn, Loc));
1501
1502             --  We do not need to reanalyze that assignment, and we do not need
1503             --  to worry about references to the temporary, but we do need to
1504             --  make sure that the temporary is not marked as a true constant
1505             --  since we now have a generate assignment to it!
1506
1507             Set_Is_True_Constant (Tnn, False);
1508          end;
1509       end if;
1510
1511       --  When we have the appropriate type of aggregate in the
1512       --  expression (it has been determined during analysis of the
1513       --  aggregate by setting the delay flag), let's perform in place
1514       --  assignment and thus avoid creating a temporay.
1515
1516       if Is_Delayed_Aggregate (Rhs) then
1517          Convert_Aggr_In_Assignment (N);
1518          Rewrite (N, Make_Null_Statement (Loc));
1519          Analyze (N);
1520          return;
1521       end if;
1522
1523       --  Apply discriminant check if required. If Lhs is an access type
1524       --  to a designated type with discriminants, we must always check.
1525
1526       if Has_Discriminants (Etype (Lhs)) then
1527
1528          --  Skip discriminant check if change of representation. Will be
1529          --  done when the change of representation is expanded out.
1530
1531          if not Change_Of_Representation (N) then
1532             Apply_Discriminant_Check (Rhs, Etype (Lhs), Lhs);
1533          end if;
1534
1535       --  If the type is private without discriminants, and the full type
1536       --  has discriminants (necessarily with defaults) a check may still be
1537       --  necessary if the Lhs is aliased. The private determinants must be
1538       --  visible to build the discriminant constraints.
1539
1540       --  Only an explicit dereference that comes from source indicates
1541       --  aliasing. Access to formals of protected operations and entries
1542       --  create dereferences but are not semantic aliasings.
1543
1544       elsif Is_Private_Type (Etype (Lhs))
1545         and then  Has_Discriminants (Typ)
1546         and then Nkind (Lhs) = N_Explicit_Dereference
1547         and then Comes_From_Source (Lhs)
1548       then
1549          declare
1550             Lt : constant Entity_Id := Etype (Lhs);
1551          begin
1552             Set_Etype (Lhs, Typ);
1553             Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
1554             Apply_Discriminant_Check (Rhs, Typ, Lhs);
1555             Set_Etype (Lhs, Lt);
1556          end;
1557
1558          --  If the Lhs has a private type with unknown discriminants, it
1559          --  may have a full view with discriminants, but those are nameable
1560          --  only in the underlying type, so convert the Rhs to it before
1561          --  potential checking.
1562
1563       elsif Has_Unknown_Discriminants (Base_Type (Etype (Lhs)))
1564         and then Has_Discriminants (Typ)
1565       then
1566          Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
1567          Apply_Discriminant_Check (Rhs, Typ, Lhs);
1568
1569       --  In the access type case, we need the same discriminant check,
1570       --  and also range checks if we have an access to constrained array.
1571
1572       elsif Is_Access_Type (Etype (Lhs))
1573         and then Is_Constrained (Designated_Type (Etype (Lhs)))
1574       then
1575          if Has_Discriminants (Designated_Type (Etype (Lhs))) then
1576
1577             --  Skip discriminant check if change of representation. Will be
1578             --  done when the change of representation is expanded out.
1579
1580             if not Change_Of_Representation (N) then
1581                Apply_Discriminant_Check (Rhs, Etype (Lhs));
1582             end if;
1583
1584          elsif Is_Array_Type (Designated_Type (Etype (Lhs))) then
1585             Apply_Range_Check (Rhs, Etype (Lhs));
1586
1587             if Is_Constrained (Etype (Lhs)) then
1588                Apply_Length_Check (Rhs, Etype (Lhs));
1589             end if;
1590
1591             if Nkind (Rhs) = N_Allocator then
1592                declare
1593                   Target_Typ : constant Entity_Id := Etype (Expression (Rhs));
1594                   C_Es       : Check_Result;
1595
1596                begin
1597                   C_Es :=
1598                     Range_Check
1599                       (Lhs,
1600                        Target_Typ,
1601                        Etype (Designated_Type (Etype (Lhs))));
1602
1603                   Insert_Range_Checks
1604                     (C_Es,
1605                      N,
1606                      Target_Typ,
1607                      Sloc (Lhs),
1608                      Lhs);
1609                end;
1610             end if;
1611          end if;
1612
1613       --  Apply range check for access type case
1614
1615       elsif Is_Access_Type (Etype (Lhs))
1616         and then Nkind (Rhs) = N_Allocator
1617         and then Nkind (Expression (Rhs)) = N_Qualified_Expression
1618       then
1619          Analyze_And_Resolve (Expression (Rhs));
1620          Apply_Range_Check
1621            (Expression (Rhs), Designated_Type (Etype (Lhs)));
1622       end if;
1623
1624       --  Ada 2005 (AI-231): Generate conversion to the null-excluding
1625       --  type to force the corresponding run-time check
1626
1627       if Is_Access_Type (Typ)
1628         and then
1629           ((Is_Entity_Name (Lhs) and then Can_Never_Be_Null (Entity (Lhs)))
1630              or else Can_Never_Be_Null (Etype (Lhs)))
1631       then
1632          Rewrite (Rhs, Convert_To (Etype (Lhs),
1633                                    Relocate_Node (Rhs)));
1634          Analyze_And_Resolve (Rhs, Etype (Lhs));
1635       end if;
1636
1637       --  If we are assigning an access type and the left side is an
1638       --  entity, then make sure that Is_Known_Non_Null properly
1639       --  reflects the state of the entity after the assignment
1640
1641       if Is_Access_Type (Typ)
1642         and then Is_Entity_Name (Lhs)
1643         and then Known_Non_Null (Rhs)
1644         and then Safe_To_Capture_Value (N, Entity (Lhs))
1645       then
1646          Set_Is_Known_Non_Null (Entity (Lhs), Known_Non_Null (Rhs));
1647       end if;
1648
1649       --  Case of assignment to a bit packed array element
1650
1651       if Nkind (Lhs) = N_Indexed_Component
1652         and then Is_Bit_Packed_Array (Etype (Prefix (Lhs)))
1653       then
1654          Expand_Bit_Packed_Element_Set (N);
1655          return;
1656
1657       elsif Is_Tagged_Type (Typ)
1658         or else (Controlled_Type (Typ) and then not Is_Array_Type (Typ))
1659       then
1660          Tagged_Case : declare
1661             L                   : List_Id := No_List;
1662             Expand_Ctrl_Actions : constant Boolean := not No_Ctrl_Actions (N);
1663
1664          begin
1665             --  In the controlled case, we need to make sure that function
1666             --  calls are evaluated before finalizing the target. In all
1667             --  cases, it makes the expansion easier if the side-effects
1668             --  are removed first.
1669
1670             Remove_Side_Effects (Lhs);
1671             Remove_Side_Effects (Rhs);
1672
1673             --  Avoid recursion in the mechanism
1674
1675             Set_Analyzed (N);
1676
1677             --  If dispatching assignment, we need to dispatch to _assign
1678
1679             if Is_Class_Wide_Type (Typ)
1680
1681                --  If the type is tagged, we may as well use the predefined
1682                --  primitive assignment. This avoids inlining a lot of code
1683                --  and in the class-wide case, the assignment is replaced by
1684                --  dispatch call to _assign. Note that this cannot be done
1685                --  when discriminant checks are locally suppressed (as in
1686                --  extension aggregate expansions) because otherwise the
1687                --  discriminant check will be performed within the _assign
1688                --  call. It is also suppressed for assignmments created by the
1689                --  expander that correspond to initializations, where we do
1690                --  want to copy the tag (No_Ctrl_Actions flag set True).
1691                --  by the expander and we do not need to mess with tags ever
1692                --  (Expand_Ctrl_Actions flag is set True in this case).
1693
1694                or else (Is_Tagged_Type (Typ)
1695                           and then Chars (Current_Scope) /= Name_uAssign
1696                           and then Expand_Ctrl_Actions
1697                           and then not Discriminant_Checks_Suppressed (Empty))
1698             then
1699                --  Fetch the primitive op _assign and proper type to call
1700                --  it. Because of possible conflits between private and
1701                --  full view the proper type is fetched directly from the
1702                --  operation profile.
1703
1704                declare
1705                   Op    : constant Entity_Id :=
1706                             Find_Prim_Op (Typ, Name_uAssign);
1707                   F_Typ : Entity_Id := Etype (First_Formal (Op));
1708
1709                begin
1710                   --  If the assignment is dispatching, make sure to use the
1711                   --  ??? where is rest of this comment ???
1712
1713                   if Is_Class_Wide_Type (Typ) then
1714                      F_Typ := Class_Wide_Type (F_Typ);
1715                   end if;
1716
1717                   L := New_List (
1718                     Make_Procedure_Call_Statement (Loc,
1719                       Name => New_Reference_To (Op, Loc),
1720                       Parameter_Associations => New_List (
1721                         Unchecked_Convert_To (F_Typ, Duplicate_Subexpr (Lhs)),
1722                         Unchecked_Convert_To (F_Typ,
1723                           Duplicate_Subexpr (Rhs)))));
1724                end;
1725
1726             else
1727                L := Make_Tag_Ctrl_Assignment (N);
1728
1729                --  We can't afford to have destructive Finalization Actions
1730                --  in the Self assignment case, so if the target and the
1731                --  source are not obviously different, code is generated to
1732                --  avoid the self assignment case
1733                --
1734                --    if lhs'address /= rhs'address then
1735                --       <code for controlled and/or tagged assignment>
1736                --    end if;
1737
1738                if not Statically_Different (Lhs, Rhs)
1739                  and then Expand_Ctrl_Actions
1740                then
1741                   L := New_List (
1742                     Make_Implicit_If_Statement (N,
1743                       Condition =>
1744                         Make_Op_Ne (Loc,
1745                           Left_Opnd =>
1746                             Make_Attribute_Reference (Loc,
1747                               Prefix         => Duplicate_Subexpr (Lhs),
1748                               Attribute_Name => Name_Address),
1749
1750                            Right_Opnd =>
1751                             Make_Attribute_Reference (Loc,
1752                               Prefix         => Duplicate_Subexpr (Rhs),
1753                               Attribute_Name => Name_Address)),
1754
1755                       Then_Statements => L));
1756                end if;
1757
1758                --  We need to set up an exception handler for implementing
1759                --  7.6.1 (18). The remaining adjustments are tackled by the
1760                --  implementation of adjust for record_controllers (see
1761                --  s-finimp.adb)
1762
1763                --  This is skipped if we have no finalization
1764
1765                if Expand_Ctrl_Actions
1766                  and then not Restriction_Active (No_Finalization)
1767                then
1768                   L := New_List (
1769                     Make_Block_Statement (Loc,
1770                       Handled_Statement_Sequence =>
1771                         Make_Handled_Sequence_Of_Statements (Loc,
1772                           Statements => L,
1773                           Exception_Handlers => New_List (
1774                             Make_Exception_Handler (Loc,
1775                               Exception_Choices =>
1776                                 New_List (Make_Others_Choice (Loc)),
1777                               Statements        => New_List (
1778                                 Make_Raise_Program_Error (Loc,
1779                                   Reason =>
1780                                     PE_Finalize_Raised_Exception)
1781                               ))))));
1782                end if;
1783             end if;
1784
1785             Rewrite (N,
1786               Make_Block_Statement (Loc,
1787                 Handled_Statement_Sequence =>
1788                   Make_Handled_Sequence_Of_Statements (Loc, Statements => L)));
1789
1790             --  If no restrictions on aborts, protect the whole assignement
1791             --  for controlled objects as per 9.8(11)
1792
1793             if Controlled_Type (Typ)
1794               and then Expand_Ctrl_Actions
1795               and then Abort_Allowed
1796             then
1797                declare
1798                   Blk : constant Entity_Id :=
1799                           New_Internal_Entity
1800                             (E_Block, Current_Scope, Sloc (N), 'B');
1801
1802                begin
1803                   Set_Scope (Blk, Current_Scope);
1804                   Set_Etype (Blk, Standard_Void_Type);
1805                   Set_Identifier (N, New_Occurrence_Of (Blk, Sloc (N)));
1806
1807                   Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
1808                   Set_At_End_Proc (Handled_Statement_Sequence (N),
1809                     New_Occurrence_Of (RTE (RE_Abort_Undefer_Direct), Loc));
1810                   Expand_At_End_Handler
1811                     (Handled_Statement_Sequence (N), Blk);
1812                end;
1813             end if;
1814
1815             Analyze (N);
1816             return;
1817          end Tagged_Case;
1818
1819       --  Array types
1820
1821       elsif Is_Array_Type (Typ) then
1822          declare
1823             Actual_Rhs : Node_Id := Rhs;
1824
1825          begin
1826             while Nkind (Actual_Rhs) = N_Type_Conversion
1827               or else
1828                   Nkind (Actual_Rhs) = N_Qualified_Expression
1829             loop
1830                Actual_Rhs := Expression (Actual_Rhs);
1831             end loop;
1832
1833             Expand_Assign_Array (N, Actual_Rhs);
1834             return;
1835          end;
1836
1837       --  Record types
1838
1839       elsif Is_Record_Type (Typ) then
1840          Expand_Assign_Record (N);
1841          return;
1842
1843       --  Scalar types. This is where we perform the processing related
1844       --  to the requirements of (RM 13.9.1(9-11)) concerning the handling
1845       --  of invalid scalar values.
1846
1847       elsif Is_Scalar_Type (Typ) then
1848
1849          --  Case where right side is known valid
1850
1851          if Expr_Known_Valid (Rhs) then
1852
1853             --  Here the right side is valid, so it is fine. The case to
1854             --  deal with is when the left side is a local variable reference
1855             --  whose value is not currently known to be valid. If this is
1856             --  the case, and the assignment appears in an unconditional
1857             --  context, then we can mark the left side as now being valid.
1858
1859             if Is_Local_Variable_Reference (Lhs)
1860               and then not Is_Known_Valid (Entity (Lhs))
1861               and then In_Unconditional_Context (N)
1862             then
1863                Set_Is_Known_Valid (Entity (Lhs), True);
1864             end if;
1865
1866          --  Case where right side may be invalid in the sense of the RM
1867          --  reference above. The RM does not require that we check for
1868          --  the validity on an assignment, but it does require that the
1869          --  assignment of an invalid value not cause erroneous behavior.
1870
1871          --  The general approach in GNAT is to use the Is_Known_Valid flag
1872          --  to avoid the need for validity checking on assignments. However
1873          --  in some cases, we have to do validity checking in order to make
1874          --  sure that the setting of this flag is correct.
1875
1876          else
1877             --  Validate right side if we are validating copies
1878
1879             if Validity_Checks_On
1880                and then Validity_Check_Copies
1881             then
1882                Ensure_Valid (Rhs);
1883
1884                --  We can propagate this to the left side where appropriate
1885
1886                if Is_Local_Variable_Reference (Lhs)
1887                  and then not Is_Known_Valid (Entity (Lhs))
1888                  and then In_Unconditional_Context (N)
1889                then
1890                   Set_Is_Known_Valid (Entity (Lhs), True);
1891                end if;
1892
1893             --  Otherwise check to see what should be done
1894
1895             --  If left side is a local variable, then we just set its
1896             --  flag to indicate that its value may no longer be valid,
1897             --  since we are copying a potentially invalid value.
1898
1899             elsif Is_Local_Variable_Reference (Lhs) then
1900                Set_Is_Known_Valid (Entity (Lhs), False);
1901
1902             --  Check for case of a nonlocal variable on the left side
1903             --  which is currently known to be valid. In this case, we
1904             --  simply ensure that the right side is valid. We only play
1905             --  the game of copying validity status for local variables,
1906             --  since we are doing this statically, not by tracing the
1907             --  full flow graph.
1908
1909             elsif Is_Entity_Name (Lhs)
1910               and then Is_Known_Valid (Entity (Lhs))
1911             then
1912                --  Note that the Ensure_Valid call is ignored if the
1913                --  Validity_Checking mode is set to none so we do not
1914                --  need to worry about that case here.
1915
1916                Ensure_Valid (Rhs);
1917
1918             --  In all other cases, we can safely copy an invalid value
1919             --  without worrying about the status of the left side. Since
1920             --  it is not a variable reference it will not be considered
1921             --  as being known to be valid in any case.
1922
1923             else
1924                null;
1925             end if;
1926          end if;
1927       end if;
1928
1929       --  Defend against invalid subscripts on left side if we are in
1930       --  standard validity checking mode. No need to do this if we
1931       --  are checking all subscripts.
1932
1933       if Validity_Checks_On
1934         and then Validity_Check_Default
1935         and then not Validity_Check_Subscripts
1936       then
1937          Check_Valid_Lvalue_Subscripts (Lhs);
1938       end if;
1939
1940    exception
1941       when RE_Not_Available =>
1942          return;
1943    end Expand_N_Assignment_Statement;
1944
1945    ------------------------------
1946    -- Expand_N_Block_Statement --
1947    ------------------------------
1948
1949    --  Encode entity names defined in block statement
1950
1951    procedure Expand_N_Block_Statement (N : Node_Id) is
1952    begin
1953       Qualify_Entity_Names (N);
1954    end Expand_N_Block_Statement;
1955
1956    -----------------------------
1957    -- Expand_N_Case_Statement --
1958    -----------------------------
1959
1960    procedure Expand_N_Case_Statement (N : Node_Id) is
1961       Loc    : constant Source_Ptr := Sloc (N);
1962       Expr   : constant Node_Id    := Expression (N);
1963       Alt    : Node_Id;
1964       Len    : Nat;
1965       Cond   : Node_Id;
1966       Choice : Node_Id;
1967       Chlist : List_Id;
1968
1969    begin
1970       --  Check for the situation where we know at compile time which
1971       --  branch will be taken
1972
1973       if Compile_Time_Known_Value (Expr) then
1974          Alt := Find_Static_Alternative (N);
1975
1976          --  Move the statements from this alternative after the case
1977          --  statement. They are already analyzed, so will be skipped
1978          --  by the analyzer.
1979
1980          Insert_List_After (N, Statements (Alt));
1981
1982          --  That leaves the case statement as a shell. The alternative
1983          --  that will be executed is reset to a null list. So now we can
1984          --  kill the entire case statement.
1985
1986          Kill_Dead_Code (Expression (N));
1987          Kill_Dead_Code (Alternatives (N));
1988          Rewrite (N, Make_Null_Statement (Loc));
1989          return;
1990       end if;
1991
1992       --  Here if the choice is not determined at compile time
1993
1994       declare
1995          Last_Alt : constant Node_Id := Last (Alternatives (N));
1996
1997          Others_Present : Boolean;
1998          Others_Node    : Node_Id;
1999
2000          Then_Stms : List_Id;
2001          Else_Stms : List_Id;
2002
2003       begin
2004          if Nkind (First (Discrete_Choices (Last_Alt))) = N_Others_Choice then
2005             Others_Present := True;
2006             Others_Node    := Last_Alt;
2007          else
2008             Others_Present := False;
2009          end if;
2010
2011          --  First step is to worry about possible invalid argument. The RM
2012          --  requires (RM 5.4(13)) that if the result is invalid (e.g. it is
2013          --  outside the base range), then Constraint_Error must be raised.
2014
2015          --  Case of validity check required (validity checks are on, the
2016          --  expression is not known to be valid, and the case statement
2017          --  comes from source -- no need to validity check internally
2018          --  generated case statements).
2019
2020          if Validity_Check_Default then
2021             Ensure_Valid (Expr);
2022          end if;
2023
2024          --  If there is only a single alternative, just replace it with
2025          --  the sequence of statements since obviously that is what is
2026          --  going to be executed in all cases.
2027
2028          Len := List_Length (Alternatives (N));
2029
2030          if Len = 1 then
2031             --  We still need to evaluate the expression if it has any
2032             --  side effects.
2033
2034             Remove_Side_Effects (Expression (N));
2035
2036             Insert_List_After (N, Statements (First (Alternatives (N))));
2037
2038             --  That leaves the case statement as a shell. The alternative
2039             --  that will be executed is reset to a null list. So now we can
2040             --  kill the entire case statement.
2041
2042             Kill_Dead_Code (Expression (N));
2043             Rewrite (N, Make_Null_Statement (Loc));
2044             return;
2045          end if;
2046
2047          --  An optimization. If there are only two alternatives, and only
2048          --  a single choice, then rewrite the whole case statement as an
2049          --  if statement, since this can result in susbequent optimizations.
2050          --  This helps not only with case statements in the source of a
2051          --  simple form, but also with generated code (discriminant check
2052          --  functions in particular)
2053
2054          if Len = 2 then
2055             Chlist := Discrete_Choices (First (Alternatives (N)));
2056
2057             if List_Length (Chlist) = 1 then
2058                Choice := First (Chlist);
2059
2060                Then_Stms := Statements (First (Alternatives (N)));
2061                Else_Stms := Statements (Last  (Alternatives (N)));
2062
2063                --  For TRUE, generate "expression", not expression = true
2064
2065                if Nkind (Choice) = N_Identifier
2066                  and then Entity (Choice) = Standard_True
2067                then
2068                   Cond := Expression (N);
2069
2070                --  For FALSE, generate "expression" and switch then/else
2071
2072                elsif Nkind (Choice) = N_Identifier
2073                  and then Entity (Choice) = Standard_False
2074                then
2075                   Cond := Expression (N);
2076                   Else_Stms := Statements (First (Alternatives (N)));
2077                   Then_Stms := Statements (Last  (Alternatives (N)));
2078
2079                --  For a range, generate "expression in range"
2080
2081                elsif Nkind (Choice) = N_Range
2082                  or else (Nkind (Choice) = N_Attribute_Reference
2083                            and then Attribute_Name (Choice) = Name_Range)
2084                  or else (Is_Entity_Name (Choice)
2085                            and then Is_Type (Entity (Choice)))
2086                  or else Nkind (Choice) = N_Subtype_Indication
2087                then
2088                   Cond :=
2089                     Make_In (Loc,
2090                       Left_Opnd  => Expression (N),
2091                       Right_Opnd => Relocate_Node (Choice));
2092
2093                --  For any other subexpression "expression = value"
2094
2095                else
2096                   Cond :=
2097                     Make_Op_Eq (Loc,
2098                       Left_Opnd  => Expression (N),
2099                       Right_Opnd => Relocate_Node (Choice));
2100                end if;
2101
2102                --  Now rewrite the case as an IF
2103
2104                Rewrite (N,
2105                  Make_If_Statement (Loc,
2106                    Condition => Cond,
2107                    Then_Statements => Then_Stms,
2108                    Else_Statements => Else_Stms));
2109                Analyze (N);
2110                return;
2111             end if;
2112          end if;
2113
2114          --  If the last alternative is not an Others choice, replace it
2115          --  with an N_Others_Choice. Note that we do not bother to call
2116          --  Analyze on the modified case statement, since it's only effect
2117          --  would be to compute the contents of the Others_Discrete_Choices
2118          --  which is not needed by the back end anyway.
2119
2120          --  The reason we do this is that the back end always needs some
2121          --  default for a switch, so if we have not supplied one in the
2122          --  processing above for validity checking, then we need to
2123          --  supply one here.
2124
2125          if not Others_Present then
2126             Others_Node := Make_Others_Choice (Sloc (Last_Alt));
2127             Set_Others_Discrete_Choices
2128               (Others_Node, Discrete_Choices (Last_Alt));
2129             Set_Discrete_Choices (Last_Alt, New_List (Others_Node));
2130          end if;
2131       end;
2132    end Expand_N_Case_Statement;
2133
2134    -----------------------------
2135    -- Expand_N_Exit_Statement --
2136    -----------------------------
2137
2138    --  The only processing required is to deal with a possible C/Fortran
2139    --  boolean value used as the condition for the exit statement.
2140
2141    procedure Expand_N_Exit_Statement (N : Node_Id) is
2142    begin
2143       Adjust_Condition (Condition (N));
2144    end Expand_N_Exit_Statement;
2145
2146    -----------------------------
2147    -- Expand_N_Goto_Statement --
2148    -----------------------------
2149
2150    --  Add poll before goto if polling active
2151
2152    procedure Expand_N_Goto_Statement (N : Node_Id) is
2153    begin
2154       Generate_Poll_Call (N);
2155    end Expand_N_Goto_Statement;
2156
2157    ---------------------------
2158    -- Expand_N_If_Statement --
2159    ---------------------------
2160
2161    --  First we deal with the case of C and Fortran convention boolean
2162    --  values, with zero/non-zero semantics.
2163
2164    --  Second, we deal with the obvious rewriting for the cases where the
2165    --  condition of the IF is known at compile time to be True or False.
2166
2167    --  Third, we remove elsif parts which have non-empty Condition_Actions
2168    --  and rewrite as independent if statements. For example:
2169
2170    --     if x then xs
2171    --     elsif y then ys
2172    --     ...
2173    --     end if;
2174
2175    --  becomes
2176    --
2177    --     if x then xs
2178    --     else
2179    --        <<condition actions of y>>
2180    --        if y then ys
2181    --        ...
2182    --        end if;
2183    --     end if;
2184
2185    --  This rewriting is needed if at least one elsif part has a non-empty
2186    --  Condition_Actions list. We also do the same processing if there is
2187    --  a constant condition in an elsif part (in conjunction with the first
2188    --  processing step mentioned above, for the recursive call made to deal
2189    --  with the created inner if, this deals with properly optimizing the
2190    --  cases of constant elsif conditions).
2191
2192    procedure Expand_N_If_Statement (N : Node_Id) is
2193       Loc    : constant Source_Ptr := Sloc (N);
2194       Hed    : Node_Id;
2195       E      : Node_Id;
2196       New_If : Node_Id;
2197
2198    begin
2199       Adjust_Condition (Condition (N));
2200
2201       --  The following loop deals with constant conditions for the IF. We
2202       --  need a loop because as we eliminate False conditions, we grab the
2203       --  first elsif condition and use it as the primary condition.
2204
2205       while Compile_Time_Known_Value (Condition (N)) loop
2206
2207          --  If condition is True, we can simply rewrite the if statement
2208          --  now by replacing it by the series of then statements.
2209
2210          if Is_True (Expr_Value (Condition (N))) then
2211
2212             --  All the else parts can be killed
2213
2214             Kill_Dead_Code (Elsif_Parts (N));
2215             Kill_Dead_Code (Else_Statements (N));
2216
2217             Hed := Remove_Head (Then_Statements (N));
2218             Insert_List_After (N, Then_Statements (N));
2219             Rewrite (N, Hed);
2220             return;
2221
2222          --  If condition is False, then we can delete the condition and
2223          --  the Then statements
2224
2225          else
2226             --  We do not delete the condition if constant condition
2227             --  warnings are enabled, since otherwise we end up deleting
2228             --  the desired warning. Of course the backend will get rid
2229             --  of this True/False test anyway, so nothing is lost here.
2230
2231             if not Constant_Condition_Warnings then
2232                Kill_Dead_Code (Condition (N));
2233             end if;
2234
2235             Kill_Dead_Code (Then_Statements (N));
2236
2237             --  If there are no elsif statements, then we simply replace
2238             --  the entire if statement by the sequence of else statements.
2239
2240             if No (Elsif_Parts (N)) then
2241
2242                if No (Else_Statements (N))
2243                  or else Is_Empty_List (Else_Statements (N))
2244                then
2245                   Rewrite (N,
2246                     Make_Null_Statement (Sloc (N)));
2247
2248                else
2249                   Hed := Remove_Head (Else_Statements (N));
2250                   Insert_List_After (N, Else_Statements (N));
2251                   Rewrite (N, Hed);
2252                end if;
2253
2254                return;
2255
2256             --  If there are elsif statements, the first of them becomes
2257             --  the if/then section of the rebuilt if statement This is
2258             --  the case where we loop to reprocess this copied condition.
2259
2260             else
2261                Hed := Remove_Head (Elsif_Parts (N));
2262                Insert_Actions      (N, Condition_Actions (Hed));
2263                Set_Condition       (N, Condition (Hed));
2264                Set_Then_Statements (N, Then_Statements (Hed));
2265
2266                if Is_Empty_List (Elsif_Parts (N)) then
2267                   Set_Elsif_Parts (N, No_List);
2268                end if;
2269             end if;
2270          end if;
2271       end loop;
2272
2273       --  Loop through elsif parts, dealing with constant conditions and
2274       --  possible expression actions that are present.
2275
2276       if Present (Elsif_Parts (N)) then
2277          E := First (Elsif_Parts (N));
2278          while Present (E) loop
2279             Adjust_Condition (Condition (E));
2280
2281             --  If there are condition actions, then we rewrite the if
2282             --  statement as indicated above. We also do the same rewrite
2283             --  if the condition is True or False. The further processing
2284             --  of this constant condition is then done by the recursive
2285             --  call to expand the newly created if statement
2286
2287             if Present (Condition_Actions (E))
2288               or else Compile_Time_Known_Value (Condition (E))
2289             then
2290                --  Note this is not an implicit if statement, since it is
2291                --  part of an explicit if statement in the source (or of an
2292                --  implicit if statement that has already been tested).
2293
2294                New_If :=
2295                  Make_If_Statement (Sloc (E),
2296                    Condition       => Condition (E),
2297                    Then_Statements => Then_Statements (E),
2298                    Elsif_Parts     => No_List,
2299                    Else_Statements => Else_Statements (N));
2300
2301                --  Elsif parts for new if come from remaining elsif's of parent
2302
2303                while Present (Next (E)) loop
2304                   if No (Elsif_Parts (New_If)) then
2305                      Set_Elsif_Parts (New_If, New_List);
2306                   end if;
2307
2308                   Append (Remove_Next (E), Elsif_Parts (New_If));
2309                end loop;
2310
2311                Set_Else_Statements (N, New_List (New_If));
2312
2313                if Present (Condition_Actions (E)) then
2314                   Insert_List_Before (New_If, Condition_Actions (E));
2315                end if;
2316
2317                Remove (E);
2318
2319                if Is_Empty_List (Elsif_Parts (N)) then
2320                   Set_Elsif_Parts (N, No_List);
2321                end if;
2322
2323                Analyze (New_If);
2324                return;
2325
2326             --  No special processing for that elsif part, move to next
2327
2328             else
2329                Next (E);
2330             end if;
2331          end loop;
2332       end if;
2333
2334       --  Some more optimizations applicable if we still have an IF statement
2335
2336       if Nkind (N) /= N_If_Statement then
2337          return;
2338       end if;
2339
2340       --  Another optimization, special cases that can be simplified
2341
2342       --     if expression then
2343       --        return true;
2344       --     else
2345       --        return false;
2346       --     end if;
2347
2348       --  can be changed to:
2349
2350       --     return expression;
2351
2352       --  and
2353
2354       --     if expression then
2355       --        return false;
2356       --     else
2357       --        return true;
2358       --     end if;
2359
2360       --  can be changed to:
2361
2362       --     return not (expression);
2363
2364       if Nkind (N) = N_If_Statement
2365          and then No (Elsif_Parts (N))
2366          and then Present (Else_Statements (N))
2367          and then List_Length (Then_Statements (N)) = 1
2368          and then List_Length (Else_Statements (N)) = 1
2369       then
2370          declare
2371             Then_Stm : constant Node_Id := First (Then_Statements (N));
2372             Else_Stm : constant Node_Id := First (Else_Statements (N));
2373
2374          begin
2375             if Nkind (Then_Stm) = N_Return_Statement
2376                  and then
2377                Nkind (Else_Stm) = N_Return_Statement
2378             then
2379                declare
2380                   Then_Expr : constant Node_Id := Expression (Then_Stm);
2381                   Else_Expr : constant Node_Id := Expression (Else_Stm);
2382
2383                begin
2384                   if Nkind (Then_Expr) = N_Identifier
2385                        and then
2386                      Nkind (Else_Expr) = N_Identifier
2387                   then
2388                      if Entity (Then_Expr) = Standard_True
2389                        and then Entity (Else_Expr) = Standard_False
2390                      then
2391                         Rewrite (N,
2392                           Make_Return_Statement (Loc,
2393                             Expression => Relocate_Node (Condition (N))));
2394                         Analyze (N);
2395                         return;
2396
2397                      elsif Entity (Then_Expr) = Standard_False
2398                        and then Entity (Else_Expr) = Standard_True
2399                      then
2400                         Rewrite (N,
2401                           Make_Return_Statement (Loc,
2402                             Expression =>
2403                               Make_Op_Not (Loc,
2404                                 Right_Opnd => Relocate_Node (Condition (N)))));
2405                         Analyze (N);
2406                         return;
2407                      end if;
2408                   end if;
2409                end;
2410             end if;
2411          end;
2412       end if;
2413    end Expand_N_If_Statement;
2414
2415    -----------------------------
2416    -- Expand_N_Loop_Statement --
2417    -----------------------------
2418
2419    --  1. Deal with while condition for C/Fortran boolean
2420    --  2. Deal with loops with a non-standard enumeration type range
2421    --  3. Deal with while loops where Condition_Actions is set
2422    --  4. Insert polling call if required
2423
2424    procedure Expand_N_Loop_Statement (N : Node_Id) is
2425       Loc  : constant Source_Ptr := Sloc (N);
2426       Isc  : constant Node_Id    := Iteration_Scheme (N);
2427
2428    begin
2429       if Present (Isc) then
2430          Adjust_Condition (Condition (Isc));
2431       end if;
2432
2433       if Is_Non_Empty_List (Statements (N)) then
2434          Generate_Poll_Call (First (Statements (N)));
2435       end if;
2436
2437       if No (Isc) then
2438          return;
2439       end if;
2440
2441       --  Handle the case where we have a for loop with the range type being
2442       --  an enumeration type with non-standard representation. In this case
2443       --  we expand:
2444
2445       --    for x in [reverse] a .. b loop
2446       --       ...
2447       --    end loop;
2448
2449       --  to
2450
2451       --    for xP in [reverse] integer
2452       --                          range etype'Pos (a) .. etype'Pos (b) loop
2453       --       declare
2454       --          x : constant etype := Pos_To_Rep (xP);
2455       --       begin
2456       --          ...
2457       --       end;
2458       --    end loop;
2459
2460       if Present (Loop_Parameter_Specification (Isc)) then
2461          declare
2462             LPS     : constant Node_Id   := Loop_Parameter_Specification (Isc);
2463             Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
2464             Ltype   : constant Entity_Id := Etype (Loop_Id);
2465             Btype   : constant Entity_Id := Base_Type (Ltype);
2466             Expr    : Node_Id;
2467             New_Id  : Entity_Id;
2468
2469          begin
2470             if not Is_Enumeration_Type (Btype)
2471               or else No (Enum_Pos_To_Rep (Btype))
2472             then
2473                return;
2474             end if;
2475
2476             New_Id :=
2477               Make_Defining_Identifier (Loc,
2478                 Chars => New_External_Name (Chars (Loop_Id), 'P'));
2479
2480             --  If the type has a contiguous representation, successive
2481             --  values can be generated as offsets from the first literal.
2482
2483             if Has_Contiguous_Rep (Btype) then
2484                Expr :=
2485                   Unchecked_Convert_To (Btype,
2486                     Make_Op_Add (Loc,
2487                       Left_Opnd =>
2488                          Make_Integer_Literal (Loc,
2489                            Enumeration_Rep (First_Literal (Btype))),
2490                       Right_Opnd => New_Reference_To (New_Id, Loc)));
2491             else
2492                --  Use the constructed array Enum_Pos_To_Rep
2493
2494                Expr :=
2495                  Make_Indexed_Component (Loc,
2496                    Prefix => New_Reference_To (Enum_Pos_To_Rep (Btype), Loc),
2497                    Expressions => New_List (New_Reference_To (New_Id, Loc)));
2498             end if;
2499
2500             Rewrite (N,
2501               Make_Loop_Statement (Loc,
2502                 Identifier => Identifier (N),
2503
2504                 Iteration_Scheme =>
2505                   Make_Iteration_Scheme (Loc,
2506                     Loop_Parameter_Specification =>
2507                       Make_Loop_Parameter_Specification (Loc,
2508                         Defining_Identifier => New_Id,
2509                         Reverse_Present => Reverse_Present (LPS),
2510
2511                         Discrete_Subtype_Definition =>
2512                           Make_Subtype_Indication (Loc,
2513
2514                             Subtype_Mark =>
2515                               New_Reference_To (Standard_Natural, Loc),
2516
2517                             Constraint =>
2518                               Make_Range_Constraint (Loc,
2519                                 Range_Expression =>
2520                                   Make_Range (Loc,
2521
2522                                     Low_Bound =>
2523                                       Make_Attribute_Reference (Loc,
2524                                         Prefix =>
2525                                           New_Reference_To (Btype, Loc),
2526
2527                                         Attribute_Name => Name_Pos,
2528
2529                                         Expressions => New_List (
2530                                           Relocate_Node
2531                                             (Type_Low_Bound (Ltype)))),
2532
2533                                     High_Bound =>
2534                                       Make_Attribute_Reference (Loc,
2535                                         Prefix =>
2536                                           New_Reference_To (Btype, Loc),
2537
2538                                         Attribute_Name => Name_Pos,
2539
2540                                         Expressions => New_List (
2541                                           Relocate_Node
2542                                             (Type_High_Bound (Ltype))))))))),
2543
2544                 Statements => New_List (
2545                   Make_Block_Statement (Loc,
2546                     Declarations => New_List (
2547                       Make_Object_Declaration (Loc,
2548                         Defining_Identifier => Loop_Id,
2549                         Constant_Present    => True,
2550                         Object_Definition   => New_Reference_To (Ltype, Loc),
2551                         Expression          => Expr)),
2552
2553                     Handled_Statement_Sequence =>
2554                       Make_Handled_Sequence_Of_Statements (Loc,
2555                         Statements => Statements (N)))),
2556
2557                 End_Label => End_Label (N)));
2558             Analyze (N);
2559          end;
2560
2561       --  Second case, if we have a while loop with Condition_Actions set,
2562       --  then we change it into a plain loop:
2563
2564       --    while C loop
2565       --       ...
2566       --    end loop;
2567
2568       --  changed to:
2569
2570       --    loop
2571       --       <<condition actions>>
2572       --       exit when not C;
2573       --       ...
2574       --    end loop
2575
2576       elsif Present (Isc)
2577         and then Present (Condition_Actions (Isc))
2578       then
2579          declare
2580             ES : Node_Id;
2581
2582          begin
2583             ES :=
2584               Make_Exit_Statement (Sloc (Condition (Isc)),
2585                 Condition =>
2586                   Make_Op_Not (Sloc (Condition (Isc)),
2587                     Right_Opnd => Condition (Isc)));
2588
2589             Prepend (ES, Statements (N));
2590             Insert_List_Before (ES, Condition_Actions (Isc));
2591
2592             --  This is not an implicit loop, since it is generated in
2593             --  response to the loop statement being processed. If this
2594             --  is itself implicit, the restriction has already been
2595             --  checked. If not, it is an explicit loop.
2596
2597             Rewrite (N,
2598               Make_Loop_Statement (Sloc (N),
2599                 Identifier => Identifier (N),
2600                 Statements => Statements (N),
2601                 End_Label  => End_Label  (N)));
2602
2603             Analyze (N);
2604          end;
2605       end if;
2606    end Expand_N_Loop_Statement;
2607
2608    -------------------------------
2609    -- Expand_N_Return_Statement --
2610    -------------------------------
2611
2612    procedure Expand_N_Return_Statement (N : Node_Id) is
2613       Loc         : constant Source_Ptr := Sloc (N);
2614       Exp         : constant Node_Id    := Expression (N);
2615       Exptyp      : Entity_Id;
2616       T           : Entity_Id;
2617       Utyp        : Entity_Id;
2618       Scope_Id    : Entity_Id;
2619       Kind        : Entity_Kind;
2620       Call        : Node_Id;
2621       Acc_Stat    : Node_Id;
2622       Goto_Stat   : Node_Id;
2623       Lab_Node    : Node_Id;
2624       Cur_Idx     : Nat;
2625       Return_Type : Entity_Id;
2626       Result_Exp  : Node_Id;
2627       Result_Id   : Entity_Id;
2628       Result_Obj  : Node_Id;
2629
2630    begin
2631       --  Case where returned expression is present
2632
2633       if Present (Exp) then
2634
2635          --  Always normalize C/Fortran boolean result. This is not always
2636          --  necessary, but it seems a good idea to minimize the passing
2637          --  around of non-normalized values, and in any case this handles
2638          --  the processing of barrier functions for protected types, which
2639          --  turn the condition into a return statement.
2640
2641          Exptyp := Etype (Exp);
2642
2643          if Is_Boolean_Type (Exptyp)
2644            and then Nonzero_Is_True (Exptyp)
2645          then
2646             Adjust_Condition (Exp);
2647             Adjust_Result_Type (Exp, Exptyp);
2648          end if;
2649
2650          --  Do validity check if enabled for returns
2651
2652          if Validity_Checks_On
2653            and then Validity_Check_Returns
2654          then
2655             Ensure_Valid (Exp);
2656          end if;
2657       end if;
2658
2659       --  Find relevant enclosing scope from which return is returning
2660
2661       Cur_Idx := Scope_Stack.Last;
2662       loop
2663          Scope_Id := Scope_Stack.Table (Cur_Idx).Entity;
2664
2665          if Ekind (Scope_Id) /= E_Block
2666            and then Ekind (Scope_Id) /= E_Loop
2667          then
2668             exit;
2669
2670          else
2671             Cur_Idx := Cur_Idx - 1;
2672             pragma Assert (Cur_Idx >= 0);
2673          end if;
2674       end loop;
2675
2676       if No (Exp) then
2677          Kind := Ekind (Scope_Id);
2678
2679          --  If it is a return from procedures do no extra steps
2680
2681          if Kind = E_Procedure or else Kind = E_Generic_Procedure then
2682             return;
2683          end if;
2684
2685          pragma Assert (Is_Entry (Scope_Id));
2686
2687          --  Look at the enclosing block to see whether the return is from
2688          --  an accept statement or an entry body.
2689
2690          for J in reverse 0 .. Cur_Idx loop
2691             Scope_Id := Scope_Stack.Table (J).Entity;
2692             exit when Is_Concurrent_Type (Scope_Id);
2693          end loop;
2694
2695          --  If it is a return from accept statement it should be expanded
2696          --  as a call to RTS Complete_Rendezvous and a goto to the end of
2697          --  the accept body.
2698
2699          --  (cf : Expand_N_Accept_Statement, Expand_N_Selective_Accept,
2700          --   Expand_N_Accept_Alternative in exp_ch9.adb)
2701
2702          if Is_Task_Type (Scope_Id) then
2703
2704             Call := (Make_Procedure_Call_Statement (Loc,
2705                       Name => New_Reference_To
2706                         (RTE (RE_Complete_Rendezvous), Loc)));
2707             Insert_Before (N, Call);
2708             --  why not insert actions here???
2709             Analyze (Call);
2710
2711             Acc_Stat := Parent (N);
2712             while Nkind (Acc_Stat) /= N_Accept_Statement loop
2713                Acc_Stat := Parent (Acc_Stat);
2714             end loop;
2715
2716             Lab_Node := Last (Statements
2717               (Handled_Statement_Sequence (Acc_Stat)));
2718
2719             Goto_Stat := Make_Goto_Statement (Loc,
2720               Name => New_Occurrence_Of
2721                 (Entity (Identifier (Lab_Node)), Loc));
2722
2723             Set_Analyzed (Goto_Stat);
2724
2725             Rewrite (N, Goto_Stat);
2726             Analyze (N);
2727
2728          --  If it is a return from an entry body, put a Complete_Entry_Body
2729          --  call in front of the return.
2730
2731          elsif Is_Protected_Type (Scope_Id) then
2732
2733             Call :=
2734               Make_Procedure_Call_Statement (Loc,
2735                 Name => New_Reference_To
2736                   (RTE (RE_Complete_Entry_Body), Loc),
2737                 Parameter_Associations => New_List
2738                   (Make_Attribute_Reference (Loc,
2739                     Prefix =>
2740                       New_Reference_To
2741                         (Object_Ref
2742                            (Corresponding_Body (Parent (Scope_Id))),
2743                         Loc),
2744                     Attribute_Name => Name_Unchecked_Access)));
2745
2746             Insert_Before (N, Call);
2747             Analyze (Call);
2748
2749          end if;
2750
2751          return;
2752       end if;
2753
2754       T := Etype (Exp);
2755       Return_Type := Etype (Scope_Id);
2756       Utyp := Underlying_Type (Return_Type);
2757
2758       --  Check the result expression of a scalar function against
2759       --  the subtype of the function by inserting a conversion.
2760       --  This conversion must eventually be performed for other
2761       --  classes of types, but for now it's only done for scalars.
2762       --  ???
2763
2764       if Is_Scalar_Type (T) then
2765          Rewrite (Exp, Convert_To (Return_Type, Exp));
2766          Analyze (Exp);
2767       end if;
2768
2769       --  Implement the rules of 6.5(8-10), which require a tag check in
2770       --  the case of a limited tagged return type, and tag reassignment
2771       --  for nonlimited tagged results. These actions are needed when
2772       --  the return type is a specific tagged type and the result
2773       --  expression is a conversion or a formal parameter, because in
2774       --  that case the tag of the expression might differ from the tag
2775       --  of the specific result type.
2776
2777       if Is_Tagged_Type (Utyp)
2778         and then not Is_Class_Wide_Type (Utyp)
2779         and then (Nkind (Exp) = N_Type_Conversion
2780                     or else Nkind (Exp) = N_Unchecked_Type_Conversion
2781                     or else (Is_Entity_Name (Exp)
2782                                and then Ekind (Entity (Exp)) in Formal_Kind))
2783       then
2784          --  When the return type is limited, perform a check that the
2785          --  tag of the result is the same as the tag of the return type.
2786
2787          if Is_Limited_Type (Return_Type) then
2788             Insert_Action (Exp,
2789               Make_Raise_Constraint_Error (Loc,
2790                 Condition =>
2791                   Make_Op_Ne (Loc,
2792                     Left_Opnd =>
2793                       Make_Selected_Component (Loc,
2794                         Prefix => Duplicate_Subexpr (Exp),
2795                         Selector_Name =>
2796                           New_Reference_To (First_Tag_Component (Utyp), Loc)),
2797                     Right_Opnd =>
2798                       Unchecked_Convert_To (RTE (RE_Tag),
2799                         New_Reference_To
2800                           (Node (First_Elmt
2801                                   (Access_Disp_Table (Base_Type (Utyp)))),
2802                            Loc))),
2803                 Reason => CE_Tag_Check_Failed));
2804
2805          --  If the result type is a specific nonlimited tagged type,
2806          --  then we have to ensure that the tag of the result is that
2807          --  of the result type. This is handled by making a copy of the
2808          --  expression in the case where it might have a different tag,
2809          --  namely when the expression is a conversion or a formal
2810          --  parameter. We create a new object of the result type and
2811          --  initialize it from the expression, which will implicitly
2812          --  force the tag to be set appropriately.
2813
2814          else
2815             Result_Id :=
2816               Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
2817             Result_Exp := New_Reference_To (Result_Id, Loc);
2818
2819             Result_Obj :=
2820               Make_Object_Declaration (Loc,
2821                 Defining_Identifier => Result_Id,
2822                 Object_Definition   => New_Reference_To (Return_Type, Loc),
2823                 Constant_Present    => True,
2824                 Expression          => Relocate_Node (Exp));
2825
2826             Set_Assignment_OK (Result_Obj);
2827             Insert_Action (Exp, Result_Obj);
2828
2829             Rewrite (Exp, Result_Exp);
2830             Analyze_And_Resolve (Exp, Return_Type);
2831          end if;
2832       end if;
2833
2834       --  Deal with returning variable length objects and controlled types
2835
2836       --  Nothing to do if we are returning by reference, or this is not
2837       --  a type that requires special processing (indicated by the fact
2838       --  that it requires a cleanup scope for the secondary stack case)
2839
2840       if Is_Return_By_Reference_Type (T)
2841         or else not Requires_Transient_Scope (Return_Type)
2842       then
2843          null;
2844
2845       --  Case of secondary stack not used
2846
2847       elsif Function_Returns_With_DSP (Scope_Id) then
2848
2849          --  Here what we need to do is to always return by reference, since
2850          --  we will return with the stack pointer depressed. We may need to
2851          --  do a copy to a local temporary before doing this return.
2852
2853          No_Secondary_Stack_Case : declare
2854             Local_Copy_Required : Boolean := False;
2855             --  Set to True if a local copy is required
2856
2857             Copy_Ent : Entity_Id;
2858             --  Used for the target entity if a copy is required
2859
2860             Decl : Node_Id;
2861             --  Declaration used to create copy if needed
2862
2863             procedure Test_Copy_Required (Expr : Node_Id);
2864             --  Determines if Expr represents a return value for which a
2865             --  copy is required. More specifically, a copy is not required
2866             --  if Expr represents an object or component of an object that
2867             --  is either in the local subprogram frame, or is constant.
2868             --  If a copy is required, then Local_Copy_Required is set True.
2869
2870             ------------------------
2871             -- Test_Copy_Required --
2872             ------------------------
2873
2874             procedure Test_Copy_Required (Expr : Node_Id) is
2875                Ent : Entity_Id;
2876
2877             begin
2878                --  If component, test prefix (object containing component)
2879
2880                if Nkind (Expr) = N_Indexed_Component
2881                     or else
2882                   Nkind (Expr) = N_Selected_Component
2883                then
2884                   Test_Copy_Required (Prefix (Expr));
2885                   return;
2886
2887                --  See if we have an entity name
2888
2889                elsif Is_Entity_Name (Expr) then
2890                   Ent := Entity (Expr);
2891
2892                   --  Constant entity is always OK, no copy required
2893
2894                   if Ekind (Ent) = E_Constant then
2895                      return;
2896
2897                   --  No copy required for local variable
2898
2899                   elsif Ekind (Ent) = E_Variable
2900                     and then Scope (Ent) = Current_Subprogram
2901                   then
2902                      return;
2903                   end if;
2904                end if;
2905
2906                --  All other cases require a copy
2907
2908                Local_Copy_Required := True;
2909             end Test_Copy_Required;
2910
2911          --  Start of processing for No_Secondary_Stack_Case
2912
2913          begin
2914             --  No copy needed if result is from a function call.
2915             --  In this case the result is already being returned by
2916             --  reference with the stack pointer depressed.
2917
2918             --  To make up for a gcc 2.8.1 deficiency (???), we perform
2919             --  the copy for array types if the constrained status of the
2920             --  target type is different from that of the expression.
2921
2922             if Requires_Transient_Scope (T)
2923               and then
2924                 (not Is_Array_Type (T)
2925                    or else Is_Constrained (T) = Is_Constrained (Return_Type)
2926                    or else Controlled_Type (T))
2927               and then Nkind (Exp) = N_Function_Call
2928             then
2929                Set_By_Ref (N);
2930
2931             --  We always need a local copy for a controlled type, since
2932             --  we are required to finalize the local value before return.
2933             --  The copy will automatically include the required finalize.
2934             --  Moreover, gigi cannot make this copy, since we need special
2935             --  processing to ensure proper behavior for finalization.
2936
2937             --  Note: the reason we are returning with a depressed stack
2938             --  pointer in the controlled case (even if the type involved
2939             --  is constrained) is that we must make a local copy to deal
2940             --  properly with the requirement that the local result be
2941             --  finalized.
2942
2943             elsif Controlled_Type (Utyp) then
2944                Copy_Ent :=
2945                  Make_Defining_Identifier (Loc,
2946                    Chars => New_Internal_Name ('R'));
2947
2948                --  Build declaration to do the copy, and insert it, setting
2949                --  Assignment_OK, because we may be copying a limited type.
2950                --  In addition we set the special flag to inhibit finalize
2951                --  attachment if this is a controlled type (since this attach
2952                --  must be done by the caller, otherwise if we attach it here
2953                --  we will finalize the returned result prematurely).
2954
2955                Decl :=
2956                  Make_Object_Declaration (Loc,
2957                    Defining_Identifier => Copy_Ent,
2958                    Object_Definition   => New_Occurrence_Of (Return_Type, Loc),
2959                    Expression          => Relocate_Node (Exp));
2960
2961                Set_Assignment_OK (Decl);
2962                Set_Delay_Finalize_Attach (Decl);
2963                Insert_Action (N, Decl);
2964
2965                --  Now the actual return uses the copied value
2966
2967                Rewrite (Exp, New_Occurrence_Of (Copy_Ent, Loc));
2968                Analyze_And_Resolve (Exp, Return_Type);
2969
2970                --  Since we have made the copy, gigi does not have to, so
2971                --  we set the By_Ref flag to prevent another copy being made.
2972
2973                Set_By_Ref (N);
2974
2975             --  Non-controlled cases
2976
2977             else
2978                Test_Copy_Required (Exp);
2979
2980                --  If a local copy is required, then gigi will make the
2981                --  copy, otherwise, we can return the result directly,
2982                --  so set By_Ref to suppress the gigi copy.
2983
2984                if not Local_Copy_Required then
2985                   Set_By_Ref (N);
2986                end if;
2987             end if;
2988          end No_Secondary_Stack_Case;
2989
2990       --  Here if secondary stack is used
2991
2992       else
2993          --  Make sure that no surrounding block will reclaim the
2994          --  secondary-stack on which we are going to put the result.
2995          --  Not only may this introduce secondary stack leaks but worse,
2996          --  if the reclamation is done too early, then the result we are
2997          --  returning may get clobbered. See example in 7417-003.
2998
2999          declare
3000             S : Entity_Id := Current_Scope;
3001
3002          begin
3003             while Ekind (S) = E_Block or else Ekind (S) = E_Loop loop
3004                Set_Sec_Stack_Needed_For_Return (S, True);
3005                S := Enclosing_Dynamic_Scope (S);
3006             end loop;
3007          end;
3008
3009          --  Optimize the case where the result is a function call. In this
3010          --  case either the result is already on the secondary stack, or is
3011          --  already being returned with the stack pointer depressed and no
3012          --  further processing is required except to set the By_Ref flag to
3013          --  ensure that gigi does not attempt an extra unnecessary copy.
3014          --  (actually not just unnecessary but harmfully wrong in the case
3015          --  of a controlled type, where gigi does not know how to do a copy).
3016          --  To make up for a gcc 2.8.1 deficiency (???), we perform
3017          --  the copy for array types if the constrained status of the
3018          --  target type is different from that of the expression.
3019
3020          if Requires_Transient_Scope (T)
3021            and then
3022               (not Is_Array_Type (T)
3023                 or else Is_Constrained (T) = Is_Constrained (Return_Type)
3024                 or else Controlled_Type (T))
3025            and then Nkind (Exp) = N_Function_Call
3026          then
3027             Set_By_Ref (N);
3028
3029          --  For controlled types, do the allocation on the sec-stack
3030          --  manually in order to call adjust at the right time
3031          --    type Anon1 is access Return_Type;
3032          --    for Anon1'Storage_pool use ss_pool;
3033          --    Anon2 : anon1 := new Return_Type'(expr);
3034          --    return Anon2.all;
3035
3036          elsif Controlled_Type (Utyp) then
3037             declare
3038                Loc        : constant Source_Ptr := Sloc (N);
3039                Temp       : constant Entity_Id :=
3040                               Make_Defining_Identifier (Loc,
3041                                 Chars => New_Internal_Name ('R'));
3042                Acc_Typ    : constant Entity_Id :=
3043                               Make_Defining_Identifier (Loc,
3044                                 Chars => New_Internal_Name ('A'));
3045                Alloc_Node : Node_Id;
3046
3047             begin
3048                Set_Ekind (Acc_Typ, E_Access_Type);
3049
3050                Set_Associated_Storage_Pool (Acc_Typ, RTE (RE_SS_Pool));
3051
3052                Alloc_Node :=
3053                  Make_Allocator (Loc,
3054                    Expression =>
3055                      Make_Qualified_Expression (Loc,
3056                        Subtype_Mark => New_Reference_To (Etype (Exp), Loc),
3057                        Expression => Relocate_Node (Exp)));
3058
3059                Insert_List_Before_And_Analyze (N, New_List (
3060                  Make_Full_Type_Declaration (Loc,
3061                    Defining_Identifier => Acc_Typ,
3062                    Type_Definition     =>
3063                      Make_Access_To_Object_Definition (Loc,
3064                        Subtype_Indication =>
3065                           New_Reference_To (Return_Type, Loc))),
3066
3067                  Make_Object_Declaration (Loc,
3068                    Defining_Identifier => Temp,
3069                    Object_Definition   => New_Reference_To (Acc_Typ, Loc),
3070                    Expression          => Alloc_Node)));
3071
3072                Rewrite (Exp,
3073                  Make_Explicit_Dereference (Loc,
3074                  Prefix => New_Reference_To (Temp, Loc)));
3075
3076                Analyze_And_Resolve (Exp, Return_Type);
3077             end;
3078
3079          --  Otherwise use the gigi mechanism to allocate result on the
3080          --  secondary stack.
3081
3082          else
3083             Set_Storage_Pool      (N, RTE (RE_SS_Pool));
3084
3085             --  If we are generating code for the Java VM do not use
3086             --  SS_Allocate since everything is heap-allocated anyway.
3087
3088             if not Java_VM then
3089                Set_Procedure_To_Call (N, RTE (RE_SS_Allocate));
3090             end if;
3091          end if;
3092       end if;
3093
3094    exception
3095       when RE_Not_Available =>
3096          return;
3097    end Expand_N_Return_Statement;
3098
3099    ------------------------------
3100    -- Make_Tag_Ctrl_Assignment --
3101    ------------------------------
3102
3103    function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
3104       Loc : constant Source_Ptr := Sloc (N);
3105       L   : constant Node_Id    := Name (N);
3106       T   : constant Entity_Id  := Underlying_Type (Etype (L));
3107
3108       Ctrl_Act : constant Boolean := Controlled_Type (T)
3109                                        and then not No_Ctrl_Actions (N);
3110
3111       Save_Tag : constant Boolean := Is_Tagged_Type (T)
3112                                        and then not No_Ctrl_Actions (N)
3113                                        and then not Java_VM;
3114       --  Tags are not saved and restored when Java_VM because JVM tags
3115       --  are represented implicitly in objects.
3116
3117       Res       : List_Id;
3118       Tag_Tmp   : Entity_Id;
3119
3120    begin
3121       Res := New_List;
3122
3123       --  Finalize the target of the assignment when controlled.
3124       --  We have two exceptions here:
3125
3126       --   1. If we are in an init proc since it is an initialization
3127       --      more than an assignment
3128
3129       --   2. If the left-hand side is a temporary that was not initialized
3130       --      (or the parent part of a temporary since it is the case in
3131       --      extension aggregates). Such a temporary does not come from
3132       --      source. We must examine the original node for the prefix, because
3133       --      it may be a component of an entry formal, in which case it has
3134       --      been rewritten and does not appear to come from source either.
3135
3136       --  Case of init proc
3137
3138       if not Ctrl_Act then
3139          null;
3140
3141       --  The left hand side is an uninitialized  temporary
3142
3143       elsif Nkind (L) = N_Type_Conversion
3144         and then Is_Entity_Name (Expression (L))
3145         and then No_Initialization (Parent (Entity (Expression (L))))
3146       then
3147          null;
3148       else
3149          Append_List_To (Res,
3150            Make_Final_Call (
3151              Ref         => Duplicate_Subexpr_No_Checks (L),
3152              Typ         => Etype (L),
3153              With_Detach => New_Reference_To (Standard_False, Loc)));
3154       end if;
3155
3156       --  Save the Tag in a local variable Tag_Tmp
3157
3158       if Save_Tag then
3159          Tag_Tmp :=
3160            Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
3161
3162          Append_To (Res,
3163            Make_Object_Declaration (Loc,
3164              Defining_Identifier => Tag_Tmp,
3165              Object_Definition => New_Reference_To (RTE (RE_Tag), Loc),
3166              Expression =>
3167                Make_Selected_Component (Loc,
3168                  Prefix        => Duplicate_Subexpr_No_Checks (L),
3169                  Selector_Name => New_Reference_To (First_Tag_Component (T),
3170                                                     Loc))));
3171
3172       --  Otherwise Tag_Tmp not used
3173
3174       else
3175          Tag_Tmp := Empty;
3176       end if;
3177
3178       --  Processing for controlled types and types with controlled components
3179
3180       --  Variables of such types contain pointers used to chain them in
3181       --  finalization lists, in addition to user data. These pointers are
3182       --  specific to each object of the type, not to the value being assigned.
3183       --  Thus they need to be left intact during the assignment. We achieve
3184       --  this by constructing a Storage_Array subtype, and by overlaying
3185       --  objects of this type on the source and target of the assignment.
3186       --  The assignment is then rewritten to assignments of slices of these
3187       --  arrays, copying the user data, and leaving the pointers untouched.
3188
3189       if Ctrl_Act then
3190          Controlled_Actions : declare
3191             Prev_Ref : Node_Id;
3192             --  A reference to the Prev component of the record controller
3193
3194             First_After_Root : Node_Id := Empty;
3195             --  Index of first byte to be copied (used to skip
3196             --  Root_Controlled in controlled objects).
3197
3198             Last_Before_Hole : Node_Id := Empty;
3199             --  Index of last byte to be copied before outermost record
3200             --  controller data.
3201
3202             Hole_Length      : Node_Id := Empty;
3203             --  Length of record controller data (Prev and Next pointers)
3204
3205             First_After_Hole : Node_Id := Empty;
3206             --  Index of first byte to be copied after outermost record
3207             --  controller data.
3208
3209             Expr, Source_Size     : Node_Id;
3210             Source_Actual_Subtype : Entity_Id;
3211             --  Used for computation of the size of the data to be copied
3212
3213             Range_Type  : Entity_Id;
3214             Opaque_Type : Entity_Id;
3215
3216             function Build_Slice
3217               (Rec : Entity_Id;
3218                Lo  : Node_Id;
3219                Hi  : Node_Id) return Node_Id;
3220             --  Build and return a slice of an array of type S overlaid
3221             --  on object Rec, with bounds specified by Lo and Hi. If either
3222             --  bound is empty, a default of S'First (respectively S'Last)
3223             --  is used.
3224
3225             -----------------
3226             -- Build_Slice --
3227             -----------------
3228
3229             function Build_Slice
3230               (Rec : Node_Id;
3231                Lo  : Node_Id;
3232                Hi  : Node_Id) return Node_Id
3233             is
3234                Lo_Bound : Node_Id;
3235                Hi_Bound : Node_Id;
3236
3237                Opaque : constant Node_Id :=
3238                           Unchecked_Convert_To (Opaque_Type,
3239                             Make_Attribute_Reference (Loc,
3240                               Prefix         => Rec,
3241                               Attribute_Name => Name_Address));
3242                --  Access value designating an opaque storage array of
3243                --  type S overlaid on record Rec.
3244
3245             begin
3246                --  Compute slice bounds using S'First (1) and S'Last
3247                --  as default values when not specified by the caller.
3248
3249                if No (Lo) then
3250                   Lo_Bound := Make_Integer_Literal (Loc, 1);
3251                else
3252                   Lo_Bound := Lo;
3253                end if;
3254
3255                if No (Hi) then
3256                   Hi_Bound := Make_Attribute_Reference (Loc,
3257                     Prefix => New_Occurrence_Of (Range_Type, Loc),
3258                     Attribute_Name => Name_Last);
3259                else
3260                   Hi_Bound := Hi;
3261                end if;
3262
3263                return Make_Slice (Loc,
3264                  Prefix =>
3265                    Opaque,
3266                  Discrete_Range => Make_Range (Loc,
3267                    Lo_Bound, Hi_Bound));
3268             end Build_Slice;
3269
3270          --  Start of processing for Controlled_Actions
3271
3272          begin
3273             --  Create a constrained subtype of Storage_Array whose size
3274             --  corresponds to the value being assigned.
3275
3276             --  subtype G is Storage_Offset range
3277             --    1 .. (Expr'Size + Storage_Unit - 1) / Storage_Unit
3278
3279             Expr := Duplicate_Subexpr_No_Checks (Expression (N));
3280
3281             if Nkind (Expr) = N_Qualified_Expression then
3282                Expr := Expression (Expr);
3283             end if;
3284
3285             Source_Actual_Subtype := Etype (Expr);
3286
3287             if Has_Discriminants (Source_Actual_Subtype)
3288               and then not Is_Constrained (Source_Actual_Subtype)
3289             then
3290                Append_To (Res,
3291                  Build_Actual_Subtype (Source_Actual_Subtype, Expr));
3292                Source_Actual_Subtype := Defining_Identifier (Last (Res));
3293             end if;
3294
3295             Source_Size :=
3296               Make_Op_Add (Loc,
3297                 Left_Opnd =>
3298                   Make_Attribute_Reference (Loc,
3299                     Prefix =>
3300                       New_Occurrence_Of (Source_Actual_Subtype, Loc),
3301                     Attribute_Name =>
3302                       Name_Size),
3303                 Right_Opnd =>
3304                   Make_Integer_Literal (Loc,
3305                   System_Storage_Unit - 1));
3306             Source_Size :=
3307               Make_Op_Divide (Loc,
3308                 Left_Opnd => Source_Size,
3309                 Right_Opnd =>
3310                   Make_Integer_Literal (Loc,
3311                     Intval => System_Storage_Unit));
3312
3313             Range_Type :=
3314               Make_Defining_Identifier (Loc,
3315                 New_Internal_Name ('G'));
3316
3317             Append_To (Res,
3318               Make_Subtype_Declaration (Loc,
3319                 Defining_Identifier => Range_Type,
3320                 Subtype_Indication =>
3321                   Make_Subtype_Indication (Loc,
3322                     Subtype_Mark =>
3323                       New_Reference_To (RTE (RE_Storage_Offset), Loc),
3324                     Constraint   => Make_Range_Constraint (Loc,
3325                       Range_Expression =>
3326                         Make_Range (Loc,
3327                           Low_Bound  => Make_Integer_Literal (Loc, 1),
3328                           High_Bound => Source_Size)))));
3329
3330             --  subtype S is Storage_Array (G)
3331
3332             Append_To (Res,
3333               Make_Subtype_Declaration (Loc,
3334                 Defining_Identifier =>
3335                   Make_Defining_Identifier (Loc,
3336                     New_Internal_Name ('S')),
3337                 Subtype_Indication  =>
3338                   Make_Subtype_Indication (Loc,
3339                     Subtype_Mark =>
3340                       New_Reference_To (RTE (RE_Storage_Array), Loc),
3341                     Constraint =>
3342                       Make_Index_Or_Discriminant_Constraint (Loc,
3343                         Constraints =>
3344                           New_List (New_Reference_To (Range_Type, Loc))))));
3345
3346             --  type A is access S
3347
3348             Opaque_Type :=
3349               Make_Defining_Identifier (Loc,
3350                 Chars => New_Internal_Name ('A'));
3351
3352             Append_To (Res,
3353               Make_Full_Type_Declaration (Loc,
3354                 Defining_Identifier => Opaque_Type,
3355                 Type_Definition     =>
3356                   Make_Access_To_Object_Definition (Loc,
3357                     Subtype_Indication =>
3358                       New_Occurrence_Of (
3359                         Defining_Identifier (Last (Res)), Loc))));
3360
3361             --  Generate appropriate slice assignments
3362
3363             First_After_Root := Make_Integer_Literal (Loc, 1);
3364
3365             --  For the case of a controlled object, skip the
3366             --  Root_Controlled part.
3367
3368             if Is_Controlled (T) then
3369                First_After_Root :=
3370                  Make_Op_Add (Loc,
3371                    First_After_Root,
3372                    Make_Op_Divide (Loc,
3373                      Make_Attribute_Reference (Loc,
3374                        Prefix =>
3375                          New_Occurrence_Of (RTE (RE_Root_Controlled), Loc),
3376                        Attribute_Name => Name_Size),
3377                      Make_Integer_Literal (Loc, System_Storage_Unit)));
3378             end if;
3379
3380             --  For the case of a record with controlled components, skip
3381             --  the Prev and Next components of the record controller.
3382             --  These components constitute a 'hole' in the middle of the
3383             --  data to be copied.
3384
3385             if Has_Controlled_Component (T) then
3386                Prev_Ref :=
3387                  Make_Selected_Component (Loc,
3388                    Prefix =>
3389                      Make_Selected_Component (Loc,
3390                        Prefix => Duplicate_Subexpr_No_Checks (L),
3391                        Selector_Name =>
3392                          New_Reference_To (Controller_Component (T), Loc)),
3393                    Selector_Name =>  Make_Identifier (Loc, Name_Prev));
3394
3395                --  Last index before hole: determined by position of
3396                --  the _Controller.Prev component.
3397
3398                Last_Before_Hole :=
3399                  Make_Defining_Identifier (Loc,
3400                    New_Internal_Name ('L'));
3401
3402                Append_To (Res,
3403                  Make_Object_Declaration (Loc,
3404                    Defining_Identifier => Last_Before_Hole,
3405                    Object_Definition   => New_Occurrence_Of (
3406                      RTE (RE_Storage_Offset), Loc),
3407                    Constant_Present    => True,
3408                    Expression          => Make_Op_Add (Loc,
3409                        Make_Attribute_Reference (Loc,
3410                          Prefix => Prev_Ref,
3411                          Attribute_Name => Name_Position),
3412                        Make_Attribute_Reference (Loc,
3413                          Prefix => New_Copy_Tree (Prefix (Prev_Ref)),
3414                          Attribute_Name => Name_Position))));
3415
3416                --  Hole length: size of the Prev and Next components
3417
3418                Hole_Length :=
3419                  Make_Op_Multiply (Loc,
3420                    Left_Opnd  => Make_Integer_Literal (Loc, Uint_2),
3421                    Right_Opnd =>
3422                      Make_Op_Divide (Loc,
3423                        Left_Opnd =>
3424                          Make_Attribute_Reference (Loc,
3425                            Prefix         => New_Copy_Tree (Prev_Ref),
3426                            Attribute_Name => Name_Size),
3427                        Right_Opnd =>
3428                          Make_Integer_Literal (Loc,
3429                            Intval => System_Storage_Unit)));
3430
3431                --  First index after hole
3432
3433                First_After_Hole :=
3434                  Make_Defining_Identifier (Loc,
3435                    New_Internal_Name ('F'));
3436
3437                Append_To (Res,
3438                  Make_Object_Declaration (Loc,
3439                    Defining_Identifier => First_After_Hole,
3440                    Object_Definition   => New_Occurrence_Of (
3441                      RTE (RE_Storage_Offset), Loc),
3442                    Constant_Present    => True,
3443                    Expression          =>
3444                      Make_Op_Add (Loc,
3445                        Left_Opnd  =>
3446                          Make_Op_Add (Loc,
3447                            Left_Opnd  =>
3448                              New_Occurrence_Of (Last_Before_Hole, Loc),
3449                            Right_Opnd => Hole_Length),
3450                        Right_Opnd => Make_Integer_Literal (Loc, 1))));
3451
3452                Last_Before_Hole := New_Occurrence_Of (Last_Before_Hole, Loc);
3453                First_After_Hole := New_Occurrence_Of (First_After_Hole, Loc);
3454             end if;
3455
3456             --  Assign the first slice (possibly skipping Root_Controlled,
3457             --  up to the beginning of the record controller if present,
3458             --  up to the end of the object if not).
3459
3460             Append_To (Res, Make_Assignment_Statement (Loc,
3461               Name       => Build_Slice (
3462                 Rec => Duplicate_Subexpr_No_Checks (L),
3463                 Lo  => First_After_Root,
3464                 Hi  => Last_Before_Hole),
3465
3466               Expression => Build_Slice (
3467                 Rec => Expression (N),
3468                 Lo  => First_After_Root,
3469                 Hi  => New_Copy_Tree (Last_Before_Hole))));
3470
3471             if Present (First_After_Hole) then
3472
3473                --  If a record controller is present, copy the second slice,
3474                --  from right after the _Controller.Next component up to the
3475                --  end of the object.
3476
3477                Append_To (Res, Make_Assignment_Statement (Loc,
3478                  Name       => Build_Slice (
3479                    Rec => Duplicate_Subexpr_No_Checks (L),
3480                    Lo  => First_After_Hole,
3481                    Hi  => Empty),
3482                  Expression => Build_Slice (
3483                    Rec => Duplicate_Subexpr_No_Checks (Expression (N)),
3484                    Lo  => New_Copy_Tree (First_After_Hole),
3485                    Hi  => Empty)));
3486             end if;
3487          end Controlled_Actions;
3488
3489       else
3490          Append_To (Res, Relocate_Node (N));
3491       end if;
3492
3493       --  Restore the tag
3494
3495       if Save_Tag then
3496          Append_To (Res,
3497            Make_Assignment_Statement (Loc,
3498              Name =>
3499                Make_Selected_Component (Loc,
3500                  Prefix        => Duplicate_Subexpr_No_Checks (L),
3501                  Selector_Name => New_Reference_To (First_Tag_Component (T),
3502                                                     Loc)),
3503              Expression => New_Reference_To (Tag_Tmp, Loc)));
3504       end if;
3505
3506       --  Adjust the target after the assignment when controlled (not in the
3507       --  init proc since it is an initialization more than an assignment).
3508
3509       if Ctrl_Act then
3510          Append_List_To (Res,
3511            Make_Adjust_Call (
3512              Ref         => Duplicate_Subexpr_Move_Checks (L),
3513              Typ         => Etype (L),
3514              Flist_Ref   => New_Reference_To (RTE (RE_Global_Final_List), Loc),
3515              With_Attach => Make_Integer_Literal (Loc, 0)));
3516       end if;
3517
3518       return Res;
3519
3520    exception
3521       --  Could use comment here ???
3522
3523       when RE_Not_Available =>
3524          return Empty_List;
3525    end Make_Tag_Ctrl_Assignment;
3526
3527    ------------------------------------
3528    -- Possible_Bit_Aligned_Component --
3529    ------------------------------------
3530
3531    function Possible_Bit_Aligned_Component (N : Node_Id) return Boolean is
3532    begin
3533       case Nkind (N) is
3534
3535          --  Case of indexed component
3536
3537          when N_Indexed_Component =>
3538             declare
3539                P    : constant Node_Id   := Prefix (N);
3540                Ptyp : constant Entity_Id := Etype (P);
3541
3542             begin
3543                --  If we know the component size and it is less than 64, then
3544                --  we are definitely OK. The back end always does assignment
3545                --  of misaligned small objects correctly.
3546
3547                if Known_Static_Component_Size (Ptyp)
3548                  and then Component_Size (Ptyp) <= 64
3549                then
3550                   return False;
3551
3552                --  Otherwise, we need to test the prefix, to see if we are
3553                --  indexing from a possibly unaligned component.
3554
3555                else
3556                   return Possible_Bit_Aligned_Component (P);
3557                end if;
3558             end;
3559
3560          --  Case of selected component
3561
3562          when N_Selected_Component =>
3563             declare
3564                P    : constant Node_Id   := Prefix (N);
3565                Comp : constant Entity_Id := Entity (Selector_Name (N));
3566
3567             begin
3568                --  If there is no component clause, then we are in the clear
3569                --  since the back end will never misalign a large component
3570                --  unless it is forced to do so. In the clear means we need
3571                --  only the recursive test on the prefix.
3572
3573                if Component_May_Be_Bit_Aligned (Comp) then
3574                   return True;
3575                else
3576                   return Possible_Bit_Aligned_Component (P);
3577                end if;
3578             end;
3579
3580          --  If we have neither a record nor array component, it means that
3581          --  we have fallen off the top testing prefixes recursively, and
3582          --  we now have a stand alone object, where we don't have a problem
3583
3584          when others =>
3585             return False;
3586
3587       end case;
3588    end Possible_Bit_Aligned_Component;
3589
3590 end Exp_Ch5;