OSDN Git Service

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