OSDN Git Service

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