OSDN Git Service

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