OSDN Git Service

2011-08-03 Gary Dismukes <dismukes@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_aggr.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                             E X P _ A G G R                              --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2011, 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 3,  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 COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Checks;   use Checks;
28 with Debug;    use Debug;
29 with Einfo;    use Einfo;
30 with Elists;   use Elists;
31 with Errout;   use Errout;
32 with Expander; use Expander;
33 with Exp_Util; use Exp_Util;
34 with Exp_Ch3;  use Exp_Ch3;
35 with Exp_Ch7;  use Exp_Ch7;
36 with Exp_Ch9;  use Exp_Ch9;
37 with Exp_Disp; use Exp_Disp;
38 with Exp_Tss;  use Exp_Tss;
39 with Fname;    use Fname;
40 with Freeze;   use Freeze;
41 with Itypes;   use Itypes;
42 with Lib;      use Lib;
43 with Namet;    use Namet;
44 with Nmake;    use Nmake;
45 with Nlists;   use Nlists;
46 with Opt;      use Opt;
47 with Restrict; use Restrict;
48 with Rident;   use Rident;
49 with Rtsfind;  use Rtsfind;
50 with Ttypes;   use Ttypes;
51 with Sem;      use Sem;
52 with Sem_Aggr; use Sem_Aggr;
53 with Sem_Aux;  use Sem_Aux;
54 with Sem_Ch3;  use Sem_Ch3;
55 with Sem_Eval; use Sem_Eval;
56 with Sem_Res;  use Sem_Res;
57 with Sem_Util; use Sem_Util;
58 with Sinfo;    use Sinfo;
59 with Snames;   use Snames;
60 with Stand;    use Stand;
61 with Targparm; use Targparm;
62 with Tbuild;   use Tbuild;
63 with Uintp;    use Uintp;
64
65 package body Exp_Aggr is
66
67    type Case_Bounds is record
68      Choice_Lo   : Node_Id;
69      Choice_Hi   : Node_Id;
70      Choice_Node : Node_Id;
71    end record;
72
73    type Case_Table_Type is array (Nat range <>) of Case_Bounds;
74    --  Table type used by Check_Case_Choices procedure
75
76    function Must_Slide
77      (Obj_Type : Entity_Id;
78       Typ      : Entity_Id) return Boolean;
79    --  A static array aggregate in an object declaration can in most cases be
80    --  expanded in place. The one exception is when the aggregate is given
81    --  with component associations that specify different bounds from those of
82    --  the type definition in the object declaration. In this pathological
83    --  case the aggregate must slide, and we must introduce an intermediate
84    --  temporary to hold it.
85    --
86    --  The same holds in an assignment to one-dimensional array of arrays,
87    --  when a component may be given with bounds that differ from those of the
88    --  component type.
89
90    procedure Sort_Case_Table (Case_Table : in out Case_Table_Type);
91    --  Sort the Case Table using the Lower Bound of each Choice as the key.
92    --  A simple insertion sort is used since the number of choices in a case
93    --  statement of variant part will usually be small and probably in near
94    --  sorted order.
95
96    function Has_Default_Init_Comps (N : Node_Id) return Boolean;
97    --  N is an aggregate (record or array). Checks the presence of default
98    --  initialization (<>) in any component (Ada 2005: AI-287).
99
100    function Is_Static_Dispatch_Table_Aggregate (N : Node_Id) return Boolean;
101    --  Returns true if N is an aggregate used to initialize the components
102    --  of an statically allocated dispatch table.
103
104    ------------------------------------------------------
105    -- Local subprograms for Record Aggregate Expansion --
106    ------------------------------------------------------
107
108    procedure Expand_Record_Aggregate
109      (N           : Node_Id;
110       Orig_Tag    : Node_Id := Empty;
111       Parent_Expr : Node_Id := Empty);
112    --  This is the top level procedure for record aggregate expansion.
113    --  Expansion for record aggregates needs expand aggregates for tagged
114    --  record types. Specifically Expand_Record_Aggregate adds the Tag
115    --  field in front of the Component_Association list that was created
116    --  during resolution by Resolve_Record_Aggregate.
117    --
118    --    N is the record aggregate node.
119    --    Orig_Tag is the value of the Tag that has to be provided for this
120    --      specific aggregate. It carries the tag corresponding to the type
121    --      of the outermost aggregate during the recursive expansion
122    --    Parent_Expr is the ancestor part of the original extension
123    --      aggregate
124
125    procedure Convert_To_Assignments (N : Node_Id; Typ : Entity_Id);
126    --  N is an N_Aggregate or an N_Extension_Aggregate. Typ is the type of the
127    --  aggregate (which can only be a record type, this procedure is only used
128    --  for record types). Transform the given aggregate into a sequence of
129    --  assignments performed component by component.
130
131    function Build_Record_Aggr_Code
132      (N                             : Node_Id;
133       Typ                           : Entity_Id;
134       Lhs                           : Node_Id;
135       Flist                         : Node_Id   := Empty;
136       Obj                           : Entity_Id := Empty;
137       Is_Limited_Ancestor_Expansion : Boolean   := False) return List_Id;
138    --  N is an N_Aggregate or an N_Extension_Aggregate. Typ is the type of the
139    --  aggregate. Target is an expression containing the location on which the
140    --  component by component assignments will take place. Returns the list of
141    --  assignments plus all other adjustments needed for tagged and controlled
142    --  types. Flist is an expression representing the finalization list on
143    --  which to attach the controlled components if any. Obj is present in the
144    --  object declaration and dynamic allocation cases, it contains an entity
145    --  that allows to know if the value being created needs to be attached to
146    --  the final list in case of pragma Finalize_Storage_Only.
147    --
148    --  ???
149    --  The meaning of the Obj formal is extremely unclear. *What* entity
150    --  should be passed? For the object declaration case we may guess that
151    --  this is the object being declared, but what about the allocator case?
152    --
153    --  Is_Limited_Ancestor_Expansion indicates that the function has been
154    --  called recursively to expand the limited ancestor to avoid copying it.
155
156    function Has_Mutable_Components (Typ : Entity_Id) return Boolean;
157    --  Return true if one of the component is of a discriminated type with
158    --  defaults. An aggregate for a type with mutable components must be
159    --  expanded into individual assignments.
160
161    procedure Initialize_Discriminants (N : Node_Id; Typ : Entity_Id);
162    --  If the type of the aggregate is a type extension with renamed discrimi-
163    --  nants, we must initialize the hidden discriminants of the parent.
164    --  Otherwise, the target object must not be initialized. The discriminants
165    --  are initialized by calling the initialization procedure for the type.
166    --  This is incorrect if the initialization of other components has any
167    --  side effects. We restrict this call to the case where the parent type
168    --  has a variant part, because this is the only case where the hidden
169    --  discriminants are accessed, namely when calling discriminant checking
170    --  functions of the parent type, and when applying a stream attribute to
171    --  an object of the derived type.
172
173    -----------------------------------------------------
174    -- Local Subprograms for Array Aggregate Expansion --
175    -----------------------------------------------------
176
177    function Aggr_Size_OK (N : Node_Id; Typ : Entity_Id) return Boolean;
178    --  Very large static aggregates present problems to the back-end, and are
179    --  transformed into assignments and loops. This function verifies that the
180    --  total number of components of an aggregate is acceptable for rewriting
181    --  into a purely positional static form. Aggr_Size_OK must be called before
182    --  calling Flatten.
183    --
184    --  This function also detects and warns about one-component aggregates that
185    --  appear in a non-static context. Even if the component value is static,
186    --  such an aggregate must be expanded into an assignment.
187
188    procedure Convert_Array_Aggr_In_Allocator
189      (Decl   : Node_Id;
190       Aggr   : Node_Id;
191       Target : Node_Id);
192    --  If the aggregate appears within an allocator and can be expanded in
193    --  place, this routine generates the individual assignments to components
194    --  of the designated object. This is an optimization over the general
195    --  case, where a temporary is first created on the stack and then used to
196    --  construct the allocated object on the heap.
197
198    procedure Convert_To_Positional
199      (N                    : Node_Id;
200       Max_Others_Replicate : Nat     := 5;
201       Handle_Bit_Packed    : Boolean := False);
202    --  If possible, convert named notation to positional notation. This
203    --  conversion is possible only in some static cases. If the conversion is
204    --  possible, then N is rewritten with the analyzed converted aggregate.
205    --  The parameter Max_Others_Replicate controls the maximum number of
206    --  values corresponding to an others choice that will be converted to
207    --  positional notation (the default of 5 is the normal limit, and reflects
208    --  the fact that normally the loop is better than a lot of separate
209    --  assignments). Note that this limit gets overridden in any case if
210    --  either of the restrictions No_Elaboration_Code or No_Implicit_Loops is
211    --  set. The parameter Handle_Bit_Packed is usually set False (since we do
212    --  not expect the back end to handle bit packed arrays, so the normal case
213    --  of conversion is pointless), but in the special case of a call from
214    --  Packed_Array_Aggregate_Handled, we set this parameter to True, since
215    --  these are cases we handle in there.
216
217    procedure Expand_Array_Aggregate (N : Node_Id);
218    --  This is the top-level routine to perform array aggregate expansion.
219    --  N is the N_Aggregate node to be expanded.
220
221    function Backend_Processing_Possible (N : Node_Id) return Boolean;
222    --  This function checks if array aggregate N can be processed directly
223    --  by the backend. If this is the case True is returned.
224
225    function Build_Array_Aggr_Code
226      (N           : Node_Id;
227       Ctype       : Entity_Id;
228       Index       : Node_Id;
229       Into        : Node_Id;
230       Scalar_Comp : Boolean;
231       Indexes     : List_Id := No_List;
232       Flist       : Node_Id := Empty) return List_Id;
233    --  This recursive routine returns a list of statements containing the
234    --  loops and assignments that are needed for the expansion of the array
235    --  aggregate N.
236    --
237    --    N is the (sub-)aggregate node to be expanded into code. This node
238    --    has been fully analyzed, and its Etype is properly set.
239    --
240    --    Index is the index node corresponding to the array sub-aggregate N.
241    --
242    --    Into is the target expression into which we are copying the aggregate.
243    --    Note that this node may not have been analyzed yet, and so the Etype
244    --    field may not be set.
245    --
246    --    Scalar_Comp is True if the component type of the aggregate is scalar.
247    --
248    --    Indexes is the current list of expressions used to index the
249    --    object we are writing into.
250    --
251    --    Flist is an expression representing the finalization list on which
252    --    to attach the controlled components if any.
253
254    function Number_Of_Choices (N : Node_Id) return Nat;
255    --  Returns the number of discrete choices (not including the others choice
256    --  if present) contained in (sub-)aggregate N.
257
258    function Late_Expansion
259      (N      : Node_Id;
260       Typ    : Entity_Id;
261       Target : Node_Id;
262       Flist  : Node_Id := Empty;
263       Obj    : Entity_Id := Empty) return List_Id;
264    --  N is a nested (record or array) aggregate that has been marked with
265    --  'Delay_Expansion'. Typ is the expected type of the aggregate and Target
266    --  is a (duplicable) expression that will hold the result of the aggregate
267    --  expansion. Flist is the finalization list to be used to attach
268    --  controlled components. 'Obj' when non empty, carries the original
269    --  object being initialized in order to know if it needs to be attached to
270    --  the previous parameter which may not be the case in the case where
271    --  Finalize_Storage_Only is set. Basically this procedure is used to
272    --  implement top-down expansions of nested aggregates. This is necessary
273    --  for avoiding temporaries at each level as well as for propagating the
274    --  right internal finalization list.
275
276    function Make_OK_Assignment_Statement
277      (Sloc       : Source_Ptr;
278       Name       : Node_Id;
279       Expression : Node_Id) return Node_Id;
280    --  This is like Make_Assignment_Statement, except that Assignment_OK
281    --  is set in the left operand. All assignments built by this unit
282    --  use this routine. This is needed to deal with assignments to
283    --  initialized constants that are done in place.
284
285    function Packed_Array_Aggregate_Handled (N : Node_Id) return Boolean;
286    --  Given an array aggregate, this function handles the case of a packed
287    --  array aggregate with all constant values, where the aggregate can be
288    --  evaluated at compile time. If this is possible, then N is rewritten
289    --  to be its proper compile time value with all the components properly
290    --  assembled. The expression is analyzed and resolved and True is
291    --  returned. If this transformation is not possible, N is unchanged
292    --  and False is returned
293
294    function Safe_Slice_Assignment (N : Node_Id) return Boolean;
295    --  If a slice assignment has an aggregate with a single others_choice,
296    --  the assignment can be done in place even if bounds are not static,
297    --  by converting it into a loop over the discrete range of the slice.
298
299    ------------------
300    -- Aggr_Size_OK --
301    ------------------
302
303    function Aggr_Size_OK (N : Node_Id; Typ : Entity_Id) return Boolean is
304       Lo   : Node_Id;
305       Hi   : Node_Id;
306       Indx : Node_Id;
307       Siz  : Int;
308       Lov  : Uint;
309       Hiv  : Uint;
310
311       --  The following constant determines the maximum size of an array
312       --  aggregate produced by converting named to positional notation (e.g.
313       --  from others clauses). This avoids running away with attempts to
314       --  convert huge aggregates, which hit memory limits in the backend.
315
316       --  The normal limit is 5000, but we increase this limit to 2**24 (about
317       --  16 million) if Restrictions (No_Elaboration_Code) or Restrictions
318       --  (No_Implicit_Loops) is specified, since in either case, we are at
319       --  risk of declaring the program illegal because of this limit.
320
321       Max_Aggr_Size : constant Nat :=
322                         5000 + (2 ** 24 - 5000) *
323                           Boolean'Pos
324                             (Restriction_Active (No_Elaboration_Code)
325                               or else
326                              Restriction_Active (No_Implicit_Loops));
327
328       function Component_Count (T : Entity_Id) return Int;
329       --  The limit is applied to the total number of components that the
330       --  aggregate will have, which is the number of static expressions
331       --  that will appear in the flattened array. This requires a recursive
332       --  computation of the number of scalar components of the structure.
333
334       ---------------------
335       -- Component_Count --
336       ---------------------
337
338       function Component_Count (T : Entity_Id) return Int is
339          Res  : Int := 0;
340          Comp : Entity_Id;
341
342       begin
343          if Is_Scalar_Type (T) then
344             return 1;
345
346          elsif Is_Record_Type (T) then
347             Comp := First_Component (T);
348             while Present (Comp) loop
349                Res := Res + Component_Count (Etype (Comp));
350                Next_Component (Comp);
351             end loop;
352
353             return Res;
354
355          elsif Is_Array_Type (T) then
356             declare
357                Lo : constant Node_Id :=
358                       Type_Low_Bound (Etype (First_Index (T)));
359                Hi : constant Node_Id :=
360                       Type_High_Bound (Etype (First_Index (T)));
361
362                Siz  : constant Int := Component_Count (Component_Type (T));
363
364             begin
365                if not Compile_Time_Known_Value (Lo)
366                  or else not Compile_Time_Known_Value (Hi)
367                then
368                   return 0;
369                else
370                   return
371                     Siz * UI_To_Int (Expr_Value (Hi) - Expr_Value (Lo) + 1);
372                end if;
373             end;
374
375          else
376             --  Can only be a null for an access type
377
378             return 1;
379          end if;
380       end Component_Count;
381
382    --  Start of processing for Aggr_Size_OK
383
384    begin
385       Siz  := Component_Count (Component_Type (Typ));
386
387       Indx := First_Index (Typ);
388       while Present (Indx) loop
389          Lo  := Type_Low_Bound (Etype (Indx));
390          Hi  := Type_High_Bound (Etype (Indx));
391
392          --  Bounds need to be known at compile time
393
394          if not Compile_Time_Known_Value (Lo)
395            or else not Compile_Time_Known_Value (Hi)
396          then
397             return False;
398          end if;
399
400          Lov := Expr_Value (Lo);
401          Hiv := Expr_Value (Hi);
402
403          --  A flat array is always safe
404
405          if Hiv < Lov then
406             return True;
407          end if;
408
409          --  One-component aggregates are suspicious, and if the context type
410          --  is an object declaration with non-static bounds it will trip gcc;
411          --  such an aggregate must be expanded into a single assignment.
412
413          if Hiv = Lov
414            and then Nkind (Parent (N)) = N_Object_Declaration
415          then
416             declare
417                Index_Type : constant Entity_Id :=
418                               Etype
419                                 (First_Index
420                                    (Etype (Defining_Identifier (Parent (N)))));
421                Indx       : Node_Id;
422
423             begin
424                if not Compile_Time_Known_Value (Type_Low_Bound (Index_Type))
425                   or else not Compile_Time_Known_Value
426                                 (Type_High_Bound (Index_Type))
427                then
428                   if Present (Component_Associations (N)) then
429                      Indx :=
430                        First (Choices (First (Component_Associations (N))));
431                      if Is_Entity_Name (Indx)
432                        and then not Is_Type (Entity (Indx))
433                      then
434                         Error_Msg_N
435                           ("single component aggregate in non-static context?",
436                             Indx);
437                         Error_Msg_N ("\maybe subtype name was meant?", Indx);
438                      end if;
439                   end if;
440
441                   return False;
442                end if;
443             end;
444          end if;
445
446          declare
447             Rng : constant Uint := Hiv - Lov + 1;
448
449          begin
450             --  Check if size is too large
451
452             if not UI_Is_In_Int_Range (Rng) then
453                return False;
454             end if;
455
456             Siz := Siz * UI_To_Int (Rng);
457          end;
458
459          if Siz <= 0
460            or else Siz > Max_Aggr_Size
461          then
462             return False;
463          end if;
464
465          --  Bounds must be in integer range, for later array construction
466
467          if not UI_Is_In_Int_Range (Lov)
468              or else
469             not UI_Is_In_Int_Range (Hiv)
470          then
471             return False;
472          end if;
473
474          Next_Index (Indx);
475       end loop;
476
477       return True;
478    end Aggr_Size_OK;
479
480    ---------------------------------
481    -- Backend_Processing_Possible --
482    ---------------------------------
483
484    --  Backend processing by Gigi/gcc is possible only if all the following
485    --  conditions are met:
486
487    --    1. N is fully positional
488
489    --    2. N is not a bit-packed array aggregate;
490
491    --    3. The size of N's array type must be known at compile time. Note
492    --       that this implies that the component size is also known
493
494    --    4. The array type of N does not follow the Fortran layout convention
495    --       or if it does it must be 1 dimensional.
496
497    --    5. The array component type may not be tagged (which could necessitate
498    --       reassignment of proper tags).
499
500    --    6. The array component type must not have unaligned bit components
501
502    --    7. None of the components of the aggregate may be bit unaligned
503    --       components.
504
505    --    8. There cannot be delayed components, since we do not know enough
506    --       at this stage to know if back end processing is possible.
507
508    --    9. There cannot be any discriminated record components, since the
509    --       back end cannot handle this complex case.
510
511    --   10. No controlled actions need to be generated for components
512
513    --   11. For a VM back end, the array should have no aliased components
514
515    function Backend_Processing_Possible (N : Node_Id) return Boolean is
516       Typ : constant Entity_Id := Etype (N);
517       --  Typ is the correct constrained array subtype of the aggregate
518
519       function Component_Check (N : Node_Id; Index : Node_Id) return Boolean;
520       --  This routine checks components of aggregate N, enforcing checks
521       --  1, 7, 8, and 9. In the multi-dimensional case, these checks are
522       --  performed on subaggregates. The Index value is the current index
523       --  being checked in the multi-dimensional case.
524
525       ---------------------
526       -- Component_Check --
527       ---------------------
528
529       function Component_Check (N : Node_Id; Index : Node_Id) return Boolean is
530          Expr : Node_Id;
531
532       begin
533          --  Checks 1: (no component associations)
534
535          if Present (Component_Associations (N)) then
536             return False;
537          end if;
538
539          --  Checks on components
540
541          --  Recurse to check subaggregates, which may appear in qualified
542          --  expressions. If delayed, the front-end will have to expand.
543          --  If the component is a discriminated record, treat as non-static,
544          --  as the back-end cannot handle this properly.
545
546          Expr := First (Expressions (N));
547          while Present (Expr) loop
548
549             --  Checks 8: (no delayed components)
550
551             if Is_Delayed_Aggregate (Expr) then
552                return False;
553             end if;
554
555             --  Checks 9: (no discriminated records)
556
557             if Present (Etype (Expr))
558               and then Is_Record_Type (Etype (Expr))
559               and then Has_Discriminants (Etype (Expr))
560             then
561                return False;
562             end if;
563
564             --  Checks 7. Component must not be bit aligned component
565
566             if Possible_Bit_Aligned_Component (Expr) then
567                return False;
568             end if;
569
570             --  Recursion to following indexes for multiple dimension case
571
572             if Present (Next_Index (Index))
573                and then not Component_Check (Expr, Next_Index (Index))
574             then
575                return False;
576             end if;
577
578             --  All checks for that component finished, on to next
579
580             Next (Expr);
581          end loop;
582
583          return True;
584       end Component_Check;
585
586    --  Start of processing for Backend_Processing_Possible
587
588    begin
589       --  Checks 2 (array not bit packed) and 10 (no controlled actions)
590
591       if Is_Bit_Packed_Array (Typ) or else Needs_Finalization (Typ) then
592          return False;
593       end if;
594
595       --  If component is limited, aggregate must be expanded because each
596       --  component assignment must be built in place.
597
598       if Is_Immutably_Limited_Type (Component_Type (Typ)) then
599          return False;
600       end if;
601
602       --  Checks 4 (array must not be multi-dimensional Fortran case)
603
604       if Convention (Typ) = Convention_Fortran
605         and then Number_Dimensions (Typ) > 1
606       then
607          return False;
608       end if;
609
610       --  Checks 3 (size of array must be known at compile time)
611
612       if not Size_Known_At_Compile_Time (Typ) then
613          return False;
614       end if;
615
616       --  Checks on components
617
618       if not Component_Check (N, First_Index (Typ)) then
619          return False;
620       end if;
621
622       --  Checks 5 (if the component type is tagged, then we may need to do
623       --    tag adjustments. Perhaps this should be refined to check for any
624       --    component associations that actually need tag adjustment, similar
625       --    to the test in Component_Not_OK_For_Backend for record aggregates
626       --    with tagged components, but not clear whether it's worthwhile ???;
627       --    in the case of the JVM, object tags are handled implicitly)
628
629       if Is_Tagged_Type (Component_Type (Typ))
630         and then Tagged_Type_Expansion
631       then
632          return False;
633       end if;
634
635       --  Checks 6 (component type must not have bit aligned components)
636
637       if Type_May_Have_Bit_Aligned_Components (Component_Type (Typ)) then
638          return False;
639       end if;
640
641       --  Checks 11: Array aggregates with aliased components are currently
642       --  not well supported by the VM backend; disable temporarily this
643       --  backend processing until it is definitely supported.
644
645       if VM_Target /= No_VM
646         and then Has_Aliased_Components (Base_Type (Typ))
647       then
648          return False;
649       end if;
650
651       --  Backend processing is possible
652
653       Set_Size_Known_At_Compile_Time (Etype (N), True);
654       return True;
655    end Backend_Processing_Possible;
656
657    ---------------------------
658    -- Build_Array_Aggr_Code --
659    ---------------------------
660
661    --  The code that we generate from a one dimensional aggregate is
662
663    --  1. If the sub-aggregate contains discrete choices we
664
665    --     (a) Sort the discrete choices
666
667    --     (b) Otherwise for each discrete choice that specifies a range we
668    --         emit a loop. If a range specifies a maximum of three values, or
669    --         we are dealing with an expression we emit a sequence of
670    --         assignments instead of a loop.
671
672    --     (c) Generate the remaining loops to cover the others choice if any
673
674    --  2. If the aggregate contains positional elements we
675
676    --     (a) translate the positional elements in a series of assignments
677
678    --     (b) Generate a final loop to cover the others choice if any.
679    --         Note that this final loop has to be a while loop since the case
680
681    --             L : Integer := Integer'Last;
682    --             H : Integer := Integer'Last;
683    --             A : array (L .. H) := (1, others =>0);
684
685    --         cannot be handled by a for loop. Thus for the following
686
687    --             array (L .. H) := (.. positional elements.., others =>E);
688
689    --         we always generate something like:
690
691    --             J : Index_Type := Index_Of_Last_Positional_Element;
692    --             while J < H loop
693    --                J := Index_Base'Succ (J)
694    --                Tmp (J) := E;
695    --             end loop;
696
697    function Build_Array_Aggr_Code
698      (N           : Node_Id;
699       Ctype       : Entity_Id;
700       Index       : Node_Id;
701       Into        : Node_Id;
702       Scalar_Comp : Boolean;
703       Indexes     : List_Id := No_List;
704       Flist       : Node_Id := Empty) return List_Id
705    is
706       Loc          : constant Source_Ptr := Sloc (N);
707       Index_Base   : constant Entity_Id  := Base_Type (Etype (Index));
708       Index_Base_L : constant Node_Id := Type_Low_Bound (Index_Base);
709       Index_Base_H : constant Node_Id := Type_High_Bound (Index_Base);
710
711       function Add (Val : Int; To : Node_Id) return Node_Id;
712       --  Returns an expression where Val is added to expression To, unless
713       --  To+Val is provably out of To's base type range. To must be an
714       --  already analyzed expression.
715
716       function Empty_Range (L, H : Node_Id) return Boolean;
717       --  Returns True if the range defined by L .. H is certainly empty
718
719       function Equal (L, H : Node_Id) return Boolean;
720       --  Returns True if L = H for sure
721
722       function Index_Base_Name return Node_Id;
723       --  Returns a new reference to the index type name
724
725       function Gen_Assign (Ind : Node_Id; Expr : Node_Id) return List_Id;
726       --  Ind must be a side-effect free expression. If the input aggregate
727       --  N to Build_Loop contains no sub-aggregates, then this function
728       --  returns the assignment statement:
729       --
730       --     Into (Indexes, Ind) := Expr;
731       --
732       --  Otherwise we call Build_Code recursively
733       --
734       --  Ada 2005 (AI-287): In case of default initialized component, Expr
735       --  is empty and we generate a call to the corresponding IP subprogram.
736
737       function Gen_Loop (L, H : Node_Id; Expr : Node_Id) return List_Id;
738       --  Nodes L and H must be side-effect free expressions.
739       --  If the input aggregate N to Build_Loop contains no sub-aggregates,
740       --  This routine returns the for loop statement
741       --
742       --     for J in Index_Base'(L) .. Index_Base'(H) loop
743       --        Into (Indexes, J) := Expr;
744       --     end loop;
745       --
746       --  Otherwise we call Build_Code recursively.
747       --  As an optimization if the loop covers 3 or less scalar elements we
748       --  generate a sequence of assignments.
749
750       function Gen_While (L, H : Node_Id; Expr : Node_Id) return List_Id;
751       --  Nodes L and H must be side-effect free expressions.
752       --  If the input aggregate N to Build_Loop contains no sub-aggregates,
753       --  This routine returns the while loop statement
754       --
755       --     J : Index_Base := L;
756       --     while J < H loop
757       --        J := Index_Base'Succ (J);
758       --        Into (Indexes, J) := Expr;
759       --     end loop;
760       --
761       --  Otherwise we call Build_Code recursively
762
763       function Local_Compile_Time_Known_Value (E : Node_Id) return Boolean;
764       function Local_Expr_Value               (E : Node_Id) return Uint;
765       --  These two Local routines are used to replace the corresponding ones
766       --  in sem_eval because while processing the bounds of an aggregate with
767       --  discrete choices whose index type is an enumeration, we build static
768       --  expressions not recognized by Compile_Time_Known_Value as such since
769       --  they have not yet been analyzed and resolved. All the expressions in
770       --  question are things like Index_Base_Name'Val (Const) which we can
771       --  easily recognize as being constant.
772
773       ---------
774       -- Add --
775       ---------
776
777       function Add (Val : Int; To : Node_Id) return Node_Id is
778          Expr_Pos : Node_Id;
779          Expr     : Node_Id;
780          To_Pos   : Node_Id;
781          U_To     : Uint;
782          U_Val    : constant Uint := UI_From_Int (Val);
783
784       begin
785          --  Note: do not try to optimize the case of Val = 0, because
786          --  we need to build a new node with the proper Sloc value anyway.
787
788          --  First test if we can do constant folding
789
790          if Local_Compile_Time_Known_Value (To) then
791             U_To := Local_Expr_Value (To) + Val;
792
793             --  Determine if our constant is outside the range of the index.
794             --  If so return an Empty node. This empty node will be caught
795             --  by Empty_Range below.
796
797             if Compile_Time_Known_Value (Index_Base_L)
798               and then U_To < Expr_Value (Index_Base_L)
799             then
800                return Empty;
801
802             elsif Compile_Time_Known_Value (Index_Base_H)
803               and then U_To > Expr_Value (Index_Base_H)
804             then
805                return Empty;
806             end if;
807
808             Expr_Pos := Make_Integer_Literal (Loc, U_To);
809             Set_Is_Static_Expression (Expr_Pos);
810
811             if not Is_Enumeration_Type (Index_Base) then
812                Expr := Expr_Pos;
813
814             --  If we are dealing with enumeration return
815             --     Index_Base'Val (Expr_Pos)
816
817             else
818                Expr :=
819                  Make_Attribute_Reference
820                    (Loc,
821                     Prefix         => Index_Base_Name,
822                     Attribute_Name => Name_Val,
823                     Expressions    => New_List (Expr_Pos));
824             end if;
825
826             return Expr;
827          end if;
828
829          --  If we are here no constant folding possible
830
831          if not Is_Enumeration_Type (Index_Base) then
832             Expr :=
833               Make_Op_Add (Loc,
834                            Left_Opnd  => Duplicate_Subexpr (To),
835                            Right_Opnd => Make_Integer_Literal (Loc, U_Val));
836
837          --  If we are dealing with enumeration return
838          --    Index_Base'Val (Index_Base'Pos (To) + Val)
839
840          else
841             To_Pos :=
842               Make_Attribute_Reference
843                 (Loc,
844                  Prefix         => Index_Base_Name,
845                  Attribute_Name => Name_Pos,
846                  Expressions    => New_List (Duplicate_Subexpr (To)));
847
848             Expr_Pos :=
849               Make_Op_Add (Loc,
850                            Left_Opnd  => To_Pos,
851                            Right_Opnd => Make_Integer_Literal (Loc, U_Val));
852
853             Expr :=
854               Make_Attribute_Reference
855                 (Loc,
856                  Prefix         => Index_Base_Name,
857                  Attribute_Name => Name_Val,
858                  Expressions    => New_List (Expr_Pos));
859          end if;
860
861          return Expr;
862       end Add;
863
864       -----------------
865       -- Empty_Range --
866       -----------------
867
868       function Empty_Range (L, H : Node_Id) return Boolean is
869          Is_Empty : Boolean := False;
870          Low      : Node_Id;
871          High     : Node_Id;
872
873       begin
874          --  First check if L or H were already detected as overflowing the
875          --  index base range type by function Add above. If this is so Add
876          --  returns the empty node.
877
878          if No (L) or else No (H) then
879             return True;
880          end if;
881
882          for J in 1 .. 3 loop
883             case J is
884
885                --  L > H    range is empty
886
887                when 1 =>
888                   Low  := L;
889                   High := H;
890
891                --  B_L > H  range must be empty
892
893                when 2 =>
894                   Low  := Index_Base_L;
895                   High := H;
896
897                --  L > B_H  range must be empty
898
899                when 3 =>
900                   Low  := L;
901                   High := Index_Base_H;
902             end case;
903
904             if Local_Compile_Time_Known_Value (Low)
905               and then Local_Compile_Time_Known_Value (High)
906             then
907                Is_Empty :=
908                  UI_Gt (Local_Expr_Value (Low), Local_Expr_Value (High));
909             end if;
910
911             exit when Is_Empty;
912          end loop;
913
914          return Is_Empty;
915       end Empty_Range;
916
917       -----------
918       -- Equal --
919       -----------
920
921       function Equal (L, H : Node_Id) return Boolean is
922       begin
923          if L = H then
924             return True;
925
926          elsif Local_Compile_Time_Known_Value (L)
927            and then Local_Compile_Time_Known_Value (H)
928          then
929             return UI_Eq (Local_Expr_Value (L), Local_Expr_Value (H));
930          end if;
931
932          return False;
933       end Equal;
934
935       ----------------
936       -- Gen_Assign --
937       ----------------
938
939       function Gen_Assign (Ind : Node_Id; Expr : Node_Id) return List_Id is
940          L : constant List_Id := New_List;
941          F : Entity_Id;
942          A : Node_Id;
943
944          New_Indexes  : List_Id;
945          Indexed_Comp : Node_Id;
946          Expr_Q       : Node_Id;
947          Comp_Type    : Entity_Id := Empty;
948
949          function Add_Loop_Actions (Lis : List_Id) return List_Id;
950          --  Collect insert_actions generated in the construction of a
951          --  loop, and prepend them to the sequence of assignments to
952          --  complete the eventual body of the loop.
953
954          ----------------------
955          -- Add_Loop_Actions --
956          ----------------------
957
958          function Add_Loop_Actions (Lis : List_Id) return List_Id is
959             Res : List_Id;
960
961          begin
962             --  Ada 2005 (AI-287): Do nothing else in case of default
963             --  initialized component.
964
965             if No (Expr) then
966                return Lis;
967
968             elsif Nkind (Parent (Expr)) = N_Component_Association
969               and then Present (Loop_Actions (Parent (Expr)))
970             then
971                Append_List (Lis, Loop_Actions (Parent (Expr)));
972                Res := Loop_Actions (Parent (Expr));
973                Set_Loop_Actions (Parent (Expr), No_List);
974                return Res;
975
976             else
977                return Lis;
978             end if;
979          end Add_Loop_Actions;
980
981       --  Start of processing for Gen_Assign
982
983       begin
984          if No (Indexes) then
985             New_Indexes := New_List;
986          else
987             New_Indexes := New_Copy_List_Tree (Indexes);
988          end if;
989
990          Append_To (New_Indexes, Ind);
991
992          if Present (Flist) then
993             F := New_Copy_Tree (Flist);
994
995          elsif Present (Etype (N)) and then Needs_Finalization (Etype (N)) then
996             if Is_Entity_Name (Into)
997               and then Present (Scope (Entity (Into)))
998             then
999                F := Find_Final_List (Scope (Entity (Into)));
1000             else
1001                F := Find_Final_List (Current_Scope);
1002             end if;
1003          else
1004             F := Empty;
1005          end if;
1006
1007          if Present (Next_Index (Index)) then
1008             return
1009               Add_Loop_Actions (
1010                 Build_Array_Aggr_Code
1011                   (N           => Expr,
1012                    Ctype       => Ctype,
1013                    Index       => Next_Index (Index),
1014                    Into        => Into,
1015                    Scalar_Comp => Scalar_Comp,
1016                    Indexes     => New_Indexes,
1017                    Flist       => F));
1018          end if;
1019
1020          --  If we get here then we are at a bottom-level (sub-)aggregate
1021
1022          Indexed_Comp :=
1023            Checks_Off
1024              (Make_Indexed_Component (Loc,
1025                 Prefix      => New_Copy_Tree (Into),
1026                 Expressions => New_Indexes));
1027
1028          Set_Assignment_OK (Indexed_Comp);
1029
1030          --  Ada 2005 (AI-287): In case of default initialized component, Expr
1031          --  is not present (and therefore we also initialize Expr_Q to empty).
1032
1033          if No (Expr) then
1034             Expr_Q := Empty;
1035          elsif Nkind (Expr) = N_Qualified_Expression then
1036             Expr_Q := Expression (Expr);
1037          else
1038             Expr_Q := Expr;
1039          end if;
1040
1041          if Present (Etype (N))
1042            and then Etype (N) /= Any_Composite
1043          then
1044             Comp_Type := Component_Type (Etype (N));
1045             pragma Assert (Comp_Type = Ctype); --  AI-287
1046
1047          elsif Present (Next (First (New_Indexes))) then
1048
1049             --  Ada 2005 (AI-287): Do nothing in case of default initialized
1050             --  component because we have received the component type in
1051             --  the formal parameter Ctype.
1052
1053             --  ??? Some assert pragmas have been added to check if this new
1054             --      formal can be used to replace this code in all cases.
1055
1056             if Present (Expr) then
1057
1058                --  This is a multidimensional array. Recover the component
1059                --  type from the outermost aggregate, because subaggregates
1060                --  do not have an assigned type.
1061
1062                declare
1063                   P : Node_Id;
1064
1065                begin
1066                   P := Parent (Expr);
1067                   while Present (P) loop
1068                      if Nkind (P) = N_Aggregate
1069                        and then Present (Etype (P))
1070                      then
1071                         Comp_Type := Component_Type (Etype (P));
1072                         exit;
1073
1074                      else
1075                         P := Parent (P);
1076                      end if;
1077                   end loop;
1078
1079                   pragma Assert (Comp_Type = Ctype); --  AI-287
1080                end;
1081             end if;
1082          end if;
1083
1084          --  Ada 2005 (AI-287): We only analyze the expression in case of non-
1085          --  default initialized components (otherwise Expr_Q is not present).
1086
1087          if Present (Expr_Q)
1088            and then Nkind_In (Expr_Q, N_Aggregate, N_Extension_Aggregate)
1089          then
1090             --  At this stage the Expression may not have been analyzed yet
1091             --  because the array aggregate code has not been updated to use
1092             --  the Expansion_Delayed flag and avoid analysis altogether to
1093             --  solve the same problem (see Resolve_Aggr_Expr). So let us do
1094             --  the analysis of non-array aggregates now in order to get the
1095             --  value of Expansion_Delayed flag for the inner aggregate ???
1096
1097             if Present (Comp_Type) and then not Is_Array_Type (Comp_Type) then
1098                Analyze_And_Resolve (Expr_Q, Comp_Type);
1099             end if;
1100
1101             if Is_Delayed_Aggregate (Expr_Q) then
1102
1103                --  This is either a subaggregate of a multidimensional array,
1104                --  or a component of an array type whose component type is
1105                --  also an array. In the latter case, the expression may have
1106                --  component associations that provide different bounds from
1107                --  those of the component type, and sliding must occur. Instead
1108                --  of decomposing the current aggregate assignment, force the
1109                --  re-analysis of the assignment, so that a temporary will be
1110                --  generated in the usual fashion, and sliding will take place.
1111
1112                if Nkind (Parent (N)) = N_Assignment_Statement
1113                  and then Is_Array_Type (Comp_Type)
1114                  and then Present (Component_Associations (Expr_Q))
1115                  and then Must_Slide (Comp_Type, Etype (Expr_Q))
1116                then
1117                   Set_Expansion_Delayed (Expr_Q, False);
1118                   Set_Analyzed (Expr_Q, False);
1119
1120                else
1121                   return
1122                     Add_Loop_Actions (
1123                       Late_Expansion (
1124                         Expr_Q, Etype (Expr_Q), Indexed_Comp, F));
1125                end if;
1126             end if;
1127          end if;
1128
1129          --  Ada 2005 (AI-287): In case of default initialized component, call
1130          --  the initialization subprogram associated with the component type.
1131          --  If the component type is an access type, add an explicit null
1132          --  assignment, because for the back-end there is an initialization
1133          --  present for the whole aggregate, and no default initialization
1134          --  will take place.
1135
1136          --  In addition, if the component type is controlled, we must call
1137          --  its Initialize procedure explicitly, because there is no explicit
1138          --  object creation that will invoke it otherwise.
1139
1140          if No (Expr) then
1141             if Present (Base_Init_Proc (Base_Type (Ctype)))
1142               or else Has_Task (Base_Type (Ctype))
1143             then
1144                Append_List_To (L,
1145                  Build_Initialization_Call (Loc,
1146                    Id_Ref            => Indexed_Comp,
1147                    Typ               => Ctype,
1148                    With_Default_Init => True));
1149
1150             elsif Is_Access_Type (Ctype) then
1151                Append_To (L,
1152                   Make_Assignment_Statement (Loc,
1153                      Name => Indexed_Comp,
1154                      Expression => Make_Null (Loc)));
1155             end if;
1156
1157             if Needs_Finalization (Ctype) then
1158                Append_List_To (L,
1159                  Make_Init_Call (
1160                    Ref         => New_Copy_Tree (Indexed_Comp),
1161                    Typ         => Ctype,
1162                    Flist_Ref   => Find_Final_List (Current_Scope),
1163                    With_Attach => Make_Integer_Literal (Loc, 1)));
1164             end if;
1165
1166          else
1167             --  Now generate the assignment with no associated controlled
1168             --  actions since the target of the assignment may not have been
1169             --  initialized, it is not possible to Finalize it as expected by
1170             --  normal controlled assignment. The rest of the controlled
1171             --  actions are done manually with the proper finalization list
1172             --  coming from the context.
1173
1174             A :=
1175               Make_OK_Assignment_Statement (Loc,
1176                 Name       => Indexed_Comp,
1177                 Expression => New_Copy_Tree (Expr));
1178
1179             if Present (Comp_Type) and then Needs_Finalization (Comp_Type) then
1180                Set_No_Ctrl_Actions (A);
1181
1182                --  If this is an aggregate for an array of arrays, each
1183                --  sub-aggregate will be expanded as well, and even with
1184                --  No_Ctrl_Actions the assignments of inner components will
1185                --  require attachment in their assignments to temporaries.
1186                --  These temporaries must be finalized for each subaggregate,
1187                --  to prevent multiple attachments of the same temporary
1188                --  location to same finalization chain (and consequently
1189                --  circular lists). To ensure that finalization takes place
1190                --  for each subaggregate we wrap the assignment in a block.
1191
1192                if Is_Array_Type (Comp_Type)
1193                  and then Nkind (Expr) = N_Aggregate
1194                then
1195                   A :=
1196                     Make_Block_Statement (Loc,
1197                       Handled_Statement_Sequence =>
1198                         Make_Handled_Sequence_Of_Statements (Loc,
1199                            Statements => New_List (A)));
1200                end if;
1201             end if;
1202
1203             Append_To (L, A);
1204
1205             --  Adjust the tag if tagged (because of possible view
1206             --  conversions), unless compiling for a VM where
1207             --  tags are implicit.
1208
1209             if Present (Comp_Type)
1210               and then Is_Tagged_Type (Comp_Type)
1211               and then Tagged_Type_Expansion
1212             then
1213                declare
1214                   Full_Typ : constant Entity_Id := Underlying_Type (Comp_Type);
1215
1216                begin
1217                   A :=
1218                     Make_OK_Assignment_Statement (Loc,
1219                       Name =>
1220                         Make_Selected_Component (Loc,
1221                           Prefix =>  New_Copy_Tree (Indexed_Comp),
1222                           Selector_Name =>
1223                             New_Reference_To
1224                               (First_Tag_Component (Full_Typ), Loc)),
1225
1226                       Expression =>
1227                         Unchecked_Convert_To (RTE (RE_Tag),
1228                           New_Reference_To
1229                             (Node (First_Elmt (Access_Disp_Table (Full_Typ))),
1230                              Loc)));
1231
1232                   Append_To (L, A);
1233                end;
1234             end if;
1235
1236             --  Adjust and attach the component to the proper final list, which
1237             --  can be the controller of the outer record object or the final
1238             --  list associated with the scope.
1239
1240             --  If the component is itself an array of controlled types, whose
1241             --  value is given by a sub-aggregate, then the attach calls have
1242             --  been generated when individual subcomponent are assigned, and
1243             --  must not be done again to prevent malformed finalization chains
1244             --  (see comments above, concerning the creation of a block to hold
1245             --  inner finalization actions).
1246
1247             if Present (Comp_Type)
1248               and then Needs_Finalization (Comp_Type)
1249               and then not Is_Limited_Type (Comp_Type)
1250               and then not
1251                 (Is_Array_Type (Comp_Type)
1252                    and then Is_Controlled (Component_Type (Comp_Type))
1253                    and then Nkind (Expr) = N_Aggregate)
1254             then
1255                Append_List_To (L,
1256                  Make_Adjust_Call (
1257                    Ref         => New_Copy_Tree (Indexed_Comp),
1258                    Typ         => Comp_Type,
1259                    Flist_Ref   => F,
1260                    With_Attach => Make_Integer_Literal (Loc, 1)));
1261             end if;
1262          end if;
1263
1264          return Add_Loop_Actions (L);
1265       end Gen_Assign;
1266
1267       --------------
1268       -- Gen_Loop --
1269       --------------
1270
1271       function Gen_Loop (L, H : Node_Id; Expr : Node_Id) return List_Id is
1272          L_J : Node_Id;
1273
1274          L_L : Node_Id;
1275          --  Index_Base'(L)
1276
1277          L_H : Node_Id;
1278          --  Index_Base'(H)
1279
1280          L_Range : Node_Id;
1281          --  Index_Base'(L) .. Index_Base'(H)
1282
1283          L_Iteration_Scheme : Node_Id;
1284          --  L_J in Index_Base'(L) .. Index_Base'(H)
1285
1286          L_Body : List_Id;
1287          --  The statements to execute in the loop
1288
1289          S : constant List_Id := New_List;
1290          --  List of statements
1291
1292          Tcopy : Node_Id;
1293          --  Copy of expression tree, used for checking purposes
1294
1295       begin
1296          --  If loop bounds define an empty range return the null statement
1297
1298          if Empty_Range (L, H) then
1299             Append_To (S, Make_Null_Statement (Loc));
1300
1301             --  Ada 2005 (AI-287): Nothing else need to be done in case of
1302             --  default initialized component.
1303
1304             if No (Expr) then
1305                null;
1306
1307             else
1308                --  The expression must be type-checked even though no component
1309                --  of the aggregate will have this value. This is done only for
1310                --  actual components of the array, not for subaggregates. Do
1311                --  the check on a copy, because the expression may be shared
1312                --  among several choices, some of which might be non-null.
1313
1314                if Present (Etype (N))
1315                  and then Is_Array_Type (Etype (N))
1316                  and then No (Next_Index (Index))
1317                then
1318                   Expander_Mode_Save_And_Set (False);
1319                   Tcopy := New_Copy_Tree (Expr);
1320                   Set_Parent (Tcopy, N);
1321                   Analyze_And_Resolve (Tcopy, Component_Type (Etype (N)));
1322                   Expander_Mode_Restore;
1323                end if;
1324             end if;
1325
1326             return S;
1327
1328          --  If loop bounds are the same then generate an assignment
1329
1330          elsif Equal (L, H) then
1331             return Gen_Assign (New_Copy_Tree (L), Expr);
1332
1333          --  If H - L <= 2 then generate a sequence of assignments when we are
1334          --  processing the bottom most aggregate and it contains scalar
1335          --  components.
1336
1337          elsif No (Next_Index (Index))
1338            and then Scalar_Comp
1339            and then Local_Compile_Time_Known_Value (L)
1340            and then Local_Compile_Time_Known_Value (H)
1341            and then Local_Expr_Value (H) - Local_Expr_Value (L) <= 2
1342          then
1343
1344             Append_List_To (S, Gen_Assign (New_Copy_Tree (L), Expr));
1345             Append_List_To (S, Gen_Assign (Add (1, To => L), Expr));
1346
1347             if Local_Expr_Value (H) - Local_Expr_Value (L) = 2 then
1348                Append_List_To (S, Gen_Assign (Add (2, To => L), Expr));
1349             end if;
1350
1351             return S;
1352          end if;
1353
1354          --  Otherwise construct the loop, starting with the loop index L_J
1355
1356          L_J := Make_Temporary (Loc, 'J', L);
1357
1358          --  Construct "L .. H" in Index_Base. We use a qualified expression
1359          --  for the bound to convert to the index base, but we don't need
1360          --  to do that if we already have the base type at hand.
1361
1362          if Etype (L) = Index_Base then
1363             L_L := L;
1364          else
1365             L_L :=
1366               Make_Qualified_Expression (Loc,
1367                 Subtype_Mark => Index_Base_Name,
1368                 Expression   => L);
1369          end if;
1370
1371          if Etype (H) = Index_Base then
1372             L_H := H;
1373          else
1374             L_H :=
1375               Make_Qualified_Expression (Loc,
1376                 Subtype_Mark => Index_Base_Name,
1377                 Expression   => H);
1378          end if;
1379
1380          L_Range :=
1381            Make_Range (Loc,
1382              Low_Bound => L_L,
1383              High_Bound => L_H);
1384
1385          --  Construct "for L_J in Index_Base range L .. H"
1386
1387          L_Iteration_Scheme :=
1388            Make_Iteration_Scheme
1389              (Loc,
1390               Loop_Parameter_Specification =>
1391                 Make_Loop_Parameter_Specification
1392                   (Loc,
1393                    Defining_Identifier         => L_J,
1394                    Discrete_Subtype_Definition => L_Range));
1395
1396          --  Construct the statements to execute in the loop body
1397
1398          L_Body := Gen_Assign (New_Reference_To (L_J, Loc), Expr);
1399
1400          --  Construct the final loop
1401
1402          Append_To (S, Make_Implicit_Loop_Statement
1403                          (Node             => N,
1404                           Identifier       => Empty,
1405                           Iteration_Scheme => L_Iteration_Scheme,
1406                           Statements       => L_Body));
1407
1408          --  A small optimization: if the aggregate is initialized with a box
1409          --  and the component type has no initialization procedure, remove the
1410          --  useless empty loop.
1411
1412          if Nkind (First (S)) = N_Loop_Statement
1413            and then Is_Empty_List (Statements (First (S)))
1414          then
1415             return New_List (Make_Null_Statement (Loc));
1416          else
1417             return S;
1418          end if;
1419       end Gen_Loop;
1420
1421       ---------------
1422       -- Gen_While --
1423       ---------------
1424
1425       --  The code built is
1426
1427       --     W_J : Index_Base := L;
1428       --     while W_J < H loop
1429       --        W_J := Index_Base'Succ (W);
1430       --        L_Body;
1431       --     end loop;
1432
1433       function Gen_While (L, H : Node_Id; Expr : Node_Id) return List_Id is
1434          W_J : Node_Id;
1435
1436          W_Decl : Node_Id;
1437          --  W_J : Base_Type := L;
1438
1439          W_Iteration_Scheme : Node_Id;
1440          --  while W_J < H
1441
1442          W_Index_Succ : Node_Id;
1443          --  Index_Base'Succ (J)
1444
1445          W_Increment : Node_Id;
1446          --  W_J := Index_Base'Succ (W)
1447
1448          W_Body : constant List_Id := New_List;
1449          --  The statements to execute in the loop
1450
1451          S : constant List_Id := New_List;
1452          --  list of statement
1453
1454       begin
1455          --  If loop bounds define an empty range or are equal return null
1456
1457          if Empty_Range (L, H) or else Equal (L, H) then
1458             Append_To (S, Make_Null_Statement (Loc));
1459             return S;
1460          end if;
1461
1462          --  Build the decl of W_J
1463
1464          W_J    := Make_Temporary (Loc, 'J', L);
1465          W_Decl :=
1466            Make_Object_Declaration
1467              (Loc,
1468               Defining_Identifier => W_J,
1469               Object_Definition   => Index_Base_Name,
1470               Expression          => L);
1471
1472          --  Theoretically we should do a New_Copy_Tree (L) here, but we know
1473          --  that in this particular case L is a fresh Expr generated by
1474          --  Add which we are the only ones to use.
1475
1476          Append_To (S, W_Decl);
1477
1478          --  Construct " while W_J < H"
1479
1480          W_Iteration_Scheme :=
1481            Make_Iteration_Scheme
1482              (Loc,
1483               Condition => Make_Op_Lt
1484                              (Loc,
1485                               Left_Opnd  => New_Reference_To (W_J, Loc),
1486                               Right_Opnd => New_Copy_Tree (H)));
1487
1488          --  Construct the statements to execute in the loop body
1489
1490          W_Index_Succ :=
1491            Make_Attribute_Reference
1492              (Loc,
1493               Prefix         => Index_Base_Name,
1494               Attribute_Name => Name_Succ,
1495               Expressions    => New_List (New_Reference_To (W_J, Loc)));
1496
1497          W_Increment  :=
1498            Make_OK_Assignment_Statement
1499              (Loc,
1500               Name       => New_Reference_To (W_J, Loc),
1501               Expression => W_Index_Succ);
1502
1503          Append_To (W_Body, W_Increment);
1504          Append_List_To (W_Body,
1505            Gen_Assign (New_Reference_To (W_J, Loc), Expr));
1506
1507          --  Construct the final loop
1508
1509          Append_To (S, Make_Implicit_Loop_Statement
1510                          (Node             => N,
1511                           Identifier       => Empty,
1512                           Iteration_Scheme => W_Iteration_Scheme,
1513                           Statements       => W_Body));
1514
1515          return S;
1516       end Gen_While;
1517
1518       ---------------------
1519       -- Index_Base_Name --
1520       ---------------------
1521
1522       function Index_Base_Name return Node_Id is
1523       begin
1524          return New_Reference_To (Index_Base, Sloc (N));
1525       end Index_Base_Name;
1526
1527       ------------------------------------
1528       -- Local_Compile_Time_Known_Value --
1529       ------------------------------------
1530
1531       function Local_Compile_Time_Known_Value (E : Node_Id) return Boolean is
1532       begin
1533          return Compile_Time_Known_Value (E)
1534            or else
1535              (Nkind (E) = N_Attribute_Reference
1536                and then Attribute_Name (E) = Name_Val
1537                and then Compile_Time_Known_Value (First (Expressions (E))));
1538       end Local_Compile_Time_Known_Value;
1539
1540       ----------------------
1541       -- Local_Expr_Value --
1542       ----------------------
1543
1544       function Local_Expr_Value (E : Node_Id) return Uint is
1545       begin
1546          if Compile_Time_Known_Value (E) then
1547             return Expr_Value (E);
1548          else
1549             return Expr_Value (First (Expressions (E)));
1550          end if;
1551       end Local_Expr_Value;
1552
1553       --  Build_Array_Aggr_Code Variables
1554
1555       Assoc  : Node_Id;
1556       Choice : Node_Id;
1557       Expr   : Node_Id;
1558       Typ    : Entity_Id;
1559
1560       Others_Expr        : Node_Id := Empty;
1561       Others_Box_Present : Boolean := False;
1562
1563       Aggr_L : constant Node_Id := Low_Bound (Aggregate_Bounds (N));
1564       Aggr_H : constant Node_Id := High_Bound (Aggregate_Bounds (N));
1565       --  The aggregate bounds of this specific sub-aggregate. Note that if
1566       --  the code generated by Build_Array_Aggr_Code is executed then these
1567       --  bounds are OK. Otherwise a Constraint_Error would have been raised.
1568
1569       Aggr_Low  : constant Node_Id := Duplicate_Subexpr_No_Checks (Aggr_L);
1570       Aggr_High : constant Node_Id := Duplicate_Subexpr_No_Checks (Aggr_H);
1571       --  After Duplicate_Subexpr these are side-effect free
1572
1573       Low        : Node_Id;
1574       High       : Node_Id;
1575
1576       Nb_Choices : Nat := 0;
1577       Table      : Case_Table_Type (1 .. Number_Of_Choices (N));
1578       --  Used to sort all the different choice values
1579
1580       Nb_Elements : Int;
1581       --  Number of elements in the positional aggregate
1582
1583       New_Code : constant List_Id := New_List;
1584
1585    --  Start of processing for Build_Array_Aggr_Code
1586
1587    begin
1588       --  First before we start, a special case. if we have a bit packed
1589       --  array represented as a modular type, then clear the value to
1590       --  zero first, to ensure that unused bits are properly cleared.
1591
1592       Typ := Etype (N);
1593
1594       if Present (Typ)
1595         and then Is_Bit_Packed_Array (Typ)
1596         and then Is_Modular_Integer_Type (Packed_Array_Type (Typ))
1597       then
1598          Append_To (New_Code,
1599            Make_Assignment_Statement (Loc,
1600              Name => New_Copy_Tree (Into),
1601              Expression =>
1602                Unchecked_Convert_To (Typ,
1603                  Make_Integer_Literal (Loc, Uint_0))));
1604       end if;
1605
1606       --  If the component type contains tasks, we need to build a Master
1607       --  entity in the current scope, because it will be needed if build-
1608       --  in-place functions are called in the expanded code.
1609
1610       if Nkind (Parent (N)) = N_Object_Declaration
1611         and then Has_Task (Typ)
1612       then
1613          Build_Master_Entity (Defining_Identifier (Parent (N)));
1614       end if;
1615
1616       --  STEP 1: Process component associations
1617
1618       --  For those associations that may generate a loop, initialize
1619       --  Loop_Actions to collect inserted actions that may be crated.
1620
1621       --  Skip this if no component associations
1622
1623       if No (Expressions (N)) then
1624
1625          --  STEP 1 (a): Sort the discrete choices
1626
1627          Assoc := First (Component_Associations (N));
1628          while Present (Assoc) loop
1629             Choice := First (Choices (Assoc));
1630             while Present (Choice) loop
1631                if Nkind (Choice) = N_Others_Choice then
1632                   Set_Loop_Actions (Assoc, New_List);
1633
1634                   if Box_Present (Assoc) then
1635                      Others_Box_Present := True;
1636                   else
1637                      Others_Expr := Expression (Assoc);
1638                   end if;
1639                   exit;
1640                end if;
1641
1642                Get_Index_Bounds (Choice, Low, High);
1643
1644                if Low /= High then
1645                   Set_Loop_Actions (Assoc, New_List);
1646                end if;
1647
1648                Nb_Choices := Nb_Choices + 1;
1649                if Box_Present (Assoc) then
1650                   Table (Nb_Choices) := (Choice_Lo   => Low,
1651                                          Choice_Hi   => High,
1652                                          Choice_Node => Empty);
1653                else
1654                   Table (Nb_Choices) := (Choice_Lo   => Low,
1655                                          Choice_Hi   => High,
1656                                          Choice_Node => Expression (Assoc));
1657                end if;
1658                Next (Choice);
1659             end loop;
1660
1661             Next (Assoc);
1662          end loop;
1663
1664          --  If there is more than one set of choices these must be static
1665          --  and we can therefore sort them. Remember that Nb_Choices does not
1666          --  account for an others choice.
1667
1668          if Nb_Choices > 1 then
1669             Sort_Case_Table (Table);
1670          end if;
1671
1672          --  STEP 1 (b):  take care of the whole set of discrete choices
1673
1674          for J in 1 .. Nb_Choices loop
1675             Low  := Table (J).Choice_Lo;
1676             High := Table (J).Choice_Hi;
1677             Expr := Table (J).Choice_Node;
1678             Append_List (Gen_Loop (Low, High, Expr), To => New_Code);
1679          end loop;
1680
1681          --  STEP 1 (c): generate the remaining loops to cover others choice
1682          --  We don't need to generate loops over empty gaps, but if there is
1683          --  a single empty range we must analyze the expression for semantics
1684
1685          if Present (Others_Expr) or else Others_Box_Present then
1686             declare
1687                First : Boolean := True;
1688
1689             begin
1690                for J in 0 .. Nb_Choices loop
1691                   if J = 0 then
1692                      Low := Aggr_Low;
1693                   else
1694                      Low := Add (1, To => Table (J).Choice_Hi);
1695                   end if;
1696
1697                   if J = Nb_Choices then
1698                      High := Aggr_High;
1699                   else
1700                      High := Add (-1, To => Table (J + 1).Choice_Lo);
1701                   end if;
1702
1703                   --  If this is an expansion within an init proc, make
1704                   --  sure that discriminant references are replaced by
1705                   --  the corresponding discriminal.
1706
1707                   if Inside_Init_Proc then
1708                      if Is_Entity_Name (Low)
1709                        and then Ekind (Entity (Low)) = E_Discriminant
1710                      then
1711                         Set_Entity (Low, Discriminal (Entity (Low)));
1712                      end if;
1713
1714                      if Is_Entity_Name (High)
1715                        and then Ekind (Entity (High)) = E_Discriminant
1716                      then
1717                         Set_Entity (High, Discriminal (Entity (High)));
1718                      end if;
1719                   end if;
1720
1721                   if First
1722                     or else not Empty_Range (Low, High)
1723                   then
1724                      First := False;
1725                      Append_List
1726                        (Gen_Loop (Low, High, Others_Expr), To => New_Code);
1727                   end if;
1728                end loop;
1729             end;
1730          end if;
1731
1732       --  STEP 2: Process positional components
1733
1734       else
1735          --  STEP 2 (a): Generate the assignments for each positional element
1736          --  Note that here we have to use Aggr_L rather than Aggr_Low because
1737          --  Aggr_L is analyzed and Add wants an analyzed expression.
1738
1739          Expr        := First (Expressions (N));
1740          Nb_Elements := -1;
1741          while Present (Expr) loop
1742             Nb_Elements := Nb_Elements + 1;
1743             Append_List (Gen_Assign (Add (Nb_Elements, To => Aggr_L), Expr),
1744                          To => New_Code);
1745             Next (Expr);
1746          end loop;
1747
1748          --  STEP 2 (b): Generate final loop if an others choice is present
1749          --  Here Nb_Elements gives the offset of the last positional element.
1750
1751          if Present (Component_Associations (N)) then
1752             Assoc := Last (Component_Associations (N));
1753
1754             --  Ada 2005 (AI-287)
1755
1756             if Box_Present (Assoc) then
1757                Append_List (Gen_While (Add (Nb_Elements, To => Aggr_L),
1758                                        Aggr_High,
1759                                        Empty),
1760                             To => New_Code);
1761             else
1762                Expr  := Expression (Assoc);
1763
1764                Append_List (Gen_While (Add (Nb_Elements, To => Aggr_L),
1765                                        Aggr_High,
1766                                        Expr), --  AI-287
1767                             To => New_Code);
1768             end if;
1769          end if;
1770       end if;
1771
1772       return New_Code;
1773    end Build_Array_Aggr_Code;
1774
1775    ----------------------------
1776    -- Build_Record_Aggr_Code --
1777    ----------------------------
1778
1779    function Build_Record_Aggr_Code
1780      (N                             : Node_Id;
1781       Typ                           : Entity_Id;
1782       Lhs                           : Node_Id;
1783       Flist                         : Node_Id   := Empty;
1784       Obj                           : Entity_Id := Empty;
1785       Is_Limited_Ancestor_Expansion : Boolean   := False) return List_Id
1786    is
1787       Loc     : constant Source_Ptr := Sloc (N);
1788       L       : constant List_Id    := New_List;
1789       N_Typ   : constant Entity_Id  := Etype (N);
1790
1791       Comp      : Node_Id;
1792       Instr     : Node_Id;
1793       Ref       : Node_Id;
1794       Target    : Entity_Id;
1795       F         : Node_Id;
1796       Comp_Type : Entity_Id;
1797       Selector  : Entity_Id;
1798       Comp_Expr : Node_Id;
1799       Expr_Q    : Node_Id;
1800
1801       Internal_Final_List : Node_Id := Empty;
1802
1803       --  If this is an internal aggregate, the External_Final_List is an
1804       --  expression for the controller record of the enclosing type.
1805
1806       --  If the current aggregate has several controlled components, this
1807       --  expression will appear in several calls to attach to the finali-
1808       --  zation list, and it must not be shared.
1809
1810       External_Final_List      : Node_Id;
1811       Ancestor_Is_Expression   : Boolean := False;
1812       Ancestor_Is_Subtype_Mark : Boolean := False;
1813
1814       Init_Typ : Entity_Id := Empty;
1815       Attach   : Node_Id;
1816
1817       Ctrl_Stuff_Done : Boolean := False;
1818       --  True if Gen_Ctrl_Actions_For_Aggr has already been called; calls
1819       --  after the first do nothing.
1820
1821       function Ancestor_Discriminant_Value (Disc : Entity_Id) return Node_Id;
1822       --  Returns the value that the given discriminant of an ancestor type
1823       --  should receive (in the absence of a conflict with the value provided
1824       --  by an ancestor part of an extension aggregate).
1825
1826       procedure Check_Ancestor_Discriminants (Anc_Typ : Entity_Id);
1827       --  Check that each of the discriminant values defined by the ancestor
1828       --  part of an extension aggregate match the corresponding values
1829       --  provided by either an association of the aggregate or by the
1830       --  constraint imposed by a parent type (RM95-4.3.2(8)).
1831
1832       function Compatible_Int_Bounds
1833         (Agg_Bounds : Node_Id;
1834          Typ_Bounds : Node_Id) return Boolean;
1835       --  Return true if Agg_Bounds are equal or within Typ_Bounds. It is
1836       --  assumed that both bounds are integer ranges.
1837
1838       procedure Gen_Ctrl_Actions_For_Aggr;
1839       --  Deal with the various controlled type data structure initializations
1840       --  (but only if it hasn't been done already).
1841
1842       function Get_Constraint_Association (T : Entity_Id) return Node_Id;
1843       --  Returns the first discriminant association in the constraint
1844       --  associated with T, if any, otherwise returns Empty.
1845
1846       function Init_Controller
1847         (Target  : Node_Id;
1848          Typ     : Entity_Id;
1849          F       : Node_Id;
1850          Attach  : Node_Id;
1851          Init_Pr : Boolean) return List_Id;
1852       --  Returns the list of statements necessary to initialize the internal
1853       --  controller of the (possible) ancestor typ into target and attach it
1854       --  to finalization list F. Init_Pr conditions the call to the init proc
1855       --  since it may already be done due to ancestor initialization.
1856
1857       procedure Init_Hidden_Discriminants (Typ : Entity_Id; List : List_Id);
1858       --  If Typ is derived, and constrains discriminants of the parent type,
1859       --  these discriminants are not components of the aggregate, and must be
1860       --  initialized. The assignments are appended to List.
1861
1862       function Is_Int_Range_Bounds (Bounds : Node_Id) return Boolean;
1863       --  Check whether Bounds is a range node and its lower and higher bounds
1864       --  are integers literals.
1865
1866       ---------------------------------
1867       -- Ancestor_Discriminant_Value --
1868       ---------------------------------
1869
1870       function Ancestor_Discriminant_Value (Disc : Entity_Id) return Node_Id is
1871          Assoc        : Node_Id;
1872          Assoc_Elmt   : Elmt_Id;
1873          Aggr_Comp    : Entity_Id;
1874          Corresp_Disc : Entity_Id;
1875          Current_Typ  : Entity_Id := Base_Type (Typ);
1876          Parent_Typ   : Entity_Id;
1877          Parent_Disc  : Entity_Id;
1878          Save_Assoc   : Node_Id := Empty;
1879
1880       begin
1881          --  First check any discriminant associations to see if any of them
1882          --  provide a value for the discriminant.
1883
1884          if Present (Discriminant_Specifications (Parent (Current_Typ))) then
1885             Assoc := First (Component_Associations (N));
1886             while Present (Assoc) loop
1887                Aggr_Comp := Entity (First (Choices (Assoc)));
1888
1889                if Ekind (Aggr_Comp) = E_Discriminant then
1890                   Save_Assoc := Expression (Assoc);
1891
1892                   Corresp_Disc := Corresponding_Discriminant (Aggr_Comp);
1893                   while Present (Corresp_Disc) loop
1894
1895                      --  If found a corresponding discriminant then return the
1896                      --  value given in the aggregate. (Note: this is not
1897                      --  correct in the presence of side effects. ???)
1898
1899                      if Disc = Corresp_Disc then
1900                         return Duplicate_Subexpr (Expression (Assoc));
1901                      end if;
1902
1903                      Corresp_Disc :=
1904                        Corresponding_Discriminant (Corresp_Disc);
1905                   end loop;
1906                end if;
1907
1908                Next (Assoc);
1909             end loop;
1910          end if;
1911
1912          --  No match found in aggregate, so chain up parent types to find
1913          --  a constraint that defines the value of the discriminant.
1914
1915          Parent_Typ := Etype (Current_Typ);
1916          while Current_Typ /= Parent_Typ loop
1917             if Has_Discriminants (Parent_Typ)
1918               and then not Has_Unknown_Discriminants (Parent_Typ)
1919             then
1920                Parent_Disc := First_Discriminant (Parent_Typ);
1921
1922                --  We either get the association from the subtype indication
1923                --  of the type definition itself, or from the discriminant
1924                --  constraint associated with the type entity (which is
1925                --  preferable, but it's not always present ???)
1926
1927                if Is_Empty_Elmt_List (
1928                  Discriminant_Constraint (Current_Typ))
1929                then
1930                   Assoc := Get_Constraint_Association (Current_Typ);
1931                   Assoc_Elmt := No_Elmt;
1932                else
1933                   Assoc_Elmt :=
1934                     First_Elmt (Discriminant_Constraint (Current_Typ));
1935                   Assoc := Node (Assoc_Elmt);
1936                end if;
1937
1938                --  Traverse the discriminants of the parent type looking
1939                --  for one that corresponds.
1940
1941                while Present (Parent_Disc) and then Present (Assoc) loop
1942                   Corresp_Disc := Parent_Disc;
1943                   while Present (Corresp_Disc)
1944                     and then Disc /= Corresp_Disc
1945                   loop
1946                      Corresp_Disc :=
1947                        Corresponding_Discriminant (Corresp_Disc);
1948                   end loop;
1949
1950                   if Disc = Corresp_Disc then
1951                      if Nkind (Assoc) = N_Discriminant_Association then
1952                         Assoc := Expression (Assoc);
1953                      end if;
1954
1955                      --  If the located association directly denotes a
1956                      --  discriminant, then use the value of a saved
1957                      --  association of the aggregate. This is a kludge to
1958                      --  handle certain cases involving multiple discriminants
1959                      --  mapped to a single discriminant of a descendant. It's
1960                      --  not clear how to locate the appropriate discriminant
1961                      --  value for such cases. ???
1962
1963                      if Is_Entity_Name (Assoc)
1964                        and then Ekind (Entity (Assoc)) = E_Discriminant
1965                      then
1966                         Assoc := Save_Assoc;
1967                      end if;
1968
1969                      return Duplicate_Subexpr (Assoc);
1970                   end if;
1971
1972                   Next_Discriminant (Parent_Disc);
1973
1974                   if No (Assoc_Elmt) then
1975                      Next (Assoc);
1976                   else
1977                      Next_Elmt (Assoc_Elmt);
1978                      if Present (Assoc_Elmt) then
1979                         Assoc := Node (Assoc_Elmt);
1980                      else
1981                         Assoc := Empty;
1982                      end if;
1983                   end if;
1984                end loop;
1985             end if;
1986
1987             Current_Typ := Parent_Typ;
1988             Parent_Typ := Etype (Current_Typ);
1989          end loop;
1990
1991          --  In some cases there's no ancestor value to locate (such as
1992          --  when an ancestor part given by an expression defines the
1993          --  discriminant value).
1994
1995          return Empty;
1996       end Ancestor_Discriminant_Value;
1997
1998       ----------------------------------
1999       -- Check_Ancestor_Discriminants --
2000       ----------------------------------
2001
2002       procedure Check_Ancestor_Discriminants (Anc_Typ : Entity_Id) is
2003          Discr      : Entity_Id;
2004          Disc_Value : Node_Id;
2005          Cond       : Node_Id;
2006
2007       begin
2008          Discr := First_Discriminant (Base_Type (Anc_Typ));
2009          while Present (Discr) loop
2010             Disc_Value := Ancestor_Discriminant_Value (Discr);
2011
2012             if Present (Disc_Value) then
2013                Cond := Make_Op_Ne (Loc,
2014                  Left_Opnd =>
2015                    Make_Selected_Component (Loc,
2016                      Prefix        => New_Copy_Tree (Target),
2017                      Selector_Name => New_Occurrence_Of (Discr, Loc)),
2018                  Right_Opnd => Disc_Value);
2019
2020                Append_To (L,
2021                  Make_Raise_Constraint_Error (Loc,
2022                    Condition => Cond,
2023                    Reason    => CE_Discriminant_Check_Failed));
2024             end if;
2025
2026             Next_Discriminant (Discr);
2027          end loop;
2028       end Check_Ancestor_Discriminants;
2029
2030       ---------------------------
2031       -- Compatible_Int_Bounds --
2032       ---------------------------
2033
2034       function Compatible_Int_Bounds
2035         (Agg_Bounds : Node_Id;
2036          Typ_Bounds : Node_Id) return Boolean
2037       is
2038          Agg_Lo : constant Uint := Intval (Low_Bound  (Agg_Bounds));
2039          Agg_Hi : constant Uint := Intval (High_Bound (Agg_Bounds));
2040          Typ_Lo : constant Uint := Intval (Low_Bound  (Typ_Bounds));
2041          Typ_Hi : constant Uint := Intval (High_Bound (Typ_Bounds));
2042       begin
2043          return Typ_Lo <= Agg_Lo and then Agg_Hi <= Typ_Hi;
2044       end Compatible_Int_Bounds;
2045
2046       --------------------------------
2047       -- Get_Constraint_Association --
2048       --------------------------------
2049
2050       function Get_Constraint_Association (T : Entity_Id) return Node_Id is
2051          Typ_Def : constant Node_Id := Type_Definition (Parent (T));
2052          Indic   : constant Node_Id := Subtype_Indication (Typ_Def);
2053
2054       begin
2055          --  ??? Also need to cover case of a type mark denoting a subtype
2056          --  with constraint.
2057
2058          if Nkind (Indic) = N_Subtype_Indication
2059            and then Present (Constraint (Indic))
2060          then
2061             return First (Constraints (Constraint (Indic)));
2062          end if;
2063
2064          return Empty;
2065       end Get_Constraint_Association;
2066
2067       ---------------------
2068       -- Init_Controller --
2069       ---------------------
2070
2071       function Init_Controller
2072         (Target  : Node_Id;
2073          Typ     : Entity_Id;
2074          F       : Node_Id;
2075          Attach  : Node_Id;
2076          Init_Pr : Boolean) return List_Id
2077       is
2078          L           : constant List_Id := New_List;
2079          Ref         : Node_Id;
2080          RC          : RE_Id;
2081          Target_Type : Entity_Id;
2082
2083       begin
2084          --  Generate:
2085          --     init-proc (target._controller);
2086          --     initialize (target._controller);
2087          --     Attach_to_Final_List (target._controller, F);
2088
2089          Ref :=
2090            Make_Selected_Component (Loc,
2091              Prefix        => Convert_To (Typ, New_Copy_Tree (Target)),
2092              Selector_Name => Make_Identifier (Loc, Name_uController));
2093          Set_Assignment_OK (Ref);
2094
2095          --  Ada 2005 (AI-287): Give support to aggregates of limited types.
2096          --  If the type is intrinsically limited the controller is limited as
2097          --  well. If it is tagged and limited then so is the controller.
2098          --  Otherwise an untagged type may have limited components without its
2099          --  full view being limited, so the controller is not limited.
2100
2101          if Nkind (Target) = N_Identifier then
2102             Target_Type := Etype (Target);
2103
2104          elsif Nkind (Target) = N_Selected_Component then
2105             Target_Type := Etype (Selector_Name (Target));
2106
2107          elsif Nkind (Target) = N_Unchecked_Type_Conversion then
2108             Target_Type := Etype (Target);
2109
2110          elsif Nkind (Target) = N_Unchecked_Expression
2111            and then Nkind (Expression (Target)) = N_Indexed_Component
2112          then
2113             Target_Type := Etype (Prefix (Expression (Target)));
2114
2115          else
2116             Target_Type := Etype (Target);
2117          end if;
2118
2119          --  If the target has not been analyzed yet, as will happen with
2120          --  delayed expansion, use the given type (either the aggregate type
2121          --  or an ancestor) to determine limitedness.
2122
2123          if No (Target_Type) then
2124             Target_Type := Typ;
2125          end if;
2126
2127          if (Is_Tagged_Type (Target_Type))
2128            and then Is_Limited_Type (Target_Type)
2129          then
2130             RC := RE_Limited_Record_Controller;
2131
2132          elsif Is_Immutably_Limited_Type (Target_Type) then
2133             RC := RE_Limited_Record_Controller;
2134
2135          else
2136             RC := RE_Record_Controller;
2137          end if;
2138
2139          if Init_Pr then
2140             Append_List_To (L,
2141               Build_Initialization_Call (Loc,
2142                 Id_Ref       => Ref,
2143                 Typ          => RTE (RC),
2144                 In_Init_Proc => Within_Init_Proc));
2145          end if;
2146
2147          Append_To (L,
2148            Make_Procedure_Call_Statement (Loc,
2149              Name =>
2150                New_Reference_To (
2151                  Find_Prim_Op (RTE (RC), Name_Initialize), Loc),
2152              Parameter_Associations =>
2153                New_List (New_Copy_Tree (Ref))));
2154
2155          Append_To (L,
2156            Make_Attach_Call (
2157              Obj_Ref     => New_Copy_Tree (Ref),
2158              Flist_Ref   => F,
2159              With_Attach => Attach));
2160
2161          return L;
2162       end Init_Controller;
2163
2164       -------------------------------
2165       -- Init_Hidden_Discriminants --
2166       -------------------------------
2167
2168       procedure Init_Hidden_Discriminants (Typ : Entity_Id; List : List_Id) is
2169          Btype       : Entity_Id;
2170          Parent_Type : Entity_Id;
2171          Disc        : Entity_Id;
2172          Discr_Val   : Elmt_Id;
2173
2174       begin
2175          Btype := Base_Type (Typ);
2176          while Is_Derived_Type (Btype)
2177             and then Present (Stored_Constraint (Btype))
2178          loop
2179             Parent_Type := Etype (Btype);
2180
2181             Disc := First_Discriminant (Parent_Type);
2182             Discr_Val := First_Elmt (Stored_Constraint (Base_Type (Typ)));
2183             while Present (Discr_Val) loop
2184
2185                --  Only those discriminants of the parent that are not
2186                --  renamed by discriminants of the derived type need to
2187                --  be added explicitly.
2188
2189                if not Is_Entity_Name (Node (Discr_Val))
2190                  or else Ekind (Entity (Node (Discr_Val))) /= E_Discriminant
2191                then
2192                   Comp_Expr :=
2193                     Make_Selected_Component (Loc,
2194                       Prefix        => New_Copy_Tree (Target),
2195                       Selector_Name => New_Occurrence_Of (Disc, Loc));
2196
2197                   Instr :=
2198                     Make_OK_Assignment_Statement (Loc,
2199                       Name       => Comp_Expr,
2200                       Expression => New_Copy_Tree (Node (Discr_Val)));
2201
2202                   Set_No_Ctrl_Actions (Instr);
2203                   Append_To (List, Instr);
2204                end if;
2205
2206                Next_Discriminant (Disc);
2207                Next_Elmt (Discr_Val);
2208             end loop;
2209
2210             Btype := Base_Type (Parent_Type);
2211          end loop;
2212       end Init_Hidden_Discriminants;
2213
2214       -------------------------
2215       -- Is_Int_Range_Bounds --
2216       -------------------------
2217
2218       function Is_Int_Range_Bounds (Bounds : Node_Id) return Boolean is
2219       begin
2220          return Nkind (Bounds) = N_Range
2221            and then Nkind (Low_Bound  (Bounds)) = N_Integer_Literal
2222            and then Nkind (High_Bound (Bounds)) = N_Integer_Literal;
2223       end Is_Int_Range_Bounds;
2224
2225       -------------------------------
2226       -- Gen_Ctrl_Actions_For_Aggr --
2227       -------------------------------
2228
2229       procedure Gen_Ctrl_Actions_For_Aggr is
2230          Alloc : Node_Id := Empty;
2231
2232       begin
2233          --  Do the work only the first time this is called
2234
2235          if Ctrl_Stuff_Done then
2236             return;
2237          end if;
2238
2239          Ctrl_Stuff_Done := True;
2240
2241          if Present (Obj)
2242            and then Finalize_Storage_Only (Typ)
2243            and then
2244              (Is_Library_Level_Entity (Obj)
2245                 or else Entity (Constant_Value (RTE (RE_Garbage_Collected))) =
2246                                                           Standard_True)
2247
2248             --  why not Is_True (Expr_Value (RTE (RE_Garbaage_Collected) ???
2249          then
2250             Attach := Make_Integer_Literal (Loc, 0);
2251
2252          elsif Nkind (Parent (N)) = N_Qualified_Expression
2253            and then Nkind (Parent (Parent (N))) = N_Allocator
2254          then
2255             Alloc  := Parent (Parent (N));
2256             Attach := Make_Integer_Literal (Loc, 2);
2257
2258          else
2259             Attach := Make_Integer_Literal (Loc, 1);
2260          end if;
2261
2262          --  Determine the external finalization list. It is either the
2263          --  finalization list of the outer-scope or the one coming from
2264          --  an outer aggregate.  When the target is not a temporary, the
2265          --  proper scope is the scope of the target rather than the
2266          --  potentially transient current scope.
2267
2268          if Needs_Finalization (Typ) then
2269
2270             --  The current aggregate belongs to an allocator which creates
2271             --  an object through an anonymous access type or acts as the root
2272             --  of a coextension chain.
2273
2274             if Present (Alloc)
2275               and then
2276                 (Is_Coextension_Root (Alloc)
2277                    or else Ekind (Etype (Alloc)) = E_Anonymous_Access_Type)
2278             then
2279                if No (Associated_Final_Chain (Etype (Alloc))) then
2280                   Build_Final_List (Alloc, Etype (Alloc));
2281                end if;
2282
2283                External_Final_List :=
2284                  Make_Selected_Component (Loc,
2285                    Prefix =>
2286                      New_Reference_To (
2287                        Associated_Final_Chain (Etype (Alloc)), Loc),
2288                    Selector_Name => Make_Identifier (Loc, Name_F));
2289
2290             elsif Present (Flist) then
2291                External_Final_List := New_Copy_Tree (Flist);
2292
2293             elsif Is_Entity_Name (Target)
2294               and then Present (Scope (Entity (Target)))
2295             then
2296                External_Final_List :=
2297                  Find_Final_List (Scope (Entity (Target)));
2298
2299             else
2300                External_Final_List := Find_Final_List (Current_Scope);
2301             end if;
2302          else
2303             External_Final_List := Empty;
2304          end if;
2305
2306          --  Initialize and attach the outer object in the is_controlled case
2307
2308          if Is_Controlled (Typ) then
2309             if Ancestor_Is_Subtype_Mark then
2310                Ref := Convert_To (Init_Typ, New_Copy_Tree (Target));
2311                Set_Assignment_OK (Ref);
2312                Append_To (L,
2313                  Make_Procedure_Call_Statement (Loc,
2314                    Name =>
2315                      New_Reference_To
2316                        (Find_Prim_Op (Init_Typ, Name_Initialize), Loc),
2317                    Parameter_Associations => New_List (New_Copy_Tree (Ref))));
2318             end if;
2319
2320             if not Has_Controlled_Component (Typ) then
2321                Ref := New_Copy_Tree (Target);
2322                Set_Assignment_OK (Ref);
2323
2324                --  This is an aggregate of a coextension. Do not produce a
2325                --  finalization call, but rather attach the reference of the
2326                --  aggregate to its coextension chain.
2327
2328                if Present (Alloc)
2329                  and then Is_Dynamic_Coextension (Alloc)
2330                then
2331                   if No (Coextensions (Alloc)) then
2332                      Set_Coextensions (Alloc, New_Elmt_List);
2333                   end if;
2334
2335                   Append_Elmt (Ref, Coextensions (Alloc));
2336                else
2337                   Append_To (L,
2338                     Make_Attach_Call (
2339                       Obj_Ref     => Ref,
2340                       Flist_Ref   => New_Copy_Tree (External_Final_List),
2341                       With_Attach => Attach));
2342                end if;
2343             end if;
2344          end if;
2345
2346          --  In the Has_Controlled component case, all the intermediate
2347          --  controllers must be initialized.
2348
2349          if Has_Controlled_Component (Typ)
2350            and not Is_Limited_Ancestor_Expansion
2351          then
2352             declare
2353                Inner_Typ : Entity_Id;
2354                Outer_Typ : Entity_Id;
2355                At_Root   : Boolean;
2356
2357             begin
2358                --  Find outer type with a controller
2359
2360                Outer_Typ := Base_Type (Typ);
2361                while Outer_Typ /= Init_Typ
2362                  and then not Has_New_Controlled_Component (Outer_Typ)
2363                loop
2364                   Outer_Typ := Etype (Outer_Typ);
2365                end loop;
2366
2367                --  Attach it to the outer record controller to the external
2368                --  final list.
2369
2370                if Outer_Typ = Init_Typ then
2371                   Append_List_To (L,
2372                     Init_Controller (
2373                       Target  => Target,
2374                       Typ     => Outer_Typ,
2375                       F       => External_Final_List,
2376                       Attach  => Attach,
2377                       Init_Pr => False));
2378
2379                   At_Root   := True;
2380                   Inner_Typ := Init_Typ;
2381
2382                else
2383                   Append_List_To (L,
2384                     Init_Controller (
2385                       Target  => Target,
2386                       Typ     => Outer_Typ,
2387                       F       => External_Final_List,
2388                       Attach  => Attach,
2389                       Init_Pr => True));
2390
2391                   Inner_Typ := Etype (Outer_Typ);
2392                   At_Root   :=
2393                     not Is_Tagged_Type (Typ) or else Inner_Typ = Outer_Typ;
2394                end if;
2395
2396                --  The outer object has to be attached as well
2397
2398                if Is_Controlled (Typ) then
2399                   Ref := New_Copy_Tree (Target);
2400                   Set_Assignment_OK (Ref);
2401                   Append_To (L,
2402                     Make_Attach_Call (
2403                       Obj_Ref     => Ref,
2404                       Flist_Ref   => New_Copy_Tree (External_Final_List),
2405                       With_Attach => New_Copy_Tree (Attach)));
2406                end if;
2407
2408                --  Initialize the internal controllers for tagged types with
2409                --  more than one controller.
2410
2411                while not At_Root and then Inner_Typ /= Init_Typ loop
2412                   if Has_New_Controlled_Component (Inner_Typ) then
2413                      F :=
2414                        Make_Selected_Component (Loc,
2415                          Prefix =>
2416                            Convert_To (Outer_Typ, New_Copy_Tree (Target)),
2417                          Selector_Name =>
2418                            Make_Identifier (Loc, Name_uController));
2419                      F :=
2420                        Make_Selected_Component (Loc,
2421                          Prefix => F,
2422                          Selector_Name => Make_Identifier (Loc, Name_F));
2423
2424                      Append_List_To (L,
2425                        Init_Controller (
2426                          Target  => Target,
2427                          Typ     => Inner_Typ,
2428                          F       => F,
2429                          Attach  => Make_Integer_Literal (Loc, 1),
2430                          Init_Pr => True));
2431                      Outer_Typ := Inner_Typ;
2432                   end if;
2433
2434                   --  Stop at the root
2435
2436                   At_Root := Inner_Typ = Etype (Inner_Typ);
2437                   Inner_Typ := Etype (Inner_Typ);
2438                end loop;
2439
2440                --  If not done yet attach the controller of the ancestor part
2441
2442                if Outer_Typ /= Init_Typ
2443                  and then Inner_Typ = Init_Typ
2444                  and then Has_Controlled_Component (Init_Typ)
2445                then
2446                   F :=
2447                     Make_Selected_Component (Loc,
2448                       Prefix => Convert_To (Outer_Typ, New_Copy_Tree (Target)),
2449                       Selector_Name =>
2450                         Make_Identifier (Loc, Name_uController));
2451                   F :=
2452                     Make_Selected_Component (Loc,
2453                       Prefix        => F,
2454                       Selector_Name => Make_Identifier (Loc, Name_F));
2455
2456                   Attach := Make_Integer_Literal (Loc, 1);
2457                   Append_List_To (L,
2458                     Init_Controller (
2459                       Target  => Target,
2460                       Typ     => Init_Typ,
2461                       F       => F,
2462                       Attach  => Attach,
2463                       Init_Pr => False));
2464
2465                      --  Note: Init_Pr is False because the ancestor part has
2466                      --  already been initialized either way (by default, if
2467                      --  given by a type name, otherwise from the expression).
2468
2469                end if;
2470             end;
2471          end if;
2472       end Gen_Ctrl_Actions_For_Aggr;
2473
2474       function Rewrite_Discriminant (Expr : Node_Id) return Traverse_Result;
2475       --  If default expression of a component mentions a discriminant of the
2476       --  type, it must be rewritten as the discriminant of the target object.
2477
2478       function Replace_Type (Expr : Node_Id) return Traverse_Result;
2479       --  If the aggregate contains a self-reference, traverse each expression
2480       --  to replace a possible self-reference with a reference to the proper
2481       --  component of the target of the assignment.
2482
2483       --------------------------
2484       -- Rewrite_Discriminant --
2485       --------------------------
2486
2487       function Rewrite_Discriminant (Expr : Node_Id) return Traverse_Result is
2488       begin
2489          if Is_Entity_Name (Expr)
2490            and then Present (Entity (Expr))
2491            and then Ekind (Entity (Expr)) = E_In_Parameter
2492            and then Present (Discriminal_Link (Entity (Expr)))
2493            and then Scope (Discriminal_Link (Entity (Expr)))
2494                       = Base_Type (Etype (N))
2495          then
2496             Rewrite (Expr,
2497               Make_Selected_Component (Loc,
2498                 Prefix        => New_Copy_Tree (Lhs),
2499                 Selector_Name => Make_Identifier (Loc, Chars (Expr))));
2500          end if;
2501          return OK;
2502       end Rewrite_Discriminant;
2503
2504       ------------------
2505       -- Replace_Type --
2506       ------------------
2507
2508       function Replace_Type (Expr : Node_Id) return Traverse_Result is
2509       begin
2510          --  Note regarding the Root_Type test below: Aggregate components for
2511          --  self-referential types include attribute references to the current
2512          --  instance, of the form: Typ'access, etc.. These references are
2513          --  rewritten as references to the target of the aggregate: the
2514          --  left-hand side of an assignment, the entity in a declaration,
2515          --  or a temporary. Without this test, we would improperly extended
2516          --  this rewriting to attribute references whose prefix was not the
2517          --  type of the aggregate.
2518
2519          if Nkind (Expr) = N_Attribute_Reference
2520            and then Is_Entity_Name (Prefix (Expr))
2521            and then Is_Type (Entity (Prefix (Expr)))
2522            and then Root_Type (Etype (N)) = Root_Type (Entity (Prefix (Expr)))
2523          then
2524             if Is_Entity_Name (Lhs) then
2525                Rewrite (Prefix (Expr),
2526                  New_Occurrence_Of (Entity (Lhs), Loc));
2527
2528             elsif Nkind (Lhs) = N_Selected_Component then
2529                Rewrite (Expr,
2530                  Make_Attribute_Reference (Loc,
2531                    Attribute_Name => Name_Unrestricted_Access,
2532                    Prefix         => New_Copy_Tree (Prefix (Lhs))));
2533                Set_Analyzed (Parent (Expr), False);
2534
2535             else
2536                Rewrite (Expr,
2537                  Make_Attribute_Reference (Loc,
2538                    Attribute_Name => Name_Unrestricted_Access,
2539                    Prefix         => New_Copy_Tree (Lhs)));
2540                Set_Analyzed (Parent (Expr), False);
2541             end if;
2542          end if;
2543
2544          return OK;
2545       end Replace_Type;
2546
2547       procedure Replace_Self_Reference is
2548         new Traverse_Proc (Replace_Type);
2549
2550       procedure Replace_Discriminants is
2551         new Traverse_Proc (Rewrite_Discriminant);
2552
2553    --  Start of processing for Build_Record_Aggr_Code
2554
2555    begin
2556       if Has_Self_Reference (N) then
2557          Replace_Self_Reference (N);
2558       end if;
2559
2560       --  If the target of the aggregate is class-wide, we must convert it
2561       --  to the actual type of the aggregate, so that the proper components
2562       --  are visible. We know already that the types are compatible.
2563
2564       if Present (Etype (Lhs))
2565         and then Is_Class_Wide_Type (Etype (Lhs))
2566       then
2567          Target := Unchecked_Convert_To (Typ, Lhs);
2568       else
2569          Target := Lhs;
2570       end if;
2571
2572       --  Deal with the ancestor part of extension aggregates or with the
2573       --  discriminants of the root type.
2574
2575       if Nkind (N) = N_Extension_Aggregate then
2576          declare
2577             A      : constant Node_Id := Ancestor_Part (N);
2578             Assign : List_Id;
2579
2580          begin
2581             --  If the ancestor part is a subtype mark "T", we generate
2582
2583             --     init-proc (T(tmp));  if T is constrained and
2584             --     init-proc (S(tmp));  where S applies an appropriate
2585             --                          constraint if T is unconstrained
2586
2587             if Is_Entity_Name (A) and then Is_Type (Entity (A)) then
2588                Ancestor_Is_Subtype_Mark := True;
2589
2590                if Is_Constrained (Entity (A)) then
2591                   Init_Typ := Entity (A);
2592
2593                --  For an ancestor part given by an unconstrained type mark,
2594                --  create a subtype constrained by appropriate corresponding
2595                --  discriminant values coming from either associations of the
2596                --  aggregate or a constraint on a parent type. The subtype will
2597                --  be used to generate the correct default value for the
2598                --  ancestor part.
2599
2600                elsif Has_Discriminants (Entity (A)) then
2601                   declare
2602                      Anc_Typ    : constant Entity_Id := Entity (A);
2603                      Anc_Constr : constant List_Id   := New_List;
2604                      Discrim    : Entity_Id;
2605                      Disc_Value : Node_Id;
2606                      New_Indic  : Node_Id;
2607                      Subt_Decl  : Node_Id;
2608
2609                   begin
2610                      Discrim := First_Discriminant (Anc_Typ);
2611                      while Present (Discrim) loop
2612                         Disc_Value := Ancestor_Discriminant_Value (Discrim);
2613                         Append_To (Anc_Constr, Disc_Value);
2614                         Next_Discriminant (Discrim);
2615                      end loop;
2616
2617                      New_Indic :=
2618                        Make_Subtype_Indication (Loc,
2619                          Subtype_Mark => New_Occurrence_Of (Anc_Typ, Loc),
2620                          Constraint   =>
2621                            Make_Index_Or_Discriminant_Constraint (Loc,
2622                              Constraints => Anc_Constr));
2623
2624                      Init_Typ := Create_Itype (Ekind (Anc_Typ), N);
2625
2626                      Subt_Decl :=
2627                        Make_Subtype_Declaration (Loc,
2628                          Defining_Identifier => Init_Typ,
2629                          Subtype_Indication  => New_Indic);
2630
2631                      --  Itypes must be analyzed with checks off Declaration
2632                      --  must have a parent for proper handling of subsidiary
2633                      --  actions.
2634
2635                      Set_Parent (Subt_Decl, N);
2636                      Analyze (Subt_Decl, Suppress => All_Checks);
2637                   end;
2638                end if;
2639
2640                Ref := Convert_To (Init_Typ, New_Copy_Tree (Target));
2641                Set_Assignment_OK (Ref);
2642
2643                if not Is_Interface (Init_Typ) then
2644                   Append_List_To (L,
2645                     Build_Initialization_Call (Loc,
2646                       Id_Ref            => Ref,
2647                       Typ               => Init_Typ,
2648                       In_Init_Proc      => Within_Init_Proc,
2649                       With_Default_Init => Has_Default_Init_Comps (N)
2650                                              or else
2651                                            Has_Task (Base_Type (Init_Typ))));
2652
2653                   if Is_Constrained (Entity (A))
2654                     and then Has_Discriminants (Entity (A))
2655                   then
2656                      Check_Ancestor_Discriminants (Entity (A));
2657                   end if;
2658                end if;
2659
2660             --  Handle calls to C++ constructors
2661
2662             elsif Is_CPP_Constructor_Call (A) then
2663                Init_Typ := Etype (A);
2664                Ref := Convert_To (Init_Typ, New_Copy_Tree (Target));
2665                Set_Assignment_OK (Ref);
2666
2667                Append_List_To (L,
2668                  Build_Initialization_Call (Loc,
2669                    Id_Ref            => Ref,
2670                    Typ               => Init_Typ,
2671                    In_Init_Proc      => Within_Init_Proc,
2672                    With_Default_Init => Has_Default_Init_Comps (N),
2673                    Constructor_Ref   => A));
2674
2675             --  Ada 2005 (AI-287): If the ancestor part is an aggregate of
2676             --  limited type, a recursive call expands the ancestor. Note that
2677             --  in the limited case, the ancestor part must be either a
2678             --  function call (possibly qualified, or wrapped in an unchecked
2679             --  conversion) or aggregate (definitely qualified).
2680             --  The ancestor part can also be a function call (that may be
2681             --  transformed into an explicit dereference) or a qualification
2682             --  of one such.
2683
2684             elsif Is_Limited_Type (Etype (A))
2685               and then Nkind_In (Unqualify (A), N_Aggregate,
2686                                                 N_Extension_Aggregate)
2687             then
2688                Ancestor_Is_Expression := True;
2689
2690                --  Set up  finalization data for enclosing record, because
2691                --  controlled subcomponents of the ancestor part will be
2692                --  attached to it.
2693
2694                Gen_Ctrl_Actions_For_Aggr;
2695
2696                Append_List_To (L,
2697                   Build_Record_Aggr_Code (
2698                     N                             => Unqualify (A),
2699                     Typ                           => Etype (Unqualify (A)),
2700                     Lhs                           => Target,
2701                     Flist                         => Flist,
2702                     Obj                           => Obj,
2703                     Is_Limited_Ancestor_Expansion => True));
2704
2705             --  If the ancestor part is an expression "E", we generate
2706
2707             --     T(tmp) := E;
2708
2709             --  In Ada 2005, this includes the case of a (possibly qualified)
2710             --  limited function call. The assignment will turn into a
2711             --  build-in-place function call (for further details, see
2712             --  Make_Build_In_Place_Call_In_Assignment).
2713
2714             else
2715                Ancestor_Is_Expression := True;
2716                Init_Typ := Etype (A);
2717
2718                --  If the ancestor part is an aggregate, force its full
2719                --  expansion, which was delayed.
2720
2721                if Nkind_In (Unqualify (A), N_Aggregate,
2722                                            N_Extension_Aggregate)
2723                then
2724                   Set_Analyzed (A, False);
2725                   Set_Analyzed (Expression (A), False);
2726                end if;
2727
2728                Ref := Convert_To (Init_Typ, New_Copy_Tree (Target));
2729                Set_Assignment_OK (Ref);
2730
2731                --  Make the assignment without usual controlled actions since
2732                --  we only want the post adjust but not the pre finalize here
2733                --  Add manual adjust when necessary.
2734
2735                Assign := New_List (
2736                  Make_OK_Assignment_Statement (Loc,
2737                    Name       => Ref,
2738                    Expression => A));
2739                Set_No_Ctrl_Actions (First (Assign));
2740
2741                --  Assign the tag now to make sure that the dispatching call in
2742                --  the subsequent deep_adjust works properly (unless VM_Target,
2743                --  where tags are implicit).
2744
2745                if Tagged_Type_Expansion then
2746                   Instr :=
2747                     Make_OK_Assignment_Statement (Loc,
2748                       Name =>
2749                         Make_Selected_Component (Loc,
2750                           Prefix => New_Copy_Tree (Target),
2751                           Selector_Name =>
2752                             New_Reference_To
2753                               (First_Tag_Component (Base_Type (Typ)), Loc)),
2754
2755                       Expression =>
2756                         Unchecked_Convert_To (RTE (RE_Tag),
2757                           New_Reference_To
2758                             (Node (First_Elmt
2759                                (Access_Disp_Table (Base_Type (Typ)))),
2760                              Loc)));
2761
2762                   Set_Assignment_OK (Name (Instr));
2763                   Append_To (Assign, Instr);
2764
2765                   --  Ada 2005 (AI-251): If tagged type has progenitors we must
2766                   --  also initialize tags of the secondary dispatch tables.
2767
2768                   if Has_Interfaces (Base_Type (Typ)) then
2769                      Init_Secondary_Tags
2770                        (Typ        => Base_Type (Typ),
2771                         Target     => Target,
2772                         Stmts_List => Assign);
2773                   end if;
2774                end if;
2775
2776                --  Call Adjust manually
2777
2778                if Needs_Finalization (Etype (A))
2779                  and then not Is_Limited_Type (Etype (A))
2780                then
2781                   Append_List_To (Assign,
2782                     Make_Adjust_Call (
2783                       Ref         => New_Copy_Tree (Ref),
2784                       Typ         => Etype (A),
2785                       Flist_Ref   => New_Reference_To (
2786                         RTE (RE_Global_Final_List), Loc),
2787                       With_Attach => Make_Integer_Literal (Loc, 0)));
2788                end if;
2789
2790                Append_To (L,
2791                  Make_Unsuppress_Block (Loc, Name_Discriminant_Check, Assign));
2792
2793                if Has_Discriminants (Init_Typ) then
2794                   Check_Ancestor_Discriminants (Init_Typ);
2795                end if;
2796             end if;
2797          end;
2798
2799          --  Generate assignments of hidden assignments. If the base type is an
2800          --  unchecked union, the discriminants are unknown to the back-end and
2801          --  absent from a value of the type, so assignments for them are not
2802          --  emitted.
2803
2804          if Has_Discriminants (Typ)
2805            and then not Is_Unchecked_Union (Base_Type (Typ))
2806          then
2807             Init_Hidden_Discriminants (Typ, L);
2808          end if;
2809
2810       --  Normal case (not an extension aggregate)
2811
2812       else
2813          --  Generate the discriminant expressions, component by component.
2814          --  If the base type is an unchecked union, the discriminants are
2815          --  unknown to the back-end and absent from a value of the type, so
2816          --  assignments for them are not emitted.
2817
2818          if Has_Discriminants (Typ)
2819            and then not Is_Unchecked_Union (Base_Type (Typ))
2820          then
2821             Init_Hidden_Discriminants (Typ, L);
2822
2823             --  Generate discriminant init values for the visible discriminants
2824
2825             declare
2826                Discriminant : Entity_Id;
2827                Discriminant_Value : Node_Id;
2828
2829             begin
2830                Discriminant := First_Stored_Discriminant (Typ);
2831                while Present (Discriminant) loop
2832                   Comp_Expr :=
2833                     Make_Selected_Component (Loc,
2834                       Prefix        => New_Copy_Tree (Target),
2835                       Selector_Name => New_Occurrence_Of (Discriminant, Loc));
2836
2837                   Discriminant_Value :=
2838                     Get_Discriminant_Value (
2839                       Discriminant,
2840                       N_Typ,
2841                       Discriminant_Constraint (N_Typ));
2842
2843                   Instr :=
2844                     Make_OK_Assignment_Statement (Loc,
2845                       Name       => Comp_Expr,
2846                       Expression => New_Copy_Tree (Discriminant_Value));
2847
2848                   Set_No_Ctrl_Actions (Instr);
2849                   Append_To (L, Instr);
2850
2851                   Next_Stored_Discriminant (Discriminant);
2852                end loop;
2853             end;
2854          end if;
2855       end if;
2856
2857       --  For CPP types we generate an implicit call to the C++ default
2858       --  constructor to ensure the proper initialization of the _Tag
2859       --  component.
2860
2861       if Is_CPP_Class (Root_Type (Typ))
2862         and then CPP_Num_Prims (Typ) > 0
2863       then
2864          Invoke_Constructor : declare
2865             CPP_Parent : constant Entity_Id :=
2866                            Enclosing_CPP_Parent (Typ);
2867
2868             procedure Invoke_IC_Proc (T : Entity_Id);
2869             --  Recursive routine used to climb to parents. Required because
2870             --  parents must be initialized before descendants to ensure
2871             --  propagation of inherited C++ slots.
2872
2873             --------------------
2874             -- Invoke_IC_Proc --
2875             --------------------
2876
2877             procedure Invoke_IC_Proc (T : Entity_Id) is
2878             begin
2879                --  Avoid generating extra calls. Initialization required
2880                --  only for types defined from the level of derivation of
2881                --  type of the constructor and the type of the aggregate.
2882
2883                if T = CPP_Parent then
2884                   return;
2885                end if;
2886
2887                Invoke_IC_Proc (Etype (T));
2888
2889                --  Generate call to the IC routine
2890
2891                if Present (CPP_Init_Proc (T)) then
2892                   Append_To (L,
2893                     Make_Procedure_Call_Statement (Loc,
2894                       New_Reference_To (CPP_Init_Proc (T), Loc)));
2895                end if;
2896             end Invoke_IC_Proc;
2897
2898          --  Start of processing for Invoke_Constructor
2899
2900          begin
2901             --  Implicit invocation of the C++ constructor
2902
2903             if Nkind (N) = N_Aggregate then
2904                Append_To (L,
2905                  Make_Procedure_Call_Statement (Loc,
2906                    Name =>
2907                      New_Reference_To
2908                        (Base_Init_Proc (CPP_Parent), Loc),
2909                    Parameter_Associations => New_List (
2910                      Unchecked_Convert_To (CPP_Parent,
2911                        New_Copy_Tree (Lhs)))));
2912             end if;
2913
2914             Invoke_IC_Proc (Typ);
2915          end Invoke_Constructor;
2916       end if;
2917
2918       --  Generate the assignments, component by component
2919
2920       --    tmp.comp1 := Expr1_From_Aggr;
2921       --    tmp.comp2 := Expr2_From_Aggr;
2922       --    ....
2923
2924       Comp := First (Component_Associations (N));
2925       while Present (Comp) loop
2926          Selector := Entity (First (Choices (Comp)));
2927
2928          --  C++ constructors
2929
2930          if Is_CPP_Constructor_Call (Expression (Comp)) then
2931             Append_List_To (L,
2932               Build_Initialization_Call (Loc,
2933                 Id_Ref            => Make_Selected_Component (Loc,
2934                                        Prefix        => New_Copy_Tree (Target),
2935                                        Selector_Name =>
2936                                          New_Occurrence_Of (Selector, Loc)),
2937                 Typ               => Etype (Selector),
2938                 Enclos_Type       => Typ,
2939                 With_Default_Init => True,
2940                 Constructor_Ref   => Expression (Comp)));
2941
2942          --  Ada 2005 (AI-287): For each default-initialized component generate
2943          --  a call to the corresponding IP subprogram if available.
2944
2945          elsif Box_Present (Comp)
2946            and then Has_Non_Null_Base_Init_Proc (Etype (Selector))
2947          then
2948             if Ekind (Selector) /= E_Discriminant then
2949                Gen_Ctrl_Actions_For_Aggr;
2950             end if;
2951
2952             --  Ada 2005 (AI-287): If the component type has tasks then
2953             --  generate the activation chain and master entities (except
2954             --  in case of an allocator because in that case these entities
2955             --  are generated by Build_Task_Allocate_Block_With_Init_Stmts).
2956
2957             declare
2958                Ctype            : constant Entity_Id := Etype (Selector);
2959                Inside_Allocator : Boolean            := False;
2960                P                : Node_Id            := Parent (N);
2961
2962             begin
2963                if Is_Task_Type (Ctype) or else Has_Task (Ctype) then
2964                   while Present (P) loop
2965                      if Nkind (P) = N_Allocator then
2966                         Inside_Allocator := True;
2967                         exit;
2968                      end if;
2969
2970                      P := Parent (P);
2971                   end loop;
2972
2973                   if not Inside_Init_Proc and not Inside_Allocator then
2974                      Build_Activation_Chain_Entity (N);
2975                   end if;
2976                end if;
2977             end;
2978
2979             Append_List_To (L,
2980               Build_Initialization_Call (Loc,
2981                 Id_Ref            => Make_Selected_Component (Loc,
2982                                        Prefix        => New_Copy_Tree (Target),
2983                                        Selector_Name =>
2984                                          New_Occurrence_Of (Selector, Loc)),
2985                 Typ               => Etype (Selector),
2986                 Enclos_Type       => Typ,
2987                 With_Default_Init => True));
2988
2989          --  Prepare for component assignment
2990
2991          elsif Ekind (Selector) /= E_Discriminant
2992            or else Nkind (N) = N_Extension_Aggregate
2993          then
2994             --  All the discriminants have now been assigned
2995
2996             --  This is now a good moment to initialize and attach all the
2997             --  controllers. Their position may depend on the discriminants.
2998
2999             if Ekind (Selector) /= E_Discriminant then
3000                Gen_Ctrl_Actions_For_Aggr;
3001             end if;
3002
3003             Comp_Type := Underlying_Type (Etype (Selector));
3004             Comp_Expr :=
3005               Make_Selected_Component (Loc,
3006                 Prefix        => New_Copy_Tree (Target),
3007                 Selector_Name => New_Occurrence_Of (Selector, Loc));
3008
3009             if Nkind (Expression (Comp)) = N_Qualified_Expression then
3010                Expr_Q := Expression (Expression (Comp));
3011             else
3012                Expr_Q := Expression (Comp);
3013             end if;
3014
3015             --  The controller is the one of the parent type defining the
3016             --  component (in case of inherited components).
3017
3018             if Needs_Finalization (Comp_Type) then
3019                Internal_Final_List :=
3020                  Make_Selected_Component (Loc,
3021                    Prefix        => Convert_To
3022                      (Scope (Original_Record_Component (Selector)),
3023                       New_Copy_Tree (Target)),
3024                    Selector_Name => Make_Identifier (Loc, Name_uController));
3025
3026                Internal_Final_List :=
3027                  Make_Selected_Component (Loc,
3028                    Prefix        => Internal_Final_List,
3029                    Selector_Name => Make_Identifier (Loc, Name_F));
3030
3031                --  The internal final list can be part of a constant object
3032
3033                Set_Assignment_OK (Internal_Final_List);
3034
3035             else
3036                Internal_Final_List := Empty;
3037             end if;
3038
3039             --  Now either create the assignment or generate the code for the
3040             --  inner aggregate top-down.
3041
3042             if Is_Delayed_Aggregate (Expr_Q) then
3043
3044                --  We have the following case of aggregate nesting inside
3045                --  an object declaration:
3046
3047                --    type Arr_Typ is array (Integer range <>) of ...;
3048
3049                --    type Rec_Typ (...) is record
3050                --       Obj_Arr_Typ : Arr_Typ (A .. B);
3051                --    end record;
3052
3053                --    Obj_Rec_Typ : Rec_Typ := (...,
3054                --      Obj_Arr_Typ => (X => (...), Y => (...)));
3055
3056                --  The length of the ranges of the aggregate and Obj_Add_Typ
3057                --  are equal (B - A = Y - X), but they do not coincide (X /=
3058                --  A and B /= Y). This case requires array sliding which is
3059                --  performed in the following manner:
3060
3061                --    subtype Arr_Sub is Arr_Typ (X .. Y);
3062                --    Temp : Arr_Sub;
3063                --    Temp (X) := (...);
3064                --    ...
3065                --    Temp (Y) := (...);
3066                --    Obj_Rec_Typ.Obj_Arr_Typ := Temp;
3067
3068                if Ekind (Comp_Type) = E_Array_Subtype
3069                  and then Is_Int_Range_Bounds (Aggregate_Bounds (Expr_Q))
3070                  and then Is_Int_Range_Bounds (First_Index (Comp_Type))
3071                  and then not
3072                    Compatible_Int_Bounds
3073                      (Agg_Bounds => Aggregate_Bounds (Expr_Q),
3074                       Typ_Bounds => First_Index (Comp_Type))
3075                then
3076                   --  Create the array subtype with bounds equal to those of
3077                   --  the corresponding aggregate.
3078
3079                   declare
3080                      SubE : constant Entity_Id := Make_Temporary (Loc, 'T');
3081
3082                      SubD : constant Node_Id :=
3083                               Make_Subtype_Declaration (Loc,
3084                                 Defining_Identifier => SubE,
3085                                 Subtype_Indication  =>
3086                                   Make_Subtype_Indication (Loc,
3087                                     Subtype_Mark =>
3088                                       New_Reference_To
3089                                         (Etype (Comp_Type), Loc),
3090                                     Constraint =>
3091                                       Make_Index_Or_Discriminant_Constraint
3092                                         (Loc,
3093                                          Constraints => New_List (
3094                                           New_Copy_Tree
3095                                             (Aggregate_Bounds (Expr_Q))))));
3096
3097                      --  Create a temporary array of the above subtype which
3098                      --  will be used to capture the aggregate assignments.
3099
3100                      TmpE : constant Entity_Id := Make_Temporary (Loc, 'A', N);
3101
3102                      TmpD : constant Node_Id :=
3103                               Make_Object_Declaration (Loc,
3104                                 Defining_Identifier => TmpE,
3105                                 Object_Definition   =>
3106                                   New_Reference_To (SubE, Loc));
3107
3108                   begin
3109                      Set_No_Initialization (TmpD);
3110                      Append_To (L, SubD);
3111                      Append_To (L, TmpD);
3112
3113                      --  Expand aggregate into assignments to the temp array
3114
3115                      Append_List_To (L,
3116                        Late_Expansion (Expr_Q, Comp_Type,
3117                          New_Reference_To (TmpE, Loc), Internal_Final_List));
3118
3119                      --  Slide
3120
3121                      Append_To (L,
3122                        Make_Assignment_Statement (Loc,
3123                          Name       => New_Copy_Tree (Comp_Expr),
3124                          Expression => New_Reference_To (TmpE, Loc)));
3125
3126                      --  Do not pass the original aggregate to Gigi as is,
3127                      --  since it will potentially clobber the front or the end
3128                      --  of the array. Setting the expression to empty is safe
3129                      --  since all aggregates are expanded into assignments.
3130
3131                      if Present (Obj) then
3132                         Set_Expression (Parent (Obj), Empty);
3133                      end if;
3134                   end;
3135
3136                --  Normal case (sliding not required)
3137
3138                else
3139                   Append_List_To (L,
3140                     Late_Expansion (Expr_Q, Comp_Type, Comp_Expr,
3141                       Internal_Final_List));
3142                end if;
3143
3144             --  Expr_Q is not delayed aggregate
3145
3146             else
3147                if Has_Discriminants (Typ) then
3148                   Replace_Discriminants (Expr_Q);
3149                end if;
3150
3151                Instr :=
3152                  Make_OK_Assignment_Statement (Loc,
3153                    Name       => Comp_Expr,
3154                    Expression => Expr_Q);
3155
3156                Set_No_Ctrl_Actions (Instr);
3157                Append_To (L, Instr);
3158
3159                --  Adjust the tag if tagged (because of possible view
3160                --  conversions), unless compiling for a VM where tags are
3161                --  implicit.
3162
3163                --    tmp.comp._tag := comp_typ'tag;
3164
3165                if Is_Tagged_Type (Comp_Type)
3166                  and then Tagged_Type_Expansion
3167                then
3168                   Instr :=
3169                     Make_OK_Assignment_Statement (Loc,
3170                       Name =>
3171                         Make_Selected_Component (Loc,
3172                           Prefix =>  New_Copy_Tree (Comp_Expr),
3173                           Selector_Name =>
3174                             New_Reference_To
3175                               (First_Tag_Component (Comp_Type), Loc)),
3176
3177                       Expression =>
3178                         Unchecked_Convert_To (RTE (RE_Tag),
3179                           New_Reference_To
3180                             (Node (First_Elmt (Access_Disp_Table (Comp_Type))),
3181                              Loc)));
3182
3183                   Append_To (L, Instr);
3184                end if;
3185
3186                --  Adjust and Attach the component to the proper controller
3187
3188                --     Adjust (tmp.comp);
3189                --     Attach_To_Final_List (tmp.comp,
3190                --       comp_typ (tmp)._record_controller.f)
3191
3192                if Needs_Finalization (Comp_Type)
3193                  and then not Is_Limited_Type (Comp_Type)
3194                then
3195                   Append_List_To (L,
3196                     Make_Adjust_Call (
3197                       Ref         => New_Copy_Tree (Comp_Expr),
3198                       Typ         => Comp_Type,
3199                       Flist_Ref   => Internal_Final_List,
3200                       With_Attach => Make_Integer_Literal (Loc, 1)));
3201                end if;
3202             end if;
3203
3204          --  ???
3205
3206          elsif Ekind (Selector) = E_Discriminant
3207            and then Nkind (N) /= N_Extension_Aggregate
3208            and then Nkind (Parent (N)) = N_Component_Association
3209            and then Is_Constrained (Typ)
3210          then
3211             --  We must check that the discriminant value imposed by the
3212             --  context is the same as the value given in the subaggregate,
3213             --  because after the expansion into assignments there is no
3214             --  record on which to perform a regular discriminant check.
3215
3216             declare
3217                D_Val : Elmt_Id;
3218                Disc  : Entity_Id;
3219
3220             begin
3221                D_Val := First_Elmt (Discriminant_Constraint (Typ));
3222                Disc  := First_Discriminant (Typ);
3223                while Chars (Disc) /= Chars (Selector) loop
3224                   Next_Discriminant (Disc);
3225                   Next_Elmt (D_Val);
3226                end loop;
3227
3228                pragma Assert (Present (D_Val));
3229
3230                --  This check cannot performed for components that are
3231                --  constrained by a current instance, because this is not a
3232                --  value that can be compared with the actual constraint.
3233
3234                if Nkind (Node (D_Val)) /= N_Attribute_Reference
3235                  or else not Is_Entity_Name (Prefix (Node (D_Val)))
3236                  or else not Is_Type (Entity (Prefix (Node (D_Val))))
3237                then
3238                   Append_To (L,
3239                   Make_Raise_Constraint_Error (Loc,
3240                     Condition =>
3241                       Make_Op_Ne (Loc,
3242                         Left_Opnd => New_Copy_Tree (Node (D_Val)),
3243                         Right_Opnd => Expression (Comp)),
3244                       Reason => CE_Discriminant_Check_Failed));
3245
3246                else
3247                   --  Find self-reference in previous discriminant assignment,
3248                   --  and replace with proper expression.
3249
3250                   declare
3251                      Ass : Node_Id;
3252
3253                   begin
3254                      Ass := First (L);
3255                      while Present (Ass) loop
3256                         if Nkind (Ass) = N_Assignment_Statement
3257                           and then Nkind (Name (Ass)) = N_Selected_Component
3258                           and then Chars (Selector_Name (Name (Ass))) =
3259                              Chars (Disc)
3260                         then
3261                            Set_Expression
3262                              (Ass, New_Copy_Tree (Expression (Comp)));
3263                            exit;
3264                         end if;
3265                         Next (Ass);
3266                      end loop;
3267                   end;
3268                end if;
3269             end;
3270          end if;
3271
3272          Next (Comp);
3273       end loop;
3274
3275       --  If the type is tagged, the tag needs to be initialized (unless
3276       --  compiling for the Java VM where tags are implicit). It is done
3277       --  late in the initialization process because in some cases, we call
3278       --  the init proc of an ancestor which will not leave out the right tag
3279
3280       if Ancestor_Is_Expression then
3281          null;
3282
3283       --  For CPP types we generated a call to the C++ default constructor
3284       --  before the components have been initialized to ensure the proper
3285       --  initialization of the _Tag component (see above).
3286
3287       elsif Is_CPP_Class (Typ) then
3288          null;
3289
3290       elsif Is_Tagged_Type (Typ) and then Tagged_Type_Expansion then
3291          Instr :=
3292            Make_OK_Assignment_Statement (Loc,
3293              Name =>
3294                Make_Selected_Component (Loc,
3295                  Prefix => New_Copy_Tree (Target),
3296                  Selector_Name =>
3297                    New_Reference_To
3298                      (First_Tag_Component (Base_Type (Typ)), Loc)),
3299
3300              Expression =>
3301                Unchecked_Convert_To (RTE (RE_Tag),
3302                  New_Reference_To
3303                    (Node (First_Elmt (Access_Disp_Table (Base_Type (Typ)))),
3304                     Loc)));
3305
3306          Append_To (L, Instr);
3307
3308          --  Ada 2005 (AI-251): If the tagged type has been derived from
3309          --  abstract interfaces we must also initialize the tags of the
3310          --  secondary dispatch tables.
3311
3312          if Has_Interfaces (Base_Type (Typ)) then
3313             Init_Secondary_Tags
3314               (Typ        => Base_Type (Typ),
3315                Target     => Target,
3316                Stmts_List => L);
3317          end if;
3318       end if;
3319
3320       --  If the controllers have not been initialized yet (by lack of non-
3321       --  discriminant components), let's do it now.
3322
3323       Gen_Ctrl_Actions_For_Aggr;
3324
3325       return L;
3326    end Build_Record_Aggr_Code;
3327
3328    -------------------------------
3329    -- Convert_Aggr_In_Allocator --
3330    -------------------------------
3331
3332    procedure Convert_Aggr_In_Allocator
3333      (Alloc :  Node_Id;
3334       Decl  :  Node_Id;
3335       Aggr  :  Node_Id)
3336    is
3337       Loc  : constant Source_Ptr := Sloc (Aggr);
3338       Typ  : constant Entity_Id  := Etype (Aggr);
3339       Temp : constant Entity_Id  := Defining_Identifier (Decl);
3340
3341       Occ  : constant Node_Id :=
3342                Unchecked_Convert_To (Typ,
3343                  Make_Explicit_Dereference (Loc,
3344                    New_Reference_To (Temp, Loc)));
3345
3346       Access_Type : constant Entity_Id := Etype (Temp);
3347       Flist       : Entity_Id;
3348
3349    begin
3350       --  If the allocator is for an access discriminant, there is no
3351       --  finalization list for the anonymous access type, and the eventual
3352       --  finalization of the object is handled through the coextension
3353       --  mechanism. If the enclosing object is not dynamically allocated,
3354       --  the access discriminant is itself placed on the stack. Otherwise,
3355       --  some other finalization list is used (see exp_ch4.adb).
3356
3357       --  Decl has been inserted in the code ahead of the allocator, using
3358       --  Insert_Actions. We use Insert_Actions below as well, to ensure that
3359       --  subsequent insertions are done in the proper order. Using (for
3360       --  example) Insert_Actions_After to place the expanded aggregate
3361       --  immediately after Decl may lead to out-of-order references if the
3362       --  allocator has generated a finalization list, as when the designated
3363       --  object is controlled and there is an open transient scope.
3364
3365       if Ekind (Access_Type) = E_Anonymous_Access_Type
3366         and then Nkind (Associated_Node_For_Itype (Access_Type)) =
3367                                               N_Discriminant_Specification
3368       then
3369          Flist := Empty;
3370
3371       elsif Needs_Finalization (Typ) then
3372          Flist := Find_Final_List (Access_Type);
3373
3374       --  Otherwise there are no controlled actions to be performed.
3375
3376       else
3377          Flist := Empty;
3378       end if;
3379
3380       if Is_Array_Type (Typ) then
3381          Convert_Array_Aggr_In_Allocator (Decl, Aggr, Occ);
3382
3383       elsif Has_Default_Init_Comps (Aggr) then
3384          declare
3385             L          : constant List_Id := New_List;
3386             Init_Stmts : List_Id;
3387
3388          begin
3389             Init_Stmts :=
3390               Late_Expansion
3391                 (Aggr, Typ, Occ,
3392                  Flist,
3393                  Associated_Final_Chain (Base_Type (Access_Type)));
3394
3395             --  ??? Dubious actual for Obj: expect 'the original object being
3396             --  initialized'
3397
3398             if Has_Task (Typ) then
3399                Build_Task_Allocate_Block_With_Init_Stmts (L, Aggr, Init_Stmts);
3400                Insert_Actions (Alloc, L);
3401             else
3402                Insert_Actions (Alloc, Init_Stmts);
3403             end if;
3404          end;
3405
3406       else
3407          Insert_Actions (Alloc,
3408            Late_Expansion
3409              (Aggr, Typ, Occ, Flist,
3410               Associated_Final_Chain (Base_Type (Access_Type))));
3411
3412          --  ??? Dubious actual for Obj: expect 'the original object being
3413          --  initialized'
3414
3415       end if;
3416    end Convert_Aggr_In_Allocator;
3417
3418    --------------------------------
3419    -- Convert_Aggr_In_Assignment --
3420    --------------------------------
3421
3422    procedure Convert_Aggr_In_Assignment (N : Node_Id) is
3423       Aggr : Node_Id            := Expression (N);
3424       Typ  : constant Entity_Id := Etype (Aggr);
3425       Occ  : constant Node_Id   := New_Copy_Tree (Name (N));
3426
3427    begin
3428       if Nkind (Aggr) = N_Qualified_Expression then
3429          Aggr := Expression (Aggr);
3430       end if;
3431
3432       Insert_Actions_After (N,
3433         Late_Expansion
3434           (Aggr, Typ, Occ,
3435            Find_Final_List (Typ, New_Copy_Tree (Occ))));
3436    end Convert_Aggr_In_Assignment;
3437
3438    ---------------------------------
3439    -- Convert_Aggr_In_Object_Decl --
3440    ---------------------------------
3441
3442    procedure Convert_Aggr_In_Object_Decl (N : Node_Id) is
3443       Obj  : constant Entity_Id  := Defining_Identifier (N);
3444       Aggr : Node_Id             := Expression (N);
3445       Loc  : constant Source_Ptr := Sloc (Aggr);
3446       Typ  : constant Entity_Id  := Etype (Aggr);
3447       Occ  : constant Node_Id    := New_Occurrence_Of (Obj, Loc);
3448
3449       function Discriminants_Ok return Boolean;
3450       --  If the object type is constrained, the discriminants in the
3451       --  aggregate must be checked against the discriminants of the subtype.
3452       --  This cannot be done using Apply_Discriminant_Checks because after
3453       --  expansion there is no aggregate left to check.
3454
3455       ----------------------
3456       -- Discriminants_Ok --
3457       ----------------------
3458
3459       function Discriminants_Ok return Boolean is
3460          Cond  : Node_Id := Empty;
3461          Check : Node_Id;
3462          D     : Entity_Id;
3463          Disc1 : Elmt_Id;
3464          Disc2 : Elmt_Id;
3465          Val1  : Node_Id;
3466          Val2  : Node_Id;
3467
3468       begin
3469          D := First_Discriminant (Typ);
3470          Disc1 := First_Elmt (Discriminant_Constraint (Typ));
3471          Disc2 := First_Elmt (Discriminant_Constraint (Etype (Obj)));
3472          while Present (Disc1) and then Present (Disc2) loop
3473             Val1 := Node (Disc1);
3474             Val2 := Node (Disc2);
3475
3476             if not Is_OK_Static_Expression (Val1)
3477               or else not Is_OK_Static_Expression (Val2)
3478             then
3479                Check := Make_Op_Ne (Loc,
3480                  Left_Opnd  => Duplicate_Subexpr (Val1),
3481                  Right_Opnd => Duplicate_Subexpr (Val2));
3482
3483                if No (Cond) then
3484                   Cond := Check;
3485
3486                else
3487                   Cond := Make_Or_Else (Loc,
3488                     Left_Opnd => Cond,
3489                     Right_Opnd => Check);
3490                end if;
3491
3492             elsif Expr_Value (Val1) /= Expr_Value (Val2) then
3493                Apply_Compile_Time_Constraint_Error (Aggr,
3494                  Msg    => "incorrect value for discriminant&?",
3495                  Reason => CE_Discriminant_Check_Failed,
3496                  Ent    => D);
3497                return False;
3498             end if;
3499
3500             Next_Discriminant (D);
3501             Next_Elmt (Disc1);
3502             Next_Elmt (Disc2);
3503          end loop;
3504
3505          --  If any discriminant constraint is non-static, emit a check
3506
3507          if Present (Cond) then
3508             Insert_Action (N,
3509               Make_Raise_Constraint_Error (Loc,
3510                 Condition => Cond,
3511                 Reason => CE_Discriminant_Check_Failed));
3512          end if;
3513
3514          return True;
3515       end Discriminants_Ok;
3516
3517    --  Start of processing for Convert_Aggr_In_Object_Decl
3518
3519    begin
3520       Set_Assignment_OK (Occ);
3521
3522       if Nkind (Aggr) = N_Qualified_Expression then
3523          Aggr := Expression (Aggr);
3524       end if;
3525
3526       if Has_Discriminants (Typ)
3527         and then Typ /= Etype (Obj)
3528         and then Is_Constrained (Etype (Obj))
3529         and then not Discriminants_Ok
3530       then
3531          return;
3532       end if;
3533
3534       --  If the context is an extended return statement, it has its own
3535       --  finalization machinery (i.e. works like a transient scope) and
3536       --  we do not want to create an additional one, because objects on
3537       --  the finalization list of the return must be moved to the caller's
3538       --  finalization list to complete the return.
3539
3540       --  However, if the aggregate is limited, it is built in place, and the
3541       --  controlled components are not assigned to intermediate temporaries
3542       --  so there is no need for a transient scope in this case either.
3543
3544       if Requires_Transient_Scope (Typ)
3545         and then Ekind (Current_Scope) /= E_Return_Statement
3546         and then not Is_Limited_Type (Typ)
3547       then
3548          Establish_Transient_Scope
3549            (Aggr,
3550             Sec_Stack =>
3551               Is_Controlled (Typ) or else Has_Controlled_Component (Typ));
3552       end if;
3553
3554       Insert_Actions_After (N, Late_Expansion (Aggr, Typ, Occ, Obj => Obj));
3555       Set_No_Initialization (N);
3556       Initialize_Discriminants (N, Typ);
3557    end Convert_Aggr_In_Object_Decl;
3558
3559    -------------------------------------
3560    -- Convert_Array_Aggr_In_Allocator --
3561    -------------------------------------
3562
3563    procedure Convert_Array_Aggr_In_Allocator
3564      (Decl   : Node_Id;
3565       Aggr   : Node_Id;
3566       Target : Node_Id)
3567    is
3568       Aggr_Code : List_Id;
3569       Typ       : constant Entity_Id := Etype (Aggr);
3570       Ctyp      : constant Entity_Id := Component_Type (Typ);
3571
3572    begin
3573       --  The target is an explicit dereference of the allocated object.
3574       --  Generate component assignments to it, as for an aggregate that
3575       --  appears on the right-hand side of an assignment statement.
3576
3577       Aggr_Code :=
3578         Build_Array_Aggr_Code (Aggr,
3579           Ctype       => Ctyp,
3580           Index       => First_Index (Typ),
3581           Into        => Target,
3582           Scalar_Comp => Is_Scalar_Type (Ctyp));
3583
3584       Insert_Actions_After (Decl, Aggr_Code);
3585    end Convert_Array_Aggr_In_Allocator;
3586
3587    ----------------------------
3588    -- Convert_To_Assignments --
3589    ----------------------------
3590
3591    procedure Convert_To_Assignments (N : Node_Id; Typ : Entity_Id) is
3592       Loc  : constant Source_Ptr := Sloc (N);
3593       T    : Entity_Id;
3594       Temp : Entity_Id;
3595
3596       Instr       : Node_Id;
3597       Target_Expr : Node_Id;
3598       Parent_Kind : Node_Kind;
3599       Unc_Decl    : Boolean := False;
3600       Parent_Node : Node_Id;
3601
3602    begin
3603       pragma Assert (not Is_Static_Dispatch_Table_Aggregate (N));
3604       pragma Assert (Is_Record_Type (Typ));
3605
3606       Parent_Node := Parent (N);
3607       Parent_Kind := Nkind (Parent_Node);
3608
3609       if Parent_Kind = N_Qualified_Expression then
3610
3611          --  Check if we are in a unconstrained declaration because in this
3612          --  case the current delayed expansion mechanism doesn't work when
3613          --  the declared object size depend on the initializing expr.
3614
3615          begin
3616             Parent_Node := Parent (Parent_Node);
3617             Parent_Kind := Nkind (Parent_Node);
3618
3619             if Parent_Kind = N_Object_Declaration then
3620                Unc_Decl :=
3621                  not Is_Entity_Name (Object_Definition (Parent_Node))
3622                    or else Has_Discriminants
3623                              (Entity (Object_Definition (Parent_Node)))
3624                    or else Is_Class_Wide_Type
3625                              (Entity (Object_Definition (Parent_Node)));
3626             end if;
3627          end;
3628       end if;
3629
3630       --  Just set the Delay flag in the cases where the transformation will be
3631       --  done top down from above.
3632
3633       if False
3634
3635          --  Internal aggregate (transformed when expanding the parent)
3636
3637          or else Parent_Kind = N_Aggregate
3638          or else Parent_Kind = N_Extension_Aggregate
3639          or else Parent_Kind = N_Component_Association
3640
3641          --  Allocator (see Convert_Aggr_In_Allocator)
3642
3643          or else Parent_Kind = N_Allocator
3644
3645          --  Object declaration (see Convert_Aggr_In_Object_Decl)
3646
3647          or else (Parent_Kind = N_Object_Declaration and then not Unc_Decl)
3648
3649          --  Safe assignment (see Convert_Aggr_Assignments). So far only the
3650          --  assignments in init procs are taken into account.
3651
3652          or else (Parent_Kind = N_Assignment_Statement
3653                    and then Inside_Init_Proc)
3654
3655          --  (Ada 2005) An inherently limited type in a return statement,
3656          --  which will be handled in a build-in-place fashion, and may be
3657          --  rewritten as an extended return and have its own finalization
3658          --  machinery. In the case of a simple return, the aggregate needs
3659          --  to be delayed until the scope for the return statement has been
3660          --  created, so that any finalization chain will be associated with
3661          --  that scope. For extended returns, we delay expansion to avoid the
3662          --  creation of an unwanted transient scope that could result in
3663          --  premature finalization of the return object (which is built in
3664          --  in place within the caller's scope).
3665
3666          or else
3667            (Is_Immutably_Limited_Type (Typ)
3668              and then
3669                (Nkind (Parent (Parent_Node)) = N_Extended_Return_Statement
3670                  or else Nkind (Parent_Node) = N_Simple_Return_Statement))
3671       then
3672          Set_Expansion_Delayed (N);
3673          return;
3674       end if;
3675
3676       if Requires_Transient_Scope (Typ) then
3677          Establish_Transient_Scope
3678            (N, Sec_Stack =>
3679                  Is_Controlled (Typ) or else Has_Controlled_Component (Typ));
3680       end if;
3681
3682       --  If the aggregate is non-limited, create a temporary. If it is limited
3683       --  and the context is an assignment, this is a subaggregate for an
3684       --  enclosing aggregate being expanded. It must be built in place, so use
3685       --  the target of the current assignment.
3686
3687       if Is_Limited_Type (Typ)
3688         and then Nkind (Parent (N)) = N_Assignment_Statement
3689       then
3690          Target_Expr := New_Copy_Tree (Name (Parent (N)));
3691          Insert_Actions
3692            (Parent (N), Build_Record_Aggr_Code (N, Typ, Target_Expr));
3693          Rewrite (Parent (N), Make_Null_Statement (Loc));
3694
3695       else
3696          Temp := Make_Temporary (Loc, 'A', N);
3697
3698          --  If the type inherits unknown discriminants, use the view with
3699          --  known discriminants if available.
3700
3701          if Has_Unknown_Discriminants (Typ)
3702             and then Present (Underlying_Record_View (Typ))
3703          then
3704             T := Underlying_Record_View (Typ);
3705          else
3706             T := Typ;
3707          end if;
3708
3709          Instr :=
3710            Make_Object_Declaration (Loc,
3711              Defining_Identifier => Temp,
3712              Object_Definition   => New_Occurrence_Of (T, Loc));
3713
3714          Set_No_Initialization (Instr);
3715          Insert_Action (N, Instr);
3716          Initialize_Discriminants (Instr, T);
3717          Target_Expr := New_Occurrence_Of (Temp, Loc);
3718          Insert_Actions (N, Build_Record_Aggr_Code (N, T, Target_Expr));
3719          Rewrite (N, New_Occurrence_Of (Temp, Loc));
3720          Analyze_And_Resolve (N, T);
3721       end if;
3722    end Convert_To_Assignments;
3723
3724    ---------------------------
3725    -- Convert_To_Positional --
3726    ---------------------------
3727
3728    procedure Convert_To_Positional
3729      (N                    : Node_Id;
3730       Max_Others_Replicate : Nat     := 5;
3731       Handle_Bit_Packed    : Boolean := False)
3732    is
3733       Typ : constant Entity_Id := Etype (N);
3734
3735       Static_Components : Boolean := True;
3736
3737       procedure Check_Static_Components;
3738       --  Check whether all components of the aggregate are compile-time known
3739       --  values, and can be passed as is to the back-end without further
3740       --  expansion.
3741
3742       function Flatten
3743         (N   : Node_Id;
3744          Ix  : Node_Id;
3745          Ixb : Node_Id) return Boolean;
3746       --  Convert the aggregate into a purely positional form if possible. On
3747       --  entry the bounds of all dimensions are known to be static, and the
3748       --  total number of components is safe enough to expand.
3749
3750       function Is_Flat (N : Node_Id; Dims : Int) return Boolean;
3751       --  Return True iff the array N is flat (which is not trivial in the case
3752       --  of multidimensional aggregates).
3753
3754       -----------------------------
3755       -- Check_Static_Components --
3756       -----------------------------
3757
3758       procedure Check_Static_Components is
3759          Expr : Node_Id;
3760
3761       begin
3762          Static_Components := True;
3763
3764          if Nkind (N) = N_String_Literal then
3765             null;
3766
3767          elsif Present (Expressions (N)) then
3768             Expr := First (Expressions (N));
3769             while Present (Expr) loop
3770                if Nkind (Expr) /= N_Aggregate
3771                  or else not Compile_Time_Known_Aggregate (Expr)
3772                  or else Expansion_Delayed (Expr)
3773                then
3774                   Static_Components := False;
3775                   exit;
3776                end if;
3777
3778                Next (Expr);
3779             end loop;
3780          end if;
3781
3782          if Nkind (N) = N_Aggregate
3783            and then  Present (Component_Associations (N))
3784          then
3785             Expr := First (Component_Associations (N));
3786             while Present (Expr) loop
3787                if Nkind_In (Expression (Expr), N_Integer_Literal,
3788                                                N_Real_Literal)
3789                then
3790                   null;
3791
3792                elsif Is_Entity_Name (Expression (Expr))
3793                  and then Present (Entity (Expression (Expr)))
3794                  and then Ekind (Entity (Expression (Expr))) =
3795                    E_Enumeration_Literal
3796                then
3797                   null;
3798
3799                elsif Nkind (Expression (Expr)) /= N_Aggregate
3800                  or else not Compile_Time_Known_Aggregate (Expression (Expr))
3801                  or else Expansion_Delayed (Expression (Expr))
3802                then
3803                   Static_Components := False;
3804                   exit;
3805                end if;
3806
3807                Next (Expr);
3808             end loop;
3809          end if;
3810       end Check_Static_Components;
3811
3812       -------------
3813       -- Flatten --
3814       -------------
3815
3816       function Flatten
3817         (N   : Node_Id;
3818          Ix  : Node_Id;
3819          Ixb : Node_Id) return Boolean
3820       is
3821          Loc : constant Source_Ptr := Sloc (N);
3822          Blo : constant Node_Id    := Type_Low_Bound (Etype (Ixb));
3823          Lo  : constant Node_Id    := Type_Low_Bound (Etype (Ix));
3824          Hi  : constant Node_Id    := Type_High_Bound (Etype (Ix));
3825          Lov : Uint;
3826          Hiv : Uint;
3827
3828       begin
3829          if Nkind (Original_Node (N)) = N_String_Literal then
3830             return True;
3831          end if;
3832
3833          if not Compile_Time_Known_Value (Lo)
3834            or else not Compile_Time_Known_Value (Hi)
3835          then
3836             return False;
3837          end if;
3838
3839          Lov := Expr_Value (Lo);
3840          Hiv := Expr_Value (Hi);
3841
3842          if Hiv < Lov
3843            or else not Compile_Time_Known_Value (Blo)
3844          then
3845             return False;
3846          end if;
3847
3848          --  Determine if set of alternatives is suitable for conversion and
3849          --  build an array containing the values in sequence.
3850
3851          declare
3852             Vals : array (UI_To_Int (Lov) .. UI_To_Int (Hiv))
3853                      of Node_Id := (others => Empty);
3854             --  The values in the aggregate sorted appropriately
3855
3856             Vlist : List_Id;
3857             --  Same data as Vals in list form
3858
3859             Rep_Count : Nat;
3860             --  Used to validate Max_Others_Replicate limit
3861
3862             Elmt         : Node_Id;
3863             Num          : Int := UI_To_Int (Lov);
3864             Choice_Index : Int;
3865             Choice       : Node_Id;
3866             Lo, Hi       : Node_Id;
3867
3868          begin
3869             if Present (Expressions (N)) then
3870                Elmt := First (Expressions (N));
3871                while Present (Elmt) loop
3872                   if Nkind (Elmt) = N_Aggregate
3873                     and then Present (Next_Index (Ix))
3874                     and then
3875                       not Flatten (Elmt, Next_Index (Ix), Next_Index (Ixb))
3876                   then
3877                      return False;
3878                   end if;
3879
3880                   Vals (Num) := Relocate_Node (Elmt);
3881                   Num := Num + 1;
3882
3883                   Next (Elmt);
3884                end loop;
3885             end if;
3886
3887             if No (Component_Associations (N)) then
3888                return True;
3889             end if;
3890
3891             Elmt := First (Component_Associations (N));
3892
3893             if Nkind (Expression (Elmt)) = N_Aggregate then
3894                if Present (Next_Index (Ix))
3895                  and then
3896                    not Flatten
3897                         (Expression (Elmt), Next_Index (Ix), Next_Index (Ixb))
3898                then
3899                   return False;
3900                end if;
3901             end if;
3902
3903             Component_Loop : while Present (Elmt) loop
3904                Choice := First (Choices (Elmt));
3905                Choice_Loop : while Present (Choice) loop
3906
3907                   --  If we have an others choice, fill in the missing elements
3908                   --  subject to the limit established by Max_Others_Replicate.
3909
3910                   if Nkind (Choice) = N_Others_Choice then
3911                      Rep_Count := 0;
3912
3913                      for J in Vals'Range loop
3914                         if No (Vals (J)) then
3915                            Vals (J) := New_Copy_Tree (Expression (Elmt));
3916                            Rep_Count := Rep_Count + 1;
3917
3918                            --  Check for maximum others replication. Note that
3919                            --  we skip this test if either of the restrictions
3920                            --  No_Elaboration_Code or No_Implicit_Loops is
3921                            --  active, if this is a preelaborable unit or a
3922                            --  predefined unit. This ensures that predefined
3923                            --  units get the same level of constant folding in
3924                            --  Ada 95 and Ada 05, where their categorization
3925                            --  has changed.
3926
3927                            declare
3928                               P : constant Entity_Id :=
3929                                     Cunit_Entity (Current_Sem_Unit);
3930
3931                            begin
3932                               --  Check if duplication OK and if so continue
3933                               --  processing.
3934
3935                               if Restriction_Active (No_Elaboration_Code)
3936                                 or else Restriction_Active (No_Implicit_Loops)
3937                                 or else Is_Preelaborated (P)
3938                                 or else (Ekind (P) = E_Package_Body
3939                                           and then
3940                                             Is_Preelaborated (Spec_Entity (P)))
3941                                 or else
3942                                   Is_Predefined_File_Name
3943                                     (Unit_File_Name (Get_Source_Unit (P)))
3944                               then
3945                                  null;
3946
3947                               --  If duplication not OK, then we return False
3948                               --  if the replication count is too high
3949
3950                               elsif Rep_Count > Max_Others_Replicate then
3951                                  return False;
3952
3953                               --  Continue on if duplication not OK, but the
3954                               --  replication count is not excessive.
3955
3956                               else
3957                                  null;
3958                               end if;
3959                            end;
3960                         end if;
3961                      end loop;
3962
3963                      exit Component_Loop;
3964
3965                   --  Case of a subtype mark, identifier or expanded name
3966
3967                   elsif Is_Entity_Name (Choice)
3968                     and then Is_Type (Entity (Choice))
3969                   then
3970                      Lo := Type_Low_Bound  (Etype (Choice));
3971                      Hi := Type_High_Bound (Etype (Choice));
3972
3973                   --  Case of subtype indication
3974
3975                   elsif Nkind (Choice) = N_Subtype_Indication then
3976                      Lo := Low_Bound  (Range_Expression (Constraint (Choice)));
3977                      Hi := High_Bound (Range_Expression (Constraint (Choice)));
3978
3979                   --  Case of a range
3980
3981                   elsif Nkind (Choice) = N_Range then
3982                      Lo := Low_Bound (Choice);
3983                      Hi := High_Bound (Choice);
3984
3985                   --  Normal subexpression case
3986
3987                   else pragma Assert (Nkind (Choice) in N_Subexpr);
3988                      if not Compile_Time_Known_Value (Choice) then
3989                         return False;
3990
3991                      else
3992                         Choice_Index := UI_To_Int (Expr_Value (Choice));
3993                         if Choice_Index in Vals'Range then
3994                            Vals (Choice_Index) :=
3995                              New_Copy_Tree (Expression (Elmt));
3996                            goto Continue;
3997
3998                         else
3999                            --  Choice is statically out-of-range, will be
4000                            --  rewritten to raise Constraint_Error.
4001
4002                            return False;
4003                         end if;
4004                      end if;
4005                   end if;
4006
4007                   --  Range cases merge with Lo,Hi set
4008
4009                   if not Compile_Time_Known_Value (Lo)
4010                        or else
4011                      not Compile_Time_Known_Value (Hi)
4012                   then
4013                      return False;
4014                   else
4015                      for J in UI_To_Int (Expr_Value (Lo)) ..
4016                               UI_To_Int (Expr_Value (Hi))
4017                      loop
4018                         Vals (J) := New_Copy_Tree (Expression (Elmt));
4019                      end loop;
4020                   end if;
4021
4022                <<Continue>>
4023                   Next (Choice);
4024                end loop Choice_Loop;
4025
4026                Next (Elmt);
4027             end loop Component_Loop;
4028
4029             --  If we get here the conversion is possible
4030
4031             Vlist := New_List;
4032             for J in Vals'Range loop
4033                Append (Vals (J), Vlist);
4034             end loop;
4035
4036             Rewrite (N, Make_Aggregate (Loc, Expressions => Vlist));
4037             Set_Aggregate_Bounds (N, Aggregate_Bounds (Original_Node (N)));
4038             return True;
4039          end;
4040       end Flatten;
4041
4042       -------------
4043       -- Is_Flat --
4044       -------------
4045
4046       function Is_Flat (N : Node_Id; Dims : Int) return Boolean is
4047          Elmt : Node_Id;
4048
4049       begin
4050          if Dims = 0 then
4051             return True;
4052
4053          elsif Nkind (N) = N_Aggregate then
4054             if Present (Component_Associations (N)) then
4055                return False;
4056
4057             else
4058                Elmt := First (Expressions (N));
4059                while Present (Elmt) loop
4060                   if not Is_Flat (Elmt, Dims - 1) then
4061                      return False;
4062                   end if;
4063
4064                   Next (Elmt);
4065                end loop;
4066
4067                return True;
4068             end if;
4069          else
4070             return True;
4071          end if;
4072       end Is_Flat;
4073
4074    --  Start of processing for Convert_To_Positional
4075
4076    begin
4077       --  Ada 2005 (AI-287): Do not convert in case of default initialized
4078       --  components because in this case will need to call the corresponding
4079       --  IP procedure.
4080
4081       if Has_Default_Init_Comps (N) then
4082          return;
4083       end if;
4084
4085       if Is_Flat (N, Number_Dimensions (Typ)) then
4086          return;
4087       end if;
4088
4089       if Is_Bit_Packed_Array (Typ)
4090         and then not Handle_Bit_Packed
4091       then
4092          return;
4093       end if;
4094
4095       --  Do not convert to positional if controlled components are involved
4096       --  since these require special processing
4097
4098       if Has_Controlled_Component (Typ) then
4099          return;
4100       end if;
4101
4102       Check_Static_Components;
4103
4104       --  If the size is known, or all the components are static, try to
4105       --  build a fully positional aggregate.
4106
4107       --  The size of the type  may not be known for an aggregate with
4108       --  discriminated array components, but if the components are static
4109       --  it is still possible to verify statically that the length is
4110       --  compatible with the upper bound of the type, and therefore it is
4111       --  worth flattening such aggregates as well.
4112
4113       --  For now the back-end expands these aggregates into individual
4114       --  assignments to the target anyway, but it is conceivable that
4115       --  it will eventually be able to treat such aggregates statically???
4116
4117       if Aggr_Size_OK (N, Typ)
4118         and then Flatten (N, First_Index (Typ), First_Index (Base_Type (Typ)))
4119       then
4120          if Static_Components then
4121             Set_Compile_Time_Known_Aggregate (N);
4122             Set_Expansion_Delayed (N, False);
4123          end if;
4124
4125          Analyze_And_Resolve (N, Typ);
4126       end if;
4127    end Convert_To_Positional;
4128
4129    ----------------------------
4130    -- Expand_Array_Aggregate --
4131    ----------------------------
4132
4133    --  Array aggregate expansion proceeds as follows:
4134
4135    --  1. If requested we generate code to perform all the array aggregate
4136    --     bound checks, specifically
4137
4138    --         (a) Check that the index range defined by aggregate bounds is
4139    --             compatible with corresponding index subtype.
4140
4141    --         (b) If an others choice is present check that no aggregate
4142    --             index is outside the bounds of the index constraint.
4143
4144    --         (c) For multidimensional arrays make sure that all subaggregates
4145    --             corresponding to the same dimension have the same bounds.
4146
4147    --  2. Check for packed array aggregate which can be converted to a
4148    --     constant so that the aggregate disappeares completely.
4149
4150    --  3. Check case of nested aggregate. Generally nested aggregates are
4151    --     handled during the processing of the parent aggregate.
4152
4153    --  4. Check if the aggregate can be statically processed. If this is the
4154    --     case pass it as is to Gigi. Note that a necessary condition for
4155    --     static processing is that the aggregate be fully positional.
4156
4157    --  5. If in place aggregate expansion is possible (i.e. no need to create
4158    --     a temporary) then mark the aggregate as such and return. Otherwise
4159    --     create a new temporary and generate the appropriate initialization
4160    --     code.
4161
4162    procedure Expand_Array_Aggregate (N : Node_Id) is
4163       Loc : constant Source_Ptr := Sloc (N);
4164
4165       Typ  : constant Entity_Id := Etype (N);
4166       Ctyp : constant Entity_Id := Component_Type (Typ);
4167       --  Typ is the correct constrained array subtype of the aggregate
4168       --  Ctyp is the corresponding component type.
4169
4170       Aggr_Dimension : constant Pos := Number_Dimensions (Typ);
4171       --  Number of aggregate index dimensions
4172
4173       Aggr_Low  : array (1 .. Aggr_Dimension) of Node_Id;
4174       Aggr_High : array (1 .. Aggr_Dimension) of Node_Id;
4175       --  Low and High bounds of the constraint for each aggregate index
4176
4177       Aggr_Index_Typ : array (1 .. Aggr_Dimension) of Entity_Id;
4178       --  The type of each index
4179
4180       Maybe_In_Place_OK : Boolean;
4181       --  If the type is neither controlled nor packed and the aggregate
4182       --  is the expression in an assignment, assignment in place may be
4183       --  possible, provided other conditions are met on the LHS.
4184
4185       Others_Present : array (1 .. Aggr_Dimension) of Boolean :=
4186                          (others => False);
4187       --  If Others_Present (J) is True, then there is an others choice
4188       --  in one of the sub-aggregates of N at dimension J.
4189
4190       procedure Build_Constrained_Type (Positional : Boolean);
4191       --  If the subtype is not static or unconstrained, build a constrained
4192       --  type using the computable sizes of the aggregate and its sub-
4193       --  aggregates.
4194
4195       procedure Check_Bounds (Aggr_Bounds : Node_Id; Index_Bounds : Node_Id);
4196       --  Checks that the bounds of Aggr_Bounds are within the bounds defined
4197       --  by Index_Bounds.
4198
4199       procedure Check_Same_Aggr_Bounds (Sub_Aggr : Node_Id; Dim : Pos);
4200       --  Checks that in a multi-dimensional array aggregate all subaggregates
4201       --  corresponding to the same dimension have the same bounds.
4202       --  Sub_Aggr is an array sub-aggregate. Dim is the dimension
4203       --  corresponding to the sub-aggregate.
4204
4205       procedure Compute_Others_Present (Sub_Aggr : Node_Id; Dim : Pos);
4206       --  Computes the values of array Others_Present. Sub_Aggr is the
4207       --  array sub-aggregate we start the computation from. Dim is the
4208       --  dimension corresponding to the sub-aggregate.
4209
4210       function In_Place_Assign_OK return Boolean;
4211       --  Simple predicate to determine whether an aggregate assignment can
4212       --  be done in place, because none of the new values can depend on the
4213       --  components of the target of the assignment.
4214
4215       procedure Others_Check (Sub_Aggr : Node_Id; Dim : Pos);
4216       --  Checks that if an others choice is present in any sub-aggregate no
4217       --  aggregate index is outside the bounds of the index constraint.
4218       --  Sub_Aggr is an array sub-aggregate. Dim is the dimension
4219       --  corresponding to the sub-aggregate.
4220
4221       function Safe_Left_Hand_Side (N : Node_Id) return Boolean;
4222       --  In addition to Maybe_In_Place_OK, in order for an aggregate to be
4223       --  built directly into the target of the assignment it must be free
4224       --  of side-effects.
4225
4226       ----------------------------
4227       -- Build_Constrained_Type --
4228       ----------------------------
4229
4230       procedure Build_Constrained_Type (Positional : Boolean) is
4231          Loc      : constant Source_Ptr := Sloc (N);
4232          Agg_Type : constant Entity_Id  := Make_Temporary (Loc, 'A');
4233          Comp     : Node_Id;
4234          Decl     : Node_Id;
4235          Typ      : constant Entity_Id := Etype (N);
4236          Indexes  : constant List_Id   := New_List;
4237          Num      : Int;
4238          Sub_Agg  : Node_Id;
4239
4240       begin
4241          --  If the aggregate is purely positional, all its subaggregates
4242          --  have the same size. We collect the dimensions from the first
4243          --  subaggregate at each level.
4244
4245          if Positional then
4246             Sub_Agg := N;
4247
4248             for D in 1 .. Number_Dimensions (Typ) loop
4249                Sub_Agg := First (Expressions (Sub_Agg));
4250
4251                Comp := Sub_Agg;
4252                Num := 0;
4253                while Present (Comp) loop
4254                   Num := Num + 1;
4255                   Next (Comp);
4256                end loop;
4257
4258                Append_To (Indexes,
4259                  Make_Range (Loc,
4260                    Low_Bound =>  Make_Integer_Literal (Loc, 1),
4261                    High_Bound => Make_Integer_Literal (Loc, Num)));
4262             end loop;
4263
4264          else
4265             --  We know the aggregate type is unconstrained and the aggregate
4266             --  is not processable by the back end, therefore not necessarily
4267             --  positional. Retrieve each dimension bounds (computed earlier).
4268
4269             for D in 1 .. Number_Dimensions (Typ) loop
4270                Append (
4271                  Make_Range (Loc,
4272                     Low_Bound  => Aggr_Low  (D),
4273                     High_Bound => Aggr_High (D)),
4274                  Indexes);
4275             end loop;
4276          end if;
4277
4278          Decl :=
4279            Make_Full_Type_Declaration (Loc,
4280                Defining_Identifier => Agg_Type,
4281                Type_Definition =>
4282                  Make_Constrained_Array_Definition (Loc,
4283                    Discrete_Subtype_Definitions => Indexes,
4284                    Component_Definition         =>
4285                      Make_Component_Definition (Loc,
4286                        Aliased_Present    => False,
4287                        Subtype_Indication =>
4288                          New_Occurrence_Of (Component_Type (Typ), Loc))));
4289
4290          Insert_Action (N, Decl);
4291          Analyze (Decl);
4292          Set_Etype (N, Agg_Type);
4293          Set_Is_Itype (Agg_Type);
4294          Freeze_Itype (Agg_Type, N);
4295       end Build_Constrained_Type;
4296
4297       ------------------
4298       -- Check_Bounds --
4299       ------------------
4300
4301       procedure Check_Bounds (Aggr_Bounds : Node_Id; Index_Bounds : Node_Id) is
4302          Aggr_Lo : Node_Id;
4303          Aggr_Hi : Node_Id;
4304
4305          Ind_Lo  : Node_Id;
4306          Ind_Hi  : Node_Id;
4307
4308          Cond    : Node_Id := Empty;
4309
4310       begin
4311          Get_Index_Bounds (Aggr_Bounds, Aggr_Lo, Aggr_Hi);
4312          Get_Index_Bounds (Index_Bounds, Ind_Lo, Ind_Hi);
4313
4314          --  Generate the following test:
4315          --
4316          --    [constraint_error when
4317          --      Aggr_Lo <= Aggr_Hi and then
4318          --        (Aggr_Lo < Ind_Lo or else Aggr_Hi > Ind_Hi)]
4319
4320          --  As an optimization try to see if some tests are trivially vacuous
4321          --  because we are comparing an expression against itself.
4322
4323          if Aggr_Lo = Ind_Lo and then Aggr_Hi = Ind_Hi then
4324             Cond := Empty;
4325
4326          elsif Aggr_Hi = Ind_Hi then
4327             Cond :=
4328               Make_Op_Lt (Loc,
4329                 Left_Opnd  => Duplicate_Subexpr_Move_Checks (Aggr_Lo),
4330                 Right_Opnd => Duplicate_Subexpr_Move_Checks (Ind_Lo));
4331
4332          elsif Aggr_Lo = Ind_Lo then
4333             Cond :=
4334               Make_Op_Gt (Loc,
4335                 Left_Opnd  => Duplicate_Subexpr_Move_Checks (Aggr_Hi),
4336                 Right_Opnd => Duplicate_Subexpr_Move_Checks (Ind_Hi));
4337
4338          else
4339             Cond :=
4340               Make_Or_Else (Loc,
4341                 Left_Opnd =>
4342                   Make_Op_Lt (Loc,
4343                     Left_Opnd  => Duplicate_Subexpr_Move_Checks (Aggr_Lo),
4344                     Right_Opnd => Duplicate_Subexpr_Move_Checks (Ind_Lo)),
4345
4346                 Right_Opnd =>
4347                   Make_Op_Gt (Loc,
4348                     Left_Opnd  => Duplicate_Subexpr (Aggr_Hi),
4349                     Right_Opnd => Duplicate_Subexpr (Ind_Hi)));
4350          end if;
4351
4352          if Present (Cond) then
4353             Cond :=
4354               Make_And_Then (Loc,
4355                 Left_Opnd =>
4356                   Make_Op_Le (Loc,
4357                     Left_Opnd  => Duplicate_Subexpr_Move_Checks (Aggr_Lo),
4358                     Right_Opnd => Duplicate_Subexpr_Move_Checks (Aggr_Hi)),
4359
4360                 Right_Opnd => Cond);
4361
4362             Set_Analyzed (Left_Opnd  (Left_Opnd (Cond)), False);
4363             Set_Analyzed (Right_Opnd (Left_Opnd (Cond)), False);
4364             Insert_Action (N,
4365               Make_Raise_Constraint_Error (Loc,
4366                 Condition => Cond,
4367                 Reason    => CE_Length_Check_Failed));
4368          end if;
4369       end Check_Bounds;
4370
4371       ----------------------------
4372       -- Check_Same_Aggr_Bounds --
4373       ----------------------------
4374
4375       procedure Check_Same_Aggr_Bounds (Sub_Aggr : Node_Id; Dim : Pos) is
4376          Sub_Lo : constant Node_Id := Low_Bound (Aggregate_Bounds (Sub_Aggr));
4377          Sub_Hi : constant Node_Id := High_Bound (Aggregate_Bounds (Sub_Aggr));
4378          --  The bounds of this specific sub-aggregate
4379
4380          Aggr_Lo : constant Node_Id := Aggr_Low (Dim);
4381          Aggr_Hi : constant Node_Id := Aggr_High (Dim);
4382          --  The bounds of the aggregate for this dimension
4383
4384          Ind_Typ : constant Entity_Id := Aggr_Index_Typ (Dim);
4385          --  The index type for this dimension.xxx
4386
4387          Cond  : Node_Id := Empty;
4388          Assoc : Node_Id;
4389          Expr  : Node_Id;
4390
4391       begin
4392          --  If index checks are on generate the test
4393
4394          --    [constraint_error when
4395          --      Aggr_Lo /= Sub_Lo or else Aggr_Hi /= Sub_Hi]
4396
4397          --  As an optimization try to see if some tests are trivially vacuos
4398          --  because we are comparing an expression against itself. Also for
4399          --  the first dimension the test is trivially vacuous because there
4400          --  is just one aggregate for dimension 1.
4401
4402          if Index_Checks_Suppressed (Ind_Typ) then
4403             Cond := Empty;
4404
4405          elsif Dim = 1
4406            or else (Aggr_Lo = Sub_Lo and then Aggr_Hi = Sub_Hi)
4407          then
4408             Cond := Empty;
4409
4410          elsif Aggr_Hi = Sub_Hi then
4411             Cond :=
4412               Make_Op_Ne (Loc,
4413                 Left_Opnd  => Duplicate_Subexpr_Move_Checks (Aggr_Lo),
4414                 Right_Opnd => Duplicate_Subexpr_Move_Checks (Sub_Lo));
4415
4416          elsif Aggr_Lo = Sub_Lo then
4417             Cond :=
4418               Make_Op_Ne (Loc,
4419                 Left_Opnd  => Duplicate_Subexpr_Move_Checks (Aggr_Hi),
4420                 Right_Opnd => Duplicate_Subexpr_Move_Checks (Sub_Hi));
4421
4422          else
4423             Cond :=
4424               Make_Or_Else (Loc,
4425                 Left_Opnd =>
4426                   Make_Op_Ne (Loc,
4427                     Left_Opnd  => Duplicate_Subexpr_Move_Checks (Aggr_Lo),
4428                     Right_Opnd => Duplicate_Subexpr_Move_Checks (Sub_Lo)),
4429
4430                 Right_Opnd =>
4431                   Make_Op_Ne (Loc,
4432                     Left_Opnd  => Duplicate_Subexpr (Aggr_Hi),
4433                     Right_Opnd => Duplicate_Subexpr (Sub_Hi)));
4434          end if;
4435
4436          if Present (Cond) then
4437             Insert_Action (N,
4438               Make_Raise_Constraint_Error (Loc,
4439                 Condition => Cond,
4440                 Reason    => CE_Length_Check_Failed));
4441          end if;
4442
4443          --  Now look inside the sub-aggregate to see if there is more work
4444
4445          if Dim < Aggr_Dimension then
4446
4447             --  Process positional components
4448
4449             if Present (Expressions (Sub_Aggr)) then
4450                Expr := First (Expressions (Sub_Aggr));
4451                while Present (Expr) loop
4452                   Check_Same_Aggr_Bounds (Expr, Dim + 1);
4453                   Next (Expr);
4454                end loop;
4455             end if;
4456
4457             --  Process component associations
4458
4459             if Present (Component_Associations (Sub_Aggr)) then
4460                Assoc := First (Component_Associations (Sub_Aggr));
4461                while Present (Assoc) loop
4462                   Expr := Expression (Assoc);
4463                   Check_Same_Aggr_Bounds (Expr, Dim + 1);
4464                   Next (Assoc);
4465                end loop;
4466             end if;
4467          end if;
4468       end Check_Same_Aggr_Bounds;
4469
4470       ----------------------------
4471       -- Compute_Others_Present --
4472       ----------------------------
4473
4474       procedure Compute_Others_Present (Sub_Aggr : Node_Id; Dim : Pos) is
4475          Assoc : Node_Id;
4476          Expr  : Node_Id;
4477
4478       begin
4479          if Present (Component_Associations (Sub_Aggr)) then
4480             Assoc := Last (Component_Associations (Sub_Aggr));
4481
4482             if Nkind (First (Choices (Assoc))) = N_Others_Choice then
4483                Others_Present (Dim) := True;
4484             end if;
4485          end if;
4486
4487          --  Now look inside the sub-aggregate to see if there is more work
4488
4489          if Dim < Aggr_Dimension then
4490
4491             --  Process positional components
4492
4493             if Present (Expressions (Sub_Aggr)) then
4494                Expr := First (Expressions (Sub_Aggr));
4495                while Present (Expr) loop
4496                   Compute_Others_Present (Expr, Dim + 1);
4497                   Next (Expr);
4498                end loop;
4499             end if;
4500
4501             --  Process component associations
4502
4503             if Present (Component_Associations (Sub_Aggr)) then
4504                Assoc := First (Component_Associations (Sub_Aggr));
4505                while Present (Assoc) loop
4506                   Expr := Expression (Assoc);
4507                   Compute_Others_Present (Expr, Dim + 1);
4508                   Next (Assoc);
4509                end loop;
4510             end if;
4511          end if;
4512       end Compute_Others_Present;
4513
4514       ------------------------
4515       -- In_Place_Assign_OK --
4516       ------------------------
4517
4518       function In_Place_Assign_OK return Boolean is
4519          Aggr_In : Node_Id;
4520          Aggr_Lo : Node_Id;
4521          Aggr_Hi : Node_Id;
4522          Obj_In  : Node_Id;
4523          Obj_Lo  : Node_Id;
4524          Obj_Hi  : Node_Id;
4525
4526          function Safe_Aggregate (Aggr : Node_Id) return Boolean;
4527          --  Check recursively that each component of a (sub)aggregate does
4528          --  not depend on the variable being assigned to.
4529
4530          function Safe_Component (Expr : Node_Id) return Boolean;
4531          --  Verify that an expression cannot depend on the variable being
4532          --  assigned to. Room for improvement here (but less than before).
4533
4534          --------------------
4535          -- Safe_Aggregate --
4536          --------------------
4537
4538          function Safe_Aggregate (Aggr : Node_Id) return Boolean is
4539             Expr : Node_Id;
4540
4541          begin
4542             if Present (Expressions (Aggr)) then
4543                Expr := First (Expressions (Aggr));
4544                while Present (Expr) loop
4545                   if Nkind (Expr) = N_Aggregate then
4546                      if not Safe_Aggregate (Expr) then
4547                         return False;
4548                      end if;
4549
4550                   elsif not Safe_Component (Expr) then
4551                      return False;
4552                   end if;
4553
4554                   Next (Expr);
4555                end loop;
4556             end if;
4557
4558             if Present (Component_Associations (Aggr)) then
4559                Expr := First (Component_Associations (Aggr));
4560                while Present (Expr) loop
4561                   if Nkind (Expression (Expr)) = N_Aggregate then
4562                      if not Safe_Aggregate (Expression (Expr)) then
4563                         return False;
4564                      end if;
4565
4566                   elsif not Safe_Component (Expression (Expr)) then
4567                      return False;
4568                   end if;
4569
4570                   Next (Expr);
4571                end loop;
4572             end if;
4573
4574             return True;
4575          end Safe_Aggregate;
4576
4577          --------------------
4578          -- Safe_Component --
4579          --------------------
4580
4581          function Safe_Component (Expr : Node_Id) return Boolean is
4582             Comp : Node_Id := Expr;
4583
4584             function Check_Component (Comp : Node_Id) return Boolean;
4585             --  Do the recursive traversal, after copy
4586
4587             ---------------------
4588             -- Check_Component --
4589             ---------------------
4590
4591             function Check_Component (Comp : Node_Id) return Boolean is
4592             begin
4593                if Is_Overloaded (Comp) then
4594                   return False;
4595                end if;
4596
4597                return Compile_Time_Known_Value (Comp)
4598
4599                  or else (Is_Entity_Name (Comp)
4600                            and then  Present (Entity (Comp))
4601                            and then No (Renamed_Object (Entity (Comp))))
4602
4603                  or else (Nkind (Comp) = N_Attribute_Reference
4604                            and then Check_Component (Prefix (Comp)))
4605
4606                  or else (Nkind (Comp) in N_Binary_Op
4607                            and then Check_Component (Left_Opnd  (Comp))
4608                            and then Check_Component (Right_Opnd (Comp)))
4609
4610                  or else (Nkind (Comp) in N_Unary_Op
4611                            and then Check_Component (Right_Opnd (Comp)))
4612
4613                  or else (Nkind (Comp) = N_Selected_Component
4614                            and then Check_Component (Prefix (Comp)))
4615
4616                  or else (Nkind (Comp) = N_Unchecked_Type_Conversion
4617                            and then Check_Component (Expression (Comp)));
4618             end Check_Component;
4619
4620          --  Start of processing for Safe_Component
4621
4622          begin
4623             --  If the component appears in an association that may
4624             --  correspond to more than one element, it is not analyzed
4625             --  before the expansion into assignments, to avoid side effects.
4626             --  We analyze, but do not resolve the copy, to obtain sufficient
4627             --  entity information for the checks that follow. If component is
4628             --  overloaded we assume an unsafe function call.
4629
4630             if not Analyzed (Comp) then
4631                if Is_Overloaded (Expr) then
4632                   return False;
4633
4634                elsif Nkind (Expr) = N_Aggregate
4635                   and then not Is_Others_Aggregate (Expr)
4636                then
4637                   return False;
4638
4639                elsif Nkind (Expr) = N_Allocator then
4640
4641                   --  For now, too complex to analyze
4642
4643                   return False;
4644                end if;
4645
4646                Comp := New_Copy_Tree (Expr);
4647                Set_Parent (Comp, Parent (Expr));
4648                Analyze (Comp);
4649             end if;
4650
4651             if Nkind (Comp) = N_Aggregate then
4652                return Safe_Aggregate (Comp);
4653             else
4654                return Check_Component (Comp);
4655             end if;
4656          end Safe_Component;
4657
4658       --  Start of processing for In_Place_Assign_OK
4659
4660       begin
4661          if Present (Component_Associations (N)) then
4662
4663             --  On assignment, sliding can take place, so we cannot do the
4664             --  assignment in place unless the bounds of the aggregate are
4665             --  statically equal to those of the target.
4666
4667             --  If the aggregate is given by an others choice, the bounds
4668             --  are derived from the left-hand side, and the assignment is
4669             --  safe if the expression is.
4670
4671             if Is_Others_Aggregate (N) then
4672                return
4673                  Safe_Component
4674                   (Expression (First (Component_Associations (N))));
4675             end if;
4676
4677             Aggr_In := First_Index (Etype (N));
4678
4679             if Nkind (Parent (N)) = N_Assignment_Statement then
4680                Obj_In  := First_Index (Etype (Name (Parent (N))));
4681
4682             else
4683                --  Context is an allocator. Check bounds of aggregate
4684                --  against given type in qualified expression.
4685
4686                pragma Assert (Nkind (Parent (Parent (N))) = N_Allocator);
4687                Obj_In :=
4688                  First_Index (Etype (Entity (Subtype_Mark (Parent (N)))));
4689             end if;
4690
4691             while Present (Aggr_In) loop
4692                Get_Index_Bounds (Aggr_In, Aggr_Lo, Aggr_Hi);
4693                Get_Index_Bounds (Obj_In, Obj_Lo, Obj_Hi);
4694
4695                if not Compile_Time_Known_Value (Aggr_Lo)
4696                  or else not Compile_Time_Known_Value (Aggr_Hi)
4697                  or else not Compile_Time_Known_Value (Obj_Lo)
4698                  or else not Compile_Time_Known_Value (Obj_Hi)
4699                  or else Expr_Value (Aggr_Lo) /= Expr_Value (Obj_Lo)
4700                  or else Expr_Value (Aggr_Hi) /= Expr_Value (Obj_Hi)
4701                then
4702                   return False;
4703                end if;
4704
4705                Next_Index (Aggr_In);
4706                Next_Index (Obj_In);
4707             end loop;
4708          end if;
4709
4710          --  Now check the component values themselves
4711
4712          return Safe_Aggregate (N);
4713       end In_Place_Assign_OK;
4714
4715       ------------------
4716       -- Others_Check --
4717       ------------------
4718
4719       procedure Others_Check (Sub_Aggr : Node_Id; Dim : Pos) is
4720          Aggr_Lo : constant Node_Id := Aggr_Low (Dim);
4721          Aggr_Hi : constant Node_Id := Aggr_High (Dim);
4722          --  The bounds of the aggregate for this dimension
4723
4724          Ind_Typ : constant Entity_Id := Aggr_Index_Typ (Dim);
4725          --  The index type for this dimension
4726
4727          Need_To_Check : Boolean := False;
4728
4729          Choices_Lo : Node_Id := Empty;
4730          Choices_Hi : Node_Id := Empty;
4731          --  The lowest and highest discrete choices for a named sub-aggregate
4732
4733          Nb_Choices : Int := -1;
4734          --  The number of discrete non-others choices in this sub-aggregate
4735
4736          Nb_Elements : Uint := Uint_0;
4737          --  The number of elements in a positional aggregate
4738
4739          Cond : Node_Id := Empty;
4740
4741          Assoc  : Node_Id;
4742          Choice : Node_Id;
4743          Expr   : Node_Id;
4744
4745       begin
4746          --  Check if we have an others choice. If we do make sure that this
4747          --  sub-aggregate contains at least one element in addition to the
4748          --  others choice.
4749
4750          if Range_Checks_Suppressed (Ind_Typ) then
4751             Need_To_Check := False;
4752
4753          elsif Present (Expressions (Sub_Aggr))
4754            and then Present (Component_Associations (Sub_Aggr))
4755          then
4756             Need_To_Check := True;
4757
4758          elsif Present (Component_Associations (Sub_Aggr)) then
4759             Assoc := Last (Component_Associations (Sub_Aggr));
4760
4761             if Nkind (First (Choices (Assoc))) /= N_Others_Choice then
4762                Need_To_Check := False;
4763
4764             else
4765                --  Count the number of discrete choices. Start with -1 because
4766                --  the others choice does not count.
4767
4768                Nb_Choices := -1;
4769                Assoc := First (Component_Associations (Sub_Aggr));
4770                while Present (Assoc) loop
4771                   Choice := First (Choices (Assoc));
4772                   while Present (Choice) loop
4773                      Nb_Choices := Nb_Choices + 1;
4774                      Next (Choice);
4775                   end loop;
4776
4777                   Next (Assoc);
4778                end loop;
4779
4780                --  If there is only an others choice nothing to do
4781
4782                Need_To_Check := (Nb_Choices > 0);
4783             end if;
4784
4785          else
4786             Need_To_Check := False;
4787          end if;
4788
4789          --  If we are dealing with a positional sub-aggregate with an others
4790          --  choice then compute the number or positional elements.
4791
4792          if Need_To_Check and then Present (Expressions (Sub_Aggr)) then
4793             Expr := First (Expressions (Sub_Aggr));
4794             Nb_Elements := Uint_0;
4795             while Present (Expr) loop
4796                Nb_Elements := Nb_Elements + 1;
4797                Next (Expr);
4798             end loop;
4799
4800          --  If the aggregate contains discrete choices and an others choice
4801          --  compute the smallest and largest discrete choice values.
4802
4803          elsif Need_To_Check then
4804             Compute_Choices_Lo_And_Choices_Hi : declare
4805
4806                Table : Case_Table_Type (1 .. Nb_Choices);
4807                --  Used to sort all the different choice values
4808
4809                J    : Pos := 1;
4810                Low  : Node_Id;
4811                High : Node_Id;
4812
4813             begin
4814                Assoc := First (Component_Associations (Sub_Aggr));
4815                while Present (Assoc) loop
4816                   Choice := First (Choices (Assoc));
4817                   while Present (Choice) loop
4818                      if Nkind (Choice) = N_Others_Choice then
4819                         exit;
4820                      end if;
4821
4822                      Get_Index_Bounds (Choice, Low, High);
4823                      Table (J).Choice_Lo := Low;
4824                      Table (J).Choice_Hi := High;
4825
4826                      J := J + 1;
4827                      Next (Choice);
4828                   end loop;
4829
4830                   Next (Assoc);
4831                end loop;
4832
4833                --  Sort the discrete choices
4834
4835                Sort_Case_Table (Table);
4836
4837                Choices_Lo := Table (1).Choice_Lo;
4838                Choices_Hi := Table (Nb_Choices).Choice_Hi;
4839             end Compute_Choices_Lo_And_Choices_Hi;
4840          end if;
4841
4842          --  If no others choice in this sub-aggregate, or the aggregate
4843          --  comprises only an others choice, nothing to do.
4844
4845          if not Need_To_Check then
4846             Cond := Empty;
4847
4848          --  If we are dealing with an aggregate containing an others choice
4849          --  and positional components, we generate the following test:
4850
4851          --    if Ind_Typ'Pos (Aggr_Lo) + (Nb_Elements - 1) >
4852          --            Ind_Typ'Pos (Aggr_Hi)
4853          --    then
4854          --       raise Constraint_Error;
4855          --    end if;
4856
4857          elsif Nb_Elements > Uint_0 then
4858             Cond :=
4859               Make_Op_Gt (Loc,
4860                 Left_Opnd  =>
4861                   Make_Op_Add (Loc,
4862                     Left_Opnd  =>
4863                       Make_Attribute_Reference (Loc,
4864                         Prefix         => New_Reference_To (Ind_Typ, Loc),
4865                         Attribute_Name => Name_Pos,
4866                         Expressions    =>
4867                           New_List
4868                             (Duplicate_Subexpr_Move_Checks (Aggr_Lo))),
4869                     Right_Opnd => Make_Integer_Literal (Loc, Nb_Elements - 1)),
4870
4871                 Right_Opnd =>
4872                   Make_Attribute_Reference (Loc,
4873                     Prefix         => New_Reference_To (Ind_Typ, Loc),
4874                     Attribute_Name => Name_Pos,
4875                     Expressions    => New_List (
4876                       Duplicate_Subexpr_Move_Checks (Aggr_Hi))));
4877
4878          --  If we are dealing with an aggregate containing an others choice
4879          --  and discrete choices we generate the following test:
4880
4881          --    [constraint_error when
4882          --      Choices_Lo < Aggr_Lo or else Choices_Hi > Aggr_Hi];
4883
4884          else
4885             Cond :=
4886               Make_Or_Else (Loc,
4887                 Left_Opnd =>
4888                   Make_Op_Lt (Loc,
4889                     Left_Opnd  =>
4890                       Duplicate_Subexpr_Move_Checks (Choices_Lo),
4891                     Right_Opnd =>
4892                       Duplicate_Subexpr_Move_Checks (Aggr_Lo)),
4893
4894                 Right_Opnd =>
4895                   Make_Op_Gt (Loc,
4896                     Left_Opnd  =>
4897                       Duplicate_Subexpr (Choices_Hi),
4898                     Right_Opnd =>
4899                       Duplicate_Subexpr (Aggr_Hi)));
4900          end if;
4901
4902          if Present (Cond) then
4903             Insert_Action (N,
4904               Make_Raise_Constraint_Error (Loc,
4905                 Condition => Cond,
4906                 Reason    => CE_Length_Check_Failed));
4907             --  Questionable reason code, shouldn't that be a
4908             --  CE_Range_Check_Failed ???
4909          end if;
4910
4911          --  Now look inside the sub-aggregate to see if there is more work
4912
4913          if Dim < Aggr_Dimension then
4914
4915             --  Process positional components
4916
4917             if Present (Expressions (Sub_Aggr)) then
4918                Expr := First (Expressions (Sub_Aggr));
4919                while Present (Expr) loop
4920                   Others_Check (Expr, Dim + 1);
4921                   Next (Expr);
4922                end loop;
4923             end if;
4924
4925             --  Process component associations
4926
4927             if Present (Component_Associations (Sub_Aggr)) then
4928                Assoc := First (Component_Associations (Sub_Aggr));
4929                while Present (Assoc) loop
4930                   Expr := Expression (Assoc);
4931                   Others_Check (Expr, Dim + 1);
4932                   Next (Assoc);
4933                end loop;
4934             end if;
4935          end if;
4936       end Others_Check;
4937
4938       -------------------------
4939       -- Safe_Left_Hand_Side --
4940       -------------------------
4941
4942       function Safe_Left_Hand_Side (N : Node_Id) return Boolean is
4943          function Is_Safe_Index (Indx : Node_Id) return Boolean;
4944          --  If the left-hand side includes an indexed component, check that
4945          --  the indexes are free of side-effect.
4946
4947          -------------------
4948          -- Is_Safe_Index --
4949          -------------------
4950
4951          function Is_Safe_Index (Indx : Node_Id) return Boolean is
4952          begin
4953             if Is_Entity_Name (Indx) then
4954                return True;
4955
4956             elsif Nkind (Indx) = N_Integer_Literal then
4957                return True;
4958
4959             elsif Nkind (Indx) = N_Function_Call
4960               and then Is_Entity_Name (Name (Indx))
4961               and then
4962                 Has_Pragma_Pure_Function (Entity (Name (Indx)))
4963             then
4964                return True;
4965
4966             elsif Nkind (Indx) = N_Type_Conversion
4967               and then Is_Safe_Index (Expression (Indx))
4968             then
4969                return True;
4970
4971             else
4972                return False;
4973             end if;
4974          end Is_Safe_Index;
4975
4976       --  Start of processing for Safe_Left_Hand_Side
4977
4978       begin
4979          if Is_Entity_Name (N) then
4980             return True;
4981
4982          elsif Nkind_In (N, N_Explicit_Dereference, N_Selected_Component)
4983            and then Safe_Left_Hand_Side (Prefix (N))
4984          then
4985             return True;
4986
4987          elsif Nkind (N) = N_Indexed_Component
4988            and then Safe_Left_Hand_Side (Prefix (N))
4989            and then
4990              Is_Safe_Index (First (Expressions (N)))
4991          then
4992             return True;
4993
4994          elsif Nkind (N) = N_Unchecked_Type_Conversion then
4995             return Safe_Left_Hand_Side (Expression (N));
4996
4997          else
4998             return False;
4999          end if;
5000       end Safe_Left_Hand_Side;
5001
5002       --  Local variables
5003
5004       Tmp : Entity_Id;
5005       --  Holds the temporary aggregate value
5006
5007       Tmp_Decl : Node_Id;
5008       --  Holds the declaration of Tmp
5009
5010       Aggr_Code   : List_Id;
5011       Parent_Node : Node_Id;
5012       Parent_Kind : Node_Kind;
5013
5014    --  Start of processing for Expand_Array_Aggregate
5015
5016    begin
5017       --  Do not touch the special aggregates of attributes used for Asm calls
5018
5019       if Is_RTE (Ctyp, RE_Asm_Input_Operand)
5020         or else Is_RTE (Ctyp, RE_Asm_Output_Operand)
5021       then
5022          return;
5023       end if;
5024
5025       --  If the semantic analyzer has determined that aggregate N will raise
5026       --  Constraint_Error at run time, then the aggregate node has been
5027       --  replaced with an N_Raise_Constraint_Error node and we should
5028       --  never get here.
5029
5030       pragma Assert (not Raises_Constraint_Error (N));
5031
5032       --  STEP 1a
5033
5034       --  Check that the index range defined by aggregate bounds is
5035       --  compatible with corresponding index subtype.
5036
5037       Index_Compatibility_Check : declare
5038          Aggr_Index_Range : Node_Id := First_Index (Typ);
5039          --  The current aggregate index range
5040
5041          Index_Constraint : Node_Id := First_Index (Etype (Typ));
5042          --  The corresponding index constraint against which we have to
5043          --  check the above aggregate index range.
5044
5045       begin
5046          Compute_Others_Present (N, 1);
5047
5048          for J in 1 .. Aggr_Dimension loop
5049             --  There is no need to emit a check if an others choice is
5050             --  present for this array aggregate dimension since in this
5051             --  case one of N's sub-aggregates has taken its bounds from the
5052             --  context and these bounds must have been checked already. In
5053             --  addition all sub-aggregates corresponding to the same
5054             --  dimension must all have the same bounds (checked in (c) below).
5055
5056             if not Range_Checks_Suppressed (Etype (Index_Constraint))
5057               and then not Others_Present (J)
5058             then
5059                --  We don't use Checks.Apply_Range_Check here because it emits
5060                --  a spurious check. Namely it checks that the range defined by
5061                --  the aggregate bounds is non empty. But we know this already
5062                --  if we get here.
5063
5064                Check_Bounds (Aggr_Index_Range, Index_Constraint);
5065             end if;
5066
5067             --  Save the low and high bounds of the aggregate index as well as
5068             --  the index type for later use in checks (b) and (c) below.
5069
5070             Aggr_Low  (J) := Low_Bound (Aggr_Index_Range);
5071             Aggr_High (J) := High_Bound (Aggr_Index_Range);
5072
5073             Aggr_Index_Typ (J) := Etype (Index_Constraint);
5074
5075             Next_Index (Aggr_Index_Range);
5076             Next_Index (Index_Constraint);
5077          end loop;
5078       end Index_Compatibility_Check;
5079
5080       --  STEP 1b
5081
5082       --  If an others choice is present check that no aggregate index is
5083       --  outside the bounds of the index constraint.
5084
5085       Others_Check (N, 1);
5086
5087       --  STEP 1c
5088
5089       --  For multidimensional arrays make sure that all subaggregates
5090       --  corresponding to the same dimension have the same bounds.
5091
5092       if Aggr_Dimension > 1 then
5093          Check_Same_Aggr_Bounds (N, 1);
5094       end if;
5095
5096       --  STEP 2
5097
5098       --  Here we test for is packed array aggregate that we can handle at
5099       --  compile time. If so, return with transformation done. Note that we do
5100       --  this even if the aggregate is nested, because once we have done this
5101       --  processing, there is no more nested aggregate!
5102
5103       if Packed_Array_Aggregate_Handled (N) then
5104          return;
5105       end if;
5106
5107       --  At this point we try to convert to positional form
5108
5109       if Ekind (Current_Scope) = E_Package
5110         and then Static_Elaboration_Desired (Current_Scope)
5111       then
5112          Convert_To_Positional (N, Max_Others_Replicate => 100);
5113
5114       else
5115          Convert_To_Positional (N);
5116       end if;
5117
5118       --  if the result is no longer an aggregate (e.g. it may be a string
5119       --  literal, or a temporary which has the needed value), then we are
5120       --  done, since there is no longer a nested aggregate.
5121
5122       if Nkind (N) /= N_Aggregate then
5123          return;
5124
5125       --  We are also done if the result is an analyzed aggregate
5126       --  This case could use more comments ???
5127
5128       elsif Analyzed (N)
5129         and then N /= Original_Node (N)
5130       then
5131          return;
5132       end if;
5133
5134       --  If all aggregate components are compile-time known and the aggregate
5135       --  has been flattened, nothing left to do. The same occurs if the
5136       --  aggregate is used to initialize the components of an statically
5137       --  allocated dispatch table.
5138
5139       if Compile_Time_Known_Aggregate (N)
5140         or else Is_Static_Dispatch_Table_Aggregate (N)
5141       then
5142          Set_Expansion_Delayed (N, False);
5143          return;
5144       end if;
5145
5146       --  Now see if back end processing is possible
5147
5148       if Backend_Processing_Possible (N) then
5149
5150          --  If the aggregate is static but the constraints are not, build
5151          --  a static subtype for the aggregate, so that Gigi can place it
5152          --  in static memory. Perform an unchecked_conversion to the non-
5153          --  static type imposed by the context.
5154
5155          declare
5156             Itype      : constant Entity_Id := Etype (N);
5157             Index      : Node_Id;
5158             Needs_Type : Boolean := False;
5159
5160          begin
5161             Index := First_Index (Itype);
5162             while Present (Index) loop
5163                if not Is_Static_Subtype (Etype (Index)) then
5164                   Needs_Type := True;
5165                   exit;
5166                else
5167                   Next_Index (Index);
5168                end if;
5169             end loop;
5170
5171             if Needs_Type then
5172                Build_Constrained_Type (Positional => True);
5173                Rewrite (N, Unchecked_Convert_To (Itype, N));
5174                Analyze (N);
5175             end if;
5176          end;
5177
5178          return;
5179       end if;
5180
5181       --  STEP 3
5182
5183       --  Delay expansion for nested aggregates: it will be taken care of
5184       --  when the parent aggregate is expanded.
5185
5186       Parent_Node := Parent (N);
5187       Parent_Kind := Nkind (Parent_Node);
5188
5189       if Parent_Kind = N_Qualified_Expression then
5190          Parent_Node := Parent (Parent_Node);
5191          Parent_Kind := Nkind (Parent_Node);
5192       end if;
5193
5194       if Parent_Kind = N_Aggregate
5195         or else Parent_Kind = N_Extension_Aggregate
5196         or else Parent_Kind = N_Component_Association
5197         or else (Parent_Kind = N_Object_Declaration
5198                   and then Needs_Finalization (Typ))
5199         or else (Parent_Kind = N_Assignment_Statement
5200                   and then Inside_Init_Proc)
5201       then
5202          if Static_Array_Aggregate (N)
5203            or else Compile_Time_Known_Aggregate (N)
5204          then
5205             Set_Expansion_Delayed (N, False);
5206             return;
5207          else
5208             Set_Expansion_Delayed (N);
5209             return;
5210          end if;
5211       end if;
5212
5213       --  STEP 4
5214
5215       --  Look if in place aggregate expansion is possible
5216
5217       --  For object declarations we build the aggregate in place, unless
5218       --  the array is bit-packed or the component is controlled.
5219
5220       --  For assignments we do the assignment in place if all the component
5221       --  associations have compile-time known values. For other cases we
5222       --  create a temporary. The analysis for safety of on-line assignment
5223       --  is delicate, i.e. we don't know how to do it fully yet ???
5224
5225       --  For allocators we assign to the designated object in place if the
5226       --  aggregate meets the same conditions as other in-place assignments.
5227       --  In this case the aggregate may not come from source but was created
5228       --  for default initialization, e.g. with Initialize_Scalars.
5229
5230       if Requires_Transient_Scope (Typ) then
5231          Establish_Transient_Scope
5232            (N, Sec_Stack => Has_Controlled_Component (Typ));
5233       end if;
5234
5235       if Has_Default_Init_Comps (N) then
5236          Maybe_In_Place_OK := False;
5237
5238       elsif Is_Bit_Packed_Array (Typ)
5239         or else Has_Controlled_Component (Typ)
5240       then
5241          Maybe_In_Place_OK := False;
5242
5243       else
5244          Maybe_In_Place_OK :=
5245           (Nkind (Parent (N)) = N_Assignment_Statement
5246             and then Comes_From_Source (N)
5247             and then In_Place_Assign_OK)
5248
5249           or else
5250             (Nkind (Parent (Parent (N))) = N_Allocator
5251               and then In_Place_Assign_OK);
5252       end if;
5253
5254       --  If this is an array of tasks, it will be expanded into build-in-place
5255       --  assignments. Build an activation chain for the tasks now.
5256
5257       if Has_Task (Etype (N)) then
5258          Build_Activation_Chain_Entity (N);
5259       end if;
5260
5261       --  Should document these individual tests ???
5262
5263       if not Has_Default_Init_Comps (N)
5264          and then Comes_From_Source (Parent (N))
5265          and then Nkind (Parent (N)) = N_Object_Declaration
5266          and then not
5267            Must_Slide (Etype (Defining_Identifier (Parent (N))), Typ)
5268          and then N = Expression (Parent (N))
5269          and then not Is_Bit_Packed_Array (Typ)
5270          and then not Has_Controlled_Component (Typ)
5271
5272       --  If the aggregate is the expression in an object declaration, it
5273       --  cannot be expanded in place. Lookahead in the current declarative
5274       --  part to find an address clause for the object being declared. If
5275       --  one is present, we cannot build in place. Unclear comment???
5276
5277          and then not Has_Following_Address_Clause (Parent (N))
5278       then
5279          Tmp := Defining_Identifier (Parent (N));
5280          Set_No_Initialization (Parent (N));
5281          Set_Expression (Parent (N), Empty);
5282
5283          --  Set the type of the entity, for use in the analysis of the
5284          --  subsequent indexed assignments. If the nominal type is not
5285          --  constrained, build a subtype from the known bounds of the
5286          --  aggregate. If the declaration has a subtype mark, use it,
5287          --  otherwise use the itype of the aggregate.
5288
5289          if not Is_Constrained (Typ) then
5290             Build_Constrained_Type (Positional => False);
5291          elsif Is_Entity_Name (Object_Definition (Parent (N)))
5292            and then Is_Constrained (Entity (Object_Definition (Parent (N))))
5293          then
5294             Set_Etype (Tmp, Entity (Object_Definition (Parent (N))));
5295          else
5296             Set_Size_Known_At_Compile_Time (Typ, False);
5297             Set_Etype (Tmp, Typ);
5298          end if;
5299
5300       elsif Maybe_In_Place_OK
5301         and then Nkind (Parent (N)) = N_Qualified_Expression
5302         and then Nkind (Parent (Parent (N))) = N_Allocator
5303       then
5304          Set_Expansion_Delayed (N);
5305          return;
5306
5307       --  In the remaining cases the aggregate is the RHS of an assignment
5308
5309       elsif Maybe_In_Place_OK
5310         and then Safe_Left_Hand_Side (Name (Parent (N)))
5311       then
5312          Tmp := Name (Parent (N));
5313
5314          if Etype (Tmp) /= Etype (N) then
5315             Apply_Length_Check (N, Etype (Tmp));
5316
5317             if Nkind (N) = N_Raise_Constraint_Error then
5318
5319                --  Static error, nothing further to expand
5320
5321                return;
5322             end if;
5323          end if;
5324
5325       elsif Maybe_In_Place_OK
5326         and then Nkind (Name (Parent (N))) = N_Slice
5327         and then Safe_Slice_Assignment (N)
5328       then
5329          --  Safe_Slice_Assignment rewrites assignment as a loop
5330
5331          return;
5332
5333       --  Step 5
5334
5335       --  In place aggregate expansion is not possible
5336
5337       else
5338          Maybe_In_Place_OK := False;
5339          Tmp := Make_Temporary (Loc, 'A', N);
5340          Tmp_Decl :=
5341            Make_Object_Declaration
5342              (Loc,
5343               Defining_Identifier => Tmp,
5344               Object_Definition   => New_Occurrence_Of (Typ, Loc));
5345          Set_No_Initialization (Tmp_Decl, True);
5346
5347          --  If we are within a loop, the temporary will be pushed on the
5348          --  stack at each iteration. If the aggregate is the expression for an
5349          --  allocator, it will be immediately copied to the heap and can
5350          --  be reclaimed at once. We create a transient scope around the
5351          --  aggregate for this purpose.
5352
5353          if Ekind (Current_Scope) = E_Loop
5354            and then Nkind (Parent (Parent (N))) = N_Allocator
5355          then
5356             Establish_Transient_Scope (N, False);
5357          end if;
5358
5359          Insert_Action (N, Tmp_Decl);
5360       end if;
5361
5362       --  Construct and insert the aggregate code. We can safely suppress index
5363       --  checks because this code is guaranteed not to raise CE on index
5364       --  checks. However we should *not* suppress all checks.
5365
5366       declare
5367          Target : Node_Id;
5368
5369       begin
5370          if Nkind (Tmp) = N_Defining_Identifier then
5371             Target := New_Reference_To (Tmp, Loc);
5372
5373          else
5374
5375             if Has_Default_Init_Comps (N) then
5376
5377                --  Ada 2005 (AI-287): This case has not been analyzed???
5378
5379                raise Program_Error;
5380             end if;
5381
5382             --  Name in assignment is explicit dereference
5383
5384             Target := New_Copy (Tmp);
5385          end if;
5386
5387          Aggr_Code :=
5388            Build_Array_Aggr_Code (N,
5389              Ctype       => Ctyp,
5390              Index       => First_Index (Typ),
5391              Into        => Target,
5392              Scalar_Comp => Is_Scalar_Type (Ctyp));
5393       end;
5394
5395       if Comes_From_Source (Tmp) then
5396          Insert_Actions_After (Parent (N), Aggr_Code);
5397
5398       else
5399          Insert_Actions (N, Aggr_Code);
5400       end if;
5401
5402       --  If the aggregate has been assigned in place, remove the original
5403       --  assignment.
5404
5405       if Nkind (Parent (N)) = N_Assignment_Statement
5406         and then Maybe_In_Place_OK
5407       then
5408          Rewrite (Parent (N), Make_Null_Statement (Loc));
5409
5410       elsif Nkind (Parent (N)) /= N_Object_Declaration
5411         or else Tmp /= Defining_Identifier (Parent (N))
5412       then
5413          Rewrite (N, New_Occurrence_Of (Tmp, Loc));
5414          Analyze_And_Resolve (N, Typ);
5415       end if;
5416    end Expand_Array_Aggregate;
5417
5418    ------------------------
5419    -- Expand_N_Aggregate --
5420    ------------------------
5421
5422    procedure Expand_N_Aggregate (N : Node_Id) is
5423    begin
5424       if Is_Record_Type (Etype (N)) then
5425          Expand_Record_Aggregate (N);
5426       else
5427          Expand_Array_Aggregate (N);
5428       end if;
5429    exception
5430       when RE_Not_Available =>
5431          return;
5432    end Expand_N_Aggregate;
5433
5434    ----------------------------------
5435    -- Expand_N_Extension_Aggregate --
5436    ----------------------------------
5437
5438    --  If the ancestor part is an expression, add a component association for
5439    --  the parent field. If the type of the ancestor part is not the direct
5440    --  parent of the expected type,  build recursively the needed ancestors.
5441    --  If the ancestor part is a subtype_mark, replace aggregate with a decla-
5442    --  ration for a temporary of the expected type, followed by individual
5443    --  assignments to the given components.
5444
5445    procedure Expand_N_Extension_Aggregate (N : Node_Id) is
5446       Loc : constant Source_Ptr := Sloc  (N);
5447       A   : constant Node_Id    := Ancestor_Part (N);
5448       Typ : constant Entity_Id  := Etype (N);
5449
5450    begin
5451       --  If the ancestor is a subtype mark, an init proc must be called
5452       --  on the resulting object which thus has to be materialized in
5453       --  the front-end
5454
5455       if Is_Entity_Name (A) and then Is_Type (Entity (A)) then
5456          Convert_To_Assignments (N, Typ);
5457
5458       --  The extension aggregate is transformed into a record aggregate
5459       --  of the following form (c1 and c2 are inherited components)
5460
5461       --   (Exp with c3 => a, c4 => b)
5462       --      ==> (c1 => Exp.c1, c2 => Exp.c2, c3 => a, c4 => b)
5463
5464       else
5465          Set_Etype (N, Typ);
5466
5467          if Tagged_Type_Expansion then
5468             Expand_Record_Aggregate (N,
5469               Orig_Tag    =>
5470                 New_Occurrence_Of
5471                   (Node (First_Elmt (Access_Disp_Table (Typ))), Loc),
5472               Parent_Expr => A);
5473
5474          --  No tag is needed in the case of a VM
5475
5476          else
5477             Expand_Record_Aggregate (N, Parent_Expr => A);
5478          end if;
5479       end if;
5480
5481    exception
5482       when RE_Not_Available =>
5483          return;
5484    end Expand_N_Extension_Aggregate;
5485
5486    -----------------------------
5487    -- Expand_Record_Aggregate --
5488    -----------------------------
5489
5490    procedure Expand_Record_Aggregate
5491      (N           : Node_Id;
5492       Orig_Tag    : Node_Id := Empty;
5493       Parent_Expr : Node_Id := Empty)
5494    is
5495       Loc      : constant Source_Ptr := Sloc  (N);
5496       Comps    : constant List_Id    := Component_Associations (N);
5497       Typ      : constant Entity_Id  := Etype (N);
5498       Base_Typ : constant Entity_Id  := Base_Type (Typ);
5499
5500       Static_Components : Boolean := True;
5501       --  Flag to indicate whether all components are compile-time known,
5502       --  and the aggregate can be constructed statically and handled by
5503       --  the back-end.
5504
5505       function Component_Not_OK_For_Backend return Boolean;
5506       --  Check for presence of component which makes it impossible for the
5507       --  backend to process the aggregate, thus requiring the use of a series
5508       --  of assignment statements. Cases checked for are a nested aggregate
5509       --  needing Late_Expansion, the presence of a tagged component which may
5510       --  need tag adjustment, and a bit unaligned component reference.
5511       --
5512       --  We also force expansion into assignments if a component is of a
5513       --  mutable type (including a private type with discriminants) because
5514       --  in that case the size of the component to be copied may be smaller
5515       --  than the side of the target, and there is no simple way for gigi
5516       --  to compute the size of the object to be copied.
5517       --
5518       --  NOTE: This is part of the ongoing work to define precisely the
5519       --  interface between front-end and back-end handling of aggregates.
5520       --  In general it is desirable to pass aggregates as they are to gigi,
5521       --  in order to minimize elaboration code. This is one case where the
5522       --  semantics of Ada complicate the analysis and lead to anomalies in
5523       --  the gcc back-end if the aggregate is not expanded into assignments.
5524
5525       ----------------------------------
5526       -- Component_Not_OK_For_Backend --
5527       ----------------------------------
5528
5529       function Component_Not_OK_For_Backend return Boolean is
5530          C      : Node_Id;
5531          Expr_Q : Node_Id;
5532
5533       begin
5534          if No (Comps) then
5535             return False;
5536          end if;
5537
5538          C := First (Comps);
5539          while Present (C) loop
5540
5541             --  If the component has box initialization, expansion is needed
5542             --  and component is not ready for backend.
5543
5544             if Box_Present (C) then
5545                return True;
5546             end if;
5547
5548             if Nkind (Expression (C)) = N_Qualified_Expression then
5549                Expr_Q := Expression (Expression (C));
5550             else
5551                Expr_Q := Expression (C);
5552             end if;
5553
5554             --  Return true if the aggregate has any associations for tagged
5555             --  components that may require tag adjustment.
5556
5557             --  These are cases where the source expression may have a tag that
5558             --  could differ from the component tag (e.g., can occur for type
5559             --  conversions and formal parameters). (Tag adjustment not needed
5560             --  if VM_Target because object tags are implicit in the machine.)
5561
5562             if Is_Tagged_Type (Etype (Expr_Q))
5563               and then (Nkind (Expr_Q) = N_Type_Conversion
5564                          or else (Is_Entity_Name (Expr_Q)
5565                                     and then
5566                                       Ekind (Entity (Expr_Q)) in Formal_Kind))
5567               and then Tagged_Type_Expansion
5568             then
5569                Static_Components := False;
5570                return True;
5571
5572             elsif Is_Delayed_Aggregate (Expr_Q) then
5573                Static_Components := False;
5574                return True;
5575
5576             elsif Possible_Bit_Aligned_Component (Expr_Q) then
5577                Static_Components := False;
5578                return True;
5579             end if;
5580
5581             if Is_Scalar_Type (Etype (Expr_Q)) then
5582                if not Compile_Time_Known_Value (Expr_Q) then
5583                   Static_Components := False;
5584                end if;
5585
5586             elsif Nkind (Expr_Q) /= N_Aggregate
5587               or else not Compile_Time_Known_Aggregate (Expr_Q)
5588             then
5589                Static_Components := False;
5590
5591                if Is_Private_Type (Etype (Expr_Q))
5592                  and then Has_Discriminants (Etype (Expr_Q))
5593                then
5594                   return True;
5595                end if;
5596             end if;
5597
5598             Next (C);
5599          end loop;
5600
5601          return False;
5602       end Component_Not_OK_For_Backend;
5603
5604       --  Remaining Expand_Record_Aggregate variables
5605
5606       Tag_Value : Node_Id;
5607       Comp      : Entity_Id;
5608       New_Comp  : Node_Id;
5609
5610    --  Start of processing for Expand_Record_Aggregate
5611
5612    begin
5613       --  If the aggregate is to be assigned to an atomic variable, we
5614       --  have to prevent a piecemeal assignment even if the aggregate
5615       --  is to be expanded. We create a temporary for the aggregate, and
5616       --  assign the temporary instead, so that the back end can generate
5617       --  an atomic move for it.
5618
5619       if Is_Atomic (Typ)
5620         and then Comes_From_Source (Parent (N))
5621         and then Is_Atomic_Aggregate (N, Typ)
5622       then
5623          return;
5624
5625       --  No special management required for aggregates used to initialize
5626       --  statically allocated dispatch tables
5627
5628       elsif Is_Static_Dispatch_Table_Aggregate (N) then
5629          return;
5630       end if;
5631
5632       --  Ada 2005 (AI-318-2): We need to convert to assignments if components
5633       --  are build-in-place function calls. The assignments will each turn
5634       --  into a build-in-place function call.  If components are all static,
5635       --  we can pass the aggregate to the backend regardless of limitedness.
5636
5637       --  Extension aggregates, aggregates in extended return statements, and
5638       --  aggregates for C++ imported types must be expanded.
5639
5640       if Ada_Version >= Ada_2005 and then Is_Immutably_Limited_Type (Typ) then
5641          if not Nkind_In (Parent (N), N_Object_Declaration,
5642                                       N_Component_Association)
5643          then
5644             Convert_To_Assignments (N, Typ);
5645
5646          elsif Nkind (N) = N_Extension_Aggregate
5647            or else Convention (Typ) = Convention_CPP
5648          then
5649             Convert_To_Assignments (N, Typ);
5650
5651          elsif not Size_Known_At_Compile_Time (Typ)
5652            or else Component_Not_OK_For_Backend
5653            or else not Static_Components
5654          then
5655             Convert_To_Assignments (N, Typ);
5656
5657          else
5658             Set_Compile_Time_Known_Aggregate (N);
5659             Set_Expansion_Delayed (N, False);
5660          end if;
5661
5662       --  Gigi doesn't properly handle temporaries of variable size so we
5663       --  generate it in the front-end
5664
5665       elsif not Size_Known_At_Compile_Time (Typ)
5666         and then Tagged_Type_Expansion
5667       then
5668          Convert_To_Assignments (N, Typ);
5669
5670       --  Temporaries for controlled aggregates need to be attached to a final
5671       --  chain in order to be properly finalized, so it has to be created in
5672       --  the front-end
5673
5674       elsif Is_Controlled (Typ)
5675         or else Has_Controlled_Component (Base_Type (Typ))
5676       then
5677          Convert_To_Assignments (N, Typ);
5678
5679          --  Ada 2005 (AI-287): In case of default initialized components we
5680          --  convert the aggregate into assignments.
5681
5682       elsif Has_Default_Init_Comps (N) then
5683          Convert_To_Assignments (N, Typ);
5684
5685       --  Check components
5686
5687       elsif Component_Not_OK_For_Backend then
5688          Convert_To_Assignments (N, Typ);
5689
5690       --  If an ancestor is private, some components are not inherited and
5691       --  we cannot expand into a record aggregate
5692
5693       elsif Has_Private_Ancestor (Typ) then
5694          Convert_To_Assignments (N, Typ);
5695
5696       --  ??? The following was done to compile fxacc00.ads in the ACVCs. Gigi
5697       --  is not able to handle the aggregate for Late_Request.
5698
5699       elsif Is_Tagged_Type (Typ) and then Has_Discriminants (Typ) then
5700          Convert_To_Assignments (N, Typ);
5701
5702       --  If the tagged types covers interface types we need to initialize all
5703       --  hidden components containing pointers to secondary dispatch tables.
5704
5705       elsif Is_Tagged_Type (Typ) and then Has_Interfaces (Typ) then
5706          Convert_To_Assignments (N, Typ);
5707
5708       --  If some components are mutable, the size of the aggregate component
5709       --  may be distinct from the default size of the type component, so
5710       --  we need to expand to insure that the back-end copies the proper
5711       --  size of the data. However, if the aggregate is the initial value of
5712       --  a constant, the target is immutable and may be built statically.
5713
5714       elsif Has_Mutable_Components (Typ)
5715         and then
5716           (Nkind (Parent (N)) /= N_Object_Declaration
5717             or else not Constant_Present (Parent (N)))
5718       then
5719          Convert_To_Assignments (N, Typ);
5720
5721       --  If the type involved has any non-bit aligned components, then we are
5722       --  not sure that the back end can handle this case correctly.
5723
5724       elsif Type_May_Have_Bit_Aligned_Components (Typ) then
5725          Convert_To_Assignments (N, Typ);
5726
5727       --  In all other cases, build a proper aggregate handlable by gigi
5728
5729       else
5730          if Nkind (N) = N_Aggregate then
5731
5732             --  If the aggregate is static and can be handled by the back-end,
5733             --  nothing left to do.
5734
5735             if Static_Components then
5736                Set_Compile_Time_Known_Aggregate (N);
5737                Set_Expansion_Delayed (N, False);
5738             end if;
5739          end if;
5740
5741          --  If no discriminants, nothing special to do
5742
5743          if not Has_Discriminants (Typ) then
5744             null;
5745
5746          --  Case of discriminants present
5747
5748          elsif Is_Derived_Type (Typ) then
5749
5750             --  For untagged types,  non-stored discriminants are replaced
5751             --  with stored discriminants, which are the ones that gigi uses
5752             --  to describe the type and its components.
5753
5754             Generate_Aggregate_For_Derived_Type : declare
5755                Constraints  : constant List_Id := New_List;
5756                First_Comp   : Node_Id;
5757                Discriminant : Entity_Id;
5758                Decl         : Node_Id;
5759                Num_Disc     : Int := 0;
5760                Num_Gird     : Int := 0;
5761
5762                procedure Prepend_Stored_Values (T : Entity_Id);
5763                --  Scan the list of stored discriminants of the type, and add
5764                --  their values to the aggregate being built.
5765
5766                ---------------------------
5767                -- Prepend_Stored_Values --
5768                ---------------------------
5769
5770                procedure Prepend_Stored_Values (T : Entity_Id) is
5771                begin
5772                   Discriminant := First_Stored_Discriminant (T);
5773                   while Present (Discriminant) loop
5774                      New_Comp :=
5775                        Make_Component_Association (Loc,
5776                          Choices    =>
5777                            New_List (New_Occurrence_Of (Discriminant, Loc)),
5778
5779                          Expression =>
5780                            New_Copy_Tree (
5781                              Get_Discriminant_Value (
5782                                  Discriminant,
5783                                  Typ,
5784                                  Discriminant_Constraint (Typ))));
5785
5786                      if No (First_Comp) then
5787                         Prepend_To (Component_Associations (N), New_Comp);
5788                      else
5789                         Insert_After (First_Comp, New_Comp);
5790                      end if;
5791
5792                      First_Comp := New_Comp;
5793                      Next_Stored_Discriminant (Discriminant);
5794                   end loop;
5795                end Prepend_Stored_Values;
5796
5797             --  Start of processing for Generate_Aggregate_For_Derived_Type
5798
5799             begin
5800                --  Remove the associations for the discriminant of derived type
5801
5802                First_Comp := First (Component_Associations (N));
5803                while Present (First_Comp) loop
5804                   Comp := First_Comp;
5805                   Next (First_Comp);
5806
5807                   if Ekind (Entity
5808                              (First (Choices (Comp)))) = E_Discriminant
5809                   then
5810                      Remove (Comp);
5811                      Num_Disc := Num_Disc + 1;
5812                   end if;
5813                end loop;
5814
5815                --  Insert stored discriminant associations in the correct
5816                --  order. If there are more stored discriminants than new
5817                --  discriminants, there is at least one new discriminant that
5818                --  constrains more than one of the stored discriminants. In
5819                --  this case we need to construct a proper subtype of the
5820                --  parent type, in order to supply values to all the
5821                --  components. Otherwise there is one-one correspondence
5822                --  between the constraints and the stored discriminants.
5823
5824                First_Comp := Empty;
5825
5826                Discriminant := First_Stored_Discriminant (Base_Type (Typ));
5827                while Present (Discriminant) loop
5828                   Num_Gird := Num_Gird + 1;
5829                   Next_Stored_Discriminant (Discriminant);
5830                end loop;
5831
5832                --  Case of more stored discriminants than new discriminants
5833
5834                if Num_Gird > Num_Disc then
5835
5836                   --  Create a proper subtype of the parent type, which is the
5837                   --  proper implementation type for the aggregate, and convert
5838                   --  it to the intended target type.
5839
5840                   Discriminant := First_Stored_Discriminant (Base_Type (Typ));
5841                   while Present (Discriminant) loop
5842                      New_Comp :=
5843                        New_Copy_Tree (
5844                          Get_Discriminant_Value (
5845                              Discriminant,
5846                              Typ,
5847                              Discriminant_Constraint (Typ)));
5848                      Append (New_Comp, Constraints);
5849                      Next_Stored_Discriminant (Discriminant);
5850                   end loop;
5851
5852                   Decl :=
5853                     Make_Subtype_Declaration (Loc,
5854                       Defining_Identifier => Make_Temporary (Loc, 'T'),
5855                       Subtype_Indication =>
5856                         Make_Subtype_Indication (Loc,
5857                           Subtype_Mark =>
5858                             New_Occurrence_Of (Etype (Base_Type (Typ)), Loc),
5859                           Constraint =>
5860                             Make_Index_Or_Discriminant_Constraint
5861                               (Loc, Constraints)));
5862
5863                   Insert_Action (N, Decl);
5864                   Prepend_Stored_Values (Base_Type (Typ));
5865
5866                   Set_Etype (N, Defining_Identifier (Decl));
5867                   Set_Analyzed (N);
5868
5869                   Rewrite (N, Unchecked_Convert_To (Typ, N));
5870                   Analyze (N);
5871
5872                --  Case where we do not have fewer new discriminants than
5873                --  stored discriminants, so in this case we can simply use the
5874                --  stored discriminants of the subtype.
5875
5876                else
5877                   Prepend_Stored_Values (Typ);
5878                end if;
5879             end Generate_Aggregate_For_Derived_Type;
5880          end if;
5881
5882          if Is_Tagged_Type (Typ) then
5883
5884             --  The tagged case, _parent and _tag component must be created
5885
5886             --  Reset null_present unconditionally. tagged records always have
5887             --  at least one field (the tag or the parent)
5888
5889             Set_Null_Record_Present (N, False);
5890
5891             --  When the current aggregate comes from the expansion of an
5892             --  extension aggregate, the parent expr is replaced by an
5893             --  aggregate formed by selected components of this expr
5894
5895             if Present (Parent_Expr)
5896               and then Is_Empty_List (Comps)
5897             then
5898                Comp := First_Component_Or_Discriminant (Typ);
5899                while Present (Comp) loop
5900
5901                   --  Skip all expander-generated components
5902
5903                   if
5904                     not Comes_From_Source (Original_Record_Component (Comp))
5905                   then
5906                      null;
5907
5908                   else
5909                      New_Comp :=
5910                        Make_Selected_Component (Loc,
5911                          Prefix =>
5912                            Unchecked_Convert_To (Typ,
5913                              Duplicate_Subexpr (Parent_Expr, True)),
5914
5915                          Selector_Name => New_Occurrence_Of (Comp, Loc));
5916
5917                      Append_To (Comps,
5918                        Make_Component_Association (Loc,
5919                          Choices    =>
5920                            New_List (New_Occurrence_Of (Comp, Loc)),
5921                          Expression =>
5922                            New_Comp));
5923
5924                      Analyze_And_Resolve (New_Comp, Etype (Comp));
5925                   end if;
5926
5927                   Next_Component_Or_Discriminant (Comp);
5928                end loop;
5929             end if;
5930
5931             --  Compute the value for the Tag now, if the type is a root it
5932             --  will be included in the aggregate right away, otherwise it will
5933             --  be propagated to the parent aggregate
5934
5935             if Present (Orig_Tag) then
5936                Tag_Value := Orig_Tag;
5937             elsif not Tagged_Type_Expansion then
5938                Tag_Value := Empty;
5939             else
5940                Tag_Value :=
5941                  New_Occurrence_Of
5942                    (Node (First_Elmt (Access_Disp_Table (Typ))), Loc);
5943             end if;
5944
5945             --  For a derived type, an aggregate for the parent is formed with
5946             --  all the inherited components.
5947
5948             if Is_Derived_Type (Typ) then
5949
5950                declare
5951                   First_Comp   : Node_Id;
5952                   Parent_Comps : List_Id;
5953                   Parent_Aggr  : Node_Id;
5954                   Parent_Name  : Node_Id;
5955
5956                begin
5957                   --  Remove the inherited component association from the
5958                   --  aggregate and store them in the parent aggregate
5959
5960                   First_Comp := First (Component_Associations (N));
5961                   Parent_Comps := New_List;
5962                   while Present (First_Comp)
5963                     and then Scope (Original_Record_Component (
5964                             Entity (First (Choices (First_Comp))))) /= Base_Typ
5965                   loop
5966                      Comp := First_Comp;
5967                      Next (First_Comp);
5968                      Remove (Comp);
5969                      Append (Comp, Parent_Comps);
5970                   end loop;
5971
5972                   Parent_Aggr := Make_Aggregate (Loc,
5973                     Component_Associations => Parent_Comps);
5974                   Set_Etype (Parent_Aggr, Etype (Base_Type (Typ)));
5975
5976                   --  Find the _parent component
5977
5978                   Comp := First_Component (Typ);
5979                   while Chars (Comp) /= Name_uParent loop
5980                      Comp := Next_Component (Comp);
5981                   end loop;
5982
5983                   Parent_Name := New_Occurrence_Of (Comp, Loc);
5984
5985                   --  Insert the parent aggregate
5986
5987                   Prepend_To (Component_Associations (N),
5988                     Make_Component_Association (Loc,
5989                       Choices    => New_List (Parent_Name),
5990                       Expression => Parent_Aggr));
5991
5992                   --  Expand recursively the parent propagating the right Tag
5993
5994                   Expand_Record_Aggregate (
5995                     Parent_Aggr, Tag_Value, Parent_Expr);
5996                end;
5997
5998             --  For a root type, the tag component is added (unless compiling
5999             --  for the VMs, where tags are implicit).
6000
6001             elsif Tagged_Type_Expansion then
6002                declare
6003                   Tag_Name  : constant Node_Id :=
6004                                 New_Occurrence_Of
6005                                   (First_Tag_Component (Typ), Loc);
6006                   Typ_Tag   : constant Entity_Id := RTE (RE_Tag);
6007                   Conv_Node : constant Node_Id :=
6008                                 Unchecked_Convert_To (Typ_Tag, Tag_Value);
6009
6010                begin
6011                   Set_Etype (Conv_Node, Typ_Tag);
6012                   Prepend_To (Component_Associations (N),
6013                     Make_Component_Association (Loc,
6014                       Choices    => New_List (Tag_Name),
6015                       Expression => Conv_Node));
6016                end;
6017             end if;
6018          end if;
6019       end if;
6020
6021    end Expand_Record_Aggregate;
6022
6023    ----------------------------
6024    -- Has_Default_Init_Comps --
6025    ----------------------------
6026
6027    function Has_Default_Init_Comps (N : Node_Id) return Boolean is
6028       Comps : constant List_Id := Component_Associations (N);
6029       C     : Node_Id;
6030       Expr  : Node_Id;
6031    begin
6032       pragma Assert (Nkind_In (N, N_Aggregate, N_Extension_Aggregate));
6033
6034       if No (Comps) then
6035          return False;
6036       end if;
6037
6038       if Has_Self_Reference (N) then
6039          return True;
6040       end if;
6041
6042       --  Check if any direct component has default initialized components
6043
6044       C := First (Comps);
6045       while Present (C) loop
6046          if Box_Present (C) then
6047             return True;
6048          end if;
6049
6050          Next (C);
6051       end loop;
6052
6053       --  Recursive call in case of aggregate expression
6054
6055       C := First (Comps);
6056       while Present (C) loop
6057          Expr := Expression (C);
6058
6059          if Present (Expr)
6060            and then
6061              Nkind_In (Expr, N_Aggregate, N_Extension_Aggregate)
6062            and then Has_Default_Init_Comps (Expr)
6063          then
6064             return True;
6065          end if;
6066
6067          Next (C);
6068       end loop;
6069
6070       return False;
6071    end Has_Default_Init_Comps;
6072
6073    --------------------------
6074    -- Is_Delayed_Aggregate --
6075    --------------------------
6076
6077    function Is_Delayed_Aggregate (N : Node_Id) return Boolean is
6078       Node : Node_Id   := N;
6079       Kind : Node_Kind := Nkind (Node);
6080
6081    begin
6082       if Kind = N_Qualified_Expression then
6083          Node := Expression (Node);
6084          Kind := Nkind (Node);
6085       end if;
6086
6087       if Kind /= N_Aggregate and then Kind /= N_Extension_Aggregate then
6088          return False;
6089       else
6090          return Expansion_Delayed (Node);
6091       end if;
6092    end Is_Delayed_Aggregate;
6093
6094    ----------------------------------------
6095    -- Is_Static_Dispatch_Table_Aggregate --
6096    ----------------------------------------
6097
6098    function Is_Static_Dispatch_Table_Aggregate (N : Node_Id) return Boolean is
6099       Typ : constant Entity_Id := Base_Type (Etype (N));
6100
6101    begin
6102       return Static_Dispatch_Tables
6103         and then Tagged_Type_Expansion
6104         and then RTU_Loaded (Ada_Tags)
6105
6106          --  Avoid circularity when rebuilding the compiler
6107
6108         and then Cunit_Entity (Get_Source_Unit (N)) /= RTU_Entity (Ada_Tags)
6109         and then (Typ = RTE (RE_Dispatch_Table_Wrapper)
6110                     or else
6111                   Typ = RTE (RE_Address_Array)
6112                     or else
6113                   Typ = RTE (RE_Type_Specific_Data)
6114                     or else
6115                   Typ = RTE (RE_Tag_Table)
6116                     or else
6117                   (RTE_Available (RE_Interface_Data)
6118                      and then Typ = RTE (RE_Interface_Data))
6119                     or else
6120                   (RTE_Available (RE_Interfaces_Array)
6121                      and then Typ = RTE (RE_Interfaces_Array))
6122                     or else
6123                   (RTE_Available (RE_Interface_Data_Element)
6124                      and then Typ = RTE (RE_Interface_Data_Element)));
6125    end Is_Static_Dispatch_Table_Aggregate;
6126
6127    --------------------
6128    -- Late_Expansion --
6129    --------------------
6130
6131    function Late_Expansion
6132      (N      : Node_Id;
6133       Typ    : Entity_Id;
6134       Target : Node_Id;
6135       Flist  : Node_Id   := Empty;
6136       Obj    : Entity_Id := Empty) return List_Id
6137    is
6138    begin
6139       if Is_Record_Type (Etype (N)) then
6140          return Build_Record_Aggr_Code (N, Typ, Target, Flist, Obj);
6141
6142       else pragma Assert (Is_Array_Type (Etype (N)));
6143          return
6144            Build_Array_Aggr_Code
6145              (N           => N,
6146               Ctype       => Component_Type (Etype (N)),
6147               Index       => First_Index (Typ),
6148               Into        => Target,
6149               Scalar_Comp => Is_Scalar_Type (Component_Type (Typ)),
6150               Indexes     => No_List,
6151               Flist       => Flist);
6152       end if;
6153    end Late_Expansion;
6154
6155    ----------------------------------
6156    -- Make_OK_Assignment_Statement --
6157    ----------------------------------
6158
6159    function Make_OK_Assignment_Statement
6160      (Sloc       : Source_Ptr;
6161       Name       : Node_Id;
6162       Expression : Node_Id) return Node_Id
6163    is
6164    begin
6165       Set_Assignment_OK (Name);
6166
6167       return Make_Assignment_Statement (Sloc, Name, Expression);
6168    end Make_OK_Assignment_Statement;
6169
6170    -----------------------
6171    -- Number_Of_Choices --
6172    -----------------------
6173
6174    function Number_Of_Choices (N : Node_Id) return Nat is
6175       Assoc  : Node_Id;
6176       Choice : Node_Id;
6177
6178       Nb_Choices : Nat := 0;
6179
6180    begin
6181       if Present (Expressions (N)) then
6182          return 0;
6183       end if;
6184
6185       Assoc := First (Component_Associations (N));
6186       while Present (Assoc) loop
6187          Choice := First (Choices (Assoc));
6188          while Present (Choice) loop
6189             if Nkind (Choice) /= N_Others_Choice then
6190                Nb_Choices := Nb_Choices + 1;
6191             end if;
6192
6193             Next (Choice);
6194          end loop;
6195
6196          Next (Assoc);
6197       end loop;
6198
6199       return Nb_Choices;
6200    end Number_Of_Choices;
6201
6202    ------------------------------------
6203    -- Packed_Array_Aggregate_Handled --
6204    ------------------------------------
6205
6206    --  The current version of this procedure will handle at compile time
6207    --  any array aggregate that meets these conditions:
6208
6209    --    One dimensional, bit packed
6210    --    Underlying packed type is modular type
6211    --    Bounds are within 32-bit Int range
6212    --    All bounds and values are static
6213
6214    function Packed_Array_Aggregate_Handled (N : Node_Id) return Boolean is
6215       Loc  : constant Source_Ptr := Sloc (N);
6216       Typ  : constant Entity_Id  := Etype (N);
6217       Ctyp : constant Entity_Id  := Component_Type (Typ);
6218
6219       Not_Handled : exception;
6220       --  Exception raised if this aggregate cannot be handled
6221
6222    begin
6223       --  For now, handle only one dimensional bit packed arrays
6224
6225       if not Is_Bit_Packed_Array (Typ)
6226         or else Number_Dimensions (Typ) > 1
6227         or else not Is_Modular_Integer_Type (Packed_Array_Type (Typ))
6228       then
6229          return False;
6230       end if;
6231
6232       if not Is_Scalar_Type (Component_Type (Typ))
6233         and then Has_Non_Standard_Rep (Component_Type (Typ))
6234       then
6235          return False;
6236       end if;
6237
6238       declare
6239          Csiz  : constant Nat := UI_To_Int (Component_Size (Typ));
6240
6241          Lo : Node_Id;
6242          Hi : Node_Id;
6243          --  Bounds of index type
6244
6245          Lob : Uint;
6246          Hib : Uint;
6247          --  Values of bounds if compile time known
6248
6249          function Get_Component_Val (N : Node_Id) return Uint;
6250          --  Given a expression value N of the component type Ctyp, returns a
6251          --  value of Csiz (component size) bits representing this value. If
6252          --  the value is non-static or any other reason exists why the value
6253          --  cannot be returned, then Not_Handled is raised.
6254
6255          -----------------------
6256          -- Get_Component_Val --
6257          -----------------------
6258
6259          function Get_Component_Val (N : Node_Id) return Uint is
6260             Val  : Uint;
6261
6262          begin
6263             --  We have to analyze the expression here before doing any further
6264             --  processing here. The analysis of such expressions is deferred
6265             --  till expansion to prevent some problems of premature analysis.
6266
6267             Analyze_And_Resolve (N, Ctyp);
6268
6269             --  Must have a compile time value. String literals have to be
6270             --  converted into temporaries as well, because they cannot easily
6271             --  be converted into their bit representation.
6272
6273             if not Compile_Time_Known_Value (N)
6274               or else Nkind (N) = N_String_Literal
6275             then
6276                raise Not_Handled;
6277             end if;
6278
6279             Val := Expr_Rep_Value (N);
6280
6281             --  Adjust for bias, and strip proper number of bits
6282
6283             if Has_Biased_Representation (Ctyp) then
6284                Val := Val - Expr_Value (Type_Low_Bound (Ctyp));
6285             end if;
6286
6287             return Val mod Uint_2 ** Csiz;
6288          end Get_Component_Val;
6289
6290       --  Here we know we have a one dimensional bit packed array
6291
6292       begin
6293          Get_Index_Bounds (First_Index (Typ), Lo, Hi);
6294
6295          --  Cannot do anything if bounds are dynamic
6296
6297          if not Compile_Time_Known_Value (Lo)
6298               or else
6299             not Compile_Time_Known_Value (Hi)
6300          then
6301             return False;
6302          end if;
6303
6304          --  Or are silly out of range of int bounds
6305
6306          Lob := Expr_Value (Lo);
6307          Hib := Expr_Value (Hi);
6308
6309          if not UI_Is_In_Int_Range (Lob)
6310               or else
6311             not UI_Is_In_Int_Range (Hib)
6312          then
6313             return False;
6314          end if;
6315
6316          --  At this stage we have a suitable aggregate for handling at compile
6317          --  time (the only remaining checks are that the values of expressions
6318          --  in the aggregate are compile time known (check is performed by
6319          --  Get_Component_Val), and that any subtypes or ranges are statically
6320          --  known.
6321
6322          --  If the aggregate is not fully positional at this stage, then
6323          --  convert it to positional form. Either this will fail, in which
6324          --  case we can do nothing, or it will succeed, in which case we have
6325          --  succeeded in handling the aggregate, or it will stay an aggregate,
6326          --  in which case we have failed to handle this case.
6327
6328          if Present (Component_Associations (N)) then
6329             Convert_To_Positional
6330              (N, Max_Others_Replicate => 64, Handle_Bit_Packed => True);
6331             return Nkind (N) /= N_Aggregate;
6332          end if;
6333
6334          --  Otherwise we are all positional, so convert to proper value
6335
6336          declare
6337             Lov : constant Int := UI_To_Int (Lob);
6338             Hiv : constant Int := UI_To_Int (Hib);
6339
6340             Len : constant Nat := Int'Max (0, Hiv - Lov + 1);
6341             --  The length of the array (number of elements)
6342
6343             Aggregate_Val : Uint;
6344             --  Value of aggregate. The value is set in the low order bits of
6345             --  this value. For the little-endian case, the values are stored
6346             --  from low-order to high-order and for the big-endian case the
6347             --  values are stored from high-order to low-order. Note that gigi
6348             --  will take care of the conversions to left justify the value in
6349             --  the big endian case (because of left justified modular type
6350             --  processing), so we do not have to worry about that here.
6351
6352             Lit : Node_Id;
6353             --  Integer literal for resulting constructed value
6354
6355             Shift : Nat;
6356             --  Shift count from low order for next value
6357
6358             Incr : Int;
6359             --  Shift increment for loop
6360
6361             Expr : Node_Id;
6362             --  Next expression from positional parameters of aggregate
6363
6364          begin
6365             --  For little endian, we fill up the low order bits of the target
6366             --  value. For big endian we fill up the high order bits of the
6367             --  target value (which is a left justified modular value).
6368
6369             if Bytes_Big_Endian xor Debug_Flag_8 then
6370                Shift := Csiz * (Len - 1);
6371                Incr  := -Csiz;
6372             else
6373                Shift := 0;
6374                Incr  := +Csiz;
6375             end if;
6376
6377             --  Loop to set the values
6378
6379             if Len = 0 then
6380                Aggregate_Val := Uint_0;
6381             else
6382                Expr := First (Expressions (N));
6383                Aggregate_Val := Get_Component_Val (Expr) * Uint_2 ** Shift;
6384
6385                for J in 2 .. Len loop
6386                   Shift := Shift + Incr;
6387                   Next (Expr);
6388                   Aggregate_Val :=
6389                     Aggregate_Val + Get_Component_Val (Expr) * Uint_2 ** Shift;
6390                end loop;
6391             end if;
6392
6393             --  Now we can rewrite with the proper value
6394
6395             Lit :=
6396               Make_Integer_Literal (Loc,
6397                 Intval => Aggregate_Val);
6398             Set_Print_In_Hex (Lit);
6399
6400             --  Construct the expression using this literal. Note that it is
6401             --  important to qualify the literal with its proper modular type
6402             --  since universal integer does not have the required range and
6403             --  also this is a left justified modular type, which is important
6404             --  in the big-endian case.
6405
6406             Rewrite (N,
6407               Unchecked_Convert_To (Typ,
6408                 Make_Qualified_Expression (Loc,
6409                   Subtype_Mark =>
6410                     New_Occurrence_Of (Packed_Array_Type (Typ), Loc),
6411                   Expression   => Lit)));
6412
6413             Analyze_And_Resolve (N, Typ);
6414             return True;
6415          end;
6416       end;
6417
6418    exception
6419       when Not_Handled =>
6420          return False;
6421    end Packed_Array_Aggregate_Handled;
6422
6423    ----------------------------
6424    -- Has_Mutable_Components --
6425    ----------------------------
6426
6427    function Has_Mutable_Components (Typ : Entity_Id) return Boolean is
6428       Comp : Entity_Id;
6429
6430    begin
6431       Comp := First_Component (Typ);
6432       while Present (Comp) loop
6433          if Is_Record_Type (Etype (Comp))
6434            and then Has_Discriminants (Etype (Comp))
6435            and then not Is_Constrained (Etype (Comp))
6436          then
6437             return True;
6438          end if;
6439
6440          Next_Component (Comp);
6441       end loop;
6442
6443       return False;
6444    end Has_Mutable_Components;
6445
6446    ------------------------------
6447    -- Initialize_Discriminants --
6448    ------------------------------
6449
6450    procedure Initialize_Discriminants (N : Node_Id; Typ : Entity_Id) is
6451       Loc  : constant Source_Ptr := Sloc (N);
6452       Bas  : constant Entity_Id  := Base_Type (Typ);
6453       Par  : constant Entity_Id  := Etype (Bas);
6454       Decl : constant Node_Id    := Parent (Par);
6455       Ref  : Node_Id;
6456
6457    begin
6458       if Is_Tagged_Type (Bas)
6459         and then Is_Derived_Type (Bas)
6460         and then Has_Discriminants (Par)
6461         and then Has_Discriminants (Bas)
6462         and then Number_Discriminants (Bas) /= Number_Discriminants (Par)
6463         and then Nkind (Decl) = N_Full_Type_Declaration
6464         and then Nkind (Type_Definition (Decl)) = N_Record_Definition
6465         and then Present
6466           (Variant_Part (Component_List (Type_Definition (Decl))))
6467         and then Nkind (N) /= N_Extension_Aggregate
6468       then
6469
6470          --   Call init proc to set discriminants.
6471          --   There should eventually be a special procedure for this ???
6472
6473          Ref := New_Reference_To (Defining_Identifier (N), Loc);
6474          Insert_Actions_After (N,
6475            Build_Initialization_Call (Sloc (N), Ref, Typ));
6476       end if;
6477    end Initialize_Discriminants;
6478
6479    ----------------
6480    -- Must_Slide --
6481    ----------------
6482
6483    function Must_Slide
6484      (Obj_Type : Entity_Id;
6485       Typ      : Entity_Id) return Boolean
6486    is
6487       L1, L2, H1, H2 : Node_Id;
6488    begin
6489       --  No sliding if the type of the object is not established yet, if it is
6490       --  an unconstrained type whose actual subtype comes from the aggregate,
6491       --  or if the two types are identical.
6492
6493       if not Is_Array_Type (Obj_Type) then
6494          return False;
6495
6496       elsif not Is_Constrained (Obj_Type) then
6497          return False;
6498
6499       elsif Typ = Obj_Type then
6500          return False;
6501
6502       else
6503          --  Sliding can only occur along the first dimension
6504
6505          Get_Index_Bounds (First_Index (Typ), L1, H1);
6506          Get_Index_Bounds (First_Index (Obj_Type), L2, H2);
6507
6508          if not Is_Static_Expression (L1)
6509            or else not Is_Static_Expression (L2)
6510            or else not Is_Static_Expression (H1)
6511            or else not Is_Static_Expression (H2)
6512          then
6513             return False;
6514          else
6515             return Expr_Value (L1) /= Expr_Value (L2)
6516               or else Expr_Value (H1) /= Expr_Value (H2);
6517          end if;
6518       end if;
6519    end Must_Slide;
6520
6521    ---------------------------
6522    -- Safe_Slice_Assignment --
6523    ---------------------------
6524
6525    function Safe_Slice_Assignment (N : Node_Id) return Boolean is
6526       Loc        : constant Source_Ptr := Sloc (Parent (N));
6527       Pref       : constant Node_Id    := Prefix (Name (Parent (N)));
6528       Range_Node : constant Node_Id    := Discrete_Range (Name (Parent (N)));
6529       Expr       : Node_Id;
6530       L_J        : Entity_Id;
6531       L_Iter     : Node_Id;
6532       L_Body     : Node_Id;
6533       Stat       : Node_Id;
6534
6535    begin
6536       --  Generate: for J in Range loop Pref (J) := Expr; end loop;
6537
6538       if Comes_From_Source (N)
6539         and then No (Expressions (N))
6540         and then Nkind (First (Choices (First (Component_Associations (N)))))
6541                    = N_Others_Choice
6542       then
6543          Expr := Expression (First (Component_Associations (N)));
6544          L_J := Make_Temporary (Loc, 'J');
6545
6546          L_Iter :=
6547            Make_Iteration_Scheme (Loc,
6548              Loop_Parameter_Specification =>
6549                Make_Loop_Parameter_Specification
6550                  (Loc,
6551                   Defining_Identifier         => L_J,
6552                   Discrete_Subtype_Definition => Relocate_Node (Range_Node)));
6553
6554          L_Body :=
6555            Make_Assignment_Statement (Loc,
6556               Name =>
6557                 Make_Indexed_Component (Loc,
6558                   Prefix      => Relocate_Node (Pref),
6559                   Expressions => New_List (New_Occurrence_Of (L_J, Loc))),
6560                Expression => Relocate_Node (Expr));
6561
6562          --  Construct the final loop
6563
6564          Stat :=
6565            Make_Implicit_Loop_Statement
6566              (Node             => Parent (N),
6567               Identifier       => Empty,
6568               Iteration_Scheme => L_Iter,
6569               Statements       => New_List (L_Body));
6570
6571          --  Set type of aggregate to be type of lhs in assignment,
6572          --  to suppress redundant length checks.
6573
6574          Set_Etype (N, Etype (Name (Parent (N))));
6575
6576          Rewrite (Parent (N), Stat);
6577          Analyze (Parent (N));
6578          return True;
6579
6580       else
6581          return False;
6582       end if;
6583    end Safe_Slice_Assignment;
6584
6585    ---------------------
6586    -- Sort_Case_Table --
6587    ---------------------
6588
6589    procedure Sort_Case_Table (Case_Table : in out Case_Table_Type) is
6590       L : constant Int := Case_Table'First;
6591       U : constant Int := Case_Table'Last;
6592       K : Int;
6593       J : Int;
6594       T : Case_Bounds;
6595
6596    begin
6597       K := L;
6598       while K /= U loop
6599          T := Case_Table (K + 1);
6600
6601          J := K + 1;
6602          while J /= L
6603            and then Expr_Value (Case_Table (J - 1).Choice_Lo) >
6604                     Expr_Value (T.Choice_Lo)
6605          loop
6606             Case_Table (J) := Case_Table (J - 1);
6607             J := J - 1;
6608          end loop;
6609
6610          Case_Table (J) := T;
6611          K := K + 1;
6612       end loop;
6613    end Sort_Case_Table;
6614
6615    ----------------------------
6616    -- Static_Array_Aggregate --
6617    ----------------------------
6618
6619    function Static_Array_Aggregate (N : Node_Id) return Boolean is
6620       Bounds : constant Node_Id := Aggregate_Bounds (N);
6621
6622       Typ       : constant Entity_Id := Etype (N);
6623       Comp_Type : constant Entity_Id := Component_Type (Typ);
6624       Agg       : Node_Id;
6625       Expr      : Node_Id;
6626       Lo        : Node_Id;
6627       Hi        : Node_Id;
6628
6629    begin
6630       if Is_Tagged_Type (Typ)
6631         or else Is_Controlled (Typ)
6632         or else Is_Packed (Typ)
6633       then
6634          return False;
6635       end if;
6636
6637       if Present (Bounds)
6638         and then Nkind (Bounds) = N_Range
6639         and then Nkind (Low_Bound  (Bounds)) = N_Integer_Literal
6640         and then Nkind (High_Bound (Bounds)) = N_Integer_Literal
6641       then
6642          Lo := Low_Bound  (Bounds);
6643          Hi := High_Bound (Bounds);
6644
6645          if No (Component_Associations (N)) then
6646
6647             --  Verify that all components are static integers
6648
6649             Expr := First (Expressions (N));
6650             while Present (Expr) loop
6651                if Nkind (Expr) /= N_Integer_Literal then
6652                   return False;
6653                end if;
6654
6655                Next (Expr);
6656             end loop;
6657
6658             return True;
6659
6660          else
6661             --  We allow only a single named association, either a static
6662             --  range or an others_clause, with a static expression.
6663
6664             Expr := First (Component_Associations (N));
6665
6666             if Present (Expressions (N)) then
6667                return False;
6668
6669             elsif Present (Next (Expr)) then
6670                return False;
6671
6672             elsif Present (Next (First (Choices (Expr)))) then
6673                return False;
6674
6675             else
6676                --  The aggregate is static if all components are literals,
6677                --  or else all its components are static aggregates for the
6678                --  component type. We also limit the size of a static aggregate
6679                --  to prevent runaway static expressions.
6680
6681                if Is_Array_Type (Comp_Type)
6682                  or else Is_Record_Type (Comp_Type)
6683                then
6684                   if Nkind (Expression (Expr)) /= N_Aggregate
6685                     or else
6686                       not Compile_Time_Known_Aggregate (Expression (Expr))
6687                   then
6688                      return False;
6689                   end if;
6690
6691                elsif Nkind (Expression (Expr)) /= N_Integer_Literal then
6692                   return False;
6693                end if;
6694
6695                if not Aggr_Size_OK (N, Typ) then
6696                   return False;
6697                end if;
6698
6699                --  Create a positional aggregate with the right number of
6700                --  copies of the expression.
6701
6702                Agg := Make_Aggregate (Sloc (N), New_List, No_List);
6703
6704                for I in UI_To_Int (Intval (Lo)) .. UI_To_Int (Intval (Hi))
6705                loop
6706                   Append_To
6707                     (Expressions (Agg), New_Copy (Expression (Expr)));
6708
6709                   --  The copied expression must be analyzed and resolved.
6710                   --  Besides setting the type, this ensures that static
6711                   --  expressions are appropriately marked as such.
6712
6713                   Analyze_And_Resolve
6714                     (Last (Expressions (Agg)), Component_Type (Typ));
6715                end loop;
6716
6717                Set_Aggregate_Bounds (Agg, Bounds);
6718                Set_Etype (Agg, Typ);
6719                Set_Analyzed (Agg);
6720                Rewrite (N, Agg);
6721                Set_Compile_Time_Known_Aggregate (N);
6722
6723                return True;
6724             end if;
6725          end if;
6726
6727       else
6728          return False;
6729       end if;
6730    end Static_Array_Aggregate;
6731
6732 end Exp_Aggr;