OSDN Git Service

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