OSDN Git Service

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