OSDN Git Service

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