OSDN Git Service

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