OSDN Git Service

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