OSDN Git Service

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