OSDN Git Service

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