OSDN Git Service

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