OSDN Git Service

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