OSDN Git Service

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