OSDN Git Service

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