OSDN Git Service

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