OSDN Git Service

2009-05-06 Gary Dismukes <dismukes@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_ch3.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              E X P _ C H 3                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2009, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Checks;   use Checks;
28 with Einfo;    use Einfo;
29 with Errout;   use Errout;
30 with Exp_Aggr; use Exp_Aggr;
31 with Exp_Atag; use Exp_Atag;
32 with Exp_Ch4;  use Exp_Ch4;
33 with Exp_Ch6;  use Exp_Ch6;
34 with Exp_Ch7;  use Exp_Ch7;
35 with Exp_Ch9;  use Exp_Ch9;
36 with Exp_Ch11; use Exp_Ch11;
37 with Exp_Disp; use Exp_Disp;
38 with Exp_Dist; use Exp_Dist;
39 with Exp_Smem; use Exp_Smem;
40 with Exp_Strm; use Exp_Strm;
41 with Exp_Tss;  use Exp_Tss;
42 with Exp_Util; use Exp_Util;
43 with Freeze;   use Freeze;
44 with Nlists;   use Nlists;
45 with Namet;    use Namet;
46 with Nmake;    use Nmake;
47 with Opt;      use Opt;
48 with Restrict; use Restrict;
49 with Rident;   use Rident;
50 with Rtsfind;  use Rtsfind;
51 with Sem;      use Sem;
52 with Sem_Aux;  use Sem_Aux;
53 with Sem_Attr; use Sem_Attr;
54 with Sem_Cat;  use Sem_Cat;
55 with Sem_Ch3;  use Sem_Ch3;
56 with Sem_Ch8;  use Sem_Ch8;
57 with Sem_Disp; use Sem_Disp;
58 with Sem_Eval; use Sem_Eval;
59 with Sem_Mech; use Sem_Mech;
60 with Sem_Res;  use Sem_Res;
61 with Sem_Type; use Sem_Type;
62 with Sem_Util; use Sem_Util;
63 with Sinfo;    use Sinfo;
64 with Stand;    use Stand;
65 with Snames;   use Snames;
66 with Targparm; use Targparm;
67 with Tbuild;   use Tbuild;
68 with Ttypes;   use Ttypes;
69 with Validsw;  use Validsw;
70
71 package body Exp_Ch3 is
72
73    -----------------------
74    -- Local Subprograms --
75    -----------------------
76
77    function Add_Final_Chain (Def_Id : Entity_Id) return Entity_Id;
78    --  Add the declaration of a finalization list to the freeze actions for
79    --  Def_Id, and return its defining identifier.
80
81    procedure Adjust_Discriminants (Rtype : Entity_Id);
82    --  This is used when freezing a record type. It attempts to construct
83    --  more restrictive subtypes for discriminants so that the max size of
84    --  the record can be calculated more accurately. See the body of this
85    --  procedure for details.
86
87    procedure Build_Array_Init_Proc (A_Type : Entity_Id; Nod : Node_Id);
88    --  Build initialization procedure for given array type. Nod is a node
89    --  used for attachment of any actions required in its construction.
90    --  It also supplies the source location used for the procedure.
91
92    function Build_Discriminant_Formals
93      (Rec_Id : Entity_Id;
94       Use_Dl : Boolean) return List_Id;
95    --  This function uses the discriminants of a type to build a list of
96    --  formal parameters, used in the following function. If the flag Use_Dl
97    --  is set, the list is built using the already defined discriminals
98    --  of the type. Otherwise new identifiers are created, with the source
99    --  names of the discriminants.
100
101    function Build_Equivalent_Array_Aggregate (T : Entity_Id) return Node_Id;
102    --  This function builds a static aggregate that can serve as the initial
103    --  value for an array type whose bounds are static, and whose component
104    --  type is a composite type that has a static equivalent aggregate.
105    --  The equivalent array aggregate is used both for object initialization
106    --  and for component initialization, when used in the following function.
107
108    function Build_Equivalent_Record_Aggregate (T : Entity_Id) return Node_Id;
109    --  This function builds a static aggregate that can serve as the initial
110    --  value for a record type whose components are scalar and initialized
111    --  with compile-time values, or arrays with similar initialization or
112    --  defaults. When possible, initialization of an object of the type can
113    --  be achieved by using a copy of the aggregate as an initial value, thus
114    --  removing the implicit call that would otherwise constitute elaboration
115    --  code.
116
117    function Build_Master_Renaming
118      (N : Node_Id;
119       T : Entity_Id) return Entity_Id;
120    --  If the designated type of an access type is a task type or contains
121    --  tasks, we make sure that a _Master variable is declared in the current
122    --  scope, and then declare a renaming for it:
123    --
124    --    atypeM : Master_Id renames _Master;
125    --
126    --  where atyp is the name of the access type. This declaration is used when
127    --  an allocator for the access type is expanded. The node is the full
128    --  declaration of the designated type that contains tasks. The renaming
129    --  declaration is inserted before N, and after the Master declaration.
130
131    procedure Build_Record_Init_Proc (N : Node_Id; Pe : Entity_Id);
132    --  Build record initialization procedure. N is the type declaration
133    --  node, and Pe is the corresponding entity for the record type.
134
135    procedure Build_Slice_Assignment (Typ : Entity_Id);
136    --  Build assignment procedure for one-dimensional arrays of controlled
137    --  types. Other array and slice assignments are expanded in-line, but
138    --  the code expansion for controlled components (when control actions
139    --  are active) can lead to very large blocks that GCC3 handles poorly.
140
141    procedure Build_Variant_Record_Equality (Typ  : Entity_Id);
142    --  Create An Equality function for the non-tagged variant record 'Typ'
143    --  and attach it to the TSS list
144
145    procedure Check_Stream_Attributes (Typ : Entity_Id);
146    --  Check that if a limited extension has a parent with user-defined stream
147    --  attributes, and does not itself have user-defined stream-attributes,
148    --  then any limited component of the extension also has the corresponding
149    --  user-defined stream attributes.
150
151    procedure Clean_Task_Names
152      (Typ     : Entity_Id;
153       Proc_Id : Entity_Id);
154    --  If an initialization procedure includes calls to generate names
155    --  for task subcomponents, indicate that secondary stack cleanup is
156    --  needed after an initialization. Typ is the component type, and Proc_Id
157    --  the initialization procedure for the enclosing composite type.
158
159    procedure Expand_Tagged_Root (T : Entity_Id);
160    --  Add a field _Tag at the beginning of the record. This field carries
161    --  the value of the access to the Dispatch table. This procedure is only
162    --  called on root type, the _Tag field being inherited by the descendants.
163
164    procedure Expand_Record_Controller (T : Entity_Id);
165    --  T must be a record type that Has_Controlled_Component. Add a field
166    --  _controller of type Record_Controller or Limited_Record_Controller
167    --  in the record T.
168
169    procedure Freeze_Array_Type (N : Node_Id);
170    --  Freeze an array type. Deals with building the initialization procedure,
171    --  creating the packed array type for a packed array and also with the
172    --  creation of the controlling procedures for the controlled case. The
173    --  argument N is the N_Freeze_Entity node for the type.
174
175    procedure Freeze_Enumeration_Type (N : Node_Id);
176    --  Freeze enumeration type with non-standard representation. Builds the
177    --  array and function needed to convert between enumeration pos and
178    --  enumeration representation values. N is the N_Freeze_Entity node
179    --  for the type.
180
181    procedure Freeze_Record_Type (N : Node_Id);
182    --  Freeze record type. Builds all necessary discriminant checking
183    --  and other ancillary functions, and builds dispatch tables where
184    --  needed. The argument N is the N_Freeze_Entity node. This processing
185    --  applies only to E_Record_Type entities, not to class wide types,
186    --  record subtypes, or private types.
187
188    procedure Freeze_Stream_Operations (N : Node_Id; Typ : Entity_Id);
189    --  Treat user-defined stream operations as renaming_as_body if the
190    --  subprogram they rename is not frozen when the type is frozen.
191
192    procedure Initialization_Warning (E : Entity_Id);
193    --  If static elaboration of the package is requested, indicate
194    --  when a type does meet the conditions for static initialization. If
195    --  E is a type, it has components that have no static initialization.
196    --  if E is an entity, its initial expression is not compile-time known.
197
198    function Init_Formals (Typ : Entity_Id) return List_Id;
199    --  This function builds the list of formals for an initialization routine.
200    --  The first formal is always _Init with the given type. For task value
201    --  record types and types containing tasks, three additional formals are
202    --  added:
203    --
204    --    _Master    : Master_Id
205    --    _Chain     : in out Activation_Chain
206    --    _Task_Name : String
207    --
208    --  The caller must append additional entries for discriminants if required.
209
210    function In_Runtime (E : Entity_Id) return Boolean;
211    --  Check if E is defined in the RTL (in a child of Ada or System). Used
212    --  to avoid to bring in the overhead of _Input, _Output for tagged types.
213
214    function Is_Variable_Size_Record (E : Entity_Id) return Boolean;
215    --  Returns true if E has variable size components
216
217    function Make_Eq_Case
218      (E     : Entity_Id;
219       CL    : Node_Id;
220       Discr : Entity_Id := Empty) return List_Id;
221    --  Building block for variant record equality. Defined to share the code
222    --  between the tagged and non-tagged case. Given a Component_List node CL,
223    --  it generates an 'if' followed by a 'case' statement that compares all
224    --  components of local temporaries named X and Y (that are declared as
225    --  formals at some upper level). E provides the Sloc to be used for the
226    --  generated code. Discr is used as the case statement switch in the case
227    --  of Unchecked_Union equality.
228
229    function Make_Eq_If
230      (E : Entity_Id;
231       L : List_Id) return Node_Id;
232    --  Building block for variant record equality. Defined to share the code
233    --  between the tagged and non-tagged case. Given the list of components
234    --  (or discriminants) L, it generates a return statement that compares all
235    --  components of local temporaries named X and Y (that are declared as
236    --  formals at some upper level). E provides the Sloc to be used for the
237    --  generated code.
238
239    procedure Make_Predefined_Primitive_Specs
240      (Tag_Typ     : Entity_Id;
241       Predef_List : out List_Id;
242       Renamed_Eq  : out Entity_Id);
243    --  Create a list with the specs of the predefined primitive operations.
244    --  For tagged types that are interfaces all these primitives are defined
245    --  abstract.
246    --
247    --  The following entries are present for all tagged types, and provide
248    --  the results of the corresponding attribute applied to the object.
249    --  Dispatching is required in general, since the result of the attribute
250    --  will vary with the actual object subtype.
251    --
252    --     _alignment     provides result of 'Alignment attribute
253    --     _size          provides result of 'Size attribute
254    --     typSR          provides result of 'Read attribute
255    --     typSW          provides result of 'Write attribute
256    --     typSI          provides result of 'Input attribute
257    --     typSO          provides result of 'Output attribute
258    --
259    --  The following entries are additionally present for non-limited tagged
260    --  types, and implement additional dispatching operations for predefined
261    --  operations:
262    --
263    --     _equality      implements "=" operator
264    --     _assign        implements assignment operation
265    --     typDF          implements deep finalization
266    --     typDA          implements deep adjust
267    --
268    --  The latter two are empty procedures unless the type contains some
269    --  controlled components that require finalization actions (the deep
270    --  in the name refers to the fact that the action applies to components).
271    --
272    --  The list is returned in Predef_List. The Parameter Renamed_Eq either
273    --  returns the value Empty, or else the defining unit name for the
274    --  predefined equality function in the case where the type has a primitive
275    --  operation that is a renaming of predefined equality (but only if there
276    --  is also an overriding user-defined equality function). The returned
277    --  Renamed_Eq will be passed to the corresponding parameter of
278    --  Predefined_Primitive_Bodies.
279
280    function Has_New_Non_Standard_Rep (T : Entity_Id) return Boolean;
281    --  returns True if there are representation clauses for type T that are not
282    --  inherited. If the result is false, the init_proc and the discriminant
283    --  checking functions of the parent can be reused by a derived type.
284
285    procedure Make_Controlling_Function_Wrappers
286      (Tag_Typ   : Entity_Id;
287       Decl_List : out List_Id;
288       Body_List : out List_Id);
289    --  Ada 2005 (AI-391): Makes specs and bodies for the wrapper functions
290    --  associated with inherited functions with controlling results which
291    --  are not overridden. The body of each wrapper function consists solely
292    --  of a return statement whose expression is an extension aggregate
293    --  invoking the inherited subprogram's parent subprogram and extended
294    --  with a null association list.
295
296    procedure Make_Null_Procedure_Specs
297      (Tag_Typ   : Entity_Id;
298       Decl_List : out List_Id);
299    --  Ada 2005 (AI-251): Makes specs for null procedures associated with any
300    --  null procedures inherited from an interface type that have not been
301    --  overridden. Only one null procedure will be created for a given set of
302    --  inherited null procedures with homographic profiles.
303
304    function Predef_Spec_Or_Body
305      (Loc      : Source_Ptr;
306       Tag_Typ  : Entity_Id;
307       Name     : Name_Id;
308       Profile  : List_Id;
309       Ret_Type : Entity_Id := Empty;
310       For_Body : Boolean   := False) return Node_Id;
311    --  This function generates the appropriate expansion for a predefined
312    --  primitive operation specified by its name, parameter profile and
313    --  return type (Empty means this is a procedure). If For_Body is false,
314    --  then the returned node is a subprogram declaration. If For_Body is
315    --  true, then the returned node is a empty subprogram body containing
316    --  no declarations and no statements.
317
318    function Predef_Stream_Attr_Spec
319      (Loc      : Source_Ptr;
320       Tag_Typ  : Entity_Id;
321       Name     : TSS_Name_Type;
322       For_Body : Boolean := False) return Node_Id;
323    --  Specialized version of Predef_Spec_Or_Body that apply to read, write,
324    --  input and output attribute whose specs are constructed in Exp_Strm.
325
326    function Predef_Deep_Spec
327      (Loc      : Source_Ptr;
328       Tag_Typ  : Entity_Id;
329       Name     : TSS_Name_Type;
330       For_Body : Boolean := False) return Node_Id;
331    --  Specialized version of Predef_Spec_Or_Body that apply to _deep_adjust
332    --  and _deep_finalize
333
334    function Predefined_Primitive_Bodies
335      (Tag_Typ    : Entity_Id;
336       Renamed_Eq : Entity_Id) return List_Id;
337    --  Create the bodies of the predefined primitives that are described in
338    --  Predefined_Primitive_Specs. When not empty, Renamed_Eq must denote
339    --  the defining unit name of the type's predefined equality as returned
340    --  by Make_Predefined_Primitive_Specs.
341
342    function Predefined_Primitive_Freeze (Tag_Typ : Entity_Id) return List_Id;
343    --  Freeze entities of all predefined primitive operations. This is needed
344    --  because the bodies of these operations do not normally do any freezing.
345
346    function Stream_Operation_OK
347      (Typ       : Entity_Id;
348       Operation : TSS_Name_Type) return Boolean;
349    --  Check whether the named stream operation must be emitted for a given
350    --  type. The rules for inheritance of stream attributes by type extensions
351    --  are enforced by this function. Furthermore, various restrictions prevent
352    --  the generation of these operations, as a useful optimization or for
353    --  certification purposes.
354
355    ---------------------
356    -- Add_Final_Chain --
357    ---------------------
358
359    function Add_Final_Chain (Def_Id : Entity_Id) return Entity_Id is
360       Loc   : constant Source_Ptr := Sloc (Def_Id);
361       Flist : Entity_Id;
362
363    begin
364       Flist :=
365         Make_Defining_Identifier (Loc,
366           New_External_Name (Chars (Def_Id), 'L'));
367
368       Append_Freeze_Action (Def_Id,
369         Make_Object_Declaration (Loc,
370           Defining_Identifier => Flist,
371           Object_Definition   =>
372             New_Reference_To (RTE (RE_List_Controller), Loc)));
373
374       return Flist;
375    end Add_Final_Chain;
376
377    --------------------------
378    -- Adjust_Discriminants --
379    --------------------------
380
381    --  This procedure attempts to define subtypes for discriminants that are
382    --  more restrictive than those declared. Such a replacement is possible if
383    --  we can demonstrate that values outside the restricted range would cause
384    --  constraint errors in any case. The advantage of restricting the
385    --  discriminant types in this way is that the maximum size of the variant
386    --  record can be calculated more conservatively.
387
388    --  An example of a situation in which we can perform this type of
389    --  restriction is the following:
390
391    --    subtype B is range 1 .. 10;
392    --    type Q is array (B range <>) of Integer;
393
394    --    type V (N : Natural) is record
395    --       C : Q (1 .. N);
396    --    end record;
397
398    --  In this situation, we can restrict the upper bound of N to 10, since
399    --  any larger value would cause a constraint error in any case.
400
401    --  There are many situations in which such restriction is possible, but
402    --  for now, we just look for cases like the above, where the component
403    --  in question is a one dimensional array whose upper bound is one of
404    --  the record discriminants. Also the component must not be part of
405    --  any variant part, since then the component does not always exist.
406
407    procedure Adjust_Discriminants (Rtype : Entity_Id) is
408       Loc   : constant Source_Ptr := Sloc (Rtype);
409       Comp  : Entity_Id;
410       Ctyp  : Entity_Id;
411       Ityp  : Entity_Id;
412       Lo    : Node_Id;
413       Hi    : Node_Id;
414       P     : Node_Id;
415       Loval : Uint;
416       Discr : Entity_Id;
417       Dtyp  : Entity_Id;
418       Dhi   : Node_Id;
419       Dhiv  : Uint;
420       Ahi   : Node_Id;
421       Ahiv  : Uint;
422       Tnn   : Entity_Id;
423
424    begin
425       Comp := First_Component (Rtype);
426       while Present (Comp) loop
427
428          --  If our parent is a variant, quit, we do not look at components
429          --  that are in variant parts, because they may not always exist.
430
431          P := Parent (Comp);   -- component declaration
432          P := Parent (P);      -- component list
433
434          exit when Nkind (Parent (P)) = N_Variant;
435
436          --  We are looking for a one dimensional array type
437
438          Ctyp := Etype (Comp);
439
440          if not Is_Array_Type (Ctyp)
441            or else Number_Dimensions (Ctyp) > 1
442          then
443             goto Continue;
444          end if;
445
446          --  The lower bound must be constant, and the upper bound is a
447          --  discriminant (which is a discriminant of the current record).
448
449          Ityp := Etype (First_Index (Ctyp));
450          Lo := Type_Low_Bound (Ityp);
451          Hi := Type_High_Bound (Ityp);
452
453          if not Compile_Time_Known_Value (Lo)
454            or else Nkind (Hi) /= N_Identifier
455            or else No (Entity (Hi))
456            or else Ekind (Entity (Hi)) /= E_Discriminant
457          then
458             goto Continue;
459          end if;
460
461          --  We have an array with appropriate bounds
462
463          Loval := Expr_Value (Lo);
464          Discr := Entity (Hi);
465          Dtyp  := Etype (Discr);
466
467          --  See if the discriminant has a known upper bound
468
469          Dhi := Type_High_Bound (Dtyp);
470
471          if not Compile_Time_Known_Value (Dhi) then
472             goto Continue;
473          end if;
474
475          Dhiv := Expr_Value (Dhi);
476
477          --  See if base type of component array has known upper bound
478
479          Ahi := Type_High_Bound (Etype (First_Index (Base_Type (Ctyp))));
480
481          if not Compile_Time_Known_Value (Ahi) then
482             goto Continue;
483          end if;
484
485          Ahiv := Expr_Value (Ahi);
486
487          --  The condition for doing the restriction is that the high bound
488          --  of the discriminant is greater than the low bound of the array,
489          --  and is also greater than the high bound of the base type index.
490
491          if Dhiv > Loval and then Dhiv > Ahiv then
492
493             --  We can reset the upper bound of the discriminant type to
494             --  whichever is larger, the low bound of the component, or
495             --  the high bound of the base type array index.
496
497             --  We build a subtype that is declared as
498
499             --     subtype Tnn is discr_type range discr_type'First .. max;
500
501             --  And insert this declaration into the tree. The type of the
502             --  discriminant is then reset to this more restricted subtype.
503
504             Tnn := Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
505
506             Insert_Action (Declaration_Node (Rtype),
507               Make_Subtype_Declaration (Loc,
508                 Defining_Identifier => Tnn,
509                 Subtype_Indication =>
510                   Make_Subtype_Indication (Loc,
511                     Subtype_Mark => New_Occurrence_Of (Dtyp, Loc),
512                     Constraint   =>
513                       Make_Range_Constraint (Loc,
514                         Range_Expression =>
515                           Make_Range (Loc,
516                             Low_Bound =>
517                               Make_Attribute_Reference (Loc,
518                                 Attribute_Name => Name_First,
519                                 Prefix => New_Occurrence_Of (Dtyp, Loc)),
520                             High_Bound =>
521                               Make_Integer_Literal (Loc,
522                                 Intval => UI_Max (Loval, Ahiv)))))));
523
524             Set_Etype (Discr, Tnn);
525          end if;
526
527       <<Continue>>
528          Next_Component (Comp);
529       end loop;
530    end Adjust_Discriminants;
531
532    ---------------------------
533    -- Build_Array_Init_Proc --
534    ---------------------------
535
536    procedure Build_Array_Init_Proc (A_Type : Entity_Id; Nod : Node_Id) is
537       Loc              : constant Source_Ptr := Sloc (Nod);
538       Comp_Type        : constant Entity_Id  := Component_Type (A_Type);
539       Index_List       : List_Id;
540       Proc_Id          : Entity_Id;
541       Body_Stmts       : List_Id;
542       Has_Default_Init : Boolean;
543
544       function Init_Component return List_Id;
545       --  Create one statement to initialize one array component, designated
546       --  by a full set of indices.
547
548       function Init_One_Dimension (N : Int) return List_Id;
549       --  Create loop to initialize one dimension of the array. The single
550       --  statement in the loop body initializes the inner dimensions if any,
551       --  or else the single component. Note that this procedure is called
552       --  recursively, with N being the dimension to be initialized. A call
553       --  with N greater than the number of dimensions simply generates the
554       --  component initialization, terminating the recursion.
555
556       --------------------
557       -- Init_Component --
558       --------------------
559
560       function Init_Component return List_Id is
561          Comp : Node_Id;
562
563       begin
564          Comp :=
565            Make_Indexed_Component (Loc,
566              Prefix => Make_Identifier (Loc, Name_uInit),
567              Expressions => Index_List);
568
569          if Needs_Simple_Initialization (Comp_Type) then
570             Set_Assignment_OK (Comp);
571             return New_List (
572               Make_Assignment_Statement (Loc,
573                 Name => Comp,
574                 Expression =>
575                   Get_Simple_Init_Val
576                     (Comp_Type, Nod, Component_Size (A_Type))));
577
578          else
579             Clean_Task_Names (Comp_Type, Proc_Id);
580             return
581               Build_Initialization_Call
582                 (Loc, Comp, Comp_Type,
583                  In_Init_Proc => True,
584                  Enclos_Type  => A_Type);
585          end if;
586       end Init_Component;
587
588       ------------------------
589       -- Init_One_Dimension --
590       ------------------------
591
592       function Init_One_Dimension (N : Int) return List_Id is
593          Index      : Entity_Id;
594
595       begin
596          --  If the component does not need initializing, then there is nothing
597          --  to do here, so we return a null body. This occurs when generating
598          --  the dummy Init_Proc needed for Initialize_Scalars processing.
599
600          if not Has_Non_Null_Base_Init_Proc (Comp_Type)
601            and then not Needs_Simple_Initialization (Comp_Type)
602            and then not Has_Task (Comp_Type)
603          then
604             return New_List (Make_Null_Statement (Loc));
605
606          --  If all dimensions dealt with, we simply initialize the component
607
608          elsif N > Number_Dimensions (A_Type) then
609             return Init_Component;
610
611          --  Here we generate the required loop
612
613          else
614             Index :=
615               Make_Defining_Identifier (Loc, New_External_Name ('J', N));
616
617             Append (New_Reference_To (Index, Loc), Index_List);
618
619             return New_List (
620               Make_Implicit_Loop_Statement (Nod,
621                 Identifier => Empty,
622                 Iteration_Scheme =>
623                   Make_Iteration_Scheme (Loc,
624                     Loop_Parameter_Specification =>
625                       Make_Loop_Parameter_Specification (Loc,
626                         Defining_Identifier => Index,
627                         Discrete_Subtype_Definition =>
628                           Make_Attribute_Reference (Loc,
629                             Prefix => Make_Identifier (Loc, Name_uInit),
630                             Attribute_Name  => Name_Range,
631                             Expressions => New_List (
632                               Make_Integer_Literal (Loc, N))))),
633                 Statements =>  Init_One_Dimension (N + 1)));
634          end if;
635       end Init_One_Dimension;
636
637    --  Start of processing for Build_Array_Init_Proc
638
639    begin
640       --  Nothing to generate in the following cases:
641
642       --    1. Initialization is suppressed for the type
643       --    2. The type is a value type, in the CIL sense.
644       --    3. An initialization already exists for the base type
645
646       if Suppress_Init_Proc (A_Type)
647         or else Is_Value_Type (Comp_Type)
648         or else Present (Base_Init_Proc (A_Type))
649       then
650          return;
651       end if;
652
653       Index_List := New_List;
654
655       --  We need an initialization procedure if any of the following is true:
656
657       --    1. The component type has an initialization procedure
658       --    2. The component type needs simple initialization
659       --    3. Tasks are present
660       --    4. The type is marked as a public entity
661
662       --  The reason for the public entity test is to deal properly with the
663       --  Initialize_Scalars pragma. This pragma can be set in the client and
664       --  not in the declaring package, this means the client will make a call
665       --  to the initialization procedure (because one of conditions 1-3 must
666       --  apply in this case), and we must generate a procedure (even if it is
667       --  null) to satisfy the call in this case.
668
669       --  Exception: do not build an array init_proc for a type whose root
670       --  type is Standard.String or Standard.Wide_[Wide_]String, since there
671       --  is no place to put the code, and in any case we handle initialization
672       --  of such types (in the Initialize_Scalars case, that's the only time
673       --  the issue arises) in a special manner anyway which does not need an
674       --  init_proc.
675
676       Has_Default_Init := Has_Non_Null_Base_Init_Proc (Comp_Type)
677                             or else Needs_Simple_Initialization (Comp_Type)
678                             or else Has_Task (Comp_Type);
679
680       if Has_Default_Init
681         or else (not Restriction_Active (No_Initialize_Scalars)
682                   and then Is_Public (A_Type)
683                   and then Root_Type (A_Type) /= Standard_String
684                   and then Root_Type (A_Type) /= Standard_Wide_String
685                   and then Root_Type (A_Type) /= Standard_Wide_Wide_String)
686       then
687          Proc_Id :=
688            Make_Defining_Identifier (Loc,
689              Chars => Make_Init_Proc_Name (A_Type));
690
691          --  If No_Default_Initialization restriction is active, then we don't
692          --  want to build an init_proc, but we need to mark that an init_proc
693          --  would be needed if this restriction was not active (so that we can
694          --  detect attempts to call it), so set a dummy init_proc in place.
695          --  This is only done though when actual default initialization is
696          --  needed (and not done when only Is_Public is True), since otherwise
697          --  objects such as arrays of scalars could be wrongly flagged as
698          --  violating the restriction.
699
700          if Restriction_Active (No_Default_Initialization) then
701             if Has_Default_Init then
702                Set_Init_Proc (A_Type, Proc_Id);
703             end if;
704
705             return;
706          end if;
707
708          Body_Stmts := Init_One_Dimension (1);
709
710          Discard_Node (
711            Make_Subprogram_Body (Loc,
712              Specification =>
713                Make_Procedure_Specification (Loc,
714                  Defining_Unit_Name => Proc_Id,
715                  Parameter_Specifications => Init_Formals (A_Type)),
716              Declarations => New_List,
717              Handled_Statement_Sequence =>
718                Make_Handled_Sequence_Of_Statements (Loc,
719                  Statements => Body_Stmts)));
720
721          Set_Ekind          (Proc_Id, E_Procedure);
722          Set_Is_Public      (Proc_Id, Is_Public (A_Type));
723          Set_Is_Internal    (Proc_Id);
724          Set_Has_Completion (Proc_Id);
725
726          if not Debug_Generated_Code then
727             Set_Debug_Info_Off (Proc_Id);
728          end if;
729
730          --  Set inlined unless controlled stuff or tasks around, in which
731          --  case we do not want to inline, because nested stuff may cause
732          --  difficulties in inter-unit inlining, and furthermore there is
733          --  in any case no point in inlining such complex init procs.
734
735          if not Has_Task (Proc_Id)
736            and then not Needs_Finalization (Proc_Id)
737          then
738             Set_Is_Inlined (Proc_Id);
739          end if;
740
741          --  Associate Init_Proc with type, and determine if the procedure
742          --  is null (happens because of the Initialize_Scalars pragma case,
743          --  where we have to generate a null procedure in case it is called
744          --  by a client with Initialize_Scalars set). Such procedures have
745          --  to be generated, but do not have to be called, so we mark them
746          --  as null to suppress the call.
747
748          Set_Init_Proc (A_Type, Proc_Id);
749
750          if List_Length (Body_Stmts) = 1
751            and then Nkind (First (Body_Stmts)) = N_Null_Statement
752          then
753             Set_Is_Null_Init_Proc (Proc_Id);
754
755          else
756             --  Try to build a static aggregate to initialize statically
757             --  objects of the type. This can only be done for constrained
758             --  one-dimensional arrays with static bounds.
759
760             Set_Static_Initialization
761               (Proc_Id,
762                 Build_Equivalent_Array_Aggregate (First_Subtype (A_Type)));
763          end if;
764       end if;
765    end Build_Array_Init_Proc;
766
767    -----------------------------
768    -- Build_Class_Wide_Master --
769    -----------------------------
770
771    procedure Build_Class_Wide_Master (T : Entity_Id) is
772       Loc  : constant Source_Ptr := Sloc (T);
773       M_Id : Entity_Id;
774       Decl : Node_Id;
775       P    : Node_Id;
776       Par  : Node_Id;
777
778    begin
779       --  Nothing to do if there is no task hierarchy
780
781       if Restriction_Active (No_Task_Hierarchy) then
782          return;
783       end if;
784
785       --  Find declaration that created the access type: either a type
786       --  declaration, or an object declaration with an access definition,
787       --  in which case the type is anonymous.
788
789       if Is_Itype (T) then
790          P := Associated_Node_For_Itype (T);
791       else
792          P := Parent (T);
793       end if;
794
795       --  Nothing to do if we already built a master entity for this scope
796
797       if not Has_Master_Entity (Scope (T)) then
798
799          --  First build the master entity
800          --    _Master : constant Master_Id := Current_Master.all;
801          --  and insert it just before the current declaration.
802
803          Decl :=
804            Make_Object_Declaration (Loc,
805              Defining_Identifier =>
806                Make_Defining_Identifier (Loc, Name_uMaster),
807              Constant_Present => True,
808              Object_Definition => New_Reference_To (Standard_Integer, Loc),
809              Expression =>
810                Make_Explicit_Dereference (Loc,
811                  New_Reference_To (RTE (RE_Current_Master), Loc)));
812
813          Insert_Action (P, Decl);
814          Analyze (Decl);
815          Set_Has_Master_Entity (Scope (T));
816
817          --  Now mark the containing scope as a task master. Masters
818          --  associated with return statements are already marked at
819          --  this stage (see Analyze_Subprogram_Body).
820
821          if Ekind (Current_Scope) /= E_Return_Statement then
822             Par := P;
823             while Nkind (Par) /= N_Compilation_Unit loop
824                Par := Parent (Par);
825
826             --  If we fall off the top, we are at the outer level, and the
827             --  environment task is our effective master, so nothing to mark.
828
829                if Nkind_In
830                    (Par, N_Task_Body, N_Block_Statement, N_Subprogram_Body)
831                then
832                   Set_Is_Task_Master (Par, True);
833                   exit;
834                end if;
835             end loop;
836          end if;
837       end if;
838
839       --  Now define the renaming of the master_id
840
841       M_Id :=
842         Make_Defining_Identifier (Loc,
843           New_External_Name (Chars (T), 'M'));
844
845       Decl :=
846         Make_Object_Renaming_Declaration (Loc,
847           Defining_Identifier => M_Id,
848           Subtype_Mark => New_Reference_To (Standard_Integer, Loc),
849           Name => Make_Identifier (Loc, Name_uMaster));
850       Insert_Before (P, Decl);
851       Analyze (Decl);
852
853       Set_Master_Id (T, M_Id);
854
855    exception
856       when RE_Not_Available =>
857          return;
858    end Build_Class_Wide_Master;
859
860    --------------------------------
861    -- Build_Discr_Checking_Funcs --
862    --------------------------------
863
864    procedure Build_Discr_Checking_Funcs (N : Node_Id) is
865       Rec_Id            : Entity_Id;
866       Loc               : Source_Ptr;
867       Enclosing_Func_Id : Entity_Id;
868       Sequence          : Nat     := 1;
869       Type_Def          : Node_Id;
870       V                 : Node_Id;
871
872       function Build_Case_Statement
873         (Case_Id : Entity_Id;
874          Variant : Node_Id) return Node_Id;
875       --  Build a case statement containing only two alternatives. The first
876       --  alternative corresponds exactly to the discrete choices given on the
877       --  variant with contains the components that we are generating the
878       --  checks for. If the discriminant is one of these return False. The
879       --  second alternative is an OTHERS choice that will return True
880       --  indicating the discriminant did not match.
881
882       function Build_Dcheck_Function
883         (Case_Id : Entity_Id;
884          Variant : Node_Id) return Entity_Id;
885       --  Build the discriminant checking function for a given variant
886
887       procedure Build_Dcheck_Functions (Variant_Part_Node : Node_Id);
888       --  Builds the discriminant checking function for each variant of the
889       --  given variant part of the record type.
890
891       --------------------------
892       -- Build_Case_Statement --
893       --------------------------
894
895       function Build_Case_Statement
896         (Case_Id : Entity_Id;
897          Variant : Node_Id) return Node_Id
898       is
899          Alt_List       : constant List_Id := New_List;
900          Actuals_List   : List_Id;
901          Case_Node      : Node_Id;
902          Case_Alt_Node  : Node_Id;
903          Choice         : Node_Id;
904          Choice_List    : List_Id;
905          D              : Entity_Id;
906          Return_Node    : Node_Id;
907
908       begin
909          Case_Node := New_Node (N_Case_Statement, Loc);
910
911          --  Replace the discriminant which controls the variant, with the name
912          --  of the formal of the checking function.
913
914          Set_Expression (Case_Node,
915            Make_Identifier (Loc, Chars (Case_Id)));
916
917          Choice := First (Discrete_Choices (Variant));
918
919          if Nkind (Choice) = N_Others_Choice then
920             Choice_List := New_Copy_List (Others_Discrete_Choices (Choice));
921          else
922             Choice_List := New_Copy_List (Discrete_Choices (Variant));
923          end if;
924
925          if not Is_Empty_List (Choice_List) then
926             Case_Alt_Node := New_Node (N_Case_Statement_Alternative, Loc);
927             Set_Discrete_Choices (Case_Alt_Node, Choice_List);
928
929             --  In case this is a nested variant, we need to return the result
930             --  of the discriminant checking function for the immediately
931             --  enclosing variant.
932
933             if Present (Enclosing_Func_Id) then
934                Actuals_List := New_List;
935
936                D := First_Discriminant (Rec_Id);
937                while Present (D) loop
938                   Append (Make_Identifier (Loc, Chars (D)), Actuals_List);
939                   Next_Discriminant (D);
940                end loop;
941
942                Return_Node :=
943                  Make_Simple_Return_Statement (Loc,
944                    Expression =>
945                      Make_Function_Call (Loc,
946                        Name =>
947                          New_Reference_To (Enclosing_Func_Id,  Loc),
948                        Parameter_Associations =>
949                          Actuals_List));
950
951             else
952                Return_Node :=
953                  Make_Simple_Return_Statement (Loc,
954                    Expression =>
955                      New_Reference_To (Standard_False, Loc));
956             end if;
957
958             Set_Statements (Case_Alt_Node, New_List (Return_Node));
959             Append (Case_Alt_Node, Alt_List);
960          end if;
961
962          Case_Alt_Node := New_Node (N_Case_Statement_Alternative, Loc);
963          Choice_List := New_List (New_Node (N_Others_Choice, Loc));
964          Set_Discrete_Choices (Case_Alt_Node, Choice_List);
965
966          Return_Node :=
967            Make_Simple_Return_Statement (Loc,
968              Expression =>
969                New_Reference_To (Standard_True, Loc));
970
971          Set_Statements (Case_Alt_Node, New_List (Return_Node));
972          Append (Case_Alt_Node, Alt_List);
973
974          Set_Alternatives (Case_Node, Alt_List);
975          return Case_Node;
976       end Build_Case_Statement;
977
978       ---------------------------
979       -- Build_Dcheck_Function --
980       ---------------------------
981
982       function Build_Dcheck_Function
983         (Case_Id : Entity_Id;
984          Variant : Node_Id) return Entity_Id
985       is
986          Body_Node           : Node_Id;
987          Func_Id             : Entity_Id;
988          Parameter_List      : List_Id;
989          Spec_Node           : Node_Id;
990
991       begin
992          Body_Node := New_Node (N_Subprogram_Body, Loc);
993          Sequence := Sequence + 1;
994
995          Func_Id :=
996            Make_Defining_Identifier (Loc,
997              Chars => New_External_Name (Chars (Rec_Id), 'D', Sequence));
998
999          Spec_Node := New_Node (N_Function_Specification, Loc);
1000          Set_Defining_Unit_Name (Spec_Node, Func_Id);
1001
1002          Parameter_List := Build_Discriminant_Formals (Rec_Id, False);
1003
1004          Set_Parameter_Specifications (Spec_Node, Parameter_List);
1005          Set_Result_Definition (Spec_Node,
1006                                 New_Reference_To (Standard_Boolean,  Loc));
1007          Set_Specification (Body_Node, Spec_Node);
1008          Set_Declarations (Body_Node, New_List);
1009
1010          Set_Handled_Statement_Sequence (Body_Node,
1011            Make_Handled_Sequence_Of_Statements (Loc,
1012              Statements => New_List (
1013                Build_Case_Statement (Case_Id, Variant))));
1014
1015          Set_Ekind       (Func_Id, E_Function);
1016          Set_Mechanism   (Func_Id, Default_Mechanism);
1017          Set_Is_Inlined  (Func_Id, True);
1018          Set_Is_Pure     (Func_Id, True);
1019          Set_Is_Public   (Func_Id, Is_Public (Rec_Id));
1020          Set_Is_Internal (Func_Id, True);
1021
1022          if not Debug_Generated_Code then
1023             Set_Debug_Info_Off (Func_Id);
1024          end if;
1025
1026          Analyze (Body_Node);
1027
1028          Append_Freeze_Action (Rec_Id, Body_Node);
1029          Set_Dcheck_Function (Variant, Func_Id);
1030          return Func_Id;
1031       end Build_Dcheck_Function;
1032
1033       ----------------------------
1034       -- Build_Dcheck_Functions --
1035       ----------------------------
1036
1037       procedure Build_Dcheck_Functions (Variant_Part_Node : Node_Id) is
1038          Component_List_Node : Node_Id;
1039          Decl                : Entity_Id;
1040          Discr_Name          : Entity_Id;
1041          Func_Id             : Entity_Id;
1042          Variant             : Node_Id;
1043          Saved_Enclosing_Func_Id : Entity_Id;
1044
1045       begin
1046          --  Build the discriminant-checking function for each variant, and
1047          --  label all components of that variant with the function's name.
1048          --  We only Generate a discriminant-checking function when the
1049          --  variant is not empty, to prevent the creation of dead code.
1050          --  The exception to that is when Frontend_Layout_On_Target is set,
1051          --  because the variant record size function generated in package
1052          --  Layout needs to generate calls to all discriminant-checking
1053          --  functions, including those for empty variants.
1054
1055          Discr_Name := Entity (Name (Variant_Part_Node));
1056          Variant := First_Non_Pragma (Variants (Variant_Part_Node));
1057
1058          while Present (Variant) loop
1059             Component_List_Node := Component_List (Variant);
1060
1061             if not Null_Present (Component_List_Node)
1062               or else Frontend_Layout_On_Target
1063             then
1064                Func_Id := Build_Dcheck_Function (Discr_Name, Variant);
1065                Decl :=
1066                  First_Non_Pragma (Component_Items (Component_List_Node));
1067
1068                while Present (Decl) loop
1069                   Set_Discriminant_Checking_Func
1070                     (Defining_Identifier (Decl), Func_Id);
1071
1072                   Next_Non_Pragma (Decl);
1073                end loop;
1074
1075                if Present (Variant_Part (Component_List_Node)) then
1076                   Saved_Enclosing_Func_Id := Enclosing_Func_Id;
1077                   Enclosing_Func_Id := Func_Id;
1078                   Build_Dcheck_Functions (Variant_Part (Component_List_Node));
1079                   Enclosing_Func_Id := Saved_Enclosing_Func_Id;
1080                end if;
1081             end if;
1082
1083             Next_Non_Pragma (Variant);
1084          end loop;
1085       end Build_Dcheck_Functions;
1086
1087    --  Start of processing for Build_Discr_Checking_Funcs
1088
1089    begin
1090       --  Only build if not done already
1091
1092       if not Discr_Check_Funcs_Built (N) then
1093          Type_Def := Type_Definition (N);
1094
1095          if Nkind (Type_Def) = N_Record_Definition then
1096             if No (Component_List (Type_Def)) then   -- null record.
1097                return;
1098             else
1099                V := Variant_Part (Component_List (Type_Def));
1100             end if;
1101
1102          else pragma Assert (Nkind (Type_Def) = N_Derived_Type_Definition);
1103             if No (Component_List (Record_Extension_Part (Type_Def))) then
1104                return;
1105             else
1106                V := Variant_Part
1107                       (Component_List (Record_Extension_Part (Type_Def)));
1108             end if;
1109          end if;
1110
1111          Rec_Id := Defining_Identifier (N);
1112
1113          if Present (V) and then not Is_Unchecked_Union (Rec_Id) then
1114             Loc := Sloc (N);
1115             Enclosing_Func_Id := Empty;
1116             Build_Dcheck_Functions (V);
1117          end if;
1118
1119          Set_Discr_Check_Funcs_Built (N);
1120       end if;
1121    end Build_Discr_Checking_Funcs;
1122
1123    --------------------------------
1124    -- Build_Discriminant_Formals --
1125    --------------------------------
1126
1127    function Build_Discriminant_Formals
1128      (Rec_Id : Entity_Id;
1129       Use_Dl : Boolean) return List_Id
1130    is
1131       Loc             : Source_Ptr       := Sloc (Rec_Id);
1132       Parameter_List  : constant List_Id := New_List;
1133       D               : Entity_Id;
1134       Formal          : Entity_Id;
1135       Param_Spec_Node : Node_Id;
1136
1137    begin
1138       if Has_Discriminants (Rec_Id) then
1139          D := First_Discriminant (Rec_Id);
1140          while Present (D) loop
1141             Loc := Sloc (D);
1142
1143             if Use_Dl then
1144                Formal := Discriminal (D);
1145             else
1146                Formal := Make_Defining_Identifier (Loc, Chars (D));
1147             end if;
1148
1149             Param_Spec_Node :=
1150               Make_Parameter_Specification (Loc,
1151                   Defining_Identifier => Formal,
1152                 Parameter_Type =>
1153                   New_Reference_To (Etype (D), Loc));
1154             Append (Param_Spec_Node, Parameter_List);
1155             Next_Discriminant (D);
1156          end loop;
1157       end if;
1158
1159       return Parameter_List;
1160    end Build_Discriminant_Formals;
1161
1162    --------------------------------------
1163    -- Build_Equivalent_Array_Aggregate --
1164    --------------------------------------
1165
1166    function Build_Equivalent_Array_Aggregate (T : Entity_Id) return Node_Id is
1167       Loc        : constant Source_Ptr := Sloc (T);
1168       Comp_Type  : constant Entity_Id := Component_Type (T);
1169       Index_Type : constant Entity_Id := Etype (First_Index (T));
1170       Proc       : constant Entity_Id := Base_Init_Proc (T);
1171       Lo, Hi     : Node_Id;
1172       Aggr       : Node_Id;
1173       Expr       : Node_Id;
1174
1175    begin
1176       if not Is_Constrained (T)
1177         or else Number_Dimensions (T) > 1
1178         or else No (Proc)
1179       then
1180          Initialization_Warning (T);
1181          return Empty;
1182       end if;
1183
1184       Lo := Type_Low_Bound  (Index_Type);
1185       Hi := Type_High_Bound (Index_Type);
1186
1187       if not Compile_Time_Known_Value (Lo)
1188         or else not Compile_Time_Known_Value (Hi)
1189       then
1190          Initialization_Warning (T);
1191          return Empty;
1192       end if;
1193
1194       if Is_Record_Type (Comp_Type)
1195         and then Present (Base_Init_Proc (Comp_Type))
1196       then
1197          Expr := Static_Initialization (Base_Init_Proc (Comp_Type));
1198
1199          if No (Expr) then
1200             Initialization_Warning (T);
1201             return Empty;
1202          end if;
1203
1204       else
1205          Initialization_Warning (T);
1206          return Empty;
1207       end if;
1208
1209       Aggr := Make_Aggregate (Loc, No_List, New_List);
1210       Set_Etype (Aggr, T);
1211       Set_Aggregate_Bounds (Aggr,
1212         Make_Range (Loc,
1213           Low_Bound  => New_Copy (Lo),
1214           High_Bound => New_Copy (Hi)));
1215       Set_Parent (Aggr, Parent (Proc));
1216
1217       Append_To (Component_Associations (Aggr),
1218          Make_Component_Association (Loc,
1219               Choices =>
1220                  New_List (
1221                    Make_Range (Loc,
1222                      Low_Bound  => New_Copy (Lo),
1223                      High_Bound => New_Copy (Hi))),
1224               Expression => Expr));
1225
1226       if Static_Array_Aggregate (Aggr) then
1227          return Aggr;
1228       else
1229          Initialization_Warning (T);
1230          return Empty;
1231       end if;
1232    end Build_Equivalent_Array_Aggregate;
1233
1234    ---------------------------------------
1235    -- Build_Equivalent_Record_Aggregate --
1236    ---------------------------------------
1237
1238    function Build_Equivalent_Record_Aggregate (T : Entity_Id) return Node_Id is
1239       Agg  : Node_Id;
1240       Comp : Entity_Id;
1241
1242       --  Start of processing for Build_Equivalent_Record_Aggregate
1243
1244    begin
1245       if not Is_Record_Type (T)
1246         or else Has_Discriminants (T)
1247         or else Is_Limited_Type (T)
1248         or else Has_Non_Standard_Rep (T)
1249       then
1250          Initialization_Warning (T);
1251          return Empty;
1252       end if;
1253
1254       Comp := First_Component (T);
1255
1256       --  A null record needs no warning
1257
1258       if No (Comp) then
1259          return Empty;
1260       end if;
1261
1262       while Present (Comp) loop
1263
1264          --  Array components are acceptable if initialized by a positional
1265          --  aggregate with static components.
1266
1267          if Is_Array_Type (Etype (Comp)) then
1268             declare
1269                Comp_Type : constant Entity_Id := Component_Type (Etype (Comp));
1270
1271             begin
1272                if Nkind (Parent (Comp)) /= N_Component_Declaration
1273                  or else No (Expression (Parent (Comp)))
1274                  or else Nkind (Expression (Parent (Comp))) /= N_Aggregate
1275                then
1276                   Initialization_Warning (T);
1277                   return Empty;
1278
1279                elsif Is_Scalar_Type (Component_Type (Etype (Comp)))
1280                   and then
1281                     (not Compile_Time_Known_Value (Type_Low_Bound (Comp_Type))
1282                       or else not Compile_Time_Known_Value
1283                           (Type_High_Bound (Comp_Type)))
1284                then
1285                   Initialization_Warning (T);
1286                   return Empty;
1287
1288                elsif
1289                  not Static_Array_Aggregate (Expression (Parent (Comp)))
1290                then
1291                   Initialization_Warning (T);
1292                   return Empty;
1293                end if;
1294             end;
1295
1296          elsif Is_Scalar_Type (Etype (Comp)) then
1297             if Nkind (Parent (Comp)) /= N_Component_Declaration
1298               or else No (Expression (Parent (Comp)))
1299               or else not Compile_Time_Known_Value (Expression (Parent (Comp)))
1300             then
1301                Initialization_Warning (T);
1302                return Empty;
1303             end if;
1304
1305          --  For now, other types are excluded
1306
1307          else
1308             Initialization_Warning (T);
1309             return Empty;
1310          end if;
1311
1312          Next_Component (Comp);
1313       end loop;
1314
1315       --  All components have static initialization. Build  positional
1316       --  aggregate from the given expressions or defaults.
1317
1318       Agg := Make_Aggregate (Sloc (T), New_List, New_List);
1319       Set_Parent (Agg, Parent (T));
1320
1321       Comp := First_Component (T);
1322       while Present (Comp) loop
1323          Append
1324            (New_Copy_Tree (Expression (Parent (Comp))), Expressions (Agg));
1325          Next_Component (Comp);
1326       end loop;
1327
1328       Analyze_And_Resolve (Agg, T);
1329       return Agg;
1330    end Build_Equivalent_Record_Aggregate;
1331
1332    -------------------------------
1333    -- Build_Initialization_Call --
1334    -------------------------------
1335
1336    --  References to a discriminant inside the record type declaration can
1337    --  appear either in the subtype_indication to constrain a record or an
1338    --  array, or as part of a larger expression given for the initial value
1339    --  of a component. In both of these cases N appears in the record
1340    --  initialization procedure and needs to be replaced by the formal
1341    --  parameter of the initialization procedure which corresponds to that
1342    --  discriminant.
1343
1344    --  In the example below, references to discriminants D1 and D2 in proc_1
1345    --  are replaced by references to formals with the same name
1346    --  (discriminals)
1347
1348    --  A similar replacement is done for calls to any record initialization
1349    --  procedure for any components that are themselves of a record type.
1350
1351    --  type R (D1, D2 : Integer) is record
1352    --     X : Integer := F * D1;
1353    --     Y : Integer := F * D2;
1354    --  end record;
1355
1356    --  procedure proc_1 (Out_2 : out R; D1 : Integer; D2 : Integer) is
1357    --  begin
1358    --     Out_2.D1 := D1;
1359    --     Out_2.D2 := D2;
1360    --     Out_2.X := F * D1;
1361    --     Out_2.Y := F * D2;
1362    --  end;
1363
1364    function Build_Initialization_Call
1365      (Loc               : Source_Ptr;
1366       Id_Ref            : Node_Id;
1367       Typ               : Entity_Id;
1368       In_Init_Proc      : Boolean := False;
1369       Enclos_Type       : Entity_Id := Empty;
1370       Discr_Map         : Elist_Id := New_Elmt_List;
1371       With_Default_Init : Boolean := False;
1372       Constructor_Ref   : Node_Id := Empty) return List_Id
1373    is
1374       Res            : constant List_Id := New_List;
1375       Arg            : Node_Id;
1376       Args           : List_Id;
1377       Controller_Typ : Entity_Id;
1378       Decl           : Node_Id;
1379       Decls          : List_Id;
1380       Discr          : Entity_Id;
1381       First_Arg      : Node_Id;
1382       Full_Init_Type : Entity_Id;
1383       Full_Type      : Entity_Id := Typ;
1384       Init_Type      : Entity_Id;
1385       Proc           : Entity_Id;
1386
1387    begin
1388       pragma Assert (Constructor_Ref = Empty
1389         or else Is_CPP_Constructor_Call (Constructor_Ref));
1390
1391       if No (Constructor_Ref) then
1392          Proc := Base_Init_Proc (Typ);
1393       else
1394          Proc := Base_Init_Proc (Typ, Entity (Name (Constructor_Ref)));
1395       end if;
1396
1397       Init_Type      := Etype (First_Formal (Proc));
1398       Full_Init_Type := Underlying_Type (Init_Type);
1399
1400       --  Nothing to do if the Init_Proc is null, unless Initialize_Scalars
1401       --  is active (in which case we make the call anyway, since in the
1402       --  actual compiled client it may be non null).
1403       --  Also nothing to do for value types.
1404
1405       if (Is_Null_Init_Proc (Proc) and then not Init_Or_Norm_Scalars)
1406         or else Is_Value_Type (Typ)
1407         or else Is_Value_Type (Component_Type (Typ))
1408       then
1409          return Empty_List;
1410       end if;
1411
1412       --  Go to full view if private type. In the case of successive
1413       --  private derivations, this can require more than one step.
1414
1415       while Is_Private_Type (Full_Type)
1416         and then Present (Full_View (Full_Type))
1417       loop
1418          Full_Type := Full_View (Full_Type);
1419       end loop;
1420
1421       --  If Typ is derived, the procedure is the initialization procedure for
1422       --  the root type. Wrap the argument in an conversion to make it type
1423       --  honest. Actually it isn't quite type honest, because there can be
1424       --  conflicts of views in the private type case. That is why we set
1425       --  Conversion_OK in the conversion node.
1426
1427       if (Is_Record_Type (Typ)
1428            or else Is_Array_Type (Typ)
1429            or else Is_Private_Type (Typ))
1430         and then Init_Type /= Base_Type (Typ)
1431       then
1432          First_Arg := OK_Convert_To (Etype (Init_Type), Id_Ref);
1433          Set_Etype (First_Arg, Init_Type);
1434
1435       else
1436          First_Arg := Id_Ref;
1437       end if;
1438
1439       Args := New_List (Convert_Concurrent (First_Arg, Typ));
1440
1441       --  In the tasks case, add _Master as the value of the _Master parameter
1442       --  and _Chain as the value of the _Chain parameter. At the outer level,
1443       --  these will be variables holding the corresponding values obtained
1444       --  from GNARL. At inner levels, they will be the parameters passed down
1445       --  through the outer routines.
1446
1447       if Has_Task (Full_Type) then
1448          if Restriction_Active (No_Task_Hierarchy) then
1449
1450             --  See comments in System.Tasking.Initialization.Init_RTS
1451             --  for the value 3 (should be rtsfindable constant ???)
1452
1453             Append_To (Args, Make_Integer_Literal (Loc, 3));
1454
1455          else
1456             Append_To (Args, Make_Identifier (Loc, Name_uMaster));
1457          end if;
1458
1459          Append_To (Args, Make_Identifier (Loc, Name_uChain));
1460
1461          --  Ada 2005 (AI-287): In case of default initialized components
1462          --  with tasks, we generate a null string actual parameter.
1463          --  This is just a workaround that must be improved later???
1464
1465          if With_Default_Init then
1466             Append_To (Args,
1467               Make_String_Literal (Loc,
1468                 Strval => ""));
1469
1470          else
1471             Decls :=
1472               Build_Task_Image_Decls (Loc, Id_Ref, Enclos_Type, In_Init_Proc);
1473             Decl  := Last (Decls);
1474
1475             Append_To (Args,
1476               New_Occurrence_Of (Defining_Identifier (Decl), Loc));
1477             Append_List (Decls, Res);
1478          end if;
1479
1480       else
1481          Decls := No_List;
1482          Decl  := Empty;
1483       end if;
1484
1485       --  Add discriminant values if discriminants are present
1486
1487       if Has_Discriminants (Full_Init_Type) then
1488          Discr := First_Discriminant (Full_Init_Type);
1489
1490          while Present (Discr) loop
1491
1492             --  If this is a discriminated concurrent type, the init_proc
1493             --  for the corresponding record is being called. Use that type
1494             --  directly to find the discriminant value, to handle properly
1495             --  intervening renamed discriminants.
1496
1497             declare
1498                T : Entity_Id := Full_Type;
1499
1500             begin
1501                if Is_Protected_Type (T) then
1502                   T := Corresponding_Record_Type (T);
1503
1504                elsif Is_Private_Type (T)
1505                  and then Present (Underlying_Full_View (T))
1506                  and then Is_Protected_Type (Underlying_Full_View (T))
1507                then
1508                   T := Corresponding_Record_Type (Underlying_Full_View (T));
1509                end if;
1510
1511                Arg :=
1512                  Get_Discriminant_Value (
1513                    Discr,
1514                    T,
1515                    Discriminant_Constraint (Full_Type));
1516             end;
1517
1518             if In_Init_Proc then
1519
1520                --  Replace any possible references to the discriminant in the
1521                --  call to the record initialization procedure with references
1522                --  to the appropriate formal parameter.
1523
1524                if Nkind (Arg) = N_Identifier
1525                   and then Ekind (Entity (Arg)) = E_Discriminant
1526                then
1527                   Arg := New_Reference_To (Discriminal (Entity (Arg)), Loc);
1528
1529                --  Case of access discriminants. We replace the reference
1530                --  to the type by a reference to the actual object
1531
1532                elsif Nkind (Arg) = N_Attribute_Reference
1533                  and then Is_Access_Type (Etype (Arg))
1534                  and then Is_Entity_Name (Prefix (Arg))
1535                  and then Is_Type (Entity (Prefix (Arg)))
1536                then
1537                   Arg :=
1538                     Make_Attribute_Reference (Loc,
1539                       Prefix         => New_Copy (Prefix (Id_Ref)),
1540                       Attribute_Name => Name_Unrestricted_Access);
1541
1542                --  Otherwise make a copy of the default expression. Note that
1543                --  we use the current Sloc for this, because we do not want the
1544                --  call to appear to be at the declaration point. Within the
1545                --  expression, replace discriminants with their discriminals.
1546
1547                else
1548                   Arg :=
1549                     New_Copy_Tree (Arg, Map => Discr_Map, New_Sloc => Loc);
1550                end if;
1551
1552             else
1553                if Is_Constrained (Full_Type) then
1554                   Arg := Duplicate_Subexpr_No_Checks (Arg);
1555                else
1556                   --  The constraints come from the discriminant default exps,
1557                   --  they must be reevaluated, so we use New_Copy_Tree but we
1558                   --  ensure the proper Sloc (for any embedded calls).
1559
1560                   Arg := New_Copy_Tree (Arg, New_Sloc => Loc);
1561                end if;
1562             end if;
1563
1564             --  Ada 2005 (AI-287): In case of default initialized components,
1565             --  we need to generate the corresponding selected component node
1566             --  to access the discriminant value. In other cases this is not
1567             --  required because we are inside the init proc and we use the
1568             --  corresponding formal.
1569
1570             if With_Default_Init
1571               and then Nkind (Id_Ref) = N_Selected_Component
1572               and then Nkind (Arg) = N_Identifier
1573             then
1574                Append_To (Args,
1575                  Make_Selected_Component (Loc,
1576                    Prefix => New_Copy_Tree (Prefix (Id_Ref)),
1577                    Selector_Name => Arg));
1578             else
1579                Append_To (Args, Arg);
1580             end if;
1581
1582             Next_Discriminant (Discr);
1583          end loop;
1584       end if;
1585
1586       --  If this is a call to initialize the parent component of a derived
1587       --  tagged type, indicate that the tag should not be set in the parent.
1588
1589       if Is_Tagged_Type (Full_Init_Type)
1590         and then not Is_CPP_Class (Full_Init_Type)
1591         and then Nkind (Id_Ref) = N_Selected_Component
1592         and then Chars (Selector_Name (Id_Ref)) = Name_uParent
1593       then
1594          Append_To (Args, New_Occurrence_Of (Standard_False, Loc));
1595
1596       elsif Present (Constructor_Ref) then
1597          Append_List_To (Args,
1598            New_Copy_List (Parameter_Associations (Constructor_Ref)));
1599       end if;
1600
1601       Append_To (Res,
1602         Make_Procedure_Call_Statement (Loc,
1603           Name => New_Occurrence_Of (Proc, Loc),
1604           Parameter_Associations => Args));
1605
1606       if Needs_Finalization (Typ)
1607         and then Nkind (Id_Ref) = N_Selected_Component
1608       then
1609          if Chars (Selector_Name (Id_Ref)) /= Name_uParent then
1610             Append_List_To (Res,
1611               Make_Init_Call (
1612                 Ref         => New_Copy_Tree (First_Arg),
1613                 Typ         => Typ,
1614                 Flist_Ref   =>
1615                   Find_Final_List (Typ, New_Copy_Tree (First_Arg)),
1616                 With_Attach => Make_Integer_Literal (Loc, 1)));
1617
1618          --  If the enclosing type is an extension with new controlled
1619          --  components, it has his own record controller. If the parent
1620          --  also had a record controller, attach it to the new one.
1621
1622          --  Build_Init_Statements relies on the fact that in this specific
1623          --  case the last statement of the result is the attach call to
1624          --  the controller. If this is changed, it must be synchronized.
1625
1626          elsif Present (Enclos_Type)
1627            and then Has_New_Controlled_Component (Enclos_Type)
1628            and then Has_Controlled_Component (Typ)
1629          then
1630             if Is_Inherently_Limited_Type (Typ) then
1631                Controller_Typ := RTE (RE_Limited_Record_Controller);
1632             else
1633                Controller_Typ := RTE (RE_Record_Controller);
1634             end if;
1635
1636             Append_List_To (Res,
1637               Make_Init_Call (
1638                 Ref       =>
1639                   Make_Selected_Component (Loc,
1640                     Prefix        => New_Copy_Tree (First_Arg),
1641                     Selector_Name => Make_Identifier (Loc, Name_uController)),
1642                 Typ       => Controller_Typ,
1643                 Flist_Ref => Find_Final_List (Typ, New_Copy_Tree (First_Arg)),
1644                 With_Attach => Make_Integer_Literal (Loc, 1)));
1645          end if;
1646       end if;
1647
1648       return Res;
1649
1650    exception
1651       when RE_Not_Available =>
1652          return Empty_List;
1653    end Build_Initialization_Call;
1654
1655    ---------------------------
1656    -- Build_Master_Renaming --
1657    ---------------------------
1658
1659    function Build_Master_Renaming
1660      (N : Node_Id;
1661       T : Entity_Id) return Entity_Id
1662    is
1663       Loc  : constant Source_Ptr := Sloc (N);
1664       M_Id : Entity_Id;
1665       Decl : Node_Id;
1666
1667    begin
1668       --  Nothing to do if there is no task hierarchy
1669
1670       if Restriction_Active (No_Task_Hierarchy) then
1671          return Empty;
1672       end if;
1673
1674       M_Id :=
1675         Make_Defining_Identifier (Loc,
1676           New_External_Name (Chars (T), 'M'));
1677
1678       Decl :=
1679         Make_Object_Renaming_Declaration (Loc,
1680           Defining_Identifier => M_Id,
1681           Subtype_Mark => New_Reference_To (RTE (RE_Master_Id), Loc),
1682           Name => Make_Identifier (Loc, Name_uMaster));
1683       Insert_Before (N, Decl);
1684       Analyze (Decl);
1685       return M_Id;
1686
1687    exception
1688       when RE_Not_Available =>
1689          return Empty;
1690    end Build_Master_Renaming;
1691
1692    ---------------------------
1693    -- Build_Master_Renaming --
1694    ---------------------------
1695
1696    procedure Build_Master_Renaming (N : Node_Id; T : Entity_Id) is
1697       M_Id : Entity_Id;
1698
1699    begin
1700       --  Nothing to do if there is no task hierarchy
1701
1702       if Restriction_Active (No_Task_Hierarchy) then
1703          return;
1704       end if;
1705
1706       M_Id := Build_Master_Renaming (N, T);
1707       Set_Master_Id (T, M_Id);
1708
1709    exception
1710       when RE_Not_Available =>
1711          return;
1712    end Build_Master_Renaming;
1713
1714    ----------------------------
1715    -- Build_Record_Init_Proc --
1716    ----------------------------
1717
1718    procedure Build_Record_Init_Proc (N : Node_Id; Pe : Entity_Id) is
1719       Loc       : Source_Ptr := Sloc (N);
1720       Discr_Map : constant Elist_Id := New_Elmt_List;
1721       Proc_Id   : Entity_Id;
1722       Rec_Type  : Entity_Id;
1723       Set_Tag   : Entity_Id := Empty;
1724
1725       function Build_Assignment (Id : Entity_Id; N : Node_Id) return List_Id;
1726       --  Build a assignment statement node which assigns to record component
1727       --  its default expression if defined. The assignment left hand side is
1728       --  marked Assignment_OK so that initialization of limited private
1729       --  records works correctly, Return also the adjustment call for
1730       --  controlled objects
1731
1732       procedure Build_Discriminant_Assignments (Statement_List : List_Id);
1733       --  If the record has discriminants, adds assignment statements to
1734       --  statement list to initialize the discriminant values from the
1735       --  arguments of the initialization procedure.
1736
1737       function Build_Init_Statements (Comp_List : Node_Id) return List_Id;
1738       --  Build a list representing a sequence of statements which initialize
1739       --  components of the given component list. This may involve building
1740       --  case statements for the variant parts.
1741
1742       function Build_Init_Call_Thru (Parameters : List_Id) return List_Id;
1743       --  Given a non-tagged type-derivation that declares discriminants,
1744       --  such as
1745       --
1746       --  type R (R1, R2 : Integer) is record ... end record;
1747       --
1748       --  type D (D1 : Integer) is new R (1, D1);
1749       --
1750       --  we make the _init_proc of D be
1751       --
1752       --       procedure _init_proc(X : D; D1 : Integer) is
1753       --       begin
1754       --          _init_proc( R(X), 1, D1);
1755       --       end _init_proc;
1756       --
1757       --  This function builds the call statement in this _init_proc.
1758
1759       procedure Build_Init_Procedure;
1760       --  Build the tree corresponding to the procedure specification and body
1761       --  of the initialization procedure (by calling all the preceding
1762       --  auxiliary routines), and install it as the _init TSS.
1763
1764       procedure Build_Offset_To_Top_Functions;
1765       --  Ada 2005 (AI-251): Build the tree corresponding to the procedure spec
1766       --  and body of the Offset_To_Top function that is generated when the
1767       --  parent of a type with discriminants has secondary dispatch tables.
1768
1769       procedure Build_Record_Checks (S : Node_Id; Check_List : List_Id);
1770       --  Add range checks to components of discriminated records. S is a
1771       --  subtype indication of a record component. Check_List is a list
1772       --  to which the check actions are appended.
1773
1774       function Component_Needs_Simple_Initialization
1775         (T : Entity_Id) return Boolean;
1776       --  Determines if a component needs simple initialization, given its type
1777       --  T. This is the same as Needs_Simple_Initialization except for the
1778       --  following difference: the types Tag and Interface_Tag, that are
1779       --  access types which would normally require simple initialization to
1780       --  null, do not require initialization as components, since they are
1781       --  explicitly initialized by other means.
1782
1783       procedure Constrain_Array
1784         (SI         : Node_Id;
1785          Check_List : List_Id);
1786       --  Called from Build_Record_Checks.
1787       --  Apply a list of index constraints to an unconstrained array type.
1788       --  The first parameter is the entity for the resulting subtype.
1789       --  Check_List is a list to which the check actions are appended.
1790
1791       procedure Constrain_Index
1792         (Index      : Node_Id;
1793          S          : Node_Id;
1794          Check_List : List_Id);
1795       --  Process an index constraint in a constrained array declaration.
1796       --  The constraint can be a subtype name, or a range with or without
1797       --  an explicit subtype mark. The index is the corresponding index of the
1798       --  unconstrained array. S is the range expression. Check_List is a list
1799       --  to which the check actions are appended (called from
1800       --  Build_Record_Checks).
1801
1802       function Parent_Subtype_Renaming_Discrims return Boolean;
1803       --  Returns True for base types N that rename discriminants, else False
1804
1805       function Requires_Init_Proc (Rec_Id : Entity_Id) return Boolean;
1806       --  Determines whether a record initialization procedure needs to be
1807       --  generated for the given record type.
1808
1809       ----------------------
1810       -- Build_Assignment --
1811       ----------------------
1812
1813       function Build_Assignment (Id : Entity_Id; N : Node_Id) return List_Id is
1814          Exp  : Node_Id := N;
1815          Lhs  : Node_Id;
1816          Typ  : constant Entity_Id := Underlying_Type (Etype (Id));
1817          Kind : Node_Kind := Nkind (N);
1818          Res  : List_Id;
1819
1820       begin
1821          Loc := Sloc (N);
1822          Lhs :=
1823            Make_Selected_Component (Loc,
1824              Prefix => Make_Identifier (Loc, Name_uInit),
1825              Selector_Name => New_Occurrence_Of (Id, Loc));
1826          Set_Assignment_OK (Lhs);
1827
1828          --  Case of an access attribute applied to the current instance.
1829          --  Replace the reference to the type by a reference to the actual
1830          --  object. (Note that this handles the case of the top level of
1831          --  the expression being given by such an attribute, but does not
1832          --  cover uses nested within an initial value expression. Nested
1833          --  uses are unlikely to occur in practice, but are theoretically
1834          --  possible. It is not clear how to handle them without fully
1835          --  traversing the expression. ???
1836
1837          if Kind = N_Attribute_Reference
1838            and then (Attribute_Name (N) = Name_Unchecked_Access
1839                        or else
1840                      Attribute_Name (N) = Name_Unrestricted_Access)
1841            and then Is_Entity_Name (Prefix (N))
1842            and then Is_Type (Entity (Prefix (N)))
1843            and then Entity (Prefix (N)) = Rec_Type
1844          then
1845             Exp :=
1846               Make_Attribute_Reference (Loc,
1847                 Prefix         => Make_Identifier (Loc, Name_uInit),
1848                 Attribute_Name => Name_Unrestricted_Access);
1849          end if;
1850
1851          --  Take a copy of Exp to ensure that later copies of this component
1852          --  declaration in derived types see the original tree, not a node
1853          --  rewritten during expansion of the init_proc.
1854
1855          Exp := New_Copy_Tree (Exp);
1856
1857          Res := New_List (
1858            Make_Assignment_Statement (Loc,
1859              Name       => Lhs,
1860              Expression => Exp));
1861
1862          Set_No_Ctrl_Actions (First (Res));
1863
1864          --  Adjust the tag if tagged (because of possible view conversions).
1865          --  Suppress the tag adjustment when VM_Target because VM tags are
1866          --  represented implicitly in objects.
1867
1868          if Is_Tagged_Type (Typ) and then VM_Target = No_VM then
1869             Append_To (Res,
1870               Make_Assignment_Statement (Loc,
1871                 Name =>
1872                   Make_Selected_Component (Loc,
1873                     Prefix =>  New_Copy_Tree (Lhs),
1874                     Selector_Name =>
1875                       New_Reference_To (First_Tag_Component (Typ), Loc)),
1876
1877                 Expression =>
1878                   Unchecked_Convert_To (RTE (RE_Tag),
1879                     New_Reference_To
1880                       (Node (First_Elmt (Access_Disp_Table (Typ))), Loc))));
1881          end if;
1882
1883          --  Adjust the component if controlled except if it is an aggregate
1884          --  that will be expanded inline
1885
1886          if Kind = N_Qualified_Expression then
1887             Kind := Nkind (Expression (N));
1888          end if;
1889
1890          if Needs_Finalization (Typ)
1891            and then not (Nkind_In (Kind, N_Aggregate, N_Extension_Aggregate))
1892            and then not Is_Inherently_Limited_Type (Typ)
1893          then
1894             Append_List_To (Res,
1895               Make_Adjust_Call (
1896                Ref          => New_Copy_Tree (Lhs),
1897                Typ          => Etype (Id),
1898                Flist_Ref    =>
1899                  Find_Final_List (Etype (Id), New_Copy_Tree (Lhs)),
1900                With_Attach  => Make_Integer_Literal (Loc, 1)));
1901          end if;
1902
1903          return Res;
1904
1905       exception
1906          when RE_Not_Available =>
1907             return Empty_List;
1908       end Build_Assignment;
1909
1910       ------------------------------------
1911       -- Build_Discriminant_Assignments --
1912       ------------------------------------
1913
1914       procedure Build_Discriminant_Assignments (Statement_List : List_Id) is
1915          D         : Entity_Id;
1916          Is_Tagged : constant Boolean := Is_Tagged_Type (Rec_Type);
1917
1918       begin
1919          if Has_Discriminants (Rec_Type)
1920            and then not Is_Unchecked_Union (Rec_Type)
1921          then
1922             D := First_Discriminant (Rec_Type);
1923
1924             while Present (D) loop
1925                --  Don't generate the assignment for discriminants in derived
1926                --  tagged types if the discriminant is a renaming of some
1927                --  ancestor discriminant. This initialization will be done
1928                --  when initializing the _parent field of the derived record.
1929
1930                if Is_Tagged and then
1931                  Present (Corresponding_Discriminant (D))
1932                then
1933                   null;
1934
1935                else
1936                   Loc := Sloc (D);
1937                   Append_List_To (Statement_List,
1938                     Build_Assignment (D,
1939                       New_Reference_To (Discriminal (D), Loc)));
1940                end if;
1941
1942                Next_Discriminant (D);
1943             end loop;
1944          end if;
1945       end Build_Discriminant_Assignments;
1946
1947       --------------------------
1948       -- Build_Init_Call_Thru --
1949       --------------------------
1950
1951       function Build_Init_Call_Thru (Parameters : List_Id) return List_Id is
1952          Parent_Proc : constant Entity_Id :=
1953                          Base_Init_Proc (Etype (Rec_Type));
1954
1955          Parent_Type : constant Entity_Id :=
1956                          Etype (First_Formal (Parent_Proc));
1957
1958          Uparent_Type : constant Entity_Id :=
1959                           Underlying_Type (Parent_Type);
1960
1961          First_Discr_Param : Node_Id;
1962
1963          Parent_Discr : Entity_Id;
1964          First_Arg    : Node_Id;
1965          Args         : List_Id;
1966          Arg          : Node_Id;
1967          Res          : List_Id;
1968
1969       begin
1970          --  First argument (_Init) is the object to be initialized.
1971          --  ??? not sure where to get a reasonable Loc for First_Arg
1972
1973          First_Arg :=
1974            OK_Convert_To (Parent_Type,
1975              New_Reference_To (Defining_Identifier (First (Parameters)), Loc));
1976
1977          Set_Etype (First_Arg, Parent_Type);
1978
1979          Args := New_List (Convert_Concurrent (First_Arg, Rec_Type));
1980
1981          --  In the tasks case,
1982          --    add _Master as the value of the _Master parameter
1983          --    add _Chain as the value of the _Chain parameter.
1984          --    add _Task_Name as the value of the _Task_Name parameter.
1985          --  At the outer level, these will be variables holding the
1986          --  corresponding values obtained from GNARL or the expander.
1987          --
1988          --  At inner levels, they will be the parameters passed down through
1989          --  the outer routines.
1990
1991          First_Discr_Param := Next (First (Parameters));
1992
1993          if Has_Task (Rec_Type) then
1994             if Restriction_Active (No_Task_Hierarchy) then
1995
1996                --  See comments in System.Tasking.Initialization.Init_RTS
1997                --  for the value 3.
1998
1999                Append_To (Args, Make_Integer_Literal (Loc, 3));
2000             else
2001                Append_To (Args, Make_Identifier (Loc, Name_uMaster));
2002             end if;
2003
2004             Append_To (Args, Make_Identifier (Loc, Name_uChain));
2005             Append_To (Args, Make_Identifier (Loc, Name_uTask_Name));
2006             First_Discr_Param := Next (Next (Next (First_Discr_Param)));
2007          end if;
2008
2009          --  Append discriminant values
2010
2011          if Has_Discriminants (Uparent_Type) then
2012             pragma Assert (not Is_Tagged_Type (Uparent_Type));
2013
2014             Parent_Discr := First_Discriminant (Uparent_Type);
2015             while Present (Parent_Discr) loop
2016
2017                --  Get the initial value for this discriminant
2018                --  ??? needs to be cleaned up to use parent_Discr_Constr
2019                --  directly.
2020
2021                declare
2022                   Discr_Value : Elmt_Id :=
2023                                   First_Elmt
2024                                     (Stored_Constraint (Rec_Type));
2025
2026                   Discr       : Entity_Id :=
2027                                   First_Stored_Discriminant (Uparent_Type);
2028                begin
2029                   while Original_Record_Component (Parent_Discr) /= Discr loop
2030                      Next_Stored_Discriminant (Discr);
2031                      Next_Elmt (Discr_Value);
2032                   end loop;
2033
2034                   Arg := Node (Discr_Value);
2035                end;
2036
2037                --  Append it to the list
2038
2039                if Nkind (Arg) = N_Identifier
2040                   and then Ekind (Entity (Arg)) = E_Discriminant
2041                then
2042                   Append_To (Args,
2043                     New_Reference_To (Discriminal (Entity (Arg)), Loc));
2044
2045                --  Case of access discriminants. We replace the reference
2046                --  to the type by a reference to the actual object.
2047
2048                --  Is above comment right??? Use of New_Copy below seems mighty
2049                --  suspicious ???
2050
2051                else
2052                   Append_To (Args, New_Copy (Arg));
2053                end if;
2054
2055                Next_Discriminant (Parent_Discr);
2056             end loop;
2057          end if;
2058
2059          Res :=
2060             New_List (
2061               Make_Procedure_Call_Statement (Loc,
2062                 Name => New_Occurrence_Of (Parent_Proc, Loc),
2063                 Parameter_Associations => Args));
2064
2065          return Res;
2066       end Build_Init_Call_Thru;
2067
2068       -----------------------------------
2069       -- Build_Offset_To_Top_Functions --
2070       -----------------------------------
2071
2072       procedure Build_Offset_To_Top_Functions is
2073
2074          procedure Build_Offset_To_Top_Function (Iface_Comp : Entity_Id);
2075          --  Generate:
2076          --    function Fxx (O : in Rec_Typ) return Storage_Offset is
2077          --    begin
2078          --       return O.Iface_Comp'Position;
2079          --    end Fxx;
2080
2081          ----------------------------------
2082          -- Build_Offset_To_Top_Function --
2083          ----------------------------------
2084
2085          procedure Build_Offset_To_Top_Function (Iface_Comp : Entity_Id) is
2086             Body_Node : Node_Id;
2087             Func_Id   : Entity_Id;
2088             Spec_Node : Node_Id;
2089
2090          begin
2091             Func_Id :=
2092               Make_Defining_Identifier (Loc,
2093                 Chars => New_Internal_Name ('F'));
2094
2095             Set_DT_Offset_To_Top_Func (Iface_Comp, Func_Id);
2096
2097             --  Generate
2098             --    function Fxx (O : in Rec_Typ) return Storage_Offset;
2099
2100             Spec_Node := New_Node (N_Function_Specification, Loc);
2101             Set_Defining_Unit_Name (Spec_Node, Func_Id);
2102             Set_Parameter_Specifications (Spec_Node, New_List (
2103               Make_Parameter_Specification (Loc,
2104                 Defining_Identifier => Make_Defining_Identifier (Loc, Name_uO),
2105                 In_Present          => True,
2106                 Parameter_Type      => New_Reference_To (Rec_Type, Loc))));
2107             Set_Result_Definition (Spec_Node,
2108               New_Reference_To (RTE (RE_Storage_Offset), Loc));
2109
2110             --  Generate
2111             --    function Fxx (O : in Rec_Typ) return Storage_Offset is
2112             --    begin
2113             --       return O.Iface_Comp'Position;
2114             --    end Fxx;
2115
2116             Body_Node := New_Node (N_Subprogram_Body, Loc);
2117             Set_Specification (Body_Node, Spec_Node);
2118             Set_Declarations (Body_Node, New_List);
2119             Set_Handled_Statement_Sequence (Body_Node,
2120               Make_Handled_Sequence_Of_Statements (Loc,
2121                 Statements => New_List (
2122                   Make_Simple_Return_Statement (Loc,
2123                     Expression =>
2124                       Make_Attribute_Reference (Loc,
2125                         Prefix =>
2126                           Make_Selected_Component (Loc,
2127                             Prefix => Make_Identifier (Loc, Name_uO),
2128                             Selector_Name => New_Reference_To
2129                                                (Iface_Comp, Loc)),
2130                         Attribute_Name => Name_Position)))));
2131
2132             Set_Ekind       (Func_Id, E_Function);
2133             Set_Mechanism   (Func_Id, Default_Mechanism);
2134             Set_Is_Internal (Func_Id, True);
2135
2136             if not Debug_Generated_Code then
2137                Set_Debug_Info_Off (Func_Id);
2138             end if;
2139
2140             Analyze (Body_Node);
2141
2142             Append_Freeze_Action (Rec_Type, Body_Node);
2143          end Build_Offset_To_Top_Function;
2144
2145          --  Local variables
2146
2147          Ifaces_Comp_List : Elist_Id;
2148          Iface_Comp_Elmt  : Elmt_Id;
2149          Iface_Comp       : Node_Id;
2150
2151       --  Start of processing for Build_Offset_To_Top_Functions
2152
2153       begin
2154          --  Offset_To_Top_Functions are built only for derivations of types
2155          --  with discriminants that cover interface types.
2156          --  Nothing is needed either in case of virtual machines, since
2157          --  interfaces are handled directly by the VM.
2158
2159          if not Is_Tagged_Type (Rec_Type)
2160            or else Etype (Rec_Type) = Rec_Type
2161            or else not Has_Discriminants (Etype (Rec_Type))
2162            or else VM_Target /= No_VM
2163          then
2164             return;
2165          end if;
2166
2167          Collect_Interface_Components (Rec_Type, Ifaces_Comp_List);
2168
2169          --  For each interface type with secondary dispatch table we generate
2170          --  the Offset_To_Top_Functions (required to displace the pointer in
2171          --  interface conversions)
2172
2173          Iface_Comp_Elmt := First_Elmt (Ifaces_Comp_List);
2174          while Present (Iface_Comp_Elmt) loop
2175             Iface_Comp := Node (Iface_Comp_Elmt);
2176             pragma Assert (Is_Interface (Related_Type (Iface_Comp)));
2177
2178             --  If the interface is a parent of Rec_Type it shares the primary
2179             --  dispatch table and hence there is no need to build the function
2180
2181             if not Is_Ancestor (Related_Type (Iface_Comp), Rec_Type) then
2182                Build_Offset_To_Top_Function (Iface_Comp);
2183             end if;
2184
2185             Next_Elmt (Iface_Comp_Elmt);
2186          end loop;
2187       end Build_Offset_To_Top_Functions;
2188
2189       --------------------------
2190       -- Build_Init_Procedure --
2191       --------------------------
2192
2193       procedure Build_Init_Procedure is
2194          Body_Node             : Node_Id;
2195          Handled_Stmt_Node     : Node_Id;
2196          Parameters            : List_Id;
2197          Proc_Spec_Node        : Node_Id;
2198          Body_Stmts            : List_Id;
2199          Record_Extension_Node : Node_Id;
2200          Init_Tags_List        : List_Id;
2201
2202       begin
2203          Body_Stmts := New_List;
2204          Body_Node := New_Node (N_Subprogram_Body, Loc);
2205          Set_Ekind (Proc_Id, E_Procedure);
2206
2207          Proc_Spec_Node := New_Node (N_Procedure_Specification, Loc);
2208          Set_Defining_Unit_Name (Proc_Spec_Node, Proc_Id);
2209
2210          Parameters := Init_Formals (Rec_Type);
2211          Append_List_To (Parameters,
2212            Build_Discriminant_Formals (Rec_Type, True));
2213
2214          --  For tagged types, we add a flag to indicate whether the routine
2215          --  is called to initialize a parent component in the init_proc of
2216          --  a type extension. If the flag is false, we do not set the tag
2217          --  because it has been set already in the extension.
2218
2219          if Is_Tagged_Type (Rec_Type)
2220            and then not Is_CPP_Class (Rec_Type)
2221          then
2222             Set_Tag :=
2223               Make_Defining_Identifier (Loc,
2224                 Chars => New_Internal_Name ('P'));
2225
2226             Append_To (Parameters,
2227               Make_Parameter_Specification (Loc,
2228                 Defining_Identifier => Set_Tag,
2229                 Parameter_Type => New_Occurrence_Of (Standard_Boolean, Loc),
2230                 Expression => New_Occurrence_Of (Standard_True, Loc)));
2231          end if;
2232
2233          Set_Parameter_Specifications (Proc_Spec_Node, Parameters);
2234          Set_Specification (Body_Node, Proc_Spec_Node);
2235          Set_Declarations (Body_Node, New_List);
2236
2237          if Parent_Subtype_Renaming_Discrims then
2238
2239             --  N is a Derived_Type_Definition that renames the parameters
2240             --  of the ancestor type. We initialize it by expanding our
2241             --  discriminants and call the ancestor _init_proc with a
2242             --  type-converted object
2243
2244             Append_List_To (Body_Stmts,
2245               Build_Init_Call_Thru (Parameters));
2246
2247          elsif Nkind (Type_Definition (N)) = N_Record_Definition then
2248             Build_Discriminant_Assignments (Body_Stmts);
2249
2250             if not Null_Present (Type_Definition (N)) then
2251                Append_List_To (Body_Stmts,
2252                  Build_Init_Statements (
2253                    Component_List (Type_Definition (N))));
2254             end if;
2255
2256          else
2257             --  N is a Derived_Type_Definition with a possible non-empty
2258             --  extension. The initialization of a type extension consists
2259             --  in the initialization of the components in the extension.
2260
2261             Build_Discriminant_Assignments (Body_Stmts);
2262
2263             Record_Extension_Node :=
2264               Record_Extension_Part (Type_Definition (N));
2265
2266             if not Null_Present (Record_Extension_Node) then
2267                declare
2268                   Stmts : constant List_Id :=
2269                             Build_Init_Statements (
2270                               Component_List (Record_Extension_Node));
2271
2272                begin
2273                   --  The parent field must be initialized first because
2274                   --  the offset of the new discriminants may depend on it
2275
2276                   Prepend_To (Body_Stmts, Remove_Head (Stmts));
2277                   Append_List_To (Body_Stmts, Stmts);
2278                end;
2279             end if;
2280          end if;
2281
2282          --  Add here the assignment to instantiate the Tag
2283
2284          --  The assignment corresponds to the code:
2285
2286          --     _Init._Tag := Typ'Tag;
2287
2288          --  Suppress the tag assignment when VM_Target because VM tags are
2289          --  represented implicitly in objects. It is also suppressed in case
2290          --  of CPP_Class types because in this case the tag is initialized in
2291          --  the C++ side.
2292
2293          if Is_Tagged_Type (Rec_Type)
2294            and then not Is_CPP_Class (Rec_Type)
2295            and then VM_Target = No_VM
2296            and then not No_Run_Time_Mode
2297          then
2298             --  Initialize the primary tag
2299
2300             Init_Tags_List := New_List (
2301               Make_Assignment_Statement (Loc,
2302                 Name =>
2303                   Make_Selected_Component (Loc,
2304                     Prefix => Make_Identifier (Loc, Name_uInit),
2305                     Selector_Name =>
2306                       New_Reference_To (First_Tag_Component (Rec_Type), Loc)),
2307
2308                 Expression =>
2309                   New_Reference_To
2310                     (Node (First_Elmt (Access_Disp_Table (Rec_Type))), Loc)));
2311
2312             --  Ada 2005 (AI-251): Initialize the secondary tags components
2313             --  located at fixed positions (tags whose position depends on
2314             --  variable size components are initialized later ---see below).
2315
2316             if Ada_Version >= Ada_05
2317               and then not Is_Interface (Rec_Type)
2318               and then Has_Interfaces (Rec_Type)
2319             then
2320                Init_Secondary_Tags
2321                  (Typ            => Rec_Type,
2322                   Target         => Make_Identifier (Loc, Name_uInit),
2323                   Stmts_List     => Init_Tags_List,
2324                   Fixed_Comps    => True,
2325                   Variable_Comps => False);
2326             end if;
2327
2328             --  The tag must be inserted before the assignments to other
2329             --  components,  because the initial value of the component may
2330             --  depend on the tag (eg. through a dispatching operation on
2331             --  an access to the current type). The tag assignment is not done
2332             --  when initializing the parent component of a type extension,
2333             --  because in that case the tag is set in the extension.
2334
2335             --  Extensions of imported C++ classes add a final complication,
2336             --  because we cannot inhibit tag setting in the constructor for
2337             --  the parent. In that case we insert the tag initialization
2338             --  after the calls to initialize the parent.
2339
2340             if not Is_CPP_Class (Root_Type (Rec_Type)) then
2341                Prepend_To (Body_Stmts,
2342                  Make_If_Statement (Loc,
2343                    Condition => New_Occurrence_Of (Set_Tag, Loc),
2344                    Then_Statements => Init_Tags_List));
2345
2346             --  CPP_Class derivation: In this case the dispatch table of the
2347             --  parent was built in the C++ side and we copy the table of the
2348             --  parent to initialize the new dispatch table.
2349
2350             else
2351                declare
2352                   Nod : Node_Id;
2353
2354                begin
2355                   --  We assume the first init_proc call is for the parent
2356
2357                   Nod := First (Body_Stmts);
2358                   while Present (Next (Nod))
2359                     and then (Nkind (Nod) /= N_Procedure_Call_Statement
2360                                or else not Is_Init_Proc (Name (Nod)))
2361                   loop
2362                      Nod := Next (Nod);
2363                   end loop;
2364
2365                   --  Generate:
2366                   --     ancestor_constructor (_init.parent);
2367                   --     if Arg2 then
2368                   --        inherit_prim_ops (_init._tag, new_dt, num_prims);
2369                   --        _init._tag := new_dt;
2370                   --     end if;
2371
2372                   Prepend_To (Init_Tags_List,
2373                     Build_Inherit_Prims (Loc,
2374                       Typ          => Rec_Type,
2375                       Old_Tag_Node =>
2376                         Make_Selected_Component (Loc,
2377                           Prefix        =>
2378                             Make_Identifier (Loc,
2379                               Chars => Name_uInit),
2380                           Selector_Name =>
2381                             New_Reference_To
2382                               (First_Tag_Component (Rec_Type), Loc)),
2383                       New_Tag_Node =>
2384                         New_Reference_To
2385                           (Node (First_Elmt (Access_Disp_Table (Rec_Type))),
2386                            Loc),
2387                       Num_Prims    =>
2388                         UI_To_Int
2389                           (DT_Entry_Count (First_Tag_Component (Rec_Type)))));
2390
2391                   Insert_After (Nod,
2392                     Make_If_Statement (Loc,
2393                       Condition => New_Occurrence_Of (Set_Tag, Loc),
2394                       Then_Statements => Init_Tags_List));
2395
2396                   --  We have inherited table of the parent from the CPP side.
2397                   --  Now we fill the slots associated with Ada primitives.
2398                   --  This needs more work to avoid its execution each time
2399                   --  an object is initialized???
2400
2401                   declare
2402                      E    : Elmt_Id;
2403                      Prim : Node_Id;
2404
2405                   begin
2406                      E := First_Elmt (Primitive_Operations (Rec_Type));
2407                      while Present (E) loop
2408                         Prim := Node (E);
2409
2410                         if not Is_Imported (Prim)
2411                           and then Convention (Prim) = Convention_CPP
2412                           and then not Present (Interface_Alias (Prim))
2413                         then
2414                            Append_List_To (Init_Tags_List,
2415                              Register_Primitive (Loc, Prim => Prim));
2416                         end if;
2417
2418                         Next_Elmt (E);
2419                      end loop;
2420                   end;
2421                end;
2422             end if;
2423
2424             --  Ada 2005 (AI-251): Initialize the secondary tag components
2425             --  located at variable positions. We delay the generation of this
2426             --  code until here because the value of the attribute 'Position
2427             --  applied to variable size components of the parent type that
2428             --  depend on discriminants is only safely read at runtime after
2429             --  the parent components have been initialized.
2430
2431             if Ada_Version >= Ada_05
2432               and then not Is_Interface (Rec_Type)
2433               and then Has_Interfaces (Rec_Type)
2434               and then Has_Discriminants (Etype (Rec_Type))
2435               and then Is_Variable_Size_Record (Etype (Rec_Type))
2436             then
2437                Init_Tags_List := New_List;
2438
2439                Init_Secondary_Tags
2440                  (Typ            => Rec_Type,
2441                   Target         => Make_Identifier (Loc, Name_uInit),
2442                   Stmts_List     => Init_Tags_List,
2443                   Fixed_Comps    => False,
2444                   Variable_Comps => True);
2445
2446                if Is_Non_Empty_List (Init_Tags_List) then
2447                   Append_List_To (Body_Stmts, Init_Tags_List);
2448                end if;
2449             end if;
2450          end if;
2451
2452          Handled_Stmt_Node := New_Node (N_Handled_Sequence_Of_Statements, Loc);
2453          Set_Statements (Handled_Stmt_Node, Body_Stmts);
2454          Set_Exception_Handlers (Handled_Stmt_Node, No_List);
2455          Set_Handled_Statement_Sequence (Body_Node, Handled_Stmt_Node);
2456
2457          if not Debug_Generated_Code then
2458             Set_Debug_Info_Off (Proc_Id);
2459          end if;
2460
2461          --  Associate Init_Proc with type, and determine if the procedure
2462          --  is null (happens because of the Initialize_Scalars pragma case,
2463          --  where we have to generate a null procedure in case it is called
2464          --  by a client with Initialize_Scalars set). Such procedures have
2465          --  to be generated, but do not have to be called, so we mark them
2466          --  as null to suppress the call.
2467
2468          Set_Init_Proc (Rec_Type, Proc_Id);
2469
2470          if List_Length (Body_Stmts) = 1
2471            and then Nkind (First (Body_Stmts)) = N_Null_Statement
2472            and then VM_Target /= CLI_Target
2473          then
2474             --  Even though the init proc may be null at this time it might get
2475             --  some stuff added to it later by the CIL backend, so always keep
2476             --  it when VM_Target = CLI_Target.
2477
2478             Set_Is_Null_Init_Proc (Proc_Id);
2479          end if;
2480       end Build_Init_Procedure;
2481
2482       ---------------------------
2483       -- Build_Init_Statements --
2484       ---------------------------
2485
2486       function Build_Init_Statements (Comp_List : Node_Id) return List_Id is
2487          Check_List     : constant List_Id := New_List;
2488          Alt_List       : List_Id;
2489          Decl           : Node_Id;
2490          Id             : Entity_Id;
2491          Names          : Node_Id;
2492          Statement_List : List_Id;
2493          Stmts          : List_Id;
2494          Typ            : Entity_Id;
2495          Variant        : Node_Id;
2496
2497          Per_Object_Constraint_Components : Boolean;
2498
2499          function Has_Access_Constraint (E : Entity_Id) return Boolean;
2500          --  Components with access discriminants that depend on the current
2501          --  instance must be initialized after all other components.
2502
2503          ---------------------------
2504          -- Has_Access_Constraint --
2505          ---------------------------
2506
2507          function Has_Access_Constraint (E : Entity_Id) return Boolean is
2508             Disc : Entity_Id;
2509             T    : constant Entity_Id := Etype (E);
2510
2511          begin
2512             if Has_Per_Object_Constraint (E)
2513               and then Has_Discriminants (T)
2514             then
2515                Disc := First_Discriminant (T);
2516                while Present (Disc) loop
2517                   if Is_Access_Type (Etype (Disc)) then
2518                      return True;
2519                   end if;
2520
2521                   Next_Discriminant (Disc);
2522                end loop;
2523
2524                return False;
2525             else
2526                return False;
2527             end if;
2528          end Has_Access_Constraint;
2529
2530       --  Start of processing for Build_Init_Statements
2531
2532       begin
2533          if Null_Present (Comp_List) then
2534             return New_List (Make_Null_Statement (Loc));
2535          end if;
2536
2537          Statement_List := New_List;
2538
2539          --  Loop through visible declarations of task types and protected
2540          --  types moving any expanded code from the spec to the body of the
2541          --  init procedure.
2542
2543          if Is_Task_Record_Type (Rec_Type)
2544            or else Is_Protected_Record_Type (Rec_Type)
2545          then
2546             declare
2547                Decl : constant Node_Id :=
2548                         Parent (Corresponding_Concurrent_Type (Rec_Type));
2549                Def  : Node_Id;
2550                N1   : Node_Id;
2551                N2   : Node_Id;
2552
2553             begin
2554                if Is_Task_Record_Type (Rec_Type) then
2555                   Def := Task_Definition (Decl);
2556                else
2557                   Def := Protected_Definition (Decl);
2558                end if;
2559
2560                if Present (Def) then
2561                   N1 := First (Visible_Declarations (Def));
2562                   while Present (N1) loop
2563                      N2 := N1;
2564                      N1 := Next (N1);
2565
2566                      if Nkind (N2) in N_Statement_Other_Than_Procedure_Call
2567                        or else Nkind (N2) in N_Raise_xxx_Error
2568                        or else Nkind (N2) = N_Procedure_Call_Statement
2569                      then
2570                         Append_To (Statement_List,
2571                           New_Copy_Tree (N2, New_Scope => Proc_Id));
2572                         Rewrite (N2, Make_Null_Statement (Sloc (N2)));
2573                         Analyze (N2);
2574                      end if;
2575                   end loop;
2576                end if;
2577             end;
2578          end if;
2579
2580          --  Loop through components, skipping pragmas, in 2 steps. The first
2581          --  step deals with regular components. The second step deals with
2582          --  components have per object constraints, and no explicit initia-
2583          --  lization.
2584
2585          Per_Object_Constraint_Components := False;
2586
2587          --  First step : regular components
2588
2589          Decl := First_Non_Pragma (Component_Items (Comp_List));
2590          while Present (Decl) loop
2591             Loc := Sloc (Decl);
2592             Build_Record_Checks
2593               (Subtype_Indication (Component_Definition (Decl)), Check_List);
2594
2595             Id := Defining_Identifier (Decl);
2596             Typ := Etype (Id);
2597
2598             if Has_Access_Constraint (Id)
2599               and then No (Expression (Decl))
2600             then
2601                --  Skip processing for now and ask for a second pass
2602
2603                Per_Object_Constraint_Components := True;
2604
2605             else
2606                --  Case of explicit initialization
2607
2608                if Present (Expression (Decl)) then
2609                   if Is_CPP_Constructor_Call (Expression (Decl)) then
2610                      Stmts :=
2611                        Build_Initialization_Call
2612                          (Loc,
2613                           Make_Selected_Component (Loc,
2614                             Prefix => Make_Identifier (Loc, Name_uInit),
2615                             Selector_Name => New_Occurrence_Of (Id, Loc)),
2616                           Typ,
2617                           In_Init_Proc => True,
2618                           Enclos_Type => Rec_Type,
2619                           Discr_Map => Discr_Map,
2620                           Constructor_Ref => Expression (Decl));
2621                   else
2622                      Stmts := Build_Assignment (Id, Expression (Decl));
2623                   end if;
2624
2625                --  Case of composite component with its own Init_Proc
2626
2627                elsif not Is_Interface (Typ)
2628                  and then Has_Non_Null_Base_Init_Proc (Typ)
2629                then
2630                   Stmts :=
2631                     Build_Initialization_Call
2632                       (Loc,
2633                        Make_Selected_Component (Loc,
2634                          Prefix => Make_Identifier (Loc, Name_uInit),
2635                          Selector_Name => New_Occurrence_Of (Id, Loc)),
2636                        Typ,
2637                        In_Init_Proc => True,
2638                        Enclos_Type => Rec_Type,
2639                        Discr_Map => Discr_Map);
2640
2641                   Clean_Task_Names (Typ, Proc_Id);
2642
2643                --  Case of component needing simple initialization
2644
2645                elsif Component_Needs_Simple_Initialization (Typ) then
2646                   Stmts :=
2647                     Build_Assignment
2648                       (Id, Get_Simple_Init_Val (Typ, N, Esize (Id)));
2649
2650                --  Nothing needed for this case
2651
2652                else
2653                   Stmts := No_List;
2654                end if;
2655
2656                if Present (Check_List) then
2657                   Append_List_To (Statement_List, Check_List);
2658                end if;
2659
2660                if Present (Stmts) then
2661
2662                   --  Add the initialization of the record controller before
2663                   --  the _Parent field is attached to it when the attachment
2664                   --  can occur. It does not work to simply initialize the
2665                   --  controller first: it must be initialized after the parent
2666                   --  if the parent holds discriminants that can be used to
2667                   --  compute the offset of the controller. We assume here that
2668                   --  the last statement of the initialization call is the
2669                   --  attachment of the parent (see Build_Initialization_Call)
2670
2671                   if Chars (Id) = Name_uController
2672                     and then Rec_Type /= Etype (Rec_Type)
2673                     and then Has_Controlled_Component (Etype (Rec_Type))
2674                     and then Has_New_Controlled_Component (Rec_Type)
2675                     and then Present (Last (Statement_List))
2676                   then
2677                      Insert_List_Before (Last (Statement_List), Stmts);
2678                   else
2679                      Append_List_To (Statement_List, Stmts);
2680                   end if;
2681                end if;
2682             end if;
2683
2684             Next_Non_Pragma (Decl);
2685          end loop;
2686
2687          if Per_Object_Constraint_Components then
2688
2689             --  Second pass: components with per-object constraints
2690
2691             Decl := First_Non_Pragma (Component_Items (Comp_List));
2692             while Present (Decl) loop
2693                Loc := Sloc (Decl);
2694                Id := Defining_Identifier (Decl);
2695                Typ := Etype (Id);
2696
2697                if Has_Access_Constraint (Id)
2698                  and then No (Expression (Decl))
2699                then
2700                   if Has_Non_Null_Base_Init_Proc (Typ) then
2701                      Append_List_To (Statement_List,
2702                        Build_Initialization_Call (Loc,
2703                          Make_Selected_Component (Loc,
2704                            Prefix        => Make_Identifier (Loc, Name_uInit),
2705                            Selector_Name => New_Occurrence_Of (Id, Loc)),
2706                          Typ,
2707                          In_Init_Proc => True,
2708                          Enclos_Type  => Rec_Type,
2709                          Discr_Map    => Discr_Map));
2710
2711                      Clean_Task_Names (Typ, Proc_Id);
2712
2713                   elsif Component_Needs_Simple_Initialization (Typ) then
2714                      Append_List_To (Statement_List,
2715                        Build_Assignment
2716                          (Id, Get_Simple_Init_Val (Typ, N, Esize (Id))));
2717                   end if;
2718                end if;
2719
2720                Next_Non_Pragma (Decl);
2721             end loop;
2722          end if;
2723
2724          --  Process the variant part
2725
2726          if Present (Variant_Part (Comp_List)) then
2727             Alt_List := New_List;
2728             Variant := First_Non_Pragma (Variants (Variant_Part (Comp_List)));
2729             while Present (Variant) loop
2730                Loc := Sloc (Variant);
2731                Append_To (Alt_List,
2732                  Make_Case_Statement_Alternative (Loc,
2733                    Discrete_Choices =>
2734                      New_Copy_List (Discrete_Choices (Variant)),
2735                    Statements =>
2736                      Build_Init_Statements (Component_List (Variant))));
2737                Next_Non_Pragma (Variant);
2738             end loop;
2739
2740             --  The expression of the case statement which is a reference
2741             --  to one of the discriminants is replaced by the appropriate
2742             --  formal parameter of the initialization procedure.
2743
2744             Append_To (Statement_List,
2745               Make_Case_Statement (Loc,
2746                 Expression =>
2747                   New_Reference_To (Discriminal (
2748                     Entity (Name (Variant_Part (Comp_List)))), Loc),
2749                 Alternatives => Alt_List));
2750          end if;
2751
2752          --  For a task record type, add the task create call and calls
2753          --  to bind any interrupt (signal) entries.
2754
2755          if Is_Task_Record_Type (Rec_Type) then
2756
2757             --  In the case of the restricted run time the ATCB has already
2758             --  been preallocated.
2759
2760             if Restricted_Profile then
2761                Append_To (Statement_List,
2762                  Make_Assignment_Statement (Loc,
2763                    Name => Make_Selected_Component (Loc,
2764                      Prefix => Make_Identifier (Loc, Name_uInit),
2765                      Selector_Name => Make_Identifier (Loc, Name_uTask_Id)),
2766                    Expression => Make_Attribute_Reference (Loc,
2767                      Prefix =>
2768                        Make_Selected_Component (Loc,
2769                          Prefix => Make_Identifier (Loc, Name_uInit),
2770                          Selector_Name =>
2771                            Make_Identifier (Loc, Name_uATCB)),
2772                      Attribute_Name => Name_Unchecked_Access)));
2773             end if;
2774
2775             Append_To (Statement_List, Make_Task_Create_Call (Rec_Type));
2776
2777             --  Generate the statements which map a string entry name to a
2778             --  task entry index. Note that the task may not have entries.
2779
2780             if Entry_Names_OK then
2781                Names := Build_Entry_Names (Rec_Type);
2782
2783                if Present (Names) then
2784                   Append_To (Statement_List, Names);
2785                end if;
2786             end if;
2787
2788             declare
2789                Task_Type : constant Entity_Id :=
2790                              Corresponding_Concurrent_Type (Rec_Type);
2791                Task_Decl : constant Node_Id := Parent (Task_Type);
2792                Task_Def  : constant Node_Id := Task_Definition (Task_Decl);
2793                Vis_Decl  : Node_Id;
2794                Ent       : Entity_Id;
2795
2796             begin
2797                if Present (Task_Def) then
2798                   Vis_Decl := First (Visible_Declarations (Task_Def));
2799                   while Present (Vis_Decl) loop
2800                      Loc := Sloc (Vis_Decl);
2801
2802                      if Nkind (Vis_Decl) = N_Attribute_Definition_Clause then
2803                         if Get_Attribute_Id (Chars (Vis_Decl)) =
2804                                                        Attribute_Address
2805                         then
2806                            Ent := Entity (Name (Vis_Decl));
2807
2808                            if Ekind (Ent) = E_Entry then
2809                               Append_To (Statement_List,
2810                                 Make_Procedure_Call_Statement (Loc,
2811                                   Name => New_Reference_To (
2812                                     RTE (RE_Bind_Interrupt_To_Entry), Loc),
2813                                   Parameter_Associations => New_List (
2814                                     Make_Selected_Component (Loc,
2815                                       Prefix =>
2816                                         Make_Identifier (Loc, Name_uInit),
2817                                       Selector_Name =>
2818                                         Make_Identifier (Loc, Name_uTask_Id)),
2819                                     Entry_Index_Expression (
2820                                       Loc, Ent, Empty, Task_Type),
2821                                     Expression (Vis_Decl))));
2822                            end if;
2823                         end if;
2824                      end if;
2825
2826                      Next (Vis_Decl);
2827                   end loop;
2828                end if;
2829             end;
2830          end if;
2831
2832          --  For a protected type, add statements generated by
2833          --  Make_Initialize_Protection.
2834
2835          if Is_Protected_Record_Type (Rec_Type) then
2836             Append_List_To (Statement_List,
2837               Make_Initialize_Protection (Rec_Type));
2838
2839             --  Generate the statements which map a string entry name to a
2840             --  protected entry index. Note that the protected type may not
2841             --  have entries.
2842
2843             if Entry_Names_OK then
2844                Names := Build_Entry_Names (Rec_Type);
2845
2846                if Present (Names) then
2847                   Append_To (Statement_List, Names);
2848                end if;
2849             end if;
2850          end if;
2851
2852          --  If no initializations when generated for component declarations
2853          --  corresponding to this Statement_List, append a null statement
2854          --  to the Statement_List to make it a valid Ada tree.
2855
2856          if Is_Empty_List (Statement_List) then
2857             Append (New_Node (N_Null_Statement, Loc), Statement_List);
2858          end if;
2859
2860          return Statement_List;
2861
2862       exception
2863          when RE_Not_Available =>
2864          return Empty_List;
2865       end Build_Init_Statements;
2866
2867       -------------------------
2868       -- Build_Record_Checks --
2869       -------------------------
2870
2871       procedure Build_Record_Checks (S : Node_Id; Check_List : List_Id) is
2872          Subtype_Mark_Id : Entity_Id;
2873
2874       begin
2875          if Nkind (S) = N_Subtype_Indication then
2876             Find_Type (Subtype_Mark (S));
2877             Subtype_Mark_Id := Entity (Subtype_Mark (S));
2878
2879             --  Remaining processing depends on type
2880
2881             case Ekind (Subtype_Mark_Id) is
2882
2883                when Array_Kind =>
2884                   Constrain_Array (S, Check_List);
2885
2886                when others =>
2887                   null;
2888             end case;
2889          end if;
2890       end Build_Record_Checks;
2891
2892       -------------------------------------------
2893       -- Component_Needs_Simple_Initialization --
2894       -------------------------------------------
2895
2896       function Component_Needs_Simple_Initialization
2897         (T : Entity_Id) return Boolean
2898       is
2899       begin
2900          return
2901            Needs_Simple_Initialization (T)
2902              and then not Is_RTE (T, RE_Tag)
2903
2904                --  Ada 2005 (AI-251): Check also the tag of abstract interfaces
2905
2906              and then not Is_RTE (T, RE_Interface_Tag);
2907       end Component_Needs_Simple_Initialization;
2908
2909       ---------------------
2910       -- Constrain_Array --
2911       ---------------------
2912
2913       procedure Constrain_Array
2914         (SI          : Node_Id;
2915          Check_List  : List_Id)
2916       is
2917          C                     : constant Node_Id := Constraint (SI);
2918          Number_Of_Constraints : Nat := 0;
2919          Index                 : Node_Id;
2920          S, T                  : Entity_Id;
2921
2922       begin
2923          T := Entity (Subtype_Mark (SI));
2924
2925          if Ekind (T) in Access_Kind then
2926             T := Designated_Type (T);
2927          end if;
2928
2929          S := First (Constraints (C));
2930
2931          while Present (S) loop
2932             Number_Of_Constraints := Number_Of_Constraints + 1;
2933             Next (S);
2934          end loop;
2935
2936          --  In either case, the index constraint must provide a discrete
2937          --  range for each index of the array type and the type of each
2938          --  discrete range must be the same as that of the corresponding
2939          --  index. (RM 3.6.1)
2940
2941          S := First (Constraints (C));
2942          Index := First_Index (T);
2943          Analyze (Index);
2944
2945          --  Apply constraints to each index type
2946
2947          for J in 1 .. Number_Of_Constraints loop
2948             Constrain_Index (Index, S, Check_List);
2949             Next (Index);
2950             Next (S);
2951          end loop;
2952
2953       end Constrain_Array;
2954
2955       ---------------------
2956       -- Constrain_Index --
2957       ---------------------
2958
2959       procedure Constrain_Index
2960         (Index        : Node_Id;
2961          S            : Node_Id;
2962          Check_List   : List_Id)
2963       is
2964          T : constant Entity_Id := Etype (Index);
2965
2966       begin
2967          if Nkind (S) = N_Range then
2968             Process_Range_Expr_In_Decl (S, T, Check_List);
2969          end if;
2970       end Constrain_Index;
2971
2972       --------------------------------------
2973       -- Parent_Subtype_Renaming_Discrims --
2974       --------------------------------------
2975
2976       function Parent_Subtype_Renaming_Discrims return Boolean is
2977          De : Entity_Id;
2978          Dp : Entity_Id;
2979
2980       begin
2981          if Base_Type (Pe) /= Pe then
2982             return False;
2983          end if;
2984
2985          if Etype (Pe) = Pe
2986            or else not Has_Discriminants (Pe)
2987            or else Is_Constrained (Pe)
2988            or else Is_Tagged_Type (Pe)
2989          then
2990             return False;
2991          end if;
2992
2993          --  If there are no explicit stored discriminants we have inherited
2994          --  the root type discriminants so far, so no renamings occurred.
2995
2996          if First_Discriminant (Pe) = First_Stored_Discriminant (Pe) then
2997             return False;
2998          end if;
2999
3000          --  Check if we have done some trivial renaming of the parent
3001          --  discriminants, i.e. something like
3002          --
3003          --    type DT (X1,X2: int) is new PT (X1,X2);
3004
3005          De := First_Discriminant (Pe);
3006          Dp := First_Discriminant (Etype (Pe));
3007
3008          while Present (De) loop
3009             pragma Assert (Present (Dp));
3010
3011             if Corresponding_Discriminant (De) /= Dp then
3012                return True;
3013             end if;
3014
3015             Next_Discriminant (De);
3016             Next_Discriminant (Dp);
3017          end loop;
3018
3019          return Present (Dp);
3020       end Parent_Subtype_Renaming_Discrims;
3021
3022       ------------------------
3023       -- Requires_Init_Proc --
3024       ------------------------
3025
3026       function Requires_Init_Proc (Rec_Id : Entity_Id) return Boolean is
3027          Comp_Decl : Node_Id;
3028          Id        : Entity_Id;
3029          Typ       : Entity_Id;
3030
3031       begin
3032          --  Definitely do not need one if specifically suppressed
3033
3034          if Suppress_Init_Proc (Rec_Id) then
3035             return False;
3036          end if;
3037
3038          --  If it is a type derived from a type with unknown discriminants,
3039          --  we cannot build an initialization procedure for it.
3040
3041          if Has_Unknown_Discriminants (Rec_Id)
3042            or else Has_Unknown_Discriminants (Etype (Rec_Id))
3043          then
3044             return False;
3045          end if;
3046
3047          --  Otherwise we need to generate an initialization procedure if
3048          --  Is_CPP_Class is False and at least one of the following applies:
3049
3050          --  1. Discriminants are present, since they need to be initialized
3051          --     with the appropriate discriminant constraint expressions.
3052          --     However, the discriminant of an unchecked union does not
3053          --     count, since the discriminant is not present.
3054
3055          --  2. The type is a tagged type, since the implicit Tag component
3056          --     needs to be initialized with a pointer to the dispatch table.
3057
3058          --  3. The type contains tasks
3059
3060          --  4. One or more components has an initial value
3061
3062          --  5. One or more components is for a type which itself requires
3063          --     an initialization procedure.
3064
3065          --  6. One or more components is a type that requires simple
3066          --     initialization (see Needs_Simple_Initialization), except
3067          --     that types Tag and Interface_Tag are excluded, since fields
3068          --     of these types are initialized by other means.
3069
3070          --  7. The type is the record type built for a task type (since at
3071          --     the very least, Create_Task must be called)
3072
3073          --  8. The type is the record type built for a protected type (since
3074          --     at least Initialize_Protection must be called)
3075
3076          --  9. The type is marked as a public entity. The reason we add this
3077          --     case (even if none of the above apply) is to properly handle
3078          --     Initialize_Scalars. If a package is compiled without an IS
3079          --     pragma, and the client is compiled with an IS pragma, then
3080          --     the client will think an initialization procedure is present
3081          --     and call it, when in fact no such procedure is required, but
3082          --     since the call is generated, there had better be a routine
3083          --     at the other end of the call, even if it does nothing!)
3084
3085          --  Note: the reason we exclude the CPP_Class case is because in this
3086          --  case the initialization is performed in the C++ side.
3087
3088          if Is_CPP_Class (Rec_Id) then
3089             return False;
3090
3091          elsif Is_Interface (Rec_Id) then
3092             return False;
3093
3094          elsif (Has_Discriminants (Rec_Id)
3095                   and then not Is_Unchecked_Union (Rec_Id))
3096            or else Is_Tagged_Type (Rec_Id)
3097            or else Is_Concurrent_Record_Type (Rec_Id)
3098            or else Has_Task (Rec_Id)
3099          then
3100             return True;
3101          end if;
3102
3103          Id := First_Component (Rec_Id);
3104          while Present (Id) loop
3105             Comp_Decl := Parent (Id);
3106             Typ := Etype (Id);
3107
3108             if Present (Expression (Comp_Decl))
3109               or else Has_Non_Null_Base_Init_Proc (Typ)
3110               or else Component_Needs_Simple_Initialization (Typ)
3111             then
3112                return True;
3113             end if;
3114
3115             Next_Component (Id);
3116          end loop;
3117
3118          --  As explained above, a record initialization procedure is needed
3119          --  for public types in case Initialize_Scalars applies to a client.
3120          --  However, such a procedure is not needed in the case where either
3121          --  of restrictions No_Initialize_Scalars or No_Default_Initialization
3122          --  applies. No_Initialize_Scalars excludes the possibility of using
3123          --  Initialize_Scalars in any partition, and No_Default_Initialization
3124          --  implies that no initialization should ever be done for objects of
3125          --  the type, so is incompatible with Initialize_Scalars.
3126
3127          if not Restriction_Active (No_Initialize_Scalars)
3128            and then not Restriction_Active (No_Default_Initialization)
3129            and then Is_Public (Rec_Id)
3130          then
3131             return True;
3132          end if;
3133
3134          return False;
3135       end Requires_Init_Proc;
3136
3137    --  Start of processing for Build_Record_Init_Proc
3138
3139    begin
3140       --  Check for value type, which means no initialization required
3141
3142       Rec_Type := Defining_Identifier (N);
3143
3144       if Is_Value_Type (Rec_Type) then
3145          return;
3146       end if;
3147
3148       --  This may be full declaration of a private type, in which case
3149       --  the visible entity is a record, and the private entity has been
3150       --  exchanged with it in the private part of the current package.
3151       --  The initialization procedure is built for the record type, which
3152       --  is retrievable from the private entity.
3153
3154       if Is_Incomplete_Or_Private_Type (Rec_Type) then
3155          Rec_Type := Underlying_Type (Rec_Type);
3156       end if;
3157
3158       --  If there are discriminants, build the discriminant map to replace
3159       --  discriminants by their discriminals in complex bound expressions.
3160       --  These only arise for the corresponding records of synchronized types.
3161
3162       if Is_Concurrent_Record_Type (Rec_Type)
3163         and then Has_Discriminants (Rec_Type)
3164       then
3165          declare
3166             Disc : Entity_Id;
3167          begin
3168             Disc := First_Discriminant (Rec_Type);
3169             while Present (Disc) loop
3170                Append_Elmt (Disc, Discr_Map);
3171                Append_Elmt (Discriminal (Disc), Discr_Map);
3172                Next_Discriminant (Disc);
3173             end loop;
3174          end;
3175       end if;
3176
3177       --  Derived types that have no type extension can use the initialization
3178       --  procedure of their parent and do not need a procedure of their own.
3179       --  This is only correct if there are no representation clauses for the
3180       --  type or its parent, and if the parent has in fact been frozen so
3181       --  that its initialization procedure exists.
3182
3183       if Is_Derived_Type (Rec_Type)
3184         and then not Is_Tagged_Type (Rec_Type)
3185         and then not Is_Unchecked_Union (Rec_Type)
3186         and then not Has_New_Non_Standard_Rep (Rec_Type)
3187         and then not Parent_Subtype_Renaming_Discrims
3188         and then Has_Non_Null_Base_Init_Proc (Etype (Rec_Type))
3189       then
3190          Copy_TSS (Base_Init_Proc (Etype (Rec_Type)), Rec_Type);
3191
3192       --  Otherwise if we need an initialization procedure, then build one,
3193       --  mark it as public and inlinable and as having a completion.
3194
3195       elsif Requires_Init_Proc (Rec_Type)
3196         or else Is_Unchecked_Union (Rec_Type)
3197       then
3198          Proc_Id :=
3199            Make_Defining_Identifier (Loc,
3200              Chars => Make_Init_Proc_Name (Rec_Type));
3201
3202          --  If No_Default_Initialization restriction is active, then we don't
3203          --  want to build an init_proc, but we need to mark that an init_proc
3204          --  would be needed if this restriction was not active (so that we can
3205          --  detect attempts to call it), so set a dummy init_proc in place.
3206
3207          if Restriction_Active (No_Default_Initialization) then
3208             Set_Init_Proc (Rec_Type, Proc_Id);
3209             return;
3210          end if;
3211
3212          Build_Offset_To_Top_Functions;
3213          Build_Init_Procedure;
3214          Set_Is_Public (Proc_Id, Is_Public (Pe));
3215
3216          --  The initialization of protected records is not worth inlining.
3217          --  In addition, when compiled for another unit for inlining purposes,
3218          --  it may make reference to entities that have not been elaborated
3219          --  yet. The initialization of controlled records contains a nested
3220          --  clean-up procedure that makes it impractical to inline as well,
3221          --  and leads to undefined symbols if inlined in a different unit.
3222          --  Similar considerations apply to task types.
3223
3224          if not Is_Concurrent_Type (Rec_Type)
3225            and then not Has_Task (Rec_Type)
3226            and then not Needs_Finalization (Rec_Type)
3227          then
3228             Set_Is_Inlined  (Proc_Id);
3229          end if;
3230
3231          Set_Is_Internal    (Proc_Id);
3232          Set_Has_Completion (Proc_Id);
3233
3234          if not Debug_Generated_Code then
3235             Set_Debug_Info_Off (Proc_Id);
3236          end if;
3237
3238          declare
3239             Agg : constant Node_Id :=
3240                     Build_Equivalent_Record_Aggregate (Rec_Type);
3241
3242             procedure Collect_Itypes (Comp : Node_Id);
3243             --  Generate references to itypes in the aggregate, because
3244             --  the first use of the aggregate may be in a nested scope.
3245
3246             --------------------
3247             -- Collect_Itypes --
3248             --------------------
3249
3250             procedure Collect_Itypes (Comp : Node_Id) is
3251                Ref      : Node_Id;
3252                Sub_Aggr : Node_Id;
3253                Typ      : constant Entity_Id := Etype (Comp);
3254
3255             begin
3256                if Is_Array_Type (Typ)
3257                  and then Is_Itype (Typ)
3258                then
3259                   Ref := Make_Itype_Reference (Loc);
3260                   Set_Itype (Ref, Typ);
3261                   Append_Freeze_Action (Rec_Type, Ref);
3262
3263                   Ref := Make_Itype_Reference (Loc);
3264                   Set_Itype (Ref, Etype (First_Index (Typ)));
3265                   Append_Freeze_Action (Rec_Type, Ref);
3266
3267                   Sub_Aggr := First (Expressions (Comp));
3268
3269                   --  Recurse on nested arrays
3270
3271                   while Present (Sub_Aggr) loop
3272                      Collect_Itypes (Sub_Aggr);
3273                      Next (Sub_Aggr);
3274                   end loop;
3275                end if;
3276             end Collect_Itypes;
3277
3278          begin
3279             --  If there is a static initialization aggregate for the type,
3280             --  generate itype references for the types of its (sub)components,
3281             --  to prevent out-of-scope errors in the resulting tree.
3282             --  The aggregate may have been rewritten as a Raise node, in which
3283             --  case there are no relevant itypes.
3284
3285             if Present (Agg)
3286               and then Nkind (Agg) = N_Aggregate
3287             then
3288                Set_Static_Initialization (Proc_Id, Agg);
3289
3290                declare
3291                   Comp  : Node_Id;
3292                begin
3293                   Comp := First (Component_Associations (Agg));
3294                   while Present (Comp) loop
3295                      Collect_Itypes (Expression (Comp));
3296                      Next (Comp);
3297                   end loop;
3298                end;
3299             end if;
3300          end;
3301       end if;
3302    end Build_Record_Init_Proc;
3303
3304    ----------------------------
3305    -- Build_Slice_Assignment --
3306    ----------------------------
3307
3308    --  Generates the following subprogram:
3309
3310    --    procedure Assign
3311    --     (Source,  Target    : Array_Type,
3312    --      Left_Lo, Left_Hi   : Index;
3313    --      Right_Lo, Right_Hi : Index;
3314    --      Rev                : Boolean)
3315    --    is
3316    --       Li1 : Index;
3317    --       Ri1 : Index;
3318
3319    --    begin
3320
3321    --       if Left_Hi < Left_Lo then
3322    --          return;
3323    --       end if;
3324
3325    --       if Rev  then
3326    --          Li1 := Left_Hi;
3327    --          Ri1 := Right_Hi;
3328    --       else
3329    --          Li1 := Left_Lo;
3330    --          Ri1 := Right_Lo;
3331    --       end if;
3332
3333    --       loop
3334    --          Target (Li1) := Source (Ri1);
3335
3336    --          if Rev then
3337    --             exit when Li1 = Left_Lo;
3338    --             Li1 := Index'pred (Li1);
3339    --             Ri1 := Index'pred (Ri1);
3340    --          else
3341    --             exit when Li1 = Left_Hi;
3342    --             Li1 := Index'succ (Li1);
3343    --             Ri1 := Index'succ (Ri1);
3344    --          end if;
3345    --       end loop;
3346    --    end Assign;
3347
3348    procedure Build_Slice_Assignment (Typ : Entity_Id) is
3349       Loc   : constant Source_Ptr := Sloc (Typ);
3350       Index : constant Entity_Id  := Base_Type (Etype (First_Index (Typ)));
3351
3352       --  Build formal parameters of procedure
3353
3354       Larray   : constant Entity_Id :=
3355                    Make_Defining_Identifier
3356                      (Loc, Chars => New_Internal_Name ('A'));
3357       Rarray   : constant Entity_Id :=
3358                    Make_Defining_Identifier
3359                      (Loc, Chars => New_Internal_Name ('R'));
3360       Left_Lo  : constant Entity_Id :=
3361                    Make_Defining_Identifier
3362                      (Loc, Chars => New_Internal_Name ('L'));
3363       Left_Hi  : constant Entity_Id :=
3364                    Make_Defining_Identifier
3365                      (Loc, Chars => New_Internal_Name ('L'));
3366       Right_Lo : constant Entity_Id :=
3367                    Make_Defining_Identifier
3368                      (Loc, Chars => New_Internal_Name ('R'));
3369       Right_Hi : constant Entity_Id :=
3370                    Make_Defining_Identifier
3371                      (Loc, Chars => New_Internal_Name ('R'));
3372       Rev      : constant Entity_Id :=
3373                    Make_Defining_Identifier
3374                      (Loc, Chars => New_Internal_Name ('D'));
3375       Proc_Name : constant Entity_Id :=
3376                     Make_Defining_Identifier (Loc,
3377                       Chars => Make_TSS_Name (Typ, TSS_Slice_Assign));
3378
3379       Lnn : constant Entity_Id :=
3380               Make_Defining_Identifier (Loc, New_Internal_Name ('L'));
3381       Rnn : constant Entity_Id :=
3382               Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
3383       --  Subscripts for left and right sides
3384
3385       Decls : List_Id;
3386       Loops : Node_Id;
3387       Stats : List_Id;
3388
3389    begin
3390       --  Build declarations for indices
3391
3392       Decls := New_List;
3393
3394       Append_To (Decls,
3395          Make_Object_Declaration (Loc,
3396            Defining_Identifier => Lnn,
3397            Object_Definition  =>
3398              New_Occurrence_Of (Index, Loc)));
3399
3400       Append_To (Decls,
3401         Make_Object_Declaration (Loc,
3402           Defining_Identifier => Rnn,
3403           Object_Definition  =>
3404             New_Occurrence_Of (Index, Loc)));
3405
3406       Stats := New_List;
3407
3408       --  Build test for empty slice case
3409
3410       Append_To (Stats,
3411         Make_If_Statement (Loc,
3412           Condition =>
3413              Make_Op_Lt (Loc,
3414                Left_Opnd  => New_Occurrence_Of (Left_Hi, Loc),
3415                Right_Opnd => New_Occurrence_Of (Left_Lo, Loc)),
3416           Then_Statements => New_List (Make_Simple_Return_Statement (Loc))));
3417
3418       --  Build initializations for indices
3419
3420       declare
3421          F_Init : constant List_Id := New_List;
3422          B_Init : constant List_Id := New_List;
3423
3424       begin
3425          Append_To (F_Init,
3426            Make_Assignment_Statement (Loc,
3427              Name => New_Occurrence_Of (Lnn, Loc),
3428              Expression => New_Occurrence_Of (Left_Lo, Loc)));
3429
3430          Append_To (F_Init,
3431            Make_Assignment_Statement (Loc,
3432              Name => New_Occurrence_Of (Rnn, Loc),
3433              Expression => New_Occurrence_Of (Right_Lo, Loc)));
3434
3435          Append_To (B_Init,
3436            Make_Assignment_Statement (Loc,
3437              Name => New_Occurrence_Of (Lnn, Loc),
3438              Expression => New_Occurrence_Of (Left_Hi, Loc)));
3439
3440          Append_To (B_Init,
3441            Make_Assignment_Statement (Loc,
3442              Name => New_Occurrence_Of (Rnn, Loc),
3443              Expression => New_Occurrence_Of (Right_Hi, Loc)));
3444
3445          Append_To (Stats,
3446            Make_If_Statement (Loc,
3447              Condition => New_Occurrence_Of (Rev, Loc),
3448              Then_Statements => B_Init,
3449              Else_Statements => F_Init));
3450       end;
3451
3452       --  Now construct the assignment statement
3453
3454       Loops :=
3455         Make_Loop_Statement (Loc,
3456           Statements => New_List (
3457             Make_Assignment_Statement (Loc,
3458               Name =>
3459                 Make_Indexed_Component (Loc,
3460                   Prefix => New_Occurrence_Of (Larray, Loc),
3461                   Expressions => New_List (New_Occurrence_Of (Lnn, Loc))),
3462               Expression =>
3463                 Make_Indexed_Component (Loc,
3464                   Prefix => New_Occurrence_Of (Rarray, Loc),
3465                   Expressions => New_List (New_Occurrence_Of (Rnn, Loc))))),
3466           End_Label  => Empty);
3467
3468       --  Build the exit condition and increment/decrement statements
3469
3470       declare
3471          F_Ass : constant List_Id := New_List;
3472          B_Ass : constant List_Id := New_List;
3473
3474       begin
3475          Append_To (F_Ass,
3476            Make_Exit_Statement (Loc,
3477              Condition =>
3478                Make_Op_Eq (Loc,
3479                  Left_Opnd  => New_Occurrence_Of (Lnn, Loc),
3480                  Right_Opnd => New_Occurrence_Of (Left_Hi, Loc))));
3481
3482          Append_To (F_Ass,
3483            Make_Assignment_Statement (Loc,
3484              Name => New_Occurrence_Of (Lnn, Loc),
3485              Expression =>
3486                Make_Attribute_Reference (Loc,
3487                  Prefix =>
3488                    New_Occurrence_Of (Index, Loc),
3489                  Attribute_Name => Name_Succ,
3490                  Expressions => New_List (
3491                    New_Occurrence_Of (Lnn, Loc)))));
3492
3493          Append_To (F_Ass,
3494            Make_Assignment_Statement (Loc,
3495              Name => New_Occurrence_Of (Rnn, Loc),
3496              Expression =>
3497                Make_Attribute_Reference (Loc,
3498                  Prefix =>
3499                    New_Occurrence_Of (Index, Loc),
3500                  Attribute_Name => Name_Succ,
3501                  Expressions => New_List (
3502                    New_Occurrence_Of (Rnn, Loc)))));
3503
3504          Append_To (B_Ass,
3505            Make_Exit_Statement (Loc,
3506              Condition =>
3507                Make_Op_Eq (Loc,
3508                  Left_Opnd  => New_Occurrence_Of (Lnn, Loc),
3509                  Right_Opnd => New_Occurrence_Of (Left_Lo, Loc))));
3510
3511          Append_To (B_Ass,
3512            Make_Assignment_Statement (Loc,
3513              Name => New_Occurrence_Of (Lnn, Loc),
3514              Expression =>
3515                Make_Attribute_Reference (Loc,
3516                  Prefix =>
3517                    New_Occurrence_Of (Index, Loc),
3518                  Attribute_Name => Name_Pred,
3519                    Expressions => New_List (
3520                      New_Occurrence_Of (Lnn, Loc)))));
3521
3522          Append_To (B_Ass,
3523            Make_Assignment_Statement (Loc,
3524              Name => New_Occurrence_Of (Rnn, Loc),
3525              Expression =>
3526                Make_Attribute_Reference (Loc,
3527                  Prefix =>
3528                    New_Occurrence_Of (Index, Loc),
3529                  Attribute_Name => Name_Pred,
3530                  Expressions => New_List (
3531                    New_Occurrence_Of (Rnn, Loc)))));
3532
3533          Append_To (Statements (Loops),
3534            Make_If_Statement (Loc,
3535              Condition => New_Occurrence_Of (Rev, Loc),
3536              Then_Statements => B_Ass,
3537              Else_Statements => F_Ass));
3538       end;
3539
3540       Append_To (Stats, Loops);
3541
3542       declare
3543          Spec    : Node_Id;
3544          Formals : List_Id := New_List;
3545
3546       begin
3547          Formals := New_List (
3548            Make_Parameter_Specification (Loc,
3549              Defining_Identifier => Larray,
3550              Out_Present => True,
3551              Parameter_Type =>
3552                New_Reference_To (Base_Type (Typ), Loc)),
3553
3554            Make_Parameter_Specification (Loc,
3555              Defining_Identifier => Rarray,
3556              Parameter_Type =>
3557                New_Reference_To (Base_Type (Typ), Loc)),
3558
3559            Make_Parameter_Specification (Loc,
3560              Defining_Identifier => Left_Lo,
3561              Parameter_Type =>
3562                New_Reference_To (Index, Loc)),
3563
3564            Make_Parameter_Specification (Loc,
3565              Defining_Identifier => Left_Hi,
3566              Parameter_Type =>
3567                New_Reference_To (Index, Loc)),
3568
3569            Make_Parameter_Specification (Loc,
3570              Defining_Identifier => Right_Lo,
3571              Parameter_Type =>
3572                New_Reference_To (Index, Loc)),
3573
3574            Make_Parameter_Specification (Loc,
3575              Defining_Identifier => Right_Hi,
3576              Parameter_Type =>
3577                New_Reference_To (Index, Loc)));
3578
3579          Append_To (Formals,
3580            Make_Parameter_Specification (Loc,
3581              Defining_Identifier => Rev,
3582              Parameter_Type =>
3583                New_Reference_To (Standard_Boolean, Loc)));
3584
3585          Spec :=
3586            Make_Procedure_Specification (Loc,
3587              Defining_Unit_Name       => Proc_Name,
3588              Parameter_Specifications => Formals);
3589
3590          Discard_Node (
3591            Make_Subprogram_Body (Loc,
3592              Specification              => Spec,
3593              Declarations               => Decls,
3594              Handled_Statement_Sequence =>
3595                Make_Handled_Sequence_Of_Statements (Loc,
3596                  Statements => Stats)));
3597       end;
3598
3599       Set_TSS (Typ, Proc_Name);
3600       Set_Is_Pure (Proc_Name);
3601    end Build_Slice_Assignment;
3602
3603    ------------------------------------
3604    -- Build_Variant_Record_Equality --
3605    ------------------------------------
3606
3607    --  Generates:
3608
3609    --    function _Equality (X, Y : T) return Boolean is
3610    --    begin
3611    --       --  Compare discriminants
3612
3613    --       if False or else X.D1 /= Y.D1 or else X.D2 /= Y.D2 then
3614    --          return False;
3615    --       end if;
3616
3617    --       --  Compare components
3618
3619    --       if False or else X.C1 /= Y.C1 or else X.C2 /= Y.C2 then
3620    --          return False;
3621    --       end if;
3622
3623    --       --  Compare variant part
3624
3625    --       case X.D1 is
3626    --          when V1 =>
3627    --             if False or else X.C2 /= Y.C2 or else X.C3 /= Y.C3 then
3628    --                return False;
3629    --             end if;
3630    --          ...
3631    --          when Vn =>
3632    --             if False or else X.Cn /= Y.Cn then
3633    --                return False;
3634    --             end if;
3635    --       end case;
3636
3637    --       return True;
3638    --    end _Equality;
3639
3640    procedure Build_Variant_Record_Equality (Typ : Entity_Id) is
3641       Loc : constant Source_Ptr := Sloc (Typ);
3642
3643       F : constant Entity_Id :=
3644             Make_Defining_Identifier (Loc,
3645               Chars => Make_TSS_Name (Typ, TSS_Composite_Equality));
3646
3647       X : constant Entity_Id :=
3648            Make_Defining_Identifier (Loc,
3649              Chars => Name_X);
3650
3651       Y : constant Entity_Id :=
3652             Make_Defining_Identifier (Loc,
3653               Chars => Name_Y);
3654
3655       Def    : constant Node_Id := Parent (Typ);
3656       Comps  : constant Node_Id := Component_List (Type_Definition (Def));
3657       Stmts  : constant List_Id := New_List;
3658       Pspecs : constant List_Id := New_List;
3659
3660    begin
3661       --  Derived Unchecked_Union types no longer inherit the equality function
3662       --  of their parent.
3663
3664       if Is_Derived_Type (Typ)
3665         and then not Is_Unchecked_Union (Typ)
3666         and then not Has_New_Non_Standard_Rep (Typ)
3667       then
3668          declare
3669             Parent_Eq : constant Entity_Id :=
3670                           TSS (Root_Type (Typ), TSS_Composite_Equality);
3671
3672          begin
3673             if Present (Parent_Eq) then
3674                Copy_TSS (Parent_Eq, Typ);
3675                return;
3676             end if;
3677          end;
3678       end if;
3679
3680       Discard_Node (
3681         Make_Subprogram_Body (Loc,
3682           Specification =>
3683             Make_Function_Specification (Loc,
3684               Defining_Unit_Name       => F,
3685               Parameter_Specifications => Pspecs,
3686               Result_Definition => New_Reference_To (Standard_Boolean, Loc)),
3687           Declarations               => New_List,
3688           Handled_Statement_Sequence =>
3689             Make_Handled_Sequence_Of_Statements (Loc,
3690               Statements => Stmts)));
3691
3692       Append_To (Pspecs,
3693         Make_Parameter_Specification (Loc,
3694           Defining_Identifier => X,
3695           Parameter_Type      => New_Reference_To (Typ, Loc)));
3696
3697       Append_To (Pspecs,
3698         Make_Parameter_Specification (Loc,
3699           Defining_Identifier => Y,
3700           Parameter_Type      => New_Reference_To (Typ, Loc)));
3701
3702       --  Unchecked_Unions require additional machinery to support equality.
3703       --  Two extra parameters (A and B) are added to the equality function
3704       --  parameter list in order to capture the inferred values of the
3705       --  discriminants in later calls.
3706
3707       if Is_Unchecked_Union (Typ) then
3708          declare
3709             Discr_Type : constant Node_Id := Etype (First_Discriminant (Typ));
3710
3711             A : constant Node_Id :=
3712                   Make_Defining_Identifier (Loc,
3713                     Chars => Name_A);
3714
3715             B : constant Node_Id :=
3716                   Make_Defining_Identifier (Loc,
3717                     Chars => Name_B);
3718
3719          begin
3720             --  Add A and B to the parameter list
3721
3722             Append_To (Pspecs,
3723               Make_Parameter_Specification (Loc,
3724                 Defining_Identifier => A,
3725                 Parameter_Type => New_Reference_To (Discr_Type, Loc)));
3726
3727             Append_To (Pspecs,
3728               Make_Parameter_Specification (Loc,
3729                 Defining_Identifier => B,
3730                 Parameter_Type => New_Reference_To (Discr_Type, Loc)));
3731
3732             --  Generate the following header code to compare the inferred
3733             --  discriminants:
3734
3735             --  if a /= b then
3736             --     return False;
3737             --  end if;
3738
3739             Append_To (Stmts,
3740               Make_If_Statement (Loc,
3741                 Condition =>
3742                   Make_Op_Ne (Loc,
3743                     Left_Opnd => New_Reference_To (A, Loc),
3744                     Right_Opnd => New_Reference_To (B, Loc)),
3745                 Then_Statements => New_List (
3746                   Make_Simple_Return_Statement (Loc,
3747                     Expression => New_Occurrence_Of (Standard_False, Loc)))));
3748
3749             --  Generate component-by-component comparison. Note that we must
3750             --  propagate one of the inferred discriminant formals to act as
3751             --  the case statement switch.
3752
3753             Append_List_To (Stmts,
3754               Make_Eq_Case (Typ, Comps, A));
3755
3756          end;
3757
3758       --  Normal case (not unchecked union)
3759
3760       else
3761          Append_To (Stmts,
3762            Make_Eq_If (Typ,
3763              Discriminant_Specifications (Def)));
3764
3765          Append_List_To (Stmts,
3766            Make_Eq_Case (Typ, Comps));
3767       end if;
3768
3769       Append_To (Stmts,
3770         Make_Simple_Return_Statement (Loc,
3771           Expression => New_Reference_To (Standard_True, Loc)));
3772
3773       Set_TSS (Typ, F);
3774       Set_Is_Pure (F);
3775
3776       if not Debug_Generated_Code then
3777          Set_Debug_Info_Off (F);
3778       end if;
3779    end Build_Variant_Record_Equality;
3780
3781    -----------------------------
3782    -- Check_Stream_Attributes --
3783    -----------------------------
3784
3785    procedure Check_Stream_Attributes (Typ : Entity_Id) is
3786       Comp      : Entity_Id;
3787       Par_Read  : constant Boolean :=
3788                     Stream_Attribute_Available (Typ, TSS_Stream_Read)
3789                       and then not Has_Specified_Stream_Read (Typ);
3790       Par_Write : constant Boolean :=
3791                     Stream_Attribute_Available (Typ, TSS_Stream_Write)
3792                       and then not Has_Specified_Stream_Write (Typ);
3793
3794       procedure Check_Attr (Nam : Name_Id; TSS_Nam : TSS_Name_Type);
3795       --  Check that Comp has a user-specified Nam stream attribute
3796
3797       ----------------
3798       -- Check_Attr --
3799       ----------------
3800
3801       procedure Check_Attr (Nam : Name_Id; TSS_Nam : TSS_Name_Type) is
3802       begin
3803          if not Stream_Attribute_Available (Etype (Comp), TSS_Nam) then
3804             Error_Msg_Name_1 := Nam;
3805             Error_Msg_N
3806               ("|component& in limited extension must have% attribute", Comp);
3807          end if;
3808       end Check_Attr;
3809
3810    --  Start of processing for Check_Stream_Attributes
3811
3812    begin
3813       if Par_Read or else Par_Write then
3814          Comp := First_Component (Typ);
3815          while Present (Comp) loop
3816             if Comes_From_Source (Comp)
3817               and then Original_Record_Component (Comp) = Comp
3818               and then Is_Limited_Type (Etype (Comp))
3819             then
3820                if Par_Read then
3821                   Check_Attr (Name_Read, TSS_Stream_Read);
3822                end if;
3823
3824                if Par_Write then
3825                   Check_Attr (Name_Write, TSS_Stream_Write);
3826                end if;
3827             end if;
3828
3829             Next_Component (Comp);
3830          end loop;
3831       end if;
3832    end Check_Stream_Attributes;
3833
3834    -----------------------------
3835    -- Expand_Record_Extension --
3836    -----------------------------
3837
3838    --  Add a field _parent at the beginning of the record extension. This is
3839    --  used to implement inheritance. Here are some examples of expansion:
3840
3841    --  1. no discriminants
3842    --      type T2 is new T1 with null record;
3843    --   gives
3844    --      type T2 is new T1 with record
3845    --        _Parent : T1;
3846    --      end record;
3847
3848    --  2. renamed discriminants
3849    --    type T2 (B, C : Int) is new T1 (A => B) with record
3850    --       _Parent : T1 (A => B);
3851    --       D : Int;
3852    --    end;
3853
3854    --  3. inherited discriminants
3855    --    type T2 is new T1 with record -- discriminant A inherited
3856    --       _Parent : T1 (A);
3857    --       D : Int;
3858    --    end;
3859
3860    procedure Expand_Record_Extension (T : Entity_Id; Def : Node_Id) is
3861       Indic        : constant Node_Id    := Subtype_Indication (Def);
3862       Loc          : constant Source_Ptr := Sloc (Def);
3863       Rec_Ext_Part : Node_Id             := Record_Extension_Part (Def);
3864       Par_Subtype  : Entity_Id;
3865       Comp_List    : Node_Id;
3866       Comp_Decl    : Node_Id;
3867       Parent_N     : Node_Id;
3868       D            : Entity_Id;
3869       List_Constr  : constant List_Id    := New_List;
3870
3871    begin
3872       --  Expand_Record_Extension is called directly from the semantics, so
3873       --  we must check to see whether expansion is active before proceeding
3874
3875       if not Expander_Active then
3876          return;
3877       end if;
3878
3879       --  This may be a derivation of an untagged private type whose full
3880       --  view is tagged, in which case the Derived_Type_Definition has no
3881       --  extension part. Build an empty one now.
3882
3883       if No (Rec_Ext_Part) then
3884          Rec_Ext_Part :=
3885            Make_Record_Definition (Loc,
3886              End_Label      => Empty,
3887              Component_List => Empty,
3888              Null_Present   => True);
3889
3890          Set_Record_Extension_Part (Def, Rec_Ext_Part);
3891          Mark_Rewrite_Insertion (Rec_Ext_Part);
3892       end if;
3893
3894       Comp_List := Component_List (Rec_Ext_Part);
3895
3896       Parent_N := Make_Defining_Identifier (Loc, Name_uParent);
3897
3898       --  If the derived type inherits its discriminants the type of the
3899       --  _parent field must be constrained by the inherited discriminants
3900
3901       if Has_Discriminants (T)
3902         and then Nkind (Indic) /= N_Subtype_Indication
3903         and then not Is_Constrained (Entity (Indic))
3904       then
3905          D := First_Discriminant (T);
3906          while Present (D) loop
3907             Append_To (List_Constr, New_Occurrence_Of (D, Loc));
3908             Next_Discriminant (D);
3909          end loop;
3910
3911          Par_Subtype :=
3912            Process_Subtype (
3913              Make_Subtype_Indication (Loc,
3914                Subtype_Mark => New_Reference_To (Entity (Indic), Loc),
3915                Constraint   =>
3916                  Make_Index_Or_Discriminant_Constraint (Loc,
3917                    Constraints => List_Constr)),
3918              Def);
3919
3920       --  Otherwise the original subtype_indication is just what is needed
3921
3922       else
3923          Par_Subtype := Process_Subtype (New_Copy_Tree (Indic), Def);
3924       end if;
3925
3926       Set_Parent_Subtype (T, Par_Subtype);
3927
3928       Comp_Decl :=
3929         Make_Component_Declaration (Loc,
3930           Defining_Identifier => Parent_N,
3931           Component_Definition =>
3932             Make_Component_Definition (Loc,
3933               Aliased_Present => False,
3934               Subtype_Indication => New_Reference_To (Par_Subtype, Loc)));
3935
3936       if Null_Present (Rec_Ext_Part) then
3937          Set_Component_List (Rec_Ext_Part,
3938            Make_Component_List (Loc,
3939              Component_Items => New_List (Comp_Decl),
3940              Variant_Part => Empty,
3941              Null_Present => False));
3942          Set_Null_Present (Rec_Ext_Part, False);
3943
3944       elsif Null_Present (Comp_List)
3945         or else Is_Empty_List (Component_Items (Comp_List))
3946       then
3947          Set_Component_Items (Comp_List, New_List (Comp_Decl));
3948          Set_Null_Present (Comp_List, False);
3949
3950       else
3951          Insert_Before (First (Component_Items (Comp_List)), Comp_Decl);
3952       end if;
3953
3954       Analyze (Comp_Decl);
3955    end Expand_Record_Extension;
3956
3957    ------------------------------------
3958    -- Expand_N_Full_Type_Declaration --
3959    ------------------------------------
3960
3961    procedure Expand_N_Full_Type_Declaration (N : Node_Id) is
3962       Def_Id : constant Entity_Id := Defining_Identifier (N);
3963       B_Id   : constant Entity_Id := Base_Type (Def_Id);
3964       Par_Id : Entity_Id;
3965       FN     : Node_Id;
3966
3967       procedure Build_Master (Def_Id : Entity_Id);
3968       --  Create the master associated with Def_Id
3969
3970       ------------------
3971       -- Build_Master --
3972       ------------------
3973
3974       procedure Build_Master (Def_Id : Entity_Id) is
3975       begin
3976          --  Anonymous access types are created for the components of the
3977          --  record parameter for an entry declaration. No master is created
3978          --  for such a type.
3979
3980          if Has_Task (Designated_Type (Def_Id))
3981            and then Comes_From_Source (N)
3982          then
3983             Build_Master_Entity (Def_Id);
3984             Build_Master_Renaming (Parent (Def_Id), Def_Id);
3985
3986          --  Create a class-wide master because a Master_Id must be generated
3987          --  for access-to-limited-class-wide types whose root may be extended
3988          --  with task components.
3989
3990          --  Note: This code covers access-to-limited-interfaces because they
3991          --        can be used to reference tasks implementing them.
3992
3993          elsif Is_Class_Wide_Type (Designated_Type (Def_Id))
3994            and then Is_Limited_Type (Designated_Type (Def_Id))
3995            and then Tasking_Allowed
3996
3997             --  Do not create a class-wide master for types whose convention is
3998             --  Java since these types cannot embed Ada tasks anyway. Note that
3999             --  the following test cannot catch the following case:
4000
4001             --      package java.lang.Object is
4002             --         type Typ is tagged limited private;
4003             --         type Ref is access all Typ'Class;
4004             --      private
4005             --         type Typ is tagged limited ...;
4006             --         pragma Convention (Typ, Java)
4007             --      end;
4008
4009             --  Because the convention appears after we have done the
4010             --  processing for type Ref.
4011
4012            and then Convention (Designated_Type (Def_Id)) /= Convention_Java
4013            and then Convention (Designated_Type (Def_Id)) /= Convention_CIL
4014          then
4015             Build_Class_Wide_Master (Def_Id);
4016          end if;
4017       end Build_Master;
4018
4019    --  Start of processing for Expand_N_Full_Type_Declaration
4020
4021    begin
4022       if Is_Access_Type (Def_Id) then
4023          Build_Master (Def_Id);
4024
4025          if Ekind (Def_Id) = E_Access_Protected_Subprogram_Type then
4026             Expand_Access_Protected_Subprogram_Type (N);
4027          end if;
4028
4029       elsif Ada_Version >= Ada_05
4030         and then Is_Array_Type (Def_Id)
4031         and then Is_Access_Type (Component_Type (Def_Id))
4032         and then Ekind (Component_Type (Def_Id)) = E_Anonymous_Access_Type
4033       then
4034          Build_Master (Component_Type (Def_Id));
4035
4036       elsif Has_Task (Def_Id) then
4037          Expand_Previous_Access_Type (Def_Id);
4038
4039       elsif Ada_Version >= Ada_05
4040         and then
4041          (Is_Record_Type (Def_Id)
4042            or else (Is_Array_Type (Def_Id)
4043                       and then Is_Record_Type (Component_Type (Def_Id))))
4044       then
4045          declare
4046             Comp : Entity_Id;
4047             Typ  : Entity_Id;
4048             M_Id : Entity_Id;
4049
4050          begin
4051             --  Look for the first anonymous access type component
4052
4053             if Is_Array_Type (Def_Id) then
4054                Comp := First_Entity (Component_Type (Def_Id));
4055             else
4056                Comp := First_Entity (Def_Id);
4057             end if;
4058
4059             while Present (Comp) loop
4060                Typ := Etype (Comp);
4061
4062                exit when Is_Access_Type (Typ)
4063                  and then Ekind (Typ) = E_Anonymous_Access_Type;
4064
4065                Next_Entity (Comp);
4066             end loop;
4067
4068             --  If found we add a renaming declaration of master_id and we
4069             --  associate it to each anonymous access type component. Do
4070             --  nothing if the access type already has a master. This will be
4071             --  the case if the array type is the packed array created for a
4072             --  user-defined array type T, where the master_id is created when
4073             --  expanding the declaration for T.
4074
4075             if Present (Comp)
4076               and then Ekind (Typ) = E_Anonymous_Access_Type
4077               and then not Restriction_Active (No_Task_Hierarchy)
4078               and then No (Master_Id (Typ))
4079
4080                --  Do not consider run-times with no tasking support
4081
4082               and then RTE_Available (RE_Current_Master)
4083               and then Has_Task (Non_Limited_Designated_Type (Typ))
4084             then
4085                Build_Master_Entity (Def_Id);
4086                M_Id := Build_Master_Renaming (N, Def_Id);
4087
4088                if Is_Array_Type (Def_Id) then
4089                   Comp := First_Entity (Component_Type (Def_Id));
4090                else
4091                   Comp := First_Entity (Def_Id);
4092                end if;
4093
4094                while Present (Comp) loop
4095                   Typ := Etype (Comp);
4096
4097                   if Is_Access_Type (Typ)
4098                     and then Ekind (Typ) = E_Anonymous_Access_Type
4099                   then
4100                      Set_Master_Id (Typ, M_Id);
4101                   end if;
4102
4103                   Next_Entity (Comp);
4104                end loop;
4105             end if;
4106          end;
4107       end if;
4108
4109       Par_Id := Etype (B_Id);
4110
4111       --  The parent type is private then we need to inherit any TSS operations
4112       --  from the full view.
4113
4114       if Ekind (Par_Id) in Private_Kind
4115         and then Present (Full_View (Par_Id))
4116       then
4117          Par_Id := Base_Type (Full_View (Par_Id));
4118       end if;
4119
4120       if Nkind (Type_Definition (Original_Node (N))) =
4121                                                 N_Derived_Type_Definition
4122         and then not Is_Tagged_Type (Def_Id)
4123         and then Present (Freeze_Node (Par_Id))
4124         and then Present (TSS_Elist (Freeze_Node (Par_Id)))
4125       then
4126          Ensure_Freeze_Node (B_Id);
4127          FN := Freeze_Node (B_Id);
4128
4129          if No (TSS_Elist (FN)) then
4130             Set_TSS_Elist (FN, New_Elmt_List);
4131          end if;
4132
4133          declare
4134             T_E  : constant Elist_Id := TSS_Elist (FN);
4135             Elmt : Elmt_Id;
4136
4137          begin
4138             Elmt := First_Elmt (TSS_Elist (Freeze_Node (Par_Id)));
4139             while Present (Elmt) loop
4140                if Chars (Node (Elmt)) /= Name_uInit then
4141                   Append_Elmt (Node (Elmt), T_E);
4142                end if;
4143
4144                Next_Elmt (Elmt);
4145             end loop;
4146
4147             --  If the derived type itself is private with a full view, then
4148             --  associate the full view with the inherited TSS_Elist as well.
4149
4150             if Ekind (B_Id) in Private_Kind
4151               and then Present (Full_View (B_Id))
4152             then
4153                Ensure_Freeze_Node (Base_Type (Full_View (B_Id)));
4154                Set_TSS_Elist
4155                  (Freeze_Node (Base_Type (Full_View (B_Id))), TSS_Elist (FN));
4156             end if;
4157          end;
4158       end if;
4159    end Expand_N_Full_Type_Declaration;
4160
4161    ---------------------------------
4162    -- Expand_N_Object_Declaration --
4163    ---------------------------------
4164
4165    --  First we do special processing for objects of a tagged type where this
4166    --  is the point at which the type is frozen. The creation of the dispatch
4167    --  table and the initialization procedure have to be deferred to this
4168    --  point, since we reference previously declared primitive subprograms.
4169
4170    --  For all types, we call an initialization procedure if there is one
4171
4172    procedure Expand_N_Object_Declaration (N : Node_Id) is
4173       Def_Id   : constant Entity_Id  := Defining_Identifier (N);
4174       Expr     : constant Node_Id    := Expression (N);
4175       Loc      : constant Source_Ptr := Sloc (N);
4176       Typ      : constant Entity_Id  := Etype (Def_Id);
4177       Base_Typ : constant Entity_Id  := Base_Type (Typ);
4178       Expr_Q   : Node_Id;
4179       Id_Ref   : Node_Id;
4180       New_Ref  : Node_Id;
4181
4182       Init_After : Node_Id := N;
4183       --  Node after which the init proc call is to be inserted. This is
4184       --  normally N, except for the case of a shared passive variable, in
4185       --  which case the init proc call must be inserted only after the bodies
4186       --  of the shared variable procedures have been seen.
4187
4188       function Rewrite_As_Renaming return Boolean;
4189       --  Indicate whether to rewrite a declaration with initialization into an
4190       --  object renaming declaration (see below).
4191
4192       -------------------------
4193       -- Rewrite_As_Renaming --
4194       -------------------------
4195
4196       function Rewrite_As_Renaming return Boolean is
4197       begin
4198          return not Aliased_Present (N)
4199            and then Is_Entity_Name (Expr_Q)
4200            and then Ekind (Entity (Expr_Q)) = E_Variable
4201            and then OK_To_Rename (Entity (Expr_Q))
4202            and then Is_Entity_Name (Object_Definition (N));
4203       end Rewrite_As_Renaming;
4204
4205    --  Start of processing for Expand_N_Object_Declaration
4206
4207    begin
4208       --  Don't do anything for deferred constants. All proper actions will be
4209       --  expanded during the full declaration.
4210
4211       if No (Expr) and Constant_Present (N) then
4212          return;
4213       end if;
4214
4215       --  Force construction of dispatch tables of library level tagged types
4216
4217       if VM_Target = No_VM
4218         and then Static_Dispatch_Tables
4219         and then Is_Library_Level_Entity (Def_Id)
4220         and then Is_Library_Level_Tagged_Type (Base_Typ)
4221         and then (Ekind (Base_Typ) = E_Record_Type
4222                     or else Ekind (Base_Typ) = E_Protected_Type
4223                     or else Ekind (Base_Typ) = E_Task_Type)
4224         and then not Has_Dispatch_Table (Base_Typ)
4225       then
4226          declare
4227             New_Nodes : List_Id := No_List;
4228
4229          begin
4230             if Is_Concurrent_Type (Base_Typ) then
4231                New_Nodes := Make_DT (Corresponding_Record_Type (Base_Typ), N);
4232             else
4233                New_Nodes := Make_DT (Base_Typ, N);
4234             end if;
4235
4236             if not Is_Empty_List (New_Nodes) then
4237                Insert_List_Before (N, New_Nodes);
4238             end if;
4239          end;
4240       end if;
4241
4242       --  Make shared memory routines for shared passive variable
4243
4244       if Is_Shared_Passive (Def_Id) then
4245          Init_After := Make_Shared_Var_Procs (N);
4246       end if;
4247
4248       --  If tasks being declared, make sure we have an activation chain
4249       --  defined for the tasks (has no effect if we already have one), and
4250       --  also that a Master variable is established and that the appropriate
4251       --  enclosing construct is established as a task master.
4252
4253       if Has_Task (Typ) then
4254          Build_Activation_Chain_Entity (N);
4255          Build_Master_Entity (Def_Id);
4256       end if;
4257
4258       --  Build a list controller for declarations where the type is anonymous
4259       --  access and the designated type is controlled. Only declarations from
4260       --  source files receive such controllers in order to provide the same
4261       --  lifespan for any potential coextensions that may be associated with
4262       --  the object. Finalization lists of internal controlled anonymous
4263       --  access objects are already handled in Expand_N_Allocator.
4264
4265       if Comes_From_Source (N)
4266         and then Ekind (Typ) = E_Anonymous_Access_Type
4267         and then Is_Controlled (Directly_Designated_Type (Typ))
4268         and then No (Associated_Final_Chain (Typ))
4269       then
4270          Build_Final_List (N, Typ);
4271       end if;
4272
4273       --  Default initialization required, and no expression present
4274
4275       if No (Expr) then
4276
4277          --  Expand Initialize call for controlled objects. One may wonder why
4278          --  the Initialize Call is not done in the regular Init procedure
4279          --  attached to the record type. That's because the init procedure is
4280          --  recursively called on each component, including _Parent, thus the
4281          --  Init call for a controlled object would generate not only one
4282          --  Initialize call as it is required but one for each ancestor of
4283          --  its type. This processing is suppressed if No_Initialization set.
4284
4285          if not Needs_Finalization (Typ)
4286            or else No_Initialization (N)
4287          then
4288             null;
4289
4290          elsif not Abort_Allowed
4291            or else not Comes_From_Source (N)
4292          then
4293             Insert_Actions_After (Init_After,
4294               Make_Init_Call (
4295                 Ref         => New_Occurrence_Of (Def_Id, Loc),
4296                 Typ         => Base_Type (Typ),
4297                 Flist_Ref   => Find_Final_List (Def_Id),
4298                 With_Attach => Make_Integer_Literal (Loc, 1)));
4299
4300          --  Abort allowed
4301
4302          else
4303             --  We need to protect the initialize call
4304
4305             --  begin
4306             --     Defer_Abort.all;
4307             --     Initialize (...);
4308             --  at end
4309             --     Undefer_Abort.all;
4310             --  end;
4311
4312             --  ??? this won't protect the initialize call for controlled
4313             --  components which are part of the init proc, so this block
4314             --  should probably also contain the call to _init_proc but this
4315             --  requires some code reorganization...
4316
4317             declare
4318                L   : constant List_Id :=
4319                        Make_Init_Call
4320                          (Ref         => New_Occurrence_Of (Def_Id, Loc),
4321                           Typ         => Base_Type (Typ),
4322                           Flist_Ref   => Find_Final_List (Def_Id),
4323                           With_Attach => Make_Integer_Literal (Loc, 1));
4324
4325                Blk : constant Node_Id :=
4326                        Make_Block_Statement (Loc,
4327                          Handled_Statement_Sequence =>
4328                            Make_Handled_Sequence_Of_Statements (Loc, L));
4329
4330             begin
4331                Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
4332                Set_At_End_Proc (Handled_Statement_Sequence (Blk),
4333                  New_Occurrence_Of (RTE (RE_Abort_Undefer_Direct), Loc));
4334                Insert_Actions_After (Init_After, New_List (Blk));
4335                Expand_At_End_Handler
4336                  (Handled_Statement_Sequence (Blk), Entity (Identifier (Blk)));
4337             end;
4338          end if;
4339
4340          --  Call type initialization procedure if there is one. We build the
4341          --  call and put it immediately after the object declaration, so that
4342          --  it will be expanded in the usual manner. Note that this will
4343          --  result in proper handling of defaulted discriminants.
4344
4345          --  Need call if there is a base init proc
4346
4347          if Has_Non_Null_Base_Init_Proc (Typ)
4348
4349             --  Suppress call if No_Initialization set on declaration
4350
4351             and then not No_Initialization (N)
4352
4353             --  Suppress call for special case of value type for VM
4354
4355             and then not Is_Value_Type (Typ)
4356
4357             --  Suppress call if Suppress_Init_Proc set on the type. This is
4358             --  needed for the derived type case, where Suppress_Initialization
4359             --  may be set for the derived type, even if there is an init proc
4360             --  defined for the root type.
4361
4362             and then not Suppress_Init_Proc (Typ)
4363          then
4364             --  Return without initializing when No_Default_Initialization
4365             --  applies. Note that the actual restriction check occurs later,
4366             --  when the object is frozen, because we don't know yet whether
4367             --  the object is imported, which is a case where the check does
4368             --  not apply.
4369
4370             if Restriction_Active (No_Default_Initialization) then
4371                return;
4372             end if;
4373
4374             --  The call to the initialization procedure does NOT freeze the
4375             --  object being initialized. This is because the call is not a
4376             --  source level call. This works fine, because the only possible
4377             --  statements depending on freeze status that can appear after the
4378             --  _Init call are rep clauses which can safely appear after actual
4379             --  references to the object.
4380
4381             Id_Ref := New_Reference_To (Def_Id, Loc);
4382             Set_Must_Not_Freeze (Id_Ref);
4383             Set_Assignment_OK (Id_Ref);
4384
4385             declare
4386                Init_Expr : constant Node_Id :=
4387                              Static_Initialization (Base_Init_Proc (Typ));
4388             begin
4389                if Present (Init_Expr) then
4390                   Set_Expression
4391                     (N, New_Copy_Tree (Init_Expr, New_Scope => Current_Scope));
4392                   return;
4393                else
4394                   Initialization_Warning (Id_Ref);
4395
4396                   Insert_Actions_After (Init_After,
4397                     Build_Initialization_Call (Loc, Id_Ref, Typ));
4398                end if;
4399             end;
4400
4401          --  If simple initialization is required, then set an appropriate
4402          --  simple initialization expression in place. This special
4403          --  initialization is required even though No_Init_Flag is present,
4404          --  but is not needed if there was an explicit initialization.
4405
4406          --  An internally generated temporary needs no initialization because
4407          --  it will be assigned subsequently. In particular, there is no point
4408          --  in applying Initialize_Scalars to such a temporary.
4409
4410          elsif Needs_Simple_Initialization (Typ)
4411            and then not Is_Internal (Def_Id)
4412            and then not Has_Init_Expression (N)
4413          then
4414             Set_No_Initialization (N, False);
4415             Set_Expression (N, Get_Simple_Init_Val (Typ, N, Esize (Def_Id)));
4416             Analyze_And_Resolve (Expression (N), Typ);
4417          end if;
4418
4419          --  Generate attribute for Persistent_BSS if needed
4420
4421          if Persistent_BSS_Mode
4422            and then Comes_From_Source (N)
4423            and then Is_Potentially_Persistent_Type (Typ)
4424            and then not Has_Init_Expression (N)
4425            and then Is_Library_Level_Entity (Def_Id)
4426          then
4427             declare
4428                Prag : Node_Id;
4429             begin
4430                Prag :=
4431                  Make_Linker_Section_Pragma
4432                    (Def_Id, Sloc (N), ".persistent.bss");
4433                Insert_After (N, Prag);
4434                Analyze (Prag);
4435             end;
4436          end if;
4437
4438          --  If access type, then we know it is null if not initialized
4439
4440          if Is_Access_Type (Typ) then
4441             Set_Is_Known_Null (Def_Id);
4442          end if;
4443
4444       --  Explicit initialization present
4445
4446       else
4447          --  Obtain actual expression from qualified expression
4448
4449          if Nkind (Expr) = N_Qualified_Expression then
4450             Expr_Q := Expression (Expr);
4451          else
4452             Expr_Q := Expr;
4453          end if;
4454
4455          --  When we have the appropriate type of aggregate in the expression
4456          --  (it has been determined during analysis of the aggregate by
4457          --  setting the delay flag), let's perform in place assignment and
4458          --  thus avoid creating a temporary.
4459
4460          if Is_Delayed_Aggregate (Expr_Q) then
4461             Convert_Aggr_In_Object_Decl (N);
4462
4463          --  Ada 2005 (AI-318-02): If the initialization expression is a call
4464          --  to a build-in-place function, then access to the declared object
4465          --  must be passed to the function. Currently we limit such functions
4466          --  to those with constrained limited result subtypes, but eventually
4467          --  plan to expand the allowed forms of functions that are treated as
4468          --  build-in-place.
4469
4470          elsif Ada_Version >= Ada_05
4471            and then Is_Build_In_Place_Function_Call (Expr_Q)
4472          then
4473             Make_Build_In_Place_Call_In_Object_Declaration (N, Expr_Q);
4474
4475             --  The previous call expands the expression initializing the
4476             --  built-in-place object into further code that will be analyzed
4477             --  later. No further expansion needed here.
4478
4479             return;
4480
4481          else
4482             --  In most cases, we must check that the initial value meets any
4483             --  constraint imposed by the declared type. However, there is one
4484             --  very important exception to this rule. If the entity has an
4485             --  unconstrained nominal subtype, then it acquired its constraints
4486             --  from the expression in the first place, and not only does this
4487             --  mean that the constraint check is not needed, but an attempt to
4488             --  perform the constraint check can cause order of elaboration
4489             --  problems.
4490
4491             if not Is_Constr_Subt_For_U_Nominal (Typ) then
4492
4493                --  If this is an allocator for an aggregate that has been
4494                --  allocated in place, delay checks until assignments are
4495                --  made, because the discriminants are not initialized.
4496
4497                if Nkind (Expr) = N_Allocator
4498                  and then No_Initialization (Expr)
4499                then
4500                   null;
4501                else
4502                   Apply_Constraint_Check (Expr, Typ);
4503                end if;
4504             end if;
4505
4506             --  Ada 2005 (AI-251): Rewrite the expression that initializes a
4507             --  class-wide object to ensure that we copy the full object,
4508             --  unless we are targetting a VM where interfaces are handled by
4509             --  VM itself. Note that if the root type of Typ is an ancestor
4510             --  of Expr's type, both types share the same dispatch table and
4511             --  there is no need to displace the pointer.
4512
4513             --  Replace
4514             --     CW : I'Class := Obj;
4515             --  by
4516             --     Temp : I'Class := I'Class (Base_Address (Obj'Address));
4517             --     CW   : I'Class renames Displace (Temp, I'Tag);
4518
4519             if Is_Interface (Typ)
4520               and then Is_Class_Wide_Type (Typ)
4521               and then
4522                 (Is_Class_Wide_Type (Etype (Expr))
4523                    or else
4524                      not Is_Ancestor (Root_Type (Typ), Etype (Expr)))
4525               and then Comes_From_Source (Def_Id)
4526               and then VM_Target = No_VM
4527             then
4528                declare
4529                   Decl_1 : Node_Id;
4530                   Decl_2 : Node_Id;
4531
4532                begin
4533                   Decl_1 :=
4534                     Make_Object_Declaration (Loc,
4535                       Defining_Identifier =>
4536                         Make_Defining_Identifier (Loc,
4537                           New_Internal_Name ('D')),
4538
4539                       Object_Definition =>
4540                         Make_Attribute_Reference (Loc,
4541                           Prefix =>
4542                             New_Occurrence_Of
4543                               (Root_Type (Etype (Def_Id)), Loc),
4544                           Attribute_Name => Name_Class),
4545
4546                       Expression =>
4547                         Unchecked_Convert_To
4548                           (Class_Wide_Type (Root_Type (Etype (Def_Id))),
4549                             Make_Explicit_Dereference (Loc,
4550                               Unchecked_Convert_To (RTE (RE_Tag_Ptr),
4551                                 Make_Function_Call (Loc,
4552                                   Name =>
4553                                     New_Reference_To (RTE (RE_Base_Address),
4554                                                       Loc),
4555                                   Parameter_Associations => New_List (
4556                                     Make_Attribute_Reference (Loc,
4557                                       Prefix         => Relocate_Node (Expr),
4558                                       Attribute_Name => Name_Address)))))));
4559
4560                   Insert_Action (N, Decl_1);
4561
4562                   Decl_2 :=
4563                     Make_Object_Renaming_Declaration (Loc,
4564                       Defining_Identifier =>
4565                         Make_Defining_Identifier (Loc,
4566                           New_Internal_Name ('D')),
4567
4568                       Subtype_Mark =>
4569                         Make_Attribute_Reference (Loc,
4570                           Prefix =>
4571                             New_Occurrence_Of
4572                               (Root_Type (Etype (Def_Id)), Loc),
4573                           Attribute_Name => Name_Class),
4574
4575                       Name =>
4576                         Unchecked_Convert_To (
4577                           Class_Wide_Type (Root_Type (Etype (Def_Id))),
4578                           Make_Explicit_Dereference (Loc,
4579                             Unchecked_Convert_To (RTE (RE_Tag_Ptr),
4580                               Make_Function_Call (Loc,
4581                                 Name =>
4582                                   New_Reference_To (RTE (RE_Displace), Loc),
4583
4584                                 Parameter_Associations => New_List (
4585                                   Make_Attribute_Reference (Loc,
4586                                     Prefix =>
4587                                       New_Reference_To
4588                                         (Defining_Identifier (Decl_1), Loc),
4589                                     Attribute_Name => Name_Address),
4590
4591                                   Unchecked_Convert_To (RTE (RE_Tag),
4592                                     New_Reference_To
4593                                       (Node
4594                                         (First_Elmt
4595                                           (Access_Disp_Table
4596                                              (Root_Type (Typ)))),
4597                                        Loc))))))));
4598
4599                   Rewrite (N, Decl_2);
4600                   Analyze (N);
4601
4602                   --  Replace internal identifier of Decl_2 by the identifier
4603                   --  found in the sources. We also have to exchange entities
4604                   --  containing their defining identifiers to ensure the
4605                   --  correct replacement of the object declaration by this
4606                   --  object renaming declaration (because such definings
4607                   --  identifier have been previously added by Enter_Name to
4608                   --  the current scope). We must preserve the homonym chain
4609                   --  of the source entity as well.
4610
4611                   Set_Chars (Defining_Identifier (N), Chars (Def_Id));
4612                   Set_Homonym (Defining_Identifier (N), Homonym (Def_Id));
4613                   Exchange_Entities (Defining_Identifier (N), Def_Id);
4614
4615                   return;
4616                end;
4617             end if;
4618
4619             --  If the type is controlled and not inherently limited, then
4620             --  the target is adjusted after the copy and attached to the
4621             --  finalization list. However, no adjustment is done in the case
4622             --  where the object was initialized by a call to a function whose
4623             --  result is built in place, since no copy occurred. (Eventually
4624             --  we plan to support in-place function results for some cases
4625             --  of nonlimited types. ???) Similarly, no adjustment is required
4626             --  if we are going to rewrite the object declaration into a
4627             --  renaming declaration.
4628
4629             if Needs_Finalization (Typ)
4630               and then not Is_Inherently_Limited_Type (Typ)
4631               and then not Rewrite_As_Renaming
4632             then
4633                Insert_Actions_After (Init_After,
4634                  Make_Adjust_Call (
4635                    Ref          => New_Reference_To (Def_Id, Loc),
4636                    Typ          => Base_Type (Typ),
4637                    Flist_Ref    => Find_Final_List (Def_Id),
4638                    With_Attach  => Make_Integer_Literal (Loc, 1)));
4639             end if;
4640
4641             --  For tagged types, when an init value is given, the tag has to
4642             --  be re-initialized separately in order to avoid the propagation
4643             --  of a wrong tag coming from a view conversion unless the type
4644             --  is class wide (in this case the tag comes from the init value).
4645             --  Suppress the tag assignment when VM_Target because VM tags are
4646             --  represented implicitly in objects. Ditto for types that are
4647             --  CPP_CLASS, and for initializations that are aggregates, because
4648             --  they have to have the right tag.
4649
4650             if Is_Tagged_Type (Typ)
4651               and then not Is_Class_Wide_Type (Typ)
4652               and then not Is_CPP_Class (Typ)
4653               and then VM_Target = No_VM
4654               and then Nkind (Expr) /= N_Aggregate
4655             then
4656                --  The re-assignment of the tag has to be done even if the
4657                --  object is a constant.
4658
4659                New_Ref :=
4660                  Make_Selected_Component (Loc,
4661                     Prefix => New_Reference_To (Def_Id, Loc),
4662                     Selector_Name =>
4663                       New_Reference_To (First_Tag_Component (Typ), Loc));
4664
4665                Set_Assignment_OK (New_Ref);
4666
4667                Insert_After (Init_After,
4668                  Make_Assignment_Statement (Loc,
4669                    Name => New_Ref,
4670                    Expression =>
4671                      Unchecked_Convert_To (RTE (RE_Tag),
4672                        New_Reference_To
4673                          (Node
4674                            (First_Elmt
4675                              (Access_Disp_Table (Base_Type (Typ)))),
4676                           Loc))));
4677
4678             elsif Is_Tagged_Type (Typ)
4679               and then Is_CPP_Constructor_Call (Expr)
4680             then
4681                --  The call to the initialization procedure does NOT freeze the
4682                --  object being initialized.
4683
4684                Id_Ref := New_Reference_To (Def_Id, Loc);
4685                Set_Must_Not_Freeze (Id_Ref);
4686                Set_Assignment_OK (Id_Ref);
4687
4688                Insert_Actions_After (Init_After,
4689                  Build_Initialization_Call (Loc, Id_Ref, Typ,
4690                    Constructor_Ref => Expr));
4691
4692                --  We remove here the original call to the constructor
4693                --  to avoid its management in the backend
4694
4695                Set_Expression (N, Empty);
4696                return;
4697
4698             --  For discrete types, set the Is_Known_Valid flag if the
4699             --  initializing value is known to be valid.
4700
4701             elsif Is_Discrete_Type (Typ) and then Expr_Known_Valid (Expr) then
4702                Set_Is_Known_Valid (Def_Id);
4703
4704             elsif Is_Access_Type (Typ) then
4705
4706                --  For access types set the Is_Known_Non_Null flag if the
4707                --  initializing value is known to be non-null. We can also set
4708                --  Can_Never_Be_Null if this is a constant.
4709
4710                if Known_Non_Null (Expr) then
4711                   Set_Is_Known_Non_Null (Def_Id, True);
4712
4713                   if Constant_Present (N) then
4714                      Set_Can_Never_Be_Null (Def_Id);
4715                   end if;
4716                end if;
4717             end if;
4718
4719             --  If validity checking on copies, validate initial expression.
4720             --  But skip this if declaration is for a generic type, since it
4721             --  makes no sense to validate generic types. Not clear if this
4722             --  can happen for legal programs, but it definitely can arise
4723             --  from previous instantiation errors.
4724
4725             if Validity_Checks_On
4726               and then Validity_Check_Copies
4727               and then not Is_Generic_Type (Etype (Def_Id))
4728             then
4729                Ensure_Valid (Expr);
4730                Set_Is_Known_Valid (Def_Id);
4731             end if;
4732          end if;
4733
4734          --  Cases where the back end cannot handle the initialization directly
4735          --  In such cases, we expand an assignment that will be appropriately
4736          --  handled by Expand_N_Assignment_Statement.
4737
4738          --  The exclusion of the unconstrained case is wrong, but for now it
4739          --  is too much trouble ???
4740
4741          if (Is_Possibly_Unaligned_Slice (Expr)
4742                or else (Is_Possibly_Unaligned_Object (Expr)
4743                           and then not Represented_As_Scalar (Etype (Expr))))
4744
4745             --  The exclusion of the unconstrained case is wrong, but for now
4746             --  it is too much trouble ???
4747
4748            and then not (Is_Array_Type (Etype (Expr))
4749                            and then not Is_Constrained (Etype (Expr)))
4750          then
4751             declare
4752                Stat : constant Node_Id :=
4753                        Make_Assignment_Statement (Loc,
4754                          Name       => New_Reference_To (Def_Id, Loc),
4755                          Expression => Relocate_Node (Expr));
4756             begin
4757                Set_Expression (N, Empty);
4758                Set_No_Initialization (N);
4759                Set_Assignment_OK (Name (Stat));
4760                Set_No_Ctrl_Actions (Stat);
4761                Insert_After_And_Analyze (Init_After, Stat);
4762             end;
4763          end if;
4764
4765          --  Final transformation, if the initializing expression is an entity
4766          --  for a variable with OK_To_Rename set, then we transform:
4767
4768          --     X : typ := expr;
4769
4770          --  into
4771
4772          --     X : typ renames expr
4773
4774          --  provided that X is not aliased. The aliased case has to be
4775          --  excluded in general because Expr will not be aliased in general.
4776          --  We also exclude controlled types because X and Expr may need to
4777          --  be attached to distinct finalization lists.
4778
4779          if Rewrite_As_Renaming then
4780             Rewrite (N,
4781               Make_Object_Renaming_Declaration (Loc,
4782                 Defining_Identifier => Defining_Identifier (N),
4783                 Subtype_Mark        => Object_Definition (N),
4784                 Name                => Expr_Q));
4785
4786             --  We do not analyze this renaming declaration, because all its
4787             --  components have already been analyzed, and if we were to go
4788             --  ahead and analyze it, we would in effect be trying to generate
4789             --  another declaration of X, which won't do!
4790
4791             Set_Renamed_Object (Defining_Identifier (N), Expr_Q);
4792             Set_Analyzed (N);
4793          end if;
4794
4795       end if;
4796
4797    exception
4798       when RE_Not_Available =>
4799          return;
4800    end Expand_N_Object_Declaration;
4801
4802    ---------------------------------
4803    -- Expand_N_Subtype_Indication --
4804    ---------------------------------
4805
4806    --  Add a check on the range of the subtype. The static case is partially
4807    --  duplicated by Process_Range_Expr_In_Decl in Sem_Ch3, but we still need
4808    --  to check here for the static case in order to avoid generating
4809    --  extraneous expanded code. Also deal with validity checking.
4810
4811    procedure Expand_N_Subtype_Indication (N : Node_Id) is
4812       Ran : constant Node_Id   := Range_Expression (Constraint (N));
4813       Typ : constant Entity_Id := Entity (Subtype_Mark (N));
4814
4815    begin
4816       if Nkind (Constraint (N)) = N_Range_Constraint then
4817          Validity_Check_Range (Range_Expression (Constraint (N)));
4818       end if;
4819
4820       if Nkind_In (Parent (N), N_Constrained_Array_Definition, N_Slice) then
4821          Apply_Range_Check (Ran, Typ);
4822       end if;
4823    end Expand_N_Subtype_Indication;
4824
4825    ---------------------------
4826    -- Expand_N_Variant_Part --
4827    ---------------------------
4828
4829    --  If the last variant does not contain the Others choice, replace it with
4830    --  an N_Others_Choice node since Gigi always wants an Others. Note that we
4831    --  do not bother to call Analyze on the modified variant part, since it's
4832    --  only effect would be to compute the Others_Discrete_Choices node
4833    --  laboriously, and of course we already know the list of choices that
4834    --  corresponds to the others choice (it's the list we are replacing!)
4835
4836    procedure Expand_N_Variant_Part (N : Node_Id) is
4837       Last_Var    : constant Node_Id := Last_Non_Pragma (Variants (N));
4838       Others_Node : Node_Id;
4839    begin
4840       if Nkind (First (Discrete_Choices (Last_Var))) /= N_Others_Choice then
4841          Others_Node := Make_Others_Choice (Sloc (Last_Var));
4842          Set_Others_Discrete_Choices
4843            (Others_Node, Discrete_Choices (Last_Var));
4844          Set_Discrete_Choices (Last_Var, New_List (Others_Node));
4845       end if;
4846    end Expand_N_Variant_Part;
4847
4848    ---------------------------------
4849    -- Expand_Previous_Access_Type --
4850    ---------------------------------
4851
4852    procedure Expand_Previous_Access_Type (Def_Id : Entity_Id) is
4853       T : Entity_Id := First_Entity (Current_Scope);
4854
4855    begin
4856       --  Find all access types declared in the current scope, whose
4857       --  designated type is Def_Id. If it does not have a Master_Id,
4858       --  create one now.
4859
4860       while Present (T) loop
4861          if Is_Access_Type (T)
4862            and then Designated_Type (T) = Def_Id
4863            and then No (Master_Id (T))
4864          then
4865             Build_Master_Entity (Def_Id);
4866             Build_Master_Renaming (Parent (Def_Id), T);
4867          end if;
4868
4869          Next_Entity (T);
4870       end loop;
4871    end Expand_Previous_Access_Type;
4872
4873    ------------------------------
4874    -- Expand_Record_Controller --
4875    ------------------------------
4876
4877    procedure Expand_Record_Controller (T : Entity_Id) is
4878       Def             : Node_Id := Type_Definition (Parent (T));
4879       Comp_List       : Node_Id;
4880       Comp_Decl       : Node_Id;
4881       Loc             : Source_Ptr;
4882       First_Comp      : Node_Id;
4883       Controller_Type : Entity_Id;
4884       Ent             : Entity_Id;
4885
4886    begin
4887       if Nkind (Def) = N_Derived_Type_Definition then
4888          Def := Record_Extension_Part (Def);
4889       end if;
4890
4891       if Null_Present (Def) then
4892          Set_Component_List (Def,
4893            Make_Component_List (Sloc (Def),
4894              Component_Items => Empty_List,
4895              Variant_Part => Empty,
4896              Null_Present => True));
4897       end if;
4898
4899       Comp_List := Component_List (Def);
4900
4901       if Null_Present (Comp_List)
4902         or else Is_Empty_List (Component_Items (Comp_List))
4903       then
4904          Loc := Sloc (Comp_List);
4905       else
4906          Loc := Sloc (First (Component_Items (Comp_List)));
4907       end if;
4908
4909       if Is_Inherently_Limited_Type (T) then
4910          Controller_Type := RTE (RE_Limited_Record_Controller);
4911       else
4912          Controller_Type := RTE (RE_Record_Controller);
4913       end if;
4914
4915       Ent := Make_Defining_Identifier (Loc, Name_uController);
4916
4917       Comp_Decl :=
4918         Make_Component_Declaration (Loc,
4919           Defining_Identifier =>  Ent,
4920           Component_Definition =>
4921             Make_Component_Definition (Loc,
4922               Aliased_Present => False,
4923               Subtype_Indication => New_Reference_To (Controller_Type, Loc)));
4924
4925       if Null_Present (Comp_List)
4926         or else Is_Empty_List (Component_Items (Comp_List))
4927       then
4928          Set_Component_Items (Comp_List, New_List (Comp_Decl));
4929          Set_Null_Present (Comp_List, False);
4930
4931       else
4932          --  The controller cannot be placed before the _Parent field since
4933          --  gigi lays out field in order and _parent must be first to preserve
4934          --  the polymorphism of tagged types.
4935
4936          First_Comp := First (Component_Items (Comp_List));
4937
4938          if not Is_Tagged_Type (T) then
4939             Insert_Before (First_Comp, Comp_Decl);
4940
4941          --  if T is a tagged type, place controller declaration after parent
4942          --  field and after eventual tags of interface types.
4943
4944          else
4945             while Present (First_Comp)
4946               and then
4947                 (Chars (Defining_Identifier (First_Comp)) = Name_uParent
4948                    or else Is_Tag (Defining_Identifier (First_Comp))
4949
4950                --  Ada 2005 (AI-251): The following condition covers secondary
4951                --  tags but also the adjacent component containing the offset
4952                --  to the base of the object (component generated if the parent
4953                --  has discriminants --- see Add_Interface_Tag_Components).
4954                --  This is required to avoid the addition of the controller
4955                --  between the secondary tag and its adjacent component.
4956
4957                    or else Present
4958                              (Related_Type
4959                                (Defining_Identifier (First_Comp))))
4960             loop
4961                Next (First_Comp);
4962             end loop;
4963
4964             --  An empty tagged extension might consist only of the parent
4965             --  component. Otherwise insert the controller before the first
4966             --  component that is neither parent nor tag.
4967
4968             if Present (First_Comp) then
4969                Insert_Before (First_Comp, Comp_Decl);
4970             else
4971                Append (Comp_Decl, Component_Items (Comp_List));
4972             end if;
4973          end if;
4974       end if;
4975
4976       Push_Scope (T);
4977       Analyze (Comp_Decl);
4978       Set_Ekind (Ent, E_Component);
4979       Init_Component_Location (Ent);
4980
4981       --  Move the _controller entity ahead in the list of internal entities
4982       --  of the enclosing record so that it is selected instead of a
4983       --  potentially inherited one.
4984
4985       declare
4986          E    : constant Entity_Id := Last_Entity (T);
4987          Comp : Entity_Id;
4988
4989       begin
4990          pragma Assert (Chars (E) = Name_uController);
4991
4992          Set_Next_Entity (E, First_Entity (T));
4993          Set_First_Entity (T, E);
4994
4995          Comp := Next_Entity (E);
4996          while Next_Entity (Comp) /= E loop
4997             Next_Entity (Comp);
4998          end loop;
4999
5000          Set_Next_Entity (Comp, Empty);
5001          Set_Last_Entity (T, Comp);
5002       end;
5003
5004       End_Scope;
5005
5006    exception
5007       when RE_Not_Available =>
5008          return;
5009    end Expand_Record_Controller;
5010
5011    ------------------------
5012    -- Expand_Tagged_Root --
5013    ------------------------
5014
5015    procedure Expand_Tagged_Root (T : Entity_Id) is
5016       Def       : constant Node_Id := Type_Definition (Parent (T));
5017       Comp_List : Node_Id;
5018       Comp_Decl : Node_Id;
5019       Sloc_N    : Source_Ptr;
5020
5021    begin
5022       if Null_Present (Def) then
5023          Set_Component_List (Def,
5024            Make_Component_List (Sloc (Def),
5025              Component_Items => Empty_List,
5026              Variant_Part => Empty,
5027              Null_Present => True));
5028       end if;
5029
5030       Comp_List := Component_List (Def);
5031
5032       if Null_Present (Comp_List)
5033         or else Is_Empty_List (Component_Items (Comp_List))
5034       then
5035          Sloc_N := Sloc (Comp_List);
5036       else
5037          Sloc_N := Sloc (First (Component_Items (Comp_List)));
5038       end if;
5039
5040       Comp_Decl :=
5041         Make_Component_Declaration (Sloc_N,
5042           Defining_Identifier => First_Tag_Component (T),
5043           Component_Definition =>
5044             Make_Component_Definition (Sloc_N,
5045               Aliased_Present => False,
5046               Subtype_Indication => New_Reference_To (RTE (RE_Tag), Sloc_N)));
5047
5048       if Null_Present (Comp_List)
5049         or else Is_Empty_List (Component_Items (Comp_List))
5050       then
5051          Set_Component_Items (Comp_List, New_List (Comp_Decl));
5052          Set_Null_Present (Comp_List, False);
5053
5054       else
5055          Insert_Before (First (Component_Items (Comp_List)), Comp_Decl);
5056       end if;
5057
5058       --  We don't Analyze the whole expansion because the tag component has
5059       --  already been analyzed previously. Here we just insure that the tree
5060       --  is coherent with the semantic decoration
5061
5062       Find_Type (Subtype_Indication (Component_Definition (Comp_Decl)));
5063
5064    exception
5065       when RE_Not_Available =>
5066          return;
5067    end Expand_Tagged_Root;
5068
5069    ----------------------
5070    -- Clean_Task_Names --
5071    ----------------------
5072
5073    procedure Clean_Task_Names
5074      (Typ     : Entity_Id;
5075       Proc_Id : Entity_Id)
5076    is
5077    begin
5078       if Has_Task (Typ)
5079         and then not Restriction_Active (No_Implicit_Heap_Allocations)
5080         and then not Global_Discard_Names
5081         and then VM_Target = No_VM
5082       then
5083          Set_Uses_Sec_Stack (Proc_Id);
5084       end if;
5085    end Clean_Task_Names;
5086
5087    -----------------------
5088    -- Freeze_Array_Type --
5089    -----------------------
5090
5091    procedure Freeze_Array_Type (N : Node_Id) is
5092       Typ      : constant Entity_Id  := Entity (N);
5093       Comp_Typ : constant Entity_Id := Component_Type (Typ);
5094       Base     : constant Entity_Id  := Base_Type (Typ);
5095
5096    begin
5097       if not Is_Bit_Packed_Array (Typ) then
5098
5099          --  If the component contains tasks, so does the array type. This may
5100          --  not be indicated in the array type because the component may have
5101          --  been a private type at the point of definition. Same if component
5102          --  type is controlled.
5103
5104          Set_Has_Task (Base, Has_Task (Comp_Typ));
5105          Set_Has_Controlled_Component (Base,
5106            Has_Controlled_Component (Comp_Typ)
5107              or else Is_Controlled (Comp_Typ));
5108
5109          if No (Init_Proc (Base)) then
5110
5111             --  If this is an anonymous array created for a declaration with
5112             --  an initial value, its init_proc will never be called. The
5113             --  initial value itself may have been expanded into assignments,
5114             --  in which case the object declaration is carries the
5115             --  No_Initialization flag.
5116
5117             if Is_Itype (Base)
5118               and then Nkind (Associated_Node_For_Itype (Base)) =
5119                                                     N_Object_Declaration
5120               and then (Present (Expression (Associated_Node_For_Itype (Base)))
5121                           or else
5122                         No_Initialization (Associated_Node_For_Itype (Base)))
5123             then
5124                null;
5125
5126             --  We do not need an init proc for string or wide [wide] string,
5127             --  since the only time these need initialization in normalize or
5128             --  initialize scalars mode, and these types are treated specially
5129             --  and do not need initialization procedures.
5130
5131             elsif Root_Type (Base) = Standard_String
5132               or else Root_Type (Base) = Standard_Wide_String
5133               or else Root_Type (Base) = Standard_Wide_Wide_String
5134             then
5135                null;
5136
5137             --  Otherwise we have to build an init proc for the subtype
5138
5139             else
5140                Build_Array_Init_Proc (Base, N);
5141             end if;
5142          end if;
5143
5144          if Typ = Base then
5145             if Has_Controlled_Component (Base) then
5146                Build_Controlling_Procs (Base);
5147
5148                if not Is_Limited_Type (Comp_Typ)
5149                  and then Number_Dimensions (Typ) = 1
5150                then
5151                   Build_Slice_Assignment (Typ);
5152                end if;
5153
5154             elsif Ekind (Comp_Typ) = E_Anonymous_Access_Type
5155               and then Needs_Finalization (Directly_Designated_Type (Comp_Typ))
5156             then
5157                Set_Associated_Final_Chain (Comp_Typ, Add_Final_Chain (Typ));
5158             end if;
5159          end if;
5160
5161       --  For packed case, default initialization, except if the component type
5162       --  is itself a packed structure with an initialization procedure, or
5163       --  initialize/normalize scalars active, and we have a base type, or the
5164       --  type is public, because in that case a client might specify
5165       --  Normalize_Scalars and there better be a public Init_Proc for it.
5166
5167       elsif (Present (Init_Proc (Component_Type (Base)))
5168                and then No (Base_Init_Proc (Base)))
5169         or else (Init_Or_Norm_Scalars and then Base = Typ)
5170         or else Is_Public (Typ)
5171       then
5172          Build_Array_Init_Proc (Base, N);
5173       end if;
5174    end Freeze_Array_Type;
5175
5176    -----------------------------
5177    -- Freeze_Enumeration_Type --
5178    -----------------------------
5179
5180    procedure Freeze_Enumeration_Type (N : Node_Id) is
5181       Typ           : constant Entity_Id  := Entity (N);
5182       Loc           : constant Source_Ptr := Sloc (Typ);
5183       Ent           : Entity_Id;
5184       Lst           : List_Id;
5185       Num           : Nat;
5186       Arr           : Entity_Id;
5187       Fent          : Entity_Id;
5188       Ityp          : Entity_Id;
5189       Is_Contiguous : Boolean;
5190       Pos_Expr      : Node_Id;
5191       Last_Repval   : Uint;
5192
5193       Func : Entity_Id;
5194       pragma Warnings (Off, Func);
5195
5196    begin
5197       --  Various optimizations possible if given representation is contiguous
5198
5199       Is_Contiguous := True;
5200
5201       Ent := First_Literal (Typ);
5202       Last_Repval := Enumeration_Rep (Ent);
5203
5204       Next_Literal (Ent);
5205       while Present (Ent) loop
5206          if Enumeration_Rep (Ent) - Last_Repval /= 1 then
5207             Is_Contiguous := False;
5208             exit;
5209          else
5210             Last_Repval := Enumeration_Rep (Ent);
5211          end if;
5212
5213          Next_Literal (Ent);
5214       end loop;
5215
5216       if Is_Contiguous then
5217          Set_Has_Contiguous_Rep (Typ);
5218          Ent := First_Literal (Typ);
5219          Num := 1;
5220          Lst := New_List (New_Reference_To (Ent, Sloc (Ent)));
5221
5222       else
5223          --  Build list of literal references
5224
5225          Lst := New_List;
5226          Num := 0;
5227
5228          Ent := First_Literal (Typ);
5229          while Present (Ent) loop
5230             Append_To (Lst, New_Reference_To (Ent, Sloc (Ent)));
5231             Num := Num + 1;
5232             Next_Literal (Ent);
5233          end loop;
5234       end if;
5235
5236       --  Now build an array declaration
5237
5238       --    typA : array (Natural range 0 .. num - 1) of ctype :=
5239       --             (v, v, v, v, v, ....)
5240
5241       --  where ctype is the corresponding integer type. If the representation
5242       --  is contiguous, we only keep the first literal, which provides the
5243       --  offset for Pos_To_Rep computations.
5244
5245       Arr :=
5246         Make_Defining_Identifier (Loc,
5247           Chars => New_External_Name (Chars (Typ), 'A'));
5248
5249       Append_Freeze_Action (Typ,
5250         Make_Object_Declaration (Loc,
5251           Defining_Identifier => Arr,
5252           Constant_Present    => True,
5253
5254           Object_Definition   =>
5255             Make_Constrained_Array_Definition (Loc,
5256               Discrete_Subtype_Definitions => New_List (
5257                 Make_Subtype_Indication (Loc,
5258                   Subtype_Mark => New_Reference_To (Standard_Natural, Loc),
5259                   Constraint =>
5260                     Make_Range_Constraint (Loc,
5261                       Range_Expression =>
5262                         Make_Range (Loc,
5263                           Low_Bound  =>
5264                             Make_Integer_Literal (Loc, 0),
5265                           High_Bound =>
5266                             Make_Integer_Literal (Loc, Num - 1))))),
5267
5268               Component_Definition =>
5269                 Make_Component_Definition (Loc,
5270                   Aliased_Present => False,
5271                   Subtype_Indication => New_Reference_To (Typ, Loc))),
5272
5273           Expression =>
5274             Make_Aggregate (Loc,
5275               Expressions => Lst)));
5276
5277       Set_Enum_Pos_To_Rep (Typ, Arr);
5278
5279       --  Now we build the function that converts representation values to
5280       --  position values. This function has the form:
5281
5282       --    function _Rep_To_Pos (A : etype; F : Boolean) return Integer is
5283       --    begin
5284       --       case ityp!(A) is
5285       --         when enum-lit'Enum_Rep => return posval;
5286       --         when enum-lit'Enum_Rep => return posval;
5287       --         ...
5288       --         when others   =>
5289       --           [raise Constraint_Error when F "invalid data"]
5290       --           return -1;
5291       --       end case;
5292       --    end;
5293
5294       --  Note: the F parameter determines whether the others case (no valid
5295       --  representation) raises Constraint_Error or returns a unique value
5296       --  of minus one. The latter case is used, e.g. in 'Valid code.
5297
5298       --  Note: the reason we use Enum_Rep values in the case here is to avoid
5299       --  the code generator making inappropriate assumptions about the range
5300       --  of the values in the case where the value is invalid. ityp is a
5301       --  signed or unsigned integer type of appropriate width.
5302
5303       --  Note: if exceptions are not supported, then we suppress the raise
5304       --  and return -1 unconditionally (this is an erroneous program in any
5305       --  case and there is no obligation to raise Constraint_Error here!) We
5306       --  also do this if pragma Restrictions (No_Exceptions) is active.
5307
5308       --  Is this right??? What about No_Exception_Propagation???
5309
5310       --  Representations are signed
5311
5312       if Enumeration_Rep (First_Literal (Typ)) < 0 then
5313
5314          --  The underlying type is signed. Reset the Is_Unsigned_Type
5315          --  explicitly, because it might have been inherited from
5316          --  parent type.
5317
5318          Set_Is_Unsigned_Type (Typ, False);
5319
5320          if Esize (Typ) <= Standard_Integer_Size then
5321             Ityp := Standard_Integer;
5322          else
5323             Ityp := Universal_Integer;
5324          end if;
5325
5326       --  Representations are unsigned
5327
5328       else
5329          if Esize (Typ) <= Standard_Integer_Size then
5330             Ityp := RTE (RE_Unsigned);
5331          else
5332             Ityp := RTE (RE_Long_Long_Unsigned);
5333          end if;
5334       end if;
5335
5336       --  The body of the function is a case statement. First collect case
5337       --  alternatives, or optimize the contiguous case.
5338
5339       Lst := New_List;
5340
5341       --  If representation is contiguous, Pos is computed by subtracting
5342       --  the representation of the first literal.
5343
5344       if Is_Contiguous then
5345          Ent := First_Literal (Typ);
5346
5347          if Enumeration_Rep (Ent) = Last_Repval then
5348
5349             --  Another special case: for a single literal, Pos is zero
5350
5351             Pos_Expr := Make_Integer_Literal (Loc, Uint_0);
5352
5353          else
5354             Pos_Expr :=
5355               Convert_To (Standard_Integer,
5356                 Make_Op_Subtract (Loc,
5357                   Left_Opnd =>
5358                      Unchecked_Convert_To (Ityp,
5359                        Make_Identifier (Loc, Name_uA)),
5360                    Right_Opnd =>
5361                      Make_Integer_Literal (Loc,
5362                         Intval =>
5363                           Enumeration_Rep (First_Literal (Typ)))));
5364          end if;
5365
5366          Append_To (Lst,
5367               Make_Case_Statement_Alternative (Loc,
5368                 Discrete_Choices => New_List (
5369                   Make_Range (Sloc (Enumeration_Rep_Expr (Ent)),
5370                     Low_Bound =>
5371                       Make_Integer_Literal (Loc,
5372                        Intval =>  Enumeration_Rep (Ent)),
5373                     High_Bound =>
5374                       Make_Integer_Literal (Loc, Intval => Last_Repval))),
5375
5376                 Statements => New_List (
5377                   Make_Simple_Return_Statement (Loc,
5378                     Expression => Pos_Expr))));
5379
5380       else
5381          Ent := First_Literal (Typ);
5382          while Present (Ent) loop
5383             Append_To (Lst,
5384               Make_Case_Statement_Alternative (Loc,
5385                 Discrete_Choices => New_List (
5386                   Make_Integer_Literal (Sloc (Enumeration_Rep_Expr (Ent)),
5387                     Intval => Enumeration_Rep (Ent))),
5388
5389                 Statements => New_List (
5390                   Make_Simple_Return_Statement (Loc,
5391                     Expression =>
5392                       Make_Integer_Literal (Loc,
5393                         Intval => Enumeration_Pos (Ent))))));
5394
5395             Next_Literal (Ent);
5396          end loop;
5397       end if;
5398
5399       --  In normal mode, add the others clause with the test
5400
5401       if not No_Exception_Handlers_Set then
5402          Append_To (Lst,
5403            Make_Case_Statement_Alternative (Loc,
5404              Discrete_Choices => New_List (Make_Others_Choice (Loc)),
5405              Statements => New_List (
5406                Make_Raise_Constraint_Error (Loc,
5407                  Condition => Make_Identifier (Loc, Name_uF),
5408                  Reason    => CE_Invalid_Data),
5409                Make_Simple_Return_Statement (Loc,
5410                  Expression =>
5411                    Make_Integer_Literal (Loc, -1)))));
5412
5413       --  If either of the restrictions No_Exceptions_Handlers/Propagation is
5414       --  active then return -1 (we cannot usefully raise Constraint_Error in
5415       --  this case). See description above for further details.
5416
5417       else
5418          Append_To (Lst,
5419            Make_Case_Statement_Alternative (Loc,
5420              Discrete_Choices => New_List (Make_Others_Choice (Loc)),
5421              Statements => New_List (
5422                Make_Simple_Return_Statement (Loc,
5423                  Expression =>
5424                    Make_Integer_Literal (Loc, -1)))));
5425       end if;
5426
5427       --  Now we can build the function body
5428
5429       Fent :=
5430         Make_Defining_Identifier (Loc, Make_TSS_Name (Typ, TSS_Rep_To_Pos));
5431
5432       Func :=
5433         Make_Subprogram_Body (Loc,
5434           Specification =>
5435             Make_Function_Specification (Loc,
5436               Defining_Unit_Name       => Fent,
5437               Parameter_Specifications => New_List (
5438                 Make_Parameter_Specification (Loc,
5439                   Defining_Identifier =>
5440                     Make_Defining_Identifier (Loc, Name_uA),
5441                   Parameter_Type => New_Reference_To (Typ, Loc)),
5442                 Make_Parameter_Specification (Loc,
5443                   Defining_Identifier =>
5444                     Make_Defining_Identifier (Loc, Name_uF),
5445                   Parameter_Type => New_Reference_To (Standard_Boolean, Loc))),
5446
5447               Result_Definition => New_Reference_To (Standard_Integer, Loc)),
5448
5449             Declarations => Empty_List,
5450
5451             Handled_Statement_Sequence =>
5452               Make_Handled_Sequence_Of_Statements (Loc,
5453                 Statements => New_List (
5454                   Make_Case_Statement (Loc,
5455                     Expression =>
5456                       Unchecked_Convert_To (Ityp,
5457                         Make_Identifier (Loc, Name_uA)),
5458                     Alternatives => Lst))));
5459
5460       Set_TSS (Typ, Fent);
5461       Set_Is_Pure (Fent);
5462
5463       if not Debug_Generated_Code then
5464          Set_Debug_Info_Off (Fent);
5465       end if;
5466
5467    exception
5468       when RE_Not_Available =>
5469          return;
5470    end Freeze_Enumeration_Type;
5471
5472    ------------------------
5473    -- Freeze_Record_Type --
5474    ------------------------
5475
5476    procedure Freeze_Record_Type (N : Node_Id) is
5477
5478       procedure Add_Internal_Interface_Entities (Tagged_Type : Entity_Id);
5479       --  Add to the list of primitives of Tagged_Types the internal entities
5480       --  associated with interface primitives that are located in secondary
5481       --  dispatch tables.
5482
5483       -------------------------------------
5484       -- Add_Internal_Interface_Entities --
5485       -------------------------------------
5486
5487       procedure Add_Internal_Interface_Entities (Tagged_Type : Entity_Id) is
5488          Elmt        : Elmt_Id;
5489          Iface       : Entity_Id;
5490          Iface_Elmt  : Elmt_Id;
5491          Iface_Prim  : Entity_Id;
5492          Ifaces_List : Elist_Id;
5493          New_Subp    : Entity_Id := Empty;
5494          Prim        : Entity_Id;
5495
5496       begin
5497          pragma Assert (Ada_Version >= Ada_05
5498            and then Is_Record_Type (Tagged_Type)
5499            and then Is_Tagged_Type (Tagged_Type)
5500            and then Has_Interfaces (Tagged_Type)
5501            and then not Is_Interface (Tagged_Type));
5502
5503          Collect_Interfaces (Tagged_Type, Ifaces_List);
5504
5505          Iface_Elmt := First_Elmt (Ifaces_List);
5506          while Present (Iface_Elmt) loop
5507             Iface := Node (Iface_Elmt);
5508
5509             --  Exclude from this processing interfaces that are parents
5510             --  of Tagged_Type because their primitives are located in the
5511             --  primary dispatch table (and hence no auxiliary internal
5512             --  entities are required to handle secondary dispatch tables
5513             --  in such case).
5514
5515             if not Is_Ancestor (Iface, Tagged_Type) then
5516                Elmt := First_Elmt (Primitive_Operations (Iface));
5517                while Present (Elmt) loop
5518                   Iface_Prim := Node (Elmt);
5519
5520                   if not Is_Predefined_Dispatching_Operation (Iface_Prim) then
5521                      Prim :=
5522                        Find_Primitive_Covering_Interface
5523                          (Tagged_Type => Tagged_Type,
5524                           Iface_Prim  => Iface_Prim);
5525
5526                      pragma Assert (Present (Prim));
5527
5528                      Derive_Subprogram
5529                        (New_Subp     => New_Subp,
5530                         Parent_Subp  => Iface_Prim,
5531                         Derived_Type => Tagged_Type,
5532                         Parent_Type  => Iface);
5533
5534                      --  Ada 2005 (AI-251): Decorate internal entity Iface_Subp
5535                      --  associated with interface types. These entities are
5536                      --  only registered in the list of primitives of its
5537                      --  corresponding tagged type because they are only used
5538                      --  to fill the contents of the secondary dispatch tables.
5539                      --  Therefore they are removed from the homonym chains.
5540
5541                      Set_Is_Hidden (New_Subp);
5542                      Set_Is_Internal (New_Subp);
5543                      Set_Alias (New_Subp, Prim);
5544                      Set_Is_Abstract_Subprogram (New_Subp,
5545                        Is_Abstract_Subprogram (Prim));
5546                      Set_Interface_Alias (New_Subp, Iface_Prim);
5547
5548                      --  Internal entities associated with interface types are
5549                      --  only registered in the list of primitives of the
5550                      --  tagged type. They are only used to fill the contents
5551                      --  of the secondary dispatch tables. Therefore they are
5552                      --  not needed in the homonym chains.
5553
5554                      Remove_Homonym (New_Subp);
5555
5556                      --  Hidden entities associated with interfaces must have
5557                      --  set the Has_Delay_Freeze attribute to ensure that, in
5558                      --  case of locally defined tagged types (or compiling
5559                      --  with static dispatch tables generation disabled) the
5560                      --  corresponding entry of the secondary dispatch table is
5561                      --  filled when such entity is frozen.
5562
5563                      Set_Has_Delayed_Freeze (New_Subp);
5564                   end if;
5565
5566                   Next_Elmt (Elmt);
5567                end loop;
5568             end if;
5569
5570             Next_Elmt (Iface_Elmt);
5571          end loop;
5572       end Add_Internal_Interface_Entities;
5573
5574       --  Local variables
5575
5576       Def_Id        : constant Node_Id := Entity (N);
5577       Type_Decl     : constant Node_Id := Parent (Def_Id);
5578       Comp          : Entity_Id;
5579       Comp_Typ      : Entity_Id;
5580       Has_Static_DT : Boolean := False;
5581       Predef_List   : List_Id;
5582
5583       Flist : Entity_Id := Empty;
5584       --  Finalization list allocated for the case of a type with anonymous
5585       --  access components whose designated type is potentially controlled.
5586
5587       Renamed_Eq : Node_Id := Empty;
5588       --  Defining unit name for the predefined equality function in the case
5589       --  where the type has a primitive operation that is a renaming of
5590       --  predefined equality (but only if there is also an overriding
5591       --  user-defined equality function). Used to pass this entity from
5592       --  Make_Predefined_Primitive_Specs to Predefined_Primitive_Bodies.
5593
5594       Wrapper_Decl_List   : List_Id := No_List;
5595       Wrapper_Body_List   : List_Id := No_List;
5596       Null_Proc_Decl_List : List_Id := No_List;
5597
5598    --  Start of processing for Freeze_Record_Type
5599
5600    begin
5601       --  Build discriminant checking functions if not a derived type (for
5602       --  derived types that are not tagged types, always use the discriminant
5603       --  checking functions of the parent type). However, for untagged types
5604       --  the derivation may have taken place before the parent was frozen, so
5605       --  we copy explicitly the discriminant checking functions from the
5606       --  parent into the components of the derived type.
5607
5608       if not Is_Derived_Type (Def_Id)
5609         or else Has_New_Non_Standard_Rep (Def_Id)
5610         or else Is_Tagged_Type (Def_Id)
5611       then
5612          Build_Discr_Checking_Funcs (Type_Decl);
5613
5614       elsif Is_Derived_Type (Def_Id)
5615         and then not Is_Tagged_Type (Def_Id)
5616
5617          --  If we have a derived Unchecked_Union, we do not inherit the
5618          --  discriminant checking functions from the parent type since the
5619          --  discriminants are non existent.
5620
5621         and then not Is_Unchecked_Union (Def_Id)
5622         and then Has_Discriminants (Def_Id)
5623       then
5624          declare
5625             Old_Comp : Entity_Id;
5626
5627          begin
5628             Old_Comp :=
5629               First_Component (Base_Type (Underlying_Type (Etype (Def_Id))));
5630             Comp := First_Component (Def_Id);
5631             while Present (Comp) loop
5632                if Ekind (Comp) = E_Component
5633                  and then Chars (Comp) = Chars (Old_Comp)
5634                then
5635                   Set_Discriminant_Checking_Func (Comp,
5636                     Discriminant_Checking_Func (Old_Comp));
5637                end if;
5638
5639                Next_Component (Old_Comp);
5640                Next_Component (Comp);
5641             end loop;
5642          end;
5643       end if;
5644
5645       if Is_Derived_Type (Def_Id)
5646         and then Is_Limited_Type (Def_Id)
5647         and then Is_Tagged_Type (Def_Id)
5648       then
5649          Check_Stream_Attributes (Def_Id);
5650       end if;
5651
5652       --  Update task and controlled component flags, because some of the
5653       --  component types may have been private at the point of the record
5654       --  declaration.
5655
5656       Comp := First_Component (Def_Id);
5657
5658       while Present (Comp) loop
5659          Comp_Typ := Etype (Comp);
5660
5661          if Has_Task (Comp_Typ) then
5662             Set_Has_Task (Def_Id);
5663
5664          elsif Has_Controlled_Component (Comp_Typ)
5665            or else (Chars (Comp) /= Name_uParent
5666                      and then Is_Controlled (Comp_Typ))
5667          then
5668             Set_Has_Controlled_Component (Def_Id);
5669
5670          elsif Ekind (Comp_Typ) = E_Anonymous_Access_Type
5671            and then Needs_Finalization (Directly_Designated_Type (Comp_Typ))
5672          then
5673             if No (Flist) then
5674                Flist := Add_Final_Chain (Def_Id);
5675             end if;
5676
5677             Set_Associated_Final_Chain (Comp_Typ, Flist);
5678          end if;
5679
5680          Next_Component (Comp);
5681       end loop;
5682
5683       --  Creation of the Dispatch Table. Note that a Dispatch Table is built
5684       --  for regular tagged types as well as for Ada types deriving from a C++
5685       --  Class, but not for tagged types directly corresponding to C++ classes
5686       --  In the later case we assume that it is created in the C++ side and we
5687       --  just use it.
5688
5689       if Is_Tagged_Type (Def_Id) then
5690          Has_Static_DT :=
5691            Static_Dispatch_Tables
5692              and then Is_Library_Level_Tagged_Type (Def_Id);
5693
5694          --  Add the _Tag component
5695
5696          if Underlying_Type (Etype (Def_Id)) = Def_Id then
5697             Expand_Tagged_Root (Def_Id);
5698          end if;
5699
5700          if Is_CPP_Class (Def_Id) then
5701             Set_All_DT_Position (Def_Id);
5702             Set_CPP_Constructors (Def_Id);
5703
5704             --  Create the tag entities with a minimum decoration
5705
5706             if VM_Target = No_VM then
5707                Append_Freeze_Actions (Def_Id, Make_Tags (Def_Id));
5708             end if;
5709
5710          else
5711             if not Has_Static_DT then
5712
5713                --  Usually inherited primitives are not delayed but the first
5714                --  Ada extension of a CPP_Class is an exception since the
5715                --  address of the inherited subprogram has to be inserted in
5716                --  the new Ada Dispatch Table and this is a freezing action.
5717
5718                --  Similarly, if this is an inherited operation whose parent is
5719                --  not frozen yet, it is not in the DT of the parent, and we
5720                --  generate an explicit freeze node for the inherited operation
5721                --  so that it is properly inserted in the DT of the current
5722                --  type.
5723
5724                declare
5725                   Elmt : Elmt_Id := First_Elmt (Primitive_Operations (Def_Id));
5726                   Subp : Entity_Id;
5727
5728                begin
5729                   while Present (Elmt) loop
5730                      Subp := Node (Elmt);
5731
5732                      if Present (Alias (Subp)) then
5733                         if Is_CPP_Class (Etype (Def_Id)) then
5734                            Set_Has_Delayed_Freeze (Subp);
5735
5736                         elsif Has_Delayed_Freeze (Alias (Subp))
5737                           and then not Is_Frozen (Alias (Subp))
5738                         then
5739                            Set_Is_Frozen (Subp, False);
5740                            Set_Has_Delayed_Freeze (Subp);
5741                         end if;
5742                      end if;
5743
5744                      Next_Elmt (Elmt);
5745                   end loop;
5746                end;
5747             end if;
5748
5749             --  Unfreeze momentarily the type to add the predefined primitives
5750             --  operations. The reason we unfreeze is so that these predefined
5751             --  operations will indeed end up as primitive operations (which
5752             --  must be before the freeze point).
5753
5754             Set_Is_Frozen (Def_Id, False);
5755
5756             --  Do not add the spec of predefined primitives in case of
5757             --  CPP tagged type derivations that have convention CPP.
5758
5759             if Is_CPP_Class (Root_Type (Def_Id))
5760               and then Convention (Def_Id) = Convention_CPP
5761             then
5762                null;
5763
5764             --  Do not add the spec of the predefined primitives if we are
5765             --  compiling under restriction No_Dispatching_Calls
5766
5767             elsif not Restriction_Active (No_Dispatching_Calls) then
5768                Make_Predefined_Primitive_Specs
5769                  (Def_Id, Predef_List, Renamed_Eq);
5770                Insert_List_Before_And_Analyze (N, Predef_List);
5771             end if;
5772
5773             --  Ada 2005 (AI-391): For a nonabstract null extension, create
5774             --  wrapper functions for each nonoverridden inherited function
5775             --  with a controlling result of the type. The wrapper for such
5776             --  a function returns an extension aggregate that invokes the
5777             --  the parent function.
5778
5779             if Ada_Version >= Ada_05
5780               and then not Is_Abstract_Type (Def_Id)
5781               and then Is_Null_Extension (Def_Id)
5782             then
5783                Make_Controlling_Function_Wrappers
5784                  (Def_Id, Wrapper_Decl_List, Wrapper_Body_List);
5785                Insert_List_Before_And_Analyze (N, Wrapper_Decl_List);
5786             end if;
5787
5788             --  Ada 2005 (AI-251): For a nonabstract type extension, build
5789             --  null procedure declarations for each set of homographic null
5790             --  procedures that are inherited from interface types but not
5791             --  overridden. This is done to ensure that the dispatch table
5792             --  entry associated with such null primitives are properly filled.
5793
5794             if Ada_Version >= Ada_05
5795               and then Etype (Def_Id) /= Def_Id
5796               and then not Is_Abstract_Type (Def_Id)
5797             then
5798                Make_Null_Procedure_Specs (Def_Id, Null_Proc_Decl_List);
5799                Insert_Actions (N, Null_Proc_Decl_List);
5800             end if;
5801
5802             --  Ada 2005 (AI-251): Add internal entities associated with
5803             --  secondary dispatch tables to the list of primitives of tagged
5804             --  types that are not interfaces
5805
5806             if Ada_Version >= Ada_05
5807               and then not Is_Interface (Def_Id)
5808               and then Has_Interfaces (Def_Id)
5809             then
5810                Add_Internal_Interface_Entities (Def_Id);
5811             end if;
5812
5813             Set_Is_Frozen (Def_Id);
5814             Set_All_DT_Position (Def_Id);
5815
5816             --  Add the controlled component before the freezing actions
5817             --  referenced in those actions.
5818
5819             if Has_New_Controlled_Component (Def_Id) then
5820                Expand_Record_Controller (Def_Id);
5821             end if;
5822
5823             --  Create and decorate the tags. Suppress their creation when
5824             --  VM_Target because the dispatching mechanism is handled
5825             --  internally by the VMs.
5826
5827             if VM_Target = No_VM then
5828                Append_Freeze_Actions (Def_Id, Make_Tags (Def_Id));
5829
5830                --  Generate dispatch table of locally defined tagged type.
5831                --  Dispatch tables of library level tagged types are built
5832                --  later (see Analyze_Declarations).
5833
5834                if VM_Target = No_VM
5835                  and then not Has_Static_DT
5836                then
5837                   Append_Freeze_Actions (Def_Id, Make_DT (Def_Id));
5838                end if;
5839             end if;
5840
5841             --  If the type has unknown discriminants, propagate dispatching
5842             --  information to its underlying record view, which does not get
5843             --  its own dispatch table.
5844
5845             if Is_Derived_Type (Def_Id)
5846               and then Has_Unknown_Discriminants (Def_Id)
5847               and then Present (Underlying_Record_View (Def_Id))
5848             then
5849                declare
5850                   Rep : constant Entity_Id :=
5851                            Underlying_Record_View (Def_Id);
5852                begin
5853                   Set_Access_Disp_Table
5854                     (Rep, Access_Disp_Table       (Def_Id));
5855                   Set_Dispatch_Table_Wrappers
5856                     (Rep, Dispatch_Table_Wrappers (Def_Id));
5857                   Set_Primitive_Operations
5858                     (Rep, Primitive_Operations    (Def_Id));
5859                end;
5860             end if;
5861
5862             --  Make sure that the primitives Initialize, Adjust and Finalize
5863             --  are Frozen before other TSS subprograms. We don't want them
5864             --  Frozen inside.
5865
5866             if Is_Controlled (Def_Id) then
5867                if not Is_Limited_Type (Def_Id) then
5868                   Append_Freeze_Actions (Def_Id,
5869                     Freeze_Entity
5870                       (Find_Prim_Op (Def_Id, Name_Adjust), Sloc (Def_Id)));
5871                end if;
5872
5873                Append_Freeze_Actions (Def_Id,
5874                  Freeze_Entity
5875                    (Find_Prim_Op (Def_Id, Name_Initialize), Sloc (Def_Id)));
5876
5877                Append_Freeze_Actions (Def_Id,
5878                  Freeze_Entity
5879                    (Find_Prim_Op (Def_Id, Name_Finalize), Sloc (Def_Id)));
5880             end if;
5881
5882             --  Freeze rest of primitive operations. There is no need to handle
5883             --  the predefined primitives if we are compiling under restriction
5884             --  No_Dispatching_Calls
5885
5886             if not Restriction_Active (No_Dispatching_Calls) then
5887                Append_Freeze_Actions
5888                  (Def_Id, Predefined_Primitive_Freeze (Def_Id));
5889             end if;
5890          end if;
5891
5892       --  In the non-tagged case, an equality function is provided only for
5893       --  variant records (that are not unchecked unions).
5894
5895       elsif Has_Discriminants (Def_Id)
5896         and then not Is_Limited_Type (Def_Id)
5897       then
5898          declare
5899             Comps : constant Node_Id :=
5900                       Component_List (Type_Definition (Type_Decl));
5901
5902          begin
5903             if Present (Comps)
5904               and then Present (Variant_Part (Comps))
5905             then
5906                Build_Variant_Record_Equality (Def_Id);
5907             end if;
5908          end;
5909       end if;
5910
5911       --  Before building the record initialization procedure, if we are
5912       --  dealing with a concurrent record value type, then we must go through
5913       --  the discriminants, exchanging discriminals between the concurrent
5914       --  type and the concurrent record value type. See the section "Handling
5915       --  of Discriminants" in the Einfo spec for details.
5916
5917       if Is_Concurrent_Record_Type (Def_Id)
5918         and then Has_Discriminants (Def_Id)
5919       then
5920          declare
5921             Ctyp : constant Entity_Id :=
5922                      Corresponding_Concurrent_Type (Def_Id);
5923             Conc_Discr : Entity_Id;
5924             Rec_Discr  : Entity_Id;
5925             Temp       : Entity_Id;
5926
5927          begin
5928             Conc_Discr := First_Discriminant (Ctyp);
5929             Rec_Discr  := First_Discriminant (Def_Id);
5930
5931             while Present (Conc_Discr) loop
5932                Temp := Discriminal (Conc_Discr);
5933                Set_Discriminal (Conc_Discr, Discriminal (Rec_Discr));
5934                Set_Discriminal (Rec_Discr, Temp);
5935
5936                Set_Discriminal_Link (Discriminal (Conc_Discr), Conc_Discr);
5937                Set_Discriminal_Link (Discriminal (Rec_Discr),  Rec_Discr);
5938
5939                Next_Discriminant (Conc_Discr);
5940                Next_Discriminant (Rec_Discr);
5941             end loop;
5942          end;
5943       end if;
5944
5945       if Has_Controlled_Component (Def_Id) then
5946          if No (Controller_Component (Def_Id)) then
5947             Expand_Record_Controller (Def_Id);
5948          end if;
5949
5950          Build_Controlling_Procs (Def_Id);
5951       end if;
5952
5953       Adjust_Discriminants (Def_Id);
5954
5955       if VM_Target = No_VM or else not Is_Interface (Def_Id) then
5956
5957          --  Do not need init for interfaces on e.g. CIL since they're
5958          --  abstract. Helps operation of peverify (the PE Verify tool).
5959
5960          Build_Record_Init_Proc (Type_Decl, Def_Id);
5961       end if;
5962
5963       --  For tagged type that are not interfaces, build bodies of primitive
5964       --  operations. Note that we do this after building the record
5965       --  initialization procedure, since the primitive operations may need
5966       --  the initialization routine. There is no need to add predefined
5967       --  primitives of interfaces because all their predefined primitives
5968       --  are abstract.
5969
5970       if Is_Tagged_Type (Def_Id)
5971         and then not Is_Interface (Def_Id)
5972       then
5973          --  Do not add the body of predefined primitives in case of
5974          --  CPP tagged type derivations that have convention CPP.
5975
5976          if Is_CPP_Class (Root_Type (Def_Id))
5977            and then Convention (Def_Id) = Convention_CPP
5978          then
5979             null;
5980
5981          --  Do not add the body of the predefined primitives if we are
5982          --  compiling under restriction No_Dispatching_Calls or if we are
5983          --  compiling a CPP tagged type.
5984
5985          elsif not Restriction_Active (No_Dispatching_Calls) then
5986             Predef_List := Predefined_Primitive_Bodies (Def_Id, Renamed_Eq);
5987             Append_Freeze_Actions (Def_Id, Predef_List);
5988          end if;
5989
5990          --  Ada 2005 (AI-391): If any wrappers were created for nonoverridden
5991          --  inherited functions, then add their bodies to the freeze actions.
5992
5993          if Present (Wrapper_Body_List) then
5994             Append_Freeze_Actions (Def_Id, Wrapper_Body_List);
5995          end if;
5996       end if;
5997    end Freeze_Record_Type;
5998
5999    ------------------------------
6000    -- Freeze_Stream_Operations --
6001    ------------------------------
6002
6003    procedure Freeze_Stream_Operations (N : Node_Id; Typ : Entity_Id) is
6004       Names     : constant array (1 .. 4) of TSS_Name_Type :=
6005                     (TSS_Stream_Input,
6006                      TSS_Stream_Output,
6007                      TSS_Stream_Read,
6008                      TSS_Stream_Write);
6009       Stream_Op : Entity_Id;
6010
6011    begin
6012       --  Primitive operations of tagged types are frozen when the dispatch
6013       --  table is constructed.
6014
6015       if not Comes_From_Source (Typ)
6016         or else Is_Tagged_Type (Typ)
6017       then
6018          return;
6019       end if;
6020
6021       for J in Names'Range loop
6022          Stream_Op := TSS (Typ, Names (J));
6023
6024          if Present (Stream_Op)
6025            and then Is_Subprogram (Stream_Op)
6026            and then Nkind (Unit_Declaration_Node (Stream_Op)) =
6027                       N_Subprogram_Declaration
6028            and then not Is_Frozen (Stream_Op)
6029          then
6030             Append_Freeze_Actions
6031                (Typ, Freeze_Entity (Stream_Op, Sloc (N)));
6032          end if;
6033       end loop;
6034    end Freeze_Stream_Operations;
6035
6036    -----------------
6037    -- Freeze_Type --
6038    -----------------
6039
6040    --  Full type declarations are expanded at the point at which the type is
6041    --  frozen. The formal N is the Freeze_Node for the type. Any statements or
6042    --  declarations generated by the freezing (e.g. the procedure generated
6043    --  for initialization) are chained in the Actions field list of the freeze
6044    --  node using Append_Freeze_Actions.
6045
6046    function Freeze_Type (N : Node_Id) return Boolean is
6047       Def_Id    : constant Entity_Id := Entity (N);
6048       RACW_Seen : Boolean := False;
6049       Result    : Boolean := False;
6050
6051    begin
6052       --  Process associated access types needing special processing
6053
6054       if Present (Access_Types_To_Process (N)) then
6055          declare
6056             E : Elmt_Id := First_Elmt (Access_Types_To_Process (N));
6057          begin
6058             while Present (E) loop
6059
6060                if Is_Remote_Access_To_Class_Wide_Type (Node (E)) then
6061                   Validate_RACW_Primitives (Node (E));
6062                   RACW_Seen := True;
6063                end if;
6064
6065                E := Next_Elmt (E);
6066             end loop;
6067          end;
6068
6069          if RACW_Seen then
6070
6071             --  If there are RACWs designating this type, make stubs now
6072
6073             Remote_Types_Tagged_Full_View_Encountered (Def_Id);
6074          end if;
6075       end if;
6076
6077       --  Freeze processing for record types
6078
6079       if Is_Record_Type (Def_Id) then
6080          if Ekind (Def_Id) = E_Record_Type then
6081             Freeze_Record_Type (N);
6082
6083          --  The subtype may have been declared before the type was frozen. If
6084          --  the type has controlled components it is necessary to create the
6085          --  entity for the controller explicitly because it did not exist at
6086          --  the point of the subtype declaration. Only the entity is needed,
6087          --  the back-end will obtain the layout from the type. This is only
6088          --  necessary if this is constrained subtype whose component list is
6089          --  not shared with the base type.
6090
6091          elsif Ekind (Def_Id) = E_Record_Subtype
6092            and then Has_Discriminants (Def_Id)
6093            and then Last_Entity (Def_Id) /= Last_Entity (Base_Type (Def_Id))
6094            and then Present (Controller_Component (Def_Id))
6095          then
6096             declare
6097                Old_C : constant Entity_Id := Controller_Component (Def_Id);
6098                New_C : Entity_Id;
6099
6100             begin
6101                if Scope (Old_C) = Base_Type (Def_Id) then
6102
6103                   --  The entity is the one in the parent. Create new one
6104
6105                   New_C := New_Copy (Old_C);
6106                   Set_Parent (New_C, Parent (Old_C));
6107                   Push_Scope (Def_Id);
6108                   Enter_Name (New_C);
6109                   End_Scope;
6110                end if;
6111             end;
6112
6113             if Is_Itype (Def_Id)
6114               and then Is_Record_Type (Underlying_Type (Scope (Def_Id)))
6115             then
6116                --  The freeze node is only used to introduce the controller,
6117                --  the back-end has no use for it for a discriminated
6118                --  component.
6119
6120                Set_Freeze_Node (Def_Id, Empty);
6121                Set_Has_Delayed_Freeze (Def_Id, False);
6122                Result := True;
6123             end if;
6124
6125          --  Similar process if the controller of the subtype is not present
6126          --  but the parent has it. This can happen with constrained
6127          --  record components where the subtype is an itype.
6128
6129          elsif Ekind (Def_Id) = E_Record_Subtype
6130            and then Is_Itype (Def_Id)
6131            and then No (Controller_Component (Def_Id))
6132            and then Present (Controller_Component (Etype (Def_Id)))
6133          then
6134             declare
6135                Old_C : constant Entity_Id :=
6136                          Controller_Component (Etype (Def_Id));
6137                New_C : constant Entity_Id := New_Copy (Old_C);
6138
6139             begin
6140                Set_Next_Entity  (New_C, First_Entity (Def_Id));
6141                Set_First_Entity (Def_Id, New_C);
6142
6143                --  The freeze node is only used to introduce the controller,
6144                --  the back-end has no use for it for a discriminated
6145                --   component.
6146
6147                Set_Freeze_Node (Def_Id, Empty);
6148                Set_Has_Delayed_Freeze (Def_Id, False);
6149                Result := True;
6150             end;
6151          end if;
6152
6153       --  Freeze processing for array types
6154
6155       elsif Is_Array_Type (Def_Id) then
6156          Freeze_Array_Type (N);
6157
6158       --  Freeze processing for access types
6159
6160       --  For pool-specific access types, find out the pool object used for
6161       --  this type, needs actual expansion of it in some cases. Here are the
6162       --  different cases :
6163
6164       --  1. Rep Clause "for Def_Id'Storage_Size use 0;"
6165       --      ---> don't use any storage pool
6166
6167       --  2. Rep Clause : for Def_Id'Storage_Size use Expr.
6168       --     Expand:
6169       --      Def_Id__Pool : Stack_Bounded_Pool (Expr, DT'Size, DT'Alignment);
6170
6171       --  3. Rep Clause "for Def_Id'Storage_Pool use a_Pool_Object"
6172       --      ---> Storage Pool is the specified one
6173
6174       --  See GNAT Pool packages in the Run-Time for more details
6175
6176       elsif Ekind (Def_Id) = E_Access_Type
6177         or else Ekind (Def_Id) = E_General_Access_Type
6178       then
6179          declare
6180             Loc         : constant Source_Ptr := Sloc (N);
6181             Desig_Type  : constant Entity_Id  := Designated_Type (Def_Id);
6182             Pool_Object : Entity_Id;
6183
6184             Freeze_Action_Typ : Entity_Id;
6185
6186          begin
6187             --  Case 1
6188
6189             --    Rep Clause "for Def_Id'Storage_Size use 0;"
6190             --    ---> don't use any storage pool
6191
6192             if No_Pool_Assigned (Def_Id) then
6193                null;
6194
6195             --  Case 2
6196
6197             --    Rep Clause : for Def_Id'Storage_Size use Expr.
6198             --    ---> Expand:
6199             --           Def_Id__Pool : Stack_Bounded_Pool
6200             --                            (Expr, DT'Size, DT'Alignment);
6201
6202             elsif Has_Storage_Size_Clause (Def_Id) then
6203                declare
6204                   DT_Size  : Node_Id;
6205                   DT_Align : Node_Id;
6206
6207                begin
6208                   --  For unconstrained composite types we give a size of zero
6209                   --  so that the pool knows that it needs a special algorithm
6210                   --  for variable size object allocation.
6211
6212                   if Is_Composite_Type (Desig_Type)
6213                     and then not Is_Constrained (Desig_Type)
6214                   then
6215                      DT_Size :=
6216                        Make_Integer_Literal (Loc, 0);
6217
6218                      DT_Align :=
6219                        Make_Integer_Literal (Loc, Maximum_Alignment);
6220
6221                   else
6222                      DT_Size :=
6223                        Make_Attribute_Reference (Loc,
6224                          Prefix => New_Reference_To (Desig_Type, Loc),
6225                          Attribute_Name => Name_Max_Size_In_Storage_Elements);
6226
6227                      DT_Align :=
6228                        Make_Attribute_Reference (Loc,
6229                          Prefix => New_Reference_To (Desig_Type, Loc),
6230                          Attribute_Name => Name_Alignment);
6231                   end if;
6232
6233                   Pool_Object :=
6234                     Make_Defining_Identifier (Loc,
6235                       Chars => New_External_Name (Chars (Def_Id), 'P'));
6236
6237                   --  We put the code associated with the pools in the entity
6238                   --  that has the later freeze node, usually the access type
6239                   --  but it can also be the designated_type; because the pool
6240                   --  code requires both those types to be frozen
6241
6242                   if Is_Frozen (Desig_Type)
6243                     and then (No (Freeze_Node (Desig_Type))
6244                                or else Analyzed (Freeze_Node (Desig_Type)))
6245                   then
6246                      Freeze_Action_Typ := Def_Id;
6247
6248                   --  A Taft amendment type cannot get the freeze actions
6249                   --  since the full view is not there.
6250
6251                   elsif Is_Incomplete_Or_Private_Type (Desig_Type)
6252                     and then No (Full_View (Desig_Type))
6253                   then
6254                      Freeze_Action_Typ := Def_Id;
6255
6256                   else
6257                      Freeze_Action_Typ := Desig_Type;
6258                   end if;
6259
6260                   Append_Freeze_Action (Freeze_Action_Typ,
6261                     Make_Object_Declaration (Loc,
6262                       Defining_Identifier => Pool_Object,
6263                       Object_Definition =>
6264                         Make_Subtype_Indication (Loc,
6265                           Subtype_Mark =>
6266                             New_Reference_To
6267                               (RTE (RE_Stack_Bounded_Pool), Loc),
6268
6269                           Constraint =>
6270                             Make_Index_Or_Discriminant_Constraint (Loc,
6271                               Constraints => New_List (
6272
6273                               --  First discriminant is the Pool Size
6274
6275                                 New_Reference_To (
6276                                   Storage_Size_Variable (Def_Id), Loc),
6277
6278                               --  Second discriminant is the element size
6279
6280                                 DT_Size,
6281
6282                               --  Third discriminant is the alignment
6283
6284                                 DT_Align)))));
6285                end;
6286
6287                Set_Associated_Storage_Pool (Def_Id, Pool_Object);
6288
6289             --  Case 3
6290
6291             --    Rep Clause "for Def_Id'Storage_Pool use a_Pool_Object"
6292             --    ---> Storage Pool is the specified one
6293
6294             elsif Present (Associated_Storage_Pool (Def_Id)) then
6295
6296                --  Nothing to do the associated storage pool has been attached
6297                --  when analyzing the rep. clause
6298
6299                null;
6300             end if;
6301
6302             --  For access-to-controlled types (including class-wide types and
6303             --  Taft-amendment types which potentially have controlled
6304             --  components), expand the list controller object that will store
6305             --  the dynamically allocated objects. Do not do this
6306             --  transformation for expander-generated access types, but do it
6307             --  for types that are the full view of types derived from other
6308             --  private types. Also suppress the list controller in the case
6309             --  of a designated type with convention Java, since this is used
6310             --  when binding to Java API specs, where there's no equivalent of
6311             --  a finalization list and we don't want to pull in the
6312             --  finalization support if not needed.
6313
6314             if not Comes_From_Source (Def_Id)
6315                and then not Has_Private_Declaration (Def_Id)
6316             then
6317                null;
6318
6319             elsif (Needs_Finalization (Desig_Type)
6320                     and then Convention (Desig_Type) /= Convention_Java
6321                     and then Convention (Desig_Type) /= Convention_CIL)
6322               or else
6323                 (Is_Incomplete_Or_Private_Type (Desig_Type)
6324                    and then No (Full_View (Desig_Type))
6325
6326                   --  An exception is made for types defined in the run-time
6327                   --  because Ada.Tags.Tag itself is such a type and cannot
6328                   --  afford this unnecessary overhead that would generates a
6329                   --  loop in the expansion scheme...
6330
6331                   and then not In_Runtime (Def_Id)
6332
6333                   --  Another exception is if Restrictions (No_Finalization)
6334                   --  is active, since then we know nothing is controlled.
6335
6336                   and then not Restriction_Active (No_Finalization))
6337
6338                --  If the designated type is not frozen yet, its controlled
6339                --  status must be retrieved explicitly.
6340
6341               or else (Is_Array_Type (Desig_Type)
6342                 and then not Is_Frozen (Desig_Type)
6343                 and then Needs_Finalization (Component_Type (Desig_Type)))
6344
6345                --  The designated type has controlled anonymous access
6346                --  discriminants.
6347
6348               or else Has_Controlled_Coextensions (Desig_Type)
6349             then
6350                Set_Associated_Final_Chain (Def_Id, Add_Final_Chain (Def_Id));
6351             end if;
6352          end;
6353
6354       --  Freeze processing for enumeration types
6355
6356       elsif Ekind (Def_Id) = E_Enumeration_Type then
6357
6358          --  We only have something to do if we have a non-standard
6359          --  representation (i.e. at least one literal whose pos value
6360          --  is not the same as its representation)
6361
6362          if Has_Non_Standard_Rep (Def_Id) then
6363             Freeze_Enumeration_Type (N);
6364          end if;
6365
6366       --  Private types that are completed by a derivation from a private
6367       --  type have an internally generated full view, that needs to be
6368       --  frozen. This must be done explicitly because the two views share
6369       --  the freeze node, and the underlying full view is not visible when
6370       --  the freeze node is analyzed.
6371
6372       elsif Is_Private_Type (Def_Id)
6373         and then Is_Derived_Type (Def_Id)
6374         and then Present (Full_View (Def_Id))
6375         and then Is_Itype (Full_View (Def_Id))
6376         and then Has_Private_Declaration (Full_View (Def_Id))
6377         and then Freeze_Node (Full_View (Def_Id)) = N
6378       then
6379          Set_Entity (N, Full_View (Def_Id));
6380          Result := Freeze_Type (N);
6381          Set_Entity (N, Def_Id);
6382
6383       --  All other types require no expander action. There are such cases
6384       --  (e.g. task types and protected types). In such cases, the freeze
6385       --  nodes are there for use by Gigi.
6386
6387       end if;
6388
6389       Freeze_Stream_Operations (N, Def_Id);
6390       return Result;
6391
6392    exception
6393       when RE_Not_Available =>
6394          return False;
6395    end Freeze_Type;
6396
6397    -------------------------
6398    -- Get_Simple_Init_Val --
6399    -------------------------
6400
6401    function Get_Simple_Init_Val
6402      (T    : Entity_Id;
6403       N    : Node_Id;
6404       Size : Uint := No_Uint) return Node_Id
6405    is
6406       Loc    : constant Source_Ptr := Sloc (N);
6407       Val    : Node_Id;
6408       Result : Node_Id;
6409       Val_RE : RE_Id;
6410
6411       Size_To_Use : Uint;
6412       --  This is the size to be used for computation of the appropriate
6413       --  initial value for the Normalize_Scalars and Initialize_Scalars case.
6414
6415       IV_Attribute : constant Boolean :=
6416                        Nkind (N) = N_Attribute_Reference
6417                          and then Attribute_Name (N) = Name_Invalid_Value;
6418
6419       Lo_Bound : Uint;
6420       Hi_Bound : Uint;
6421       --  These are the values computed by the procedure Check_Subtype_Bounds
6422
6423       procedure Check_Subtype_Bounds;
6424       --  This procedure examines the subtype T, and its ancestor subtypes and
6425       --  derived types to determine the best known information about the
6426       --  bounds of the subtype. After the call Lo_Bound is set either to
6427       --  No_Uint if no information can be determined, or to a value which
6428       --  represents a known low bound, i.e. a valid value of the subtype can
6429       --  not be less than this value. Hi_Bound is similarly set to a known
6430       --  high bound (valid value cannot be greater than this).
6431
6432       --------------------------
6433       -- Check_Subtype_Bounds --
6434       --------------------------
6435
6436       procedure Check_Subtype_Bounds is
6437          ST1  : Entity_Id;
6438          ST2  : Entity_Id;
6439          Lo   : Node_Id;
6440          Hi   : Node_Id;
6441          Loval : Uint;
6442          Hival : Uint;
6443
6444       begin
6445          Lo_Bound := No_Uint;
6446          Hi_Bound := No_Uint;
6447
6448          --  Loop to climb ancestor subtypes and derived types
6449
6450          ST1 := T;
6451          loop
6452             if not Is_Discrete_Type (ST1) then
6453                return;
6454             end if;
6455
6456             Lo := Type_Low_Bound (ST1);
6457             Hi := Type_High_Bound (ST1);
6458
6459             if Compile_Time_Known_Value (Lo) then
6460                Loval := Expr_Value (Lo);
6461
6462                if Lo_Bound = No_Uint or else Lo_Bound < Loval then
6463                   Lo_Bound := Loval;
6464                end if;
6465             end if;
6466
6467             if Compile_Time_Known_Value (Hi) then
6468                Hival := Expr_Value (Hi);
6469
6470                if Hi_Bound = No_Uint or else Hi_Bound > Hival then
6471                   Hi_Bound := Hival;
6472                end if;
6473             end if;
6474
6475             ST2 := Ancestor_Subtype (ST1);
6476
6477             if No (ST2) then
6478                ST2 := Etype (ST1);
6479             end if;
6480
6481             exit when ST1 = ST2;
6482             ST1 := ST2;
6483          end loop;
6484       end Check_Subtype_Bounds;
6485
6486    --  Start of processing for Get_Simple_Init_Val
6487
6488    begin
6489       --  For a private type, we should always have an underlying type
6490       --  (because this was already checked in Needs_Simple_Initialization).
6491       --  What we do is to get the value for the underlying type and then do
6492       --  an Unchecked_Convert to the private type.
6493
6494       if Is_Private_Type (T) then
6495          Val := Get_Simple_Init_Val (Underlying_Type (T), N, Size);
6496
6497          --  A special case, if the underlying value is null, then qualify it
6498          --  with the underlying type, so that the null is properly typed
6499          --  Similarly, if it is an aggregate it must be qualified, because an
6500          --  unchecked conversion does not provide a context for it.
6501
6502          if Nkind_In (Val, N_Null, N_Aggregate) then
6503             Val :=
6504               Make_Qualified_Expression (Loc,
6505                 Subtype_Mark =>
6506                   New_Occurrence_Of (Underlying_Type (T), Loc),
6507                 Expression => Val);
6508          end if;
6509
6510          Result := Unchecked_Convert_To (T, Val);
6511
6512          --  Don't truncate result (important for Initialize/Normalize_Scalars)
6513
6514          if Nkind (Result) = N_Unchecked_Type_Conversion
6515            and then Is_Scalar_Type (Underlying_Type (T))
6516          then
6517             Set_No_Truncation (Result);
6518          end if;
6519
6520          return Result;
6521
6522       --  For scalars, we must have normalize/initialize scalars case, or
6523       --  if the node N is an 'Invalid_Value attribute node.
6524
6525       elsif Is_Scalar_Type (T) then
6526          pragma Assert (Init_Or_Norm_Scalars or IV_Attribute);
6527
6528          --  Compute size of object. If it is given by the caller, we can use
6529          --  it directly, otherwise we use Esize (T) as an estimate. As far as
6530          --  we know this covers all cases correctly.
6531
6532          if Size = No_Uint or else Size <= Uint_0 then
6533             Size_To_Use := UI_Max (Uint_1, Esize (T));
6534          else
6535             Size_To_Use := Size;
6536          end if;
6537
6538          --  Maximum size to use is 64 bits, since we will create values
6539          --  of type Unsigned_64 and the range must fit this type.
6540
6541          if Size_To_Use /= No_Uint and then Size_To_Use > Uint_64 then
6542             Size_To_Use := Uint_64;
6543          end if;
6544
6545          --  Check known bounds of subtype
6546
6547          Check_Subtype_Bounds;
6548
6549          --  Processing for Normalize_Scalars case
6550
6551          if Normalize_Scalars and then not IV_Attribute then
6552
6553             --  If zero is invalid, it is a convenient value to use that is
6554             --  for sure an appropriate invalid value in all situations.
6555
6556             if Lo_Bound /= No_Uint and then Lo_Bound > Uint_0 then
6557                Val := Make_Integer_Literal (Loc, 0);
6558
6559             --  Cases where all one bits is the appropriate invalid value
6560
6561             --  For modular types, all 1 bits is either invalid or valid. If
6562             --  it is valid, then there is nothing that can be done since there
6563             --  are no invalid values (we ruled out zero already).
6564
6565             --  For signed integer types that have no negative values, either
6566             --  there is room for negative values, or there is not. If there
6567             --  is, then all 1 bits may be interpreted as minus one, which is
6568             --  certainly invalid. Alternatively it is treated as the largest
6569             --  positive value, in which case the observation for modular types
6570             --  still applies.
6571
6572             --  For float types, all 1-bits is a NaN (not a number), which is
6573             --  certainly an appropriately invalid value.
6574
6575             elsif Is_Unsigned_Type (T)
6576               or else Is_Floating_Point_Type (T)
6577               or else Is_Enumeration_Type (T)
6578             then
6579                Val := Make_Integer_Literal (Loc, 2 ** Size_To_Use - 1);
6580
6581                --  Resolve as Unsigned_64, because the largest number we
6582                --  can generate is out of range of universal integer.
6583
6584                Analyze_And_Resolve (Val, RTE (RE_Unsigned_64));
6585
6586             --  Case of signed types
6587
6588             else
6589                declare
6590                   Signed_Size : constant Uint :=
6591                                   UI_Min (Uint_63, Size_To_Use - 1);
6592
6593                begin
6594                   --  Normally we like to use the most negative number. The
6595                   --  one exception is when this number is in the known
6596                   --  subtype range and the largest positive number is not in
6597                   --  the known subtype range.
6598
6599                   --  For this exceptional case, use largest positive value
6600
6601                   if Lo_Bound /= No_Uint and then Hi_Bound /= No_Uint
6602                     and then Lo_Bound <= (-(2 ** Signed_Size))
6603                     and then Hi_Bound < 2 ** Signed_Size
6604                   then
6605                      Val := Make_Integer_Literal (Loc, 2 ** Signed_Size - 1);
6606
6607                      --  Normal case of largest negative value
6608
6609                   else
6610                      Val := Make_Integer_Literal (Loc, -(2 ** Signed_Size));
6611                   end if;
6612                end;
6613             end if;
6614
6615          --  Here for Initialize_Scalars case (or Invalid_Value attribute used)
6616
6617          else
6618             --  For float types, use float values from System.Scalar_Values
6619
6620             if Is_Floating_Point_Type (T) then
6621                if Root_Type (T) = Standard_Short_Float then
6622                   Val_RE := RE_IS_Isf;
6623                elsif Root_Type (T) = Standard_Float then
6624                   Val_RE := RE_IS_Ifl;
6625                elsif Root_Type (T) = Standard_Long_Float then
6626                   Val_RE := RE_IS_Ilf;
6627                else pragma Assert (Root_Type (T) = Standard_Long_Long_Float);
6628                   Val_RE := RE_IS_Ill;
6629                end if;
6630
6631             --  If zero is invalid, use zero values from System.Scalar_Values
6632
6633             elsif Lo_Bound /= No_Uint and then Lo_Bound > Uint_0 then
6634                if Size_To_Use <= 8 then
6635                   Val_RE := RE_IS_Iz1;
6636                elsif Size_To_Use <= 16 then
6637                   Val_RE := RE_IS_Iz2;
6638                elsif Size_To_Use <= 32 then
6639                   Val_RE := RE_IS_Iz4;
6640                else
6641                   Val_RE := RE_IS_Iz8;
6642                end if;
6643
6644             --  For unsigned, use unsigned values from System.Scalar_Values
6645
6646             elsif Is_Unsigned_Type (T) then
6647                if Size_To_Use <= 8 then
6648                   Val_RE := RE_IS_Iu1;
6649                elsif Size_To_Use <= 16 then
6650                   Val_RE := RE_IS_Iu2;
6651                elsif Size_To_Use <= 32 then
6652                   Val_RE := RE_IS_Iu4;
6653                else
6654                   Val_RE := RE_IS_Iu8;
6655                end if;
6656
6657             --  For signed, use signed values from System.Scalar_Values
6658
6659             else
6660                if Size_To_Use <= 8 then
6661                   Val_RE := RE_IS_Is1;
6662                elsif Size_To_Use <= 16 then
6663                   Val_RE := RE_IS_Is2;
6664                elsif Size_To_Use <= 32 then
6665                   Val_RE := RE_IS_Is4;
6666                else
6667                   Val_RE := RE_IS_Is8;
6668                end if;
6669             end if;
6670
6671             Val := New_Occurrence_Of (RTE (Val_RE), Loc);
6672          end if;
6673
6674          --  The final expression is obtained by doing an unchecked conversion
6675          --  of this result to the base type of the required subtype. We use
6676          --  the base type to avoid the unchecked conversion from chopping
6677          --  bits, and then we set Kill_Range_Check to preserve the "bad"
6678          --  value.
6679
6680          Result := Unchecked_Convert_To (Base_Type (T), Val);
6681
6682          --  Ensure result is not truncated, since we want the "bad" bits
6683          --  and also kill range check on result.
6684
6685          if Nkind (Result) = N_Unchecked_Type_Conversion then
6686             Set_No_Truncation (Result);
6687             Set_Kill_Range_Check (Result, True);
6688          end if;
6689
6690          return Result;
6691
6692       --  String or Wide_[Wide]_String (must have Initialize_Scalars set)
6693
6694       elsif Root_Type (T) = Standard_String
6695               or else
6696             Root_Type (T) = Standard_Wide_String
6697               or else
6698             Root_Type (T) = Standard_Wide_Wide_String
6699       then
6700          pragma Assert (Init_Or_Norm_Scalars);
6701
6702          return
6703            Make_Aggregate (Loc,
6704              Component_Associations => New_List (
6705                Make_Component_Association (Loc,
6706                  Choices => New_List (
6707                    Make_Others_Choice (Loc)),
6708                  Expression =>
6709                    Get_Simple_Init_Val
6710                      (Component_Type (T), N, Esize (Root_Type (T))))));
6711
6712       --  Access type is initialized to null
6713
6714       elsif Is_Access_Type (T) then
6715          return
6716            Make_Null (Loc);
6717
6718       --  No other possibilities should arise, since we should only be
6719       --  calling Get_Simple_Init_Val if Needs_Simple_Initialization
6720       --  returned True, indicating one of the above cases held.
6721
6722       else
6723          raise Program_Error;
6724       end if;
6725
6726    exception
6727       when RE_Not_Available =>
6728          return Empty;
6729    end Get_Simple_Init_Val;
6730
6731    ------------------------------
6732    -- Has_New_Non_Standard_Rep --
6733    ------------------------------
6734
6735    function Has_New_Non_Standard_Rep (T : Entity_Id) return Boolean is
6736    begin
6737       if not Is_Derived_Type (T) then
6738          return Has_Non_Standard_Rep (T)
6739            or else Has_Non_Standard_Rep (Root_Type (T));
6740
6741       --  If Has_Non_Standard_Rep is not set on the derived type, the
6742       --  representation is fully inherited.
6743
6744       elsif not Has_Non_Standard_Rep (T) then
6745          return False;
6746
6747       else
6748          return First_Rep_Item (T) /= First_Rep_Item (Root_Type (T));
6749
6750          --  May need a more precise check here: the First_Rep_Item may
6751          --  be a stream attribute, which does not affect the representation
6752          --  of the type ???
6753       end if;
6754    end Has_New_Non_Standard_Rep;
6755
6756    ----------------
6757    -- In_Runtime --
6758    ----------------
6759
6760    function In_Runtime (E : Entity_Id) return Boolean is
6761       S1 : Entity_Id;
6762
6763    begin
6764       S1 := Scope (E);
6765       while Scope (S1) /= Standard_Standard loop
6766          S1 := Scope (S1);
6767       end loop;
6768
6769       return Chars (S1) = Name_System or else Chars (S1) = Name_Ada;
6770    end In_Runtime;
6771
6772    ----------------------------
6773    -- Initialization_Warning --
6774    ----------------------------
6775
6776    procedure Initialization_Warning (E : Entity_Id) is
6777       Warning_Needed : Boolean;
6778
6779    begin
6780       Warning_Needed := False;
6781
6782       if Ekind (Current_Scope) = E_Package
6783         and then Static_Elaboration_Desired (Current_Scope)
6784       then
6785          if Is_Type (E) then
6786             if Is_Record_Type (E) then
6787                if Has_Discriminants (E)
6788                  or else Is_Limited_Type (E)
6789                  or else Has_Non_Standard_Rep (E)
6790                then
6791                   Warning_Needed := True;
6792
6793                else
6794                   --  Verify that at least one component has an initialization
6795                   --  expression. No need for a warning on a type if all its
6796                   --  components have no initialization.
6797
6798                   declare
6799                      Comp : Entity_Id;
6800
6801                   begin
6802                      Comp := First_Component (E);
6803                      while Present (Comp) loop
6804                         if Ekind (Comp) = E_Discriminant
6805                           or else
6806                             (Nkind (Parent (Comp)) = N_Component_Declaration
6807                                and then Present (Expression (Parent (Comp))))
6808                         then
6809                            Warning_Needed := True;
6810                            exit;
6811                         end if;
6812
6813                         Next_Component (Comp);
6814                      end loop;
6815                   end;
6816                end if;
6817
6818                if Warning_Needed then
6819                   Error_Msg_N
6820                     ("Objects of the type cannot be initialized " &
6821                        "statically by default?",
6822                        Parent (E));
6823                end if;
6824             end if;
6825
6826          else
6827             Error_Msg_N ("Object cannot be initialized statically?", E);
6828          end if;
6829       end if;
6830    end Initialization_Warning;
6831
6832    ------------------
6833    -- Init_Formals --
6834    ------------------
6835
6836    function Init_Formals (Typ : Entity_Id) return List_Id is
6837       Loc     : constant Source_Ptr := Sloc (Typ);
6838       Formals : List_Id;
6839
6840    begin
6841       --  First parameter is always _Init : in out typ. Note that we need
6842       --  this to be in/out because in the case of the task record value,
6843       --  there are default record fields (_Priority, _Size, -Task_Info)
6844       --  that may be referenced in the generated initialization routine.
6845
6846       Formals := New_List (
6847         Make_Parameter_Specification (Loc,
6848           Defining_Identifier =>
6849             Make_Defining_Identifier (Loc, Name_uInit),
6850           In_Present  => True,
6851           Out_Present => True,
6852           Parameter_Type => New_Reference_To (Typ, Loc)));
6853
6854       --  For task record value, or type that contains tasks, add two more
6855       --  formals, _Master : Master_Id and _Chain : in out Activation_Chain
6856       --  We also add these parameters for the task record type case.
6857
6858       if Has_Task (Typ)
6859         or else (Is_Record_Type (Typ) and then Is_Task_Record_Type (Typ))
6860       then
6861          Append_To (Formals,
6862            Make_Parameter_Specification (Loc,
6863              Defining_Identifier =>
6864                Make_Defining_Identifier (Loc, Name_uMaster),
6865              Parameter_Type => New_Reference_To (RTE (RE_Master_Id), Loc)));
6866
6867          Append_To (Formals,
6868            Make_Parameter_Specification (Loc,
6869              Defining_Identifier =>
6870                Make_Defining_Identifier (Loc, Name_uChain),
6871              In_Present => True,
6872              Out_Present => True,
6873              Parameter_Type =>
6874                New_Reference_To (RTE (RE_Activation_Chain), Loc)));
6875
6876          Append_To (Formals,
6877            Make_Parameter_Specification (Loc,
6878              Defining_Identifier =>
6879                Make_Defining_Identifier (Loc, Name_uTask_Name),
6880              In_Present => True,
6881              Parameter_Type =>
6882                New_Reference_To (Standard_String, Loc)));
6883       end if;
6884
6885       return Formals;
6886
6887    exception
6888       when RE_Not_Available =>
6889          return Empty_List;
6890    end Init_Formals;
6891
6892    -------------------------
6893    -- Init_Secondary_Tags --
6894    -------------------------
6895
6896    procedure Init_Secondary_Tags
6897      (Typ            : Entity_Id;
6898       Target         : Node_Id;
6899       Stmts_List     : List_Id;
6900       Fixed_Comps    : Boolean := True;
6901       Variable_Comps : Boolean := True)
6902    is
6903       Loc : constant Source_Ptr := Sloc (Target);
6904
6905       procedure Inherit_CPP_Tag
6906         (Typ       : Entity_Id;
6907          Iface     : Entity_Id;
6908          Tag_Comp  : Entity_Id;
6909          Iface_Tag : Node_Id);
6910       --  Inherit the C++ tag of the secondary dispatch table of Typ associated
6911       --  with Iface. Tag_Comp is the component of Typ that stores Iface_Tag.
6912
6913       procedure Initialize_Tag
6914         (Typ       : Entity_Id;
6915          Iface     : Entity_Id;
6916          Tag_Comp  : Entity_Id;
6917          Iface_Tag : Node_Id);
6918       --  Initialize the tag of the secondary dispatch table of Typ associated
6919       --  with Iface. Tag_Comp is the component of Typ that stores Iface_Tag.
6920       --  Compiling under the CPP full ABI compatibility mode, if the ancestor
6921       --  of Typ CPP tagged type we generate code to inherit the contents of
6922       --  the dispatch table directly from the ancestor.
6923
6924       ---------------------
6925       -- Inherit_CPP_Tag --
6926       ---------------------
6927
6928       procedure Inherit_CPP_Tag
6929         (Typ       : Entity_Id;
6930          Iface     : Entity_Id;
6931          Tag_Comp  : Entity_Id;
6932          Iface_Tag : Node_Id)
6933       is
6934       begin
6935          pragma Assert (Is_CPP_Class (Etype (Typ)));
6936
6937          Append_To (Stmts_List,
6938            Build_Inherit_Prims (Loc,
6939              Typ          => Iface,
6940              Old_Tag_Node =>
6941                Make_Selected_Component (Loc,
6942                  Prefix        => New_Copy_Tree (Target),
6943                  Selector_Name => New_Reference_To (Tag_Comp, Loc)),
6944              New_Tag_Node =>
6945                New_Reference_To (Iface_Tag, Loc),
6946              Num_Prims    =>
6947                UI_To_Int (DT_Entry_Count (First_Tag_Component (Iface)))));
6948       end Inherit_CPP_Tag;
6949
6950       --------------------
6951       -- Initialize_Tag --
6952       --------------------
6953
6954       procedure Initialize_Tag
6955         (Typ       : Entity_Id;
6956          Iface     : Entity_Id;
6957          Tag_Comp  : Entity_Id;
6958          Iface_Tag : Node_Id)
6959       is
6960          Comp_Typ           : Entity_Id;
6961          Offset_To_Top_Comp : Entity_Id := Empty;
6962
6963       begin
6964          --  Initialize the pointer to the secondary DT associated with the
6965          --  interface.
6966
6967          if not Is_Ancestor (Iface, Typ) then
6968             Append_To (Stmts_List,
6969               Make_Assignment_Statement (Loc,
6970                 Name =>
6971                   Make_Selected_Component (Loc,
6972                     Prefix => New_Copy_Tree (Target),
6973                     Selector_Name => New_Reference_To (Tag_Comp, Loc)),
6974                 Expression =>
6975                   New_Reference_To (Iface_Tag, Loc)));
6976          end if;
6977
6978          Comp_Typ := Scope (Tag_Comp);
6979
6980          --  Initialize the entries of the table of interfaces. We generate a
6981          --  different call when the parent of the type has variable size
6982          --  components.
6983
6984          if Comp_Typ /= Etype (Comp_Typ)
6985            and then Is_Variable_Size_Record (Etype (Comp_Typ))
6986            and then Chars (Tag_Comp) /= Name_uTag
6987          then
6988             pragma Assert (Present (DT_Offset_To_Top_Func (Tag_Comp)));
6989
6990             --  Issue error if Set_Dynamic_Offset_To_Top is not available in a
6991             --  configurable run-time environment.
6992
6993             if not RTE_Available (RE_Set_Dynamic_Offset_To_Top) then
6994                Error_Msg_CRT
6995                  ("variable size record with interface types", Typ);
6996                return;
6997             end if;
6998
6999             --  Generate:
7000             --    Set_Dynamic_Offset_To_Top
7001             --      (This         => Init,
7002             --       Interface_T  => Iface'Tag,
7003             --       Offset_Value => n,
7004             --       Offset_Func  => Fn'Address)
7005
7006             Append_To (Stmts_List,
7007               Make_Procedure_Call_Statement (Loc,
7008                 Name => New_Reference_To
7009                           (RTE (RE_Set_Dynamic_Offset_To_Top), Loc),
7010                 Parameter_Associations => New_List (
7011                   Make_Attribute_Reference (Loc,
7012                     Prefix => New_Copy_Tree (Target),
7013                     Attribute_Name => Name_Address),
7014
7015                   Unchecked_Convert_To (RTE (RE_Tag),
7016                     New_Reference_To
7017                       (Node (First_Elmt (Access_Disp_Table (Iface))),
7018                        Loc)),
7019
7020                   Unchecked_Convert_To
7021                     (RTE (RE_Storage_Offset),
7022                      Make_Attribute_Reference (Loc,
7023                        Prefix         =>
7024                          Make_Selected_Component (Loc,
7025                            Prefix => New_Copy_Tree (Target),
7026                            Selector_Name =>
7027                              New_Reference_To (Tag_Comp, Loc)),
7028                        Attribute_Name => Name_Position)),
7029
7030                   Unchecked_Convert_To (RTE (RE_Offset_To_Top_Function_Ptr),
7031                     Make_Attribute_Reference (Loc,
7032                       Prefix => New_Reference_To
7033                                   (DT_Offset_To_Top_Func (Tag_Comp), Loc),
7034                       Attribute_Name => Name_Address)))));
7035
7036             --  In this case the next component stores the value of the
7037             --  offset to the top.
7038
7039             Offset_To_Top_Comp := Next_Entity (Tag_Comp);
7040             pragma Assert (Present (Offset_To_Top_Comp));
7041
7042             Append_To (Stmts_List,
7043               Make_Assignment_Statement (Loc,
7044                 Name =>
7045                   Make_Selected_Component (Loc,
7046                     Prefix => New_Copy_Tree (Target),
7047                     Selector_Name => New_Reference_To
7048                                        (Offset_To_Top_Comp, Loc)),
7049                 Expression =>
7050                   Make_Attribute_Reference (Loc,
7051                     Prefix         =>
7052                       Make_Selected_Component (Loc,
7053                         Prefix => New_Copy_Tree (Target),
7054                         Selector_Name =>
7055                           New_Reference_To (Tag_Comp, Loc)),
7056                   Attribute_Name => Name_Position)));
7057
7058          --  Normal case: No discriminants in the parent type
7059
7060          else
7061             --  Don't need to set any value if this interface shares
7062             --  the primary dispatch table.
7063
7064             if not Is_Ancestor (Iface, Typ) then
7065                Append_To (Stmts_List,
7066                  Build_Set_Static_Offset_To_Top (Loc,
7067                    Iface_Tag    => New_Reference_To (Iface_Tag, Loc),
7068                    Offset_Value =>
7069                      Unchecked_Convert_To (RTE (RE_Storage_Offset),
7070                        Make_Attribute_Reference (Loc,
7071                          Prefix =>
7072                            Make_Selected_Component (Loc,
7073                              Prefix        => New_Copy_Tree (Target),
7074                              Selector_Name =>
7075                                New_Reference_To (Tag_Comp, Loc)),
7076                          Attribute_Name => Name_Position))));
7077             end if;
7078
7079             --  Generate:
7080             --    Register_Interface_Offset
7081             --      (This         => Init,
7082             --       Interface_T  => Iface'Tag,
7083             --       Is_Constant  => True,
7084             --       Offset_Value => n,
7085             --       Offset_Func  => null);
7086
7087             if RTE_Available (RE_Register_Interface_Offset) then
7088                Append_To (Stmts_List,
7089                  Make_Procedure_Call_Statement (Loc,
7090                    Name => New_Reference_To
7091                              (RTE (RE_Register_Interface_Offset), Loc),
7092                    Parameter_Associations => New_List (
7093                      Make_Attribute_Reference (Loc,
7094                        Prefix         => New_Copy_Tree (Target),
7095                        Attribute_Name => Name_Address),
7096
7097                      Unchecked_Convert_To (RTE (RE_Tag),
7098                        New_Reference_To
7099                          (Node (First_Elmt (Access_Disp_Table (Iface))), Loc)),
7100
7101                      New_Occurrence_Of (Standard_True, Loc),
7102
7103                      Unchecked_Convert_To
7104                        (RTE (RE_Storage_Offset),
7105                         Make_Attribute_Reference (Loc,
7106                           Prefix =>
7107                             Make_Selected_Component (Loc,
7108                               Prefix         => New_Copy_Tree (Target),
7109                               Selector_Name  =>
7110                                 New_Reference_To (Tag_Comp, Loc)),
7111                          Attribute_Name => Name_Position)),
7112
7113                      Make_Null (Loc))));
7114             end if;
7115          end if;
7116       end Initialize_Tag;
7117
7118       --  Local variables
7119
7120       Full_Typ         : Entity_Id;
7121       Ifaces_List      : Elist_Id;
7122       Ifaces_Comp_List : Elist_Id;
7123       Ifaces_Tag_List  : Elist_Id;
7124       Iface_Elmt       : Elmt_Id;
7125       Iface_Comp_Elmt  : Elmt_Id;
7126       Iface_Tag_Elmt   : Elmt_Id;
7127       Tag_Comp         : Node_Id;
7128       In_Variable_Pos  : Boolean;
7129
7130    --  Start of processing for Init_Secondary_Tags
7131
7132    begin
7133       --  Handle private types
7134
7135       if Present (Full_View (Typ)) then
7136          Full_Typ := Full_View (Typ);
7137       else
7138          Full_Typ := Typ;
7139       end if;
7140
7141       Collect_Interfaces_Info
7142         (Full_Typ, Ifaces_List, Ifaces_Comp_List, Ifaces_Tag_List);
7143
7144       Iface_Elmt      := First_Elmt (Ifaces_List);
7145       Iface_Comp_Elmt := First_Elmt (Ifaces_Comp_List);
7146       Iface_Tag_Elmt  := First_Elmt (Ifaces_Tag_List);
7147       while Present (Iface_Elmt) loop
7148          Tag_Comp := Node (Iface_Comp_Elmt);
7149
7150          --  If we are compiling under the CPP full ABI compatibility mode and
7151          --  the ancestor is a CPP_Pragma tagged type then we generate code to
7152          --  inherit the contents of the dispatch table directly from the
7153          --  ancestor.
7154
7155          if Is_CPP_Class (Etype (Full_Typ)) then
7156             Inherit_CPP_Tag (Full_Typ,
7157               Iface     => Node (Iface_Elmt),
7158               Tag_Comp  => Tag_Comp,
7159               Iface_Tag => Node (Iface_Tag_Elmt));
7160
7161          --  Otherwise generate code to initialize the tag
7162
7163          else
7164             --  Check if the parent of the record type has variable size
7165             --  components.
7166
7167             In_Variable_Pos := Scope (Tag_Comp) /= Etype (Scope (Tag_Comp))
7168               and then Is_Variable_Size_Record (Etype (Scope (Tag_Comp)));
7169
7170             if (In_Variable_Pos and then Variable_Comps)
7171               or else (not In_Variable_Pos and then Fixed_Comps)
7172             then
7173                Initialize_Tag (Full_Typ,
7174                  Iface     => Node (Iface_Elmt),
7175                  Tag_Comp  => Tag_Comp,
7176                  Iface_Tag => Node (Iface_Tag_Elmt));
7177             end if;
7178          end if;
7179
7180          Next_Elmt (Iface_Elmt);
7181          Next_Elmt (Iface_Comp_Elmt);
7182          Next_Elmt (Iface_Tag_Elmt);
7183       end loop;
7184    end Init_Secondary_Tags;
7185
7186    -----------------------------
7187    -- Is_Variable_Size_Record --
7188    -----------------------------
7189
7190    function Is_Variable_Size_Record (E : Entity_Id) return Boolean is
7191       Comp     : Entity_Id;
7192       Comp_Typ : Entity_Id;
7193       Idx      : Node_Id;
7194
7195       function Is_Constant_Bound (Exp : Node_Id) return Boolean;
7196       --  To simplify handling of array components. Determines whether the
7197       --  given bound is constant (a constant or enumeration literal, or an
7198       --  integer literal) as opposed to per-object, through an expression
7199       --  or a discriminant.
7200
7201       -----------------------
7202       -- Is_Constant_Bound --
7203       -----------------------
7204
7205       function Is_Constant_Bound (Exp : Node_Id) return Boolean is
7206       begin
7207          if Nkind (Exp) = N_Integer_Literal then
7208             return True;
7209          else
7210             return
7211               Is_Entity_Name (Exp)
7212                 and then Present (Entity (Exp))
7213                 and then
7214                  (Ekind (Entity (Exp)) = E_Constant
7215                    or else Ekind (Entity (Exp)) = E_Enumeration_Literal);
7216          end if;
7217       end Is_Constant_Bound;
7218
7219    --  Start of processing for Is_Variable_Sized_Record
7220
7221    begin
7222       pragma Assert (Is_Record_Type (E));
7223
7224       Comp := First_Entity (E);
7225       while Present (Comp) loop
7226          Comp_Typ := Etype (Comp);
7227
7228          if Is_Record_Type (Comp_Typ) then
7229
7230             --  Recursive call if the record type has discriminants
7231
7232             if Has_Discriminants (Comp_Typ)
7233               and then Is_Variable_Size_Record (Comp_Typ)
7234             then
7235                return True;
7236             end if;
7237
7238          elsif Is_Array_Type (Comp_Typ) then
7239
7240             --  Check if some index is initialized with a non-constant value
7241
7242             Idx := First_Index (Comp_Typ);
7243             while Present (Idx) loop
7244                if Nkind (Idx) = N_Range then
7245                   if not Is_Constant_Bound (Low_Bound  (Idx))
7246                        or else
7247                      not Is_Constant_Bound (High_Bound (Idx))
7248                   then
7249                      return True;
7250                   end if;
7251                end if;
7252
7253                Idx := Next_Index (Idx);
7254             end loop;
7255          end if;
7256
7257          Next_Entity (Comp);
7258       end loop;
7259
7260       return False;
7261    end Is_Variable_Size_Record;
7262
7263    ----------------------------------------
7264    -- Make_Controlling_Function_Wrappers --
7265    ----------------------------------------
7266
7267    procedure Make_Controlling_Function_Wrappers
7268      (Tag_Typ   : Entity_Id;
7269       Decl_List : out List_Id;
7270       Body_List : out List_Id)
7271    is
7272       Loc         : constant Source_Ptr := Sloc (Tag_Typ);
7273       Prim_Elmt   : Elmt_Id;
7274       Subp        : Entity_Id;
7275       Actual_List : List_Id;
7276       Formal_List : List_Id;
7277       Formal      : Entity_Id;
7278       Par_Formal  : Entity_Id;
7279       Formal_Node : Node_Id;
7280       Func_Body   : Node_Id;
7281       Func_Decl   : Node_Id;
7282       Func_Spec   : Node_Id;
7283       Return_Stmt : Node_Id;
7284
7285    begin
7286       Decl_List := New_List;
7287       Body_List := New_List;
7288
7289       Prim_Elmt := First_Elmt (Primitive_Operations (Tag_Typ));
7290
7291       while Present (Prim_Elmt) loop
7292          Subp := Node (Prim_Elmt);
7293
7294          --  If a primitive function with a controlling result of the type has
7295          --  not been overridden by the user, then we must create a wrapper
7296          --  function here that effectively overrides it and invokes the
7297          --  (non-abstract) parent function. This can only occur for a null
7298          --  extension. Note that functions with anonymous controlling access
7299          --  results don't qualify and must be overridden. We also exclude
7300          --  Input attributes, since each type will have its own version of
7301          --  Input constructed by the expander. The test for Comes_From_Source
7302          --  is needed to distinguish inherited operations from renamings
7303          --  (which also have Alias set).
7304
7305          --  The function may be abstract, or require_Overriding may be set
7306          --  for it, because tests for null extensions may already have reset
7307          --  the Is_Abstract_Subprogram_Flag. If Requires_Overriding is not
7308          --  set, functions that need wrappers are recognized by having an
7309          --  alias that returns the parent type.
7310
7311          if Comes_From_Source (Subp)
7312            or else No (Alias (Subp))
7313            or else Ekind (Subp) /= E_Function
7314            or else not Has_Controlling_Result (Subp)
7315            or else Is_Access_Type (Etype (Subp))
7316            or else Is_Abstract_Subprogram (Alias (Subp))
7317            or else Is_TSS (Subp, TSS_Stream_Input)
7318          then
7319             goto Next_Prim;
7320
7321          elsif Is_Abstract_Subprogram (Subp)
7322            or else Requires_Overriding (Subp)
7323            or else
7324              (Is_Null_Extension (Etype (Subp))
7325                and then Etype (Alias (Subp)) /= Etype (Subp))
7326          then
7327             Formal_List := No_List;
7328             Formal := First_Formal (Subp);
7329
7330             if Present (Formal) then
7331                Formal_List := New_List;
7332
7333                while Present (Formal) loop
7334                   Append
7335                     (Make_Parameter_Specification
7336                        (Loc,
7337                         Defining_Identifier =>
7338                           Make_Defining_Identifier (Sloc (Formal),
7339                             Chars => Chars (Formal)),
7340                         In_Present  => In_Present (Parent (Formal)),
7341                         Out_Present => Out_Present (Parent (Formal)),
7342                         Null_Exclusion_Present =>
7343                           Null_Exclusion_Present (Parent (Formal)),
7344                         Parameter_Type =>
7345                           New_Reference_To (Etype (Formal), Loc),
7346                         Expression =>
7347                           New_Copy_Tree (Expression (Parent (Formal)))),
7348                      Formal_List);
7349
7350                   Next_Formal (Formal);
7351                end loop;
7352             end if;
7353
7354             Func_Spec :=
7355               Make_Function_Specification (Loc,
7356                 Defining_Unit_Name       =>
7357                   Make_Defining_Identifier (Loc,
7358                     Chars => Chars (Subp)),
7359                 Parameter_Specifications => Formal_List,
7360                 Result_Definition        =>
7361                   New_Reference_To (Etype (Subp), Loc));
7362
7363             Func_Decl := Make_Subprogram_Declaration (Loc, Func_Spec);
7364             Append_To (Decl_List, Func_Decl);
7365
7366             --  Build a wrapper body that calls the parent function. The body
7367             --  contains a single return statement that returns an extension
7368             --  aggregate whose ancestor part is a call to the parent function,
7369             --  passing the formals as actuals (with any controlling arguments
7370             --  converted to the types of the corresponding formals of the
7371             --  parent function, which might be anonymous access types), and
7372             --  having a null extension.
7373
7374             Formal      := First_Formal (Subp);
7375             Par_Formal  := First_Formal (Alias (Subp));
7376             Formal_Node := First (Formal_List);
7377
7378             if Present (Formal) then
7379                Actual_List := New_List;
7380             else
7381                Actual_List := No_List;
7382             end if;
7383
7384             while Present (Formal) loop
7385                if Is_Controlling_Formal (Formal) then
7386                   Append_To (Actual_List,
7387                     Make_Type_Conversion (Loc,
7388                       Subtype_Mark =>
7389                         New_Occurrence_Of (Etype (Par_Formal), Loc),
7390                       Expression   =>
7391                         New_Reference_To
7392                           (Defining_Identifier (Formal_Node), Loc)));
7393                else
7394                   Append_To
7395                     (Actual_List,
7396                      New_Reference_To
7397                        (Defining_Identifier (Formal_Node), Loc));
7398                end if;
7399
7400                Next_Formal (Formal);
7401                Next_Formal (Par_Formal);
7402                Next (Formal_Node);
7403             end loop;
7404
7405             Return_Stmt :=
7406               Make_Simple_Return_Statement (Loc,
7407                 Expression =>
7408                   Make_Extension_Aggregate (Loc,
7409                     Ancestor_Part =>
7410                       Make_Function_Call (Loc,
7411                         Name => New_Reference_To (Alias (Subp), Loc),
7412                         Parameter_Associations => Actual_List),
7413                     Null_Record_Present => True));
7414
7415             Func_Body :=
7416               Make_Subprogram_Body (Loc,
7417                 Specification => New_Copy_Tree (Func_Spec),
7418                 Declarations => Empty_List,
7419                 Handled_Statement_Sequence =>
7420                   Make_Handled_Sequence_Of_Statements (Loc,
7421                     Statements => New_List (Return_Stmt)));
7422
7423             Set_Defining_Unit_Name
7424               (Specification (Func_Body),
7425                 Make_Defining_Identifier (Loc, Chars (Subp)));
7426
7427             Append_To (Body_List, Func_Body);
7428
7429             --  Replace the inherited function with the wrapper function
7430             --  in the primitive operations list.
7431
7432             Override_Dispatching_Operation
7433               (Tag_Typ, Subp, New_Op => Defining_Unit_Name (Func_Spec));
7434          end if;
7435
7436       <<Next_Prim>>
7437          Next_Elmt (Prim_Elmt);
7438       end loop;
7439    end Make_Controlling_Function_Wrappers;
7440
7441    ------------------
7442    -- Make_Eq_Case --
7443    ------------------
7444
7445    --  <Make_Eq_If shared components>
7446    --  case X.D1 is
7447    --     when V1 => <Make_Eq_Case> on subcomponents
7448    --     ...
7449    --     when Vn => <Make_Eq_Case> on subcomponents
7450    --  end case;
7451
7452    function Make_Eq_Case
7453      (E     : Entity_Id;
7454       CL    : Node_Id;
7455       Discr : Entity_Id := Empty) return List_Id
7456    is
7457       Loc      : constant Source_Ptr := Sloc (E);
7458       Result   : constant List_Id    := New_List;
7459       Variant  : Node_Id;
7460       Alt_List : List_Id;
7461
7462    begin
7463       Append_To (Result, Make_Eq_If (E, Component_Items (CL)));
7464
7465       if No (Variant_Part (CL)) then
7466          return Result;
7467       end if;
7468
7469       Variant := First_Non_Pragma (Variants (Variant_Part (CL)));
7470
7471       if No (Variant) then
7472          return Result;
7473       end if;
7474
7475       Alt_List := New_List;
7476
7477       while Present (Variant) loop
7478          Append_To (Alt_List,
7479            Make_Case_Statement_Alternative (Loc,
7480              Discrete_Choices => New_Copy_List (Discrete_Choices (Variant)),
7481              Statements => Make_Eq_Case (E, Component_List (Variant))));
7482
7483          Next_Non_Pragma (Variant);
7484       end loop;
7485
7486       --  If we have an Unchecked_Union, use one of the parameters that
7487       --  captures the discriminants.
7488
7489       if Is_Unchecked_Union (E) then
7490          Append_To (Result,
7491            Make_Case_Statement (Loc,
7492              Expression => New_Reference_To (Discr, Loc),
7493              Alternatives => Alt_List));
7494
7495       else
7496          Append_To (Result,
7497            Make_Case_Statement (Loc,
7498              Expression =>
7499                Make_Selected_Component (Loc,
7500                  Prefix => Make_Identifier (Loc, Name_X),
7501                  Selector_Name => New_Copy (Name (Variant_Part (CL)))),
7502              Alternatives => Alt_List));
7503       end if;
7504
7505       return Result;
7506    end Make_Eq_Case;
7507
7508    ----------------
7509    -- Make_Eq_If --
7510    ----------------
7511
7512    --  Generates:
7513
7514    --    if
7515    --      X.C1 /= Y.C1
7516    --        or else
7517    --      X.C2 /= Y.C2
7518    --        ...
7519    --    then
7520    --       return False;
7521    --    end if;
7522
7523    --  or a null statement if the list L is empty
7524
7525    function Make_Eq_If
7526      (E : Entity_Id;
7527       L : List_Id) return Node_Id
7528    is
7529       Loc        : constant Source_Ptr := Sloc (E);
7530       C          : Node_Id;
7531       Field_Name : Name_Id;
7532       Cond       : Node_Id;
7533
7534    begin
7535       if No (L) then
7536          return Make_Null_Statement (Loc);
7537
7538       else
7539          Cond := Empty;
7540
7541          C := First_Non_Pragma (L);
7542          while Present (C) loop
7543             Field_Name := Chars (Defining_Identifier (C));
7544
7545             --  The tags must not be compared: they are not part of the value.
7546             --  Ditto for the controller component, if present.
7547
7548             --  Note also that in the following, we use Make_Identifier for
7549             --  the component names. Use of New_Reference_To to identify the
7550             --  components would be incorrect because the wrong entities for
7551             --  discriminants could be picked up in the private type case.
7552
7553             if Field_Name /= Name_uTag
7554                  and then
7555                Field_Name /= Name_uController
7556             then
7557                Evolve_Or_Else (Cond,
7558                  Make_Op_Ne (Loc,
7559                    Left_Opnd =>
7560                      Make_Selected_Component (Loc,
7561                        Prefix        => Make_Identifier (Loc, Name_X),
7562                        Selector_Name =>
7563                          Make_Identifier (Loc, Field_Name)),
7564
7565                    Right_Opnd =>
7566                      Make_Selected_Component (Loc,
7567                        Prefix        => Make_Identifier (Loc, Name_Y),
7568                        Selector_Name =>
7569                          Make_Identifier (Loc, Field_Name))));
7570             end if;
7571
7572             Next_Non_Pragma (C);
7573          end loop;
7574
7575          if No (Cond) then
7576             return Make_Null_Statement (Loc);
7577
7578          else
7579             return
7580               Make_Implicit_If_Statement (E,
7581                 Condition => Cond,
7582                 Then_Statements => New_List (
7583                   Make_Simple_Return_Statement (Loc,
7584                     Expression => New_Occurrence_Of (Standard_False, Loc))));
7585          end if;
7586       end if;
7587    end Make_Eq_If;
7588
7589    -------------------------------
7590    -- Make_Null_Procedure_Specs --
7591    -------------------------------
7592
7593    procedure Make_Null_Procedure_Specs
7594      (Tag_Typ   : Entity_Id;
7595       Decl_List : out List_Id)
7596    is
7597       Loc : constant Source_Ptr := Sloc (Tag_Typ);
7598
7599       Formal         : Entity_Id;
7600       Formal_List    : List_Id;
7601       New_Param_Spec : Node_Id;
7602       Parent_Subp    : Entity_Id;
7603       Prim_Elmt      : Elmt_Id;
7604       Proc_Decl      : Node_Id;
7605       Subp           : Entity_Id;
7606
7607       function Is_Null_Interface_Primitive (E : Entity_Id) return Boolean;
7608       --  Returns True if E is a null procedure that is an interface primitive
7609
7610       ---------------------------------
7611       -- Is_Null_Interface_Primitive --
7612       ---------------------------------
7613
7614       function Is_Null_Interface_Primitive (E : Entity_Id) return Boolean is
7615       begin
7616          return Comes_From_Source (E)
7617            and then Is_Dispatching_Operation (E)
7618            and then Ekind (E) = E_Procedure
7619            and then Null_Present (Parent (E))
7620            and then Is_Interface (Find_Dispatching_Type (E));
7621       end Is_Null_Interface_Primitive;
7622
7623    --  Start of processing for Make_Null_Procedure_Specs
7624
7625    begin
7626       Decl_List := New_List;
7627       Prim_Elmt := First_Elmt (Primitive_Operations (Tag_Typ));
7628       while Present (Prim_Elmt) loop
7629          Subp := Node (Prim_Elmt);
7630
7631          --  If a null procedure inherited from an interface has not been
7632          --  overridden, then we build a null procedure declaration to
7633          --  override the inherited procedure.
7634
7635          Parent_Subp := Alias (Subp);
7636
7637          if Present (Parent_Subp)
7638            and then Is_Null_Interface_Primitive (Parent_Subp)
7639          then
7640             Formal_List := No_List;
7641             Formal := First_Formal (Subp);
7642
7643             if Present (Formal) then
7644                Formal_List := New_List;
7645
7646                while Present (Formal) loop
7647
7648                   --  Copy the parameter spec including default expressions
7649
7650                   New_Param_Spec :=
7651                     New_Copy_Tree (Parent (Formal), New_Sloc => Loc);
7652
7653                   --  Generate a new defining identifier for the new formal.
7654                   --  required because New_Copy_Tree does not duplicate
7655                   --  semantic fields (except itypes).
7656
7657                   Set_Defining_Identifier (New_Param_Spec,
7658                     Make_Defining_Identifier (Sloc (Formal),
7659                       Chars => Chars (Formal)));
7660
7661                   --  For controlling arguments we must change their
7662                   --  parameter type to reference the tagged type (instead
7663                   --  of the interface type)
7664
7665                   if Is_Controlling_Formal (Formal) then
7666                      if Nkind (Parameter_Type (Parent (Formal)))
7667                        = N_Identifier
7668                      then
7669                         Set_Parameter_Type (New_Param_Spec,
7670                           New_Occurrence_Of (Tag_Typ, Loc));
7671
7672                      else pragma Assert
7673                             (Nkind (Parameter_Type (Parent (Formal)))
7674                                = N_Access_Definition);
7675                         Set_Subtype_Mark (Parameter_Type (New_Param_Spec),
7676                           New_Occurrence_Of (Tag_Typ, Loc));
7677                      end if;
7678                   end if;
7679
7680                   Append (New_Param_Spec, Formal_List);
7681
7682                   Next_Formal (Formal);
7683                end loop;
7684             end if;
7685
7686             Proc_Decl :=
7687               Make_Subprogram_Declaration (Loc,
7688                 Make_Procedure_Specification (Loc,
7689                   Defining_Unit_Name =>
7690                     Make_Defining_Identifier (Loc, Chars (Subp)),
7691                   Parameter_Specifications => Formal_List,
7692                   Null_Present => True));
7693             Append_To (Decl_List, Proc_Decl);
7694             Analyze (Proc_Decl);
7695          end if;
7696
7697          Next_Elmt (Prim_Elmt);
7698       end loop;
7699    end Make_Null_Procedure_Specs;
7700
7701    -------------------------------------
7702    -- Make_Predefined_Primitive_Specs --
7703    -------------------------------------
7704
7705    procedure Make_Predefined_Primitive_Specs
7706      (Tag_Typ     : Entity_Id;
7707       Predef_List : out List_Id;
7708       Renamed_Eq  : out Entity_Id)
7709    is
7710       Loc       : constant Source_Ptr := Sloc (Tag_Typ);
7711       Res       : constant List_Id    := New_List;
7712       Prim      : Elmt_Id;
7713       Eq_Needed : Boolean;
7714       Eq_Spec   : Node_Id;
7715       Eq_Name   : Name_Id := Name_Op_Eq;
7716
7717       function Is_Predefined_Eq_Renaming (Prim : Node_Id) return Boolean;
7718       --  Returns true if Prim is a renaming of an unresolved predefined
7719       --  equality operation.
7720
7721       -------------------------------
7722       -- Is_Predefined_Eq_Renaming --
7723       -------------------------------
7724
7725       function Is_Predefined_Eq_Renaming (Prim : Node_Id) return Boolean is
7726       begin
7727          return Chars (Prim) /= Name_Op_Eq
7728            and then Present (Alias (Prim))
7729            and then Comes_From_Source (Prim)
7730            and then Is_Intrinsic_Subprogram (Alias (Prim))
7731            and then Chars (Alias (Prim)) = Name_Op_Eq;
7732       end Is_Predefined_Eq_Renaming;
7733
7734    --  Start of processing for Make_Predefined_Primitive_Specs
7735
7736    begin
7737       Renamed_Eq := Empty;
7738
7739       --  Spec of _Size
7740
7741       Append_To (Res, Predef_Spec_Or_Body (Loc,
7742         Tag_Typ => Tag_Typ,
7743         Name    => Name_uSize,
7744         Profile => New_List (
7745           Make_Parameter_Specification (Loc,
7746             Defining_Identifier => Make_Defining_Identifier (Loc, Name_X),
7747             Parameter_Type      => New_Reference_To (Tag_Typ, Loc))),
7748
7749         Ret_Type => Standard_Long_Long_Integer));
7750
7751       --  Spec of _Alignment
7752
7753       Append_To (Res, Predef_Spec_Or_Body (Loc,
7754         Tag_Typ => Tag_Typ,
7755         Name    => Name_uAlignment,
7756         Profile => New_List (
7757           Make_Parameter_Specification (Loc,
7758             Defining_Identifier => Make_Defining_Identifier (Loc, Name_X),
7759             Parameter_Type      => New_Reference_To (Tag_Typ, Loc))),
7760
7761         Ret_Type => Standard_Integer));
7762
7763       --  Specs for dispatching stream attributes
7764
7765       declare
7766          Stream_Op_TSS_Names :
7767            constant array (Integer range <>) of TSS_Name_Type :=
7768              (TSS_Stream_Read,
7769               TSS_Stream_Write,
7770               TSS_Stream_Input,
7771               TSS_Stream_Output);
7772
7773       begin
7774          for Op in Stream_Op_TSS_Names'Range loop
7775             if Stream_Operation_OK (Tag_Typ, Stream_Op_TSS_Names (Op)) then
7776                Append_To (Res,
7777                  Predef_Stream_Attr_Spec (Loc, Tag_Typ,
7778                   Stream_Op_TSS_Names (Op)));
7779             end if;
7780          end loop;
7781       end;
7782
7783       --  Spec of "=" is expanded if the type is not limited and if a
7784       --  user defined "=" was not already declared for the non-full
7785       --  view of a private extension
7786
7787       if not Is_Limited_Type (Tag_Typ) then
7788          Eq_Needed := True;
7789          Prim := First_Elmt (Primitive_Operations (Tag_Typ));
7790          while Present (Prim) loop
7791
7792             --  If a primitive is encountered that renames the predefined
7793             --  equality operator before reaching any explicit equality
7794             --  primitive, then we still need to create a predefined
7795             --  equality function, because calls to it can occur via
7796             --  the renaming. A new name is created for the equality
7797             --  to avoid conflicting with any user-defined equality.
7798             --  (Note that this doesn't account for renamings of
7799             --  equality nested within subpackages???)
7800
7801             if Is_Predefined_Eq_Renaming (Node (Prim)) then
7802                Eq_Name := New_External_Name (Chars (Node (Prim)), 'E');
7803
7804             --  User-defined equality
7805
7806             elsif Chars (Node (Prim)) = Name_Op_Eq
7807               and then Etype (First_Formal (Node (Prim))) =
7808                          Etype (Next_Formal (First_Formal (Node (Prim))))
7809               and then Base_Type (Etype (Node (Prim))) = Standard_Boolean
7810             then
7811                if No (Alias (Node (Prim)))
7812                  or else Nkind (Unit_Declaration_Node (Node (Prim))) =
7813                            N_Subprogram_Renaming_Declaration
7814                then
7815                   Eq_Needed := False;
7816                   exit;
7817
7818                --  If the parent is not an interface type and has an abstract
7819                --  equality function, the inherited equality is abstract as
7820                --  well, and no body can be created for it.
7821
7822                elsif not Is_Interface (Etype (Tag_Typ))
7823                  and then Present (Alias (Node (Prim)))
7824                  and then Is_Abstract_Subprogram (Alias (Node (Prim)))
7825                then
7826                   Eq_Needed := False;
7827                   exit;
7828
7829                --  If the type has an equality function corresponding with
7830                --  a primitive defined in an interface type, the inherited
7831                --  equality is abstract as well, and no body can be created
7832                --  for it.
7833
7834                elsif Present (Alias (Node (Prim)))
7835                  and then Comes_From_Source (Ultimate_Alias (Node (Prim)))
7836                  and then
7837                    Is_Interface
7838                      (Find_Dispatching_Type (Ultimate_Alias (Node (Prim))))
7839                then
7840                   Eq_Needed := False;
7841                   exit;
7842                end if;
7843             end if;
7844
7845             Next_Elmt (Prim);
7846          end loop;
7847
7848          --  If a renaming of predefined equality was found but there was no
7849          --  user-defined equality (so Eq_Needed is still true), then set the
7850          --  name back to Name_Op_Eq. But in the case where a user-defined
7851          --  equality was located after such a renaming, then the predefined
7852          --  equality function is still needed, so Eq_Needed must be set back
7853          --  to True.
7854
7855          if Eq_Name /= Name_Op_Eq then
7856             if Eq_Needed then
7857                Eq_Name := Name_Op_Eq;
7858             else
7859                Eq_Needed := True;
7860             end if;
7861          end if;
7862
7863          if Eq_Needed then
7864             Eq_Spec := Predef_Spec_Or_Body (Loc,
7865               Tag_Typ => Tag_Typ,
7866               Name    => Eq_Name,
7867               Profile => New_List (
7868                 Make_Parameter_Specification (Loc,
7869                   Defining_Identifier =>
7870                     Make_Defining_Identifier (Loc, Name_X),
7871                     Parameter_Type      => New_Reference_To (Tag_Typ, Loc)),
7872                 Make_Parameter_Specification (Loc,
7873                   Defining_Identifier =>
7874                     Make_Defining_Identifier (Loc, Name_Y),
7875                     Parameter_Type      => New_Reference_To (Tag_Typ, Loc))),
7876                 Ret_Type => Standard_Boolean);
7877             Append_To (Res, Eq_Spec);
7878
7879             if Eq_Name /= Name_Op_Eq then
7880                Renamed_Eq := Defining_Unit_Name (Specification (Eq_Spec));
7881
7882                Prim := First_Elmt (Primitive_Operations (Tag_Typ));
7883                while Present (Prim) loop
7884
7885                   --  Any renamings of equality that appeared before an
7886                   --  overriding equality must be updated to refer to the
7887                   --  entity for the predefined equality, otherwise calls via
7888                   --  the renaming would get incorrectly resolved to call the
7889                   --  user-defined equality function.
7890
7891                   if Is_Predefined_Eq_Renaming (Node (Prim)) then
7892                      Set_Alias (Node (Prim), Renamed_Eq);
7893
7894                   --  Exit upon encountering a user-defined equality
7895
7896                   elsif Chars (Node (Prim)) = Name_Op_Eq
7897                     and then No (Alias (Node (Prim)))
7898                   then
7899                      exit;
7900                   end if;
7901
7902                   Next_Elmt (Prim);
7903                end loop;
7904             end if;
7905          end if;
7906
7907          --  Spec for dispatching assignment
7908
7909          Append_To (Res, Predef_Spec_Or_Body (Loc,
7910            Tag_Typ => Tag_Typ,
7911            Name    => Name_uAssign,
7912            Profile => New_List (
7913              Make_Parameter_Specification (Loc,
7914                Defining_Identifier => Make_Defining_Identifier (Loc, Name_X),
7915                Out_Present         => True,
7916                Parameter_Type      => New_Reference_To (Tag_Typ, Loc)),
7917
7918              Make_Parameter_Specification (Loc,
7919                Defining_Identifier => Make_Defining_Identifier (Loc, Name_Y),
7920                Parameter_Type      => New_Reference_To (Tag_Typ, Loc)))));
7921       end if;
7922
7923       --  Ada 2005: Generate declarations for the following primitive
7924       --  operations for limited interfaces and synchronized types that
7925       --  implement a limited interface.
7926
7927       --    Disp_Asynchronous_Select
7928       --    Disp_Conditional_Select
7929       --    Disp_Get_Prim_Op_Kind
7930       --    Disp_Get_Task_Id
7931       --    Disp_Requeue
7932       --    Disp_Timed_Select
7933
7934       --  These operations cannot be implemented on VM targets, so we simply
7935       --  disable their generation in this case. Disable the generation of
7936       --  these bodies if No_Dispatching_Calls, Ravenscar or ZFP is active.
7937
7938       if Ada_Version >= Ada_05
7939         and then VM_Target = No_VM
7940         and then not Restriction_Active (No_Dispatching_Calls)
7941         and then not Restriction_Active (No_Select_Statements)
7942         and then RTE_Available (RE_Select_Specific_Data)
7943       then
7944          --  These primitives are defined abstract in interface types
7945
7946          if Is_Interface (Tag_Typ)
7947            and then Is_Limited_Record (Tag_Typ)
7948          then
7949             Append_To (Res,
7950               Make_Abstract_Subprogram_Declaration (Loc,
7951                 Specification =>
7952                   Make_Disp_Asynchronous_Select_Spec (Tag_Typ)));
7953
7954             Append_To (Res,
7955               Make_Abstract_Subprogram_Declaration (Loc,
7956                 Specification =>
7957                   Make_Disp_Conditional_Select_Spec (Tag_Typ)));
7958
7959             Append_To (Res,
7960               Make_Abstract_Subprogram_Declaration (Loc,
7961                 Specification =>
7962                   Make_Disp_Get_Prim_Op_Kind_Spec (Tag_Typ)));
7963
7964             Append_To (Res,
7965               Make_Abstract_Subprogram_Declaration (Loc,
7966                 Specification =>
7967                   Make_Disp_Get_Task_Id_Spec (Tag_Typ)));
7968
7969             Append_To (Res,
7970               Make_Abstract_Subprogram_Declaration (Loc,
7971                 Specification =>
7972                   Make_Disp_Requeue_Spec (Tag_Typ)));
7973
7974             Append_To (Res,
7975               Make_Abstract_Subprogram_Declaration (Loc,
7976                 Specification =>
7977                   Make_Disp_Timed_Select_Spec (Tag_Typ)));
7978
7979          --  If the ancestor is an interface type we declare non-abstract
7980          --  primitives to override the abstract primitives of the interface
7981          --  type.
7982
7983          elsif (not Is_Interface (Tag_Typ)
7984                   and then Is_Interface (Etype (Tag_Typ))
7985                   and then Is_Limited_Record (Etype (Tag_Typ)))
7986              or else
7987                (Is_Concurrent_Record_Type (Tag_Typ)
7988                   and then Has_Interfaces (Tag_Typ))
7989          then
7990             Append_To (Res,
7991               Make_Subprogram_Declaration (Loc,
7992                 Specification =>
7993                   Make_Disp_Asynchronous_Select_Spec (Tag_Typ)));
7994
7995             Append_To (Res,
7996               Make_Subprogram_Declaration (Loc,
7997                 Specification =>
7998                   Make_Disp_Conditional_Select_Spec (Tag_Typ)));
7999
8000             Append_To (Res,
8001               Make_Subprogram_Declaration (Loc,
8002                 Specification =>
8003                   Make_Disp_Get_Prim_Op_Kind_Spec (Tag_Typ)));
8004
8005             Append_To (Res,
8006               Make_Subprogram_Declaration (Loc,
8007                 Specification =>
8008                   Make_Disp_Get_Task_Id_Spec (Tag_Typ)));
8009
8010             Append_To (Res,
8011               Make_Subprogram_Declaration (Loc,
8012                 Specification =>
8013                   Make_Disp_Requeue_Spec (Tag_Typ)));
8014
8015             Append_To (Res,
8016               Make_Subprogram_Declaration (Loc,
8017                 Specification =>
8018                   Make_Disp_Timed_Select_Spec (Tag_Typ)));
8019          end if;
8020       end if;
8021
8022       --  Specs for finalization actions that may be required in case a future
8023       --  extension contain a controlled element. We generate those only for
8024       --  root tagged types where they will get dummy bodies or when the type
8025       --  has controlled components and their body must be generated. It is
8026       --  also impossible to provide those for tagged types defined within
8027       --  s-finimp since it would involve circularity problems
8028
8029       if In_Finalization_Root (Tag_Typ) then
8030          null;
8031
8032       --  We also skip these if finalization is not available
8033
8034       elsif Restriction_Active (No_Finalization) then
8035          null;
8036
8037       elsif Etype (Tag_Typ) = Tag_Typ
8038         or else Needs_Finalization (Tag_Typ)
8039
8040          --  Ada 2005 (AI-251): We must also generate these subprograms if
8041          --  the immediate ancestor is an interface to ensure the correct
8042          --  initialization of its dispatch table.
8043
8044         or else (not Is_Interface (Tag_Typ)
8045                    and then Is_Interface (Etype (Tag_Typ)))
8046
8047          --  Ada 205 (AI-251): We must also generate these subprograms if
8048          --  the parent of an nonlimited interface is a limited interface
8049
8050         or else (Is_Interface (Tag_Typ)
8051                   and then not Is_Limited_Interface (Tag_Typ)
8052                   and then Is_Limited_Interface (Etype (Tag_Typ)))
8053       then
8054          if not Is_Limited_Type (Tag_Typ) then
8055             Append_To (Res,
8056               Predef_Deep_Spec (Loc, Tag_Typ, TSS_Deep_Adjust));
8057          end if;
8058
8059          Append_To (Res, Predef_Deep_Spec (Loc, Tag_Typ, TSS_Deep_Finalize));
8060       end if;
8061
8062       Predef_List := Res;
8063    end Make_Predefined_Primitive_Specs;
8064
8065    ---------------------------------
8066    -- Needs_Simple_Initialization --
8067    ---------------------------------
8068
8069    function Needs_Simple_Initialization (T : Entity_Id) return Boolean is
8070    begin
8071       --  Check for private type, in which case test applies to the underlying
8072       --  type of the private type.
8073
8074       if Is_Private_Type (T) then
8075          declare
8076             RT : constant Entity_Id := Underlying_Type (T);
8077
8078          begin
8079             if Present (RT) then
8080                return Needs_Simple_Initialization (RT);
8081             else
8082                return False;
8083             end if;
8084          end;
8085
8086       --  Cases needing simple initialization are access types, and, if pragma
8087       --  Normalize_Scalars or Initialize_Scalars is in effect, then all scalar
8088       --  types.
8089
8090       elsif Is_Access_Type (T)
8091         or else (Init_Or_Norm_Scalars and then (Is_Scalar_Type (T)))
8092       then
8093          return True;
8094
8095       --  If Initialize/Normalize_Scalars is in effect, string objects also
8096       --  need initialization, unless they are created in the course of
8097       --  expanding an aggregate (since in the latter case they will be
8098       --  filled with appropriate initializing values before they are used).
8099
8100       elsif Init_Or_Norm_Scalars
8101         and then
8102           (Root_Type (T) = Standard_String
8103              or else Root_Type (T) = Standard_Wide_String
8104              or else Root_Type (T) = Standard_Wide_Wide_String)
8105         and then
8106           (not Is_Itype (T)
8107             or else Nkind (Associated_Node_For_Itype (T)) /= N_Aggregate)
8108       then
8109          return True;
8110
8111       else
8112          return False;
8113       end if;
8114    end Needs_Simple_Initialization;
8115
8116    ----------------------
8117    -- Predef_Deep_Spec --
8118    ----------------------
8119
8120    function Predef_Deep_Spec
8121      (Loc      : Source_Ptr;
8122       Tag_Typ  : Entity_Id;
8123       Name     : TSS_Name_Type;
8124       For_Body : Boolean := False) return Node_Id
8125    is
8126       Prof   : List_Id;
8127       Type_B : Entity_Id;
8128
8129    begin
8130       if Name = TSS_Deep_Finalize then
8131          Prof := New_List;
8132          Type_B := Standard_Boolean;
8133
8134       else
8135          Prof := New_List (
8136            Make_Parameter_Specification (Loc,
8137              Defining_Identifier => Make_Defining_Identifier (Loc, Name_L),
8138              In_Present          => True,
8139              Out_Present         => True,
8140              Parameter_Type      =>
8141                New_Reference_To (RTE (RE_Finalizable_Ptr), Loc)));
8142          Type_B := Standard_Short_Short_Integer;
8143       end if;
8144
8145       Append_To (Prof,
8146            Make_Parameter_Specification (Loc,
8147              Defining_Identifier => Make_Defining_Identifier (Loc, Name_V),
8148              In_Present          => True,
8149              Out_Present         => True,
8150              Parameter_Type      => New_Reference_To (Tag_Typ, Loc)));
8151
8152       Append_To (Prof,
8153            Make_Parameter_Specification (Loc,
8154              Defining_Identifier => Make_Defining_Identifier (Loc, Name_B),
8155              Parameter_Type      => New_Reference_To (Type_B, Loc)));
8156
8157       return Predef_Spec_Or_Body (Loc,
8158         Name     => Make_TSS_Name (Tag_Typ, Name),
8159         Tag_Typ  => Tag_Typ,
8160         Profile  => Prof,
8161         For_Body => For_Body);
8162
8163    exception
8164       when RE_Not_Available =>
8165          return Empty;
8166    end Predef_Deep_Spec;
8167
8168    -------------------------
8169    -- Predef_Spec_Or_Body --
8170    -------------------------
8171
8172    function Predef_Spec_Or_Body
8173      (Loc      : Source_Ptr;
8174       Tag_Typ  : Entity_Id;
8175       Name     : Name_Id;
8176       Profile  : List_Id;
8177       Ret_Type : Entity_Id := Empty;
8178       For_Body : Boolean := False) return Node_Id
8179    is
8180       Id   : constant Entity_Id := Make_Defining_Identifier (Loc, Name);
8181       Spec : Node_Id;
8182
8183    begin
8184       Set_Is_Public (Id, Is_Public (Tag_Typ));
8185
8186       --  The internal flag is set to mark these declarations because they have
8187       --  specific properties. First, they are primitives even if they are not
8188       --  defined in the type scope (the freezing point is not necessarily in
8189       --  the same scope). Second, the predefined equality can be overridden by
8190       --  a user-defined equality, no body will be generated in this case.
8191
8192       Set_Is_Internal (Id);
8193
8194       if not Debug_Generated_Code then
8195          Set_Debug_Info_Off (Id);
8196       end if;
8197
8198       if No (Ret_Type) then
8199          Spec :=
8200            Make_Procedure_Specification (Loc,
8201              Defining_Unit_Name       => Id,
8202              Parameter_Specifications => Profile);
8203       else
8204          Spec :=
8205            Make_Function_Specification (Loc,
8206              Defining_Unit_Name       => Id,
8207              Parameter_Specifications => Profile,
8208              Result_Definition        =>
8209                New_Reference_To (Ret_Type, Loc));
8210       end if;
8211
8212       if Is_Interface (Tag_Typ) then
8213          return Make_Abstract_Subprogram_Declaration (Loc, Spec);
8214
8215       --  If body case, return empty subprogram body. Note that this is ill-
8216       --  formed, because there is not even a null statement, and certainly not
8217       --  a return in the function case. The caller is expected to do surgery
8218       --  on the body to add the appropriate stuff.
8219
8220       elsif For_Body then
8221          return Make_Subprogram_Body (Loc, Spec, Empty_List, Empty);
8222
8223       --  For the case of an Input attribute predefined for an abstract type,
8224       --  generate an abstract specification. This will never be called, but we
8225       --  need the slot allocated in the dispatching table so that attributes
8226       --  typ'Class'Input and typ'Class'Output will work properly.
8227
8228       elsif Is_TSS (Name, TSS_Stream_Input)
8229         and then Is_Abstract_Type (Tag_Typ)
8230       then
8231          return Make_Abstract_Subprogram_Declaration (Loc, Spec);
8232
8233       --  Normal spec case, where we return a subprogram declaration
8234
8235       else
8236          return Make_Subprogram_Declaration (Loc, Spec);
8237       end if;
8238    end Predef_Spec_Or_Body;
8239
8240    -----------------------------
8241    -- Predef_Stream_Attr_Spec --
8242    -----------------------------
8243
8244    function Predef_Stream_Attr_Spec
8245      (Loc      : Source_Ptr;
8246       Tag_Typ  : Entity_Id;
8247       Name     : TSS_Name_Type;
8248       For_Body : Boolean := False) return Node_Id
8249    is
8250       Ret_Type : Entity_Id;
8251
8252    begin
8253       if Name = TSS_Stream_Input then
8254          Ret_Type := Tag_Typ;
8255       else
8256          Ret_Type := Empty;
8257       end if;
8258
8259       return Predef_Spec_Or_Body (Loc,
8260         Name     => Make_TSS_Name (Tag_Typ, Name),
8261         Tag_Typ  => Tag_Typ,
8262         Profile  => Build_Stream_Attr_Profile (Loc, Tag_Typ, Name),
8263         Ret_Type => Ret_Type,
8264         For_Body => For_Body);
8265    end Predef_Stream_Attr_Spec;
8266
8267    ---------------------------------
8268    -- Predefined_Primitive_Bodies --
8269    ---------------------------------
8270
8271    function Predefined_Primitive_Bodies
8272      (Tag_Typ    : Entity_Id;
8273       Renamed_Eq : Entity_Id) return List_Id
8274    is
8275       Loc       : constant Source_Ptr := Sloc (Tag_Typ);
8276       Res       : constant List_Id    := New_List;
8277       Decl      : Node_Id;
8278       Prim      : Elmt_Id;
8279       Eq_Needed : Boolean;
8280       Eq_Name   : Name_Id;
8281       Ent       : Entity_Id;
8282
8283       pragma Warnings (Off, Ent);
8284
8285    begin
8286       pragma Assert (not Is_Interface (Tag_Typ));
8287
8288       --  See if we have a predefined "=" operator
8289
8290       if Present (Renamed_Eq) then
8291          Eq_Needed := True;
8292          Eq_Name   := Chars (Renamed_Eq);
8293
8294       --  If the parent is an interface type then it has defined all the
8295       --  predefined primitives abstract and we need to check if the type
8296       --  has some user defined "=" function to avoid generating it.
8297
8298       elsif Is_Interface (Etype (Tag_Typ)) then
8299          Eq_Needed := True;
8300          Eq_Name := Name_Op_Eq;
8301
8302          Prim := First_Elmt (Primitive_Operations (Tag_Typ));
8303          while Present (Prim) loop
8304             if Chars (Node (Prim)) = Name_Op_Eq
8305               and then not Is_Internal (Node (Prim))
8306             then
8307                Eq_Needed := False;
8308                Eq_Name := No_Name;
8309                exit;
8310             end if;
8311
8312             Next_Elmt (Prim);
8313          end loop;
8314
8315       else
8316          Eq_Needed := False;
8317          Eq_Name   := No_Name;
8318
8319          Prim := First_Elmt (Primitive_Operations (Tag_Typ));
8320          while Present (Prim) loop
8321             if Chars (Node (Prim)) = Name_Op_Eq
8322               and then Is_Internal (Node (Prim))
8323             then
8324                Eq_Needed := True;
8325                Eq_Name := Name_Op_Eq;
8326                exit;
8327             end if;
8328
8329             Next_Elmt (Prim);
8330          end loop;
8331       end if;
8332
8333       --  Body of _Alignment
8334
8335       Decl := Predef_Spec_Or_Body (Loc,
8336         Tag_Typ => Tag_Typ,
8337         Name    => Name_uAlignment,
8338         Profile => New_List (
8339           Make_Parameter_Specification (Loc,
8340             Defining_Identifier => Make_Defining_Identifier (Loc, Name_X),
8341             Parameter_Type      => New_Reference_To (Tag_Typ, Loc))),
8342
8343         Ret_Type => Standard_Integer,
8344         For_Body => True);
8345
8346       Set_Handled_Statement_Sequence (Decl,
8347         Make_Handled_Sequence_Of_Statements (Loc, New_List (
8348           Make_Simple_Return_Statement (Loc,
8349             Expression =>
8350               Make_Attribute_Reference (Loc,
8351                 Prefix => Make_Identifier (Loc, Name_X),
8352                 Attribute_Name  => Name_Alignment)))));
8353
8354       Append_To (Res, Decl);
8355
8356       --  Body of _Size
8357
8358       Decl := Predef_Spec_Or_Body (Loc,
8359         Tag_Typ => Tag_Typ,
8360         Name    => Name_uSize,
8361         Profile => New_List (
8362           Make_Parameter_Specification (Loc,
8363             Defining_Identifier => Make_Defining_Identifier (Loc, Name_X),
8364             Parameter_Type      => New_Reference_To (Tag_Typ, Loc))),
8365
8366         Ret_Type => Standard_Long_Long_Integer,
8367         For_Body => True);
8368
8369       Set_Handled_Statement_Sequence (Decl,
8370         Make_Handled_Sequence_Of_Statements (Loc, New_List (
8371           Make_Simple_Return_Statement (Loc,
8372             Expression =>
8373               Make_Attribute_Reference (Loc,
8374                 Prefix => Make_Identifier (Loc, Name_X),
8375                 Attribute_Name  => Name_Size)))));
8376
8377       Append_To (Res, Decl);
8378
8379       --  Bodies for Dispatching stream IO routines. We need these only for
8380       --  non-limited types (in the limited case there is no dispatching).
8381       --  We also skip them if dispatching or finalization are not available.
8382
8383       if Stream_Operation_OK (Tag_Typ, TSS_Stream_Read)
8384         and then No (TSS (Tag_Typ, TSS_Stream_Read))
8385       then
8386          Build_Record_Read_Procedure (Loc, Tag_Typ, Decl, Ent);
8387          Append_To (Res, Decl);
8388       end if;
8389
8390       if Stream_Operation_OK (Tag_Typ, TSS_Stream_Write)
8391         and then No (TSS (Tag_Typ, TSS_Stream_Write))
8392       then
8393          Build_Record_Write_Procedure (Loc, Tag_Typ, Decl, Ent);
8394          Append_To (Res, Decl);
8395       end if;
8396
8397       --  Skip body of _Input for the abstract case, since the corresponding
8398       --  spec is abstract (see Predef_Spec_Or_Body).
8399
8400       if not Is_Abstract_Type (Tag_Typ)
8401         and then Stream_Operation_OK (Tag_Typ, TSS_Stream_Input)
8402         and then No (TSS (Tag_Typ, TSS_Stream_Input))
8403       then
8404          Build_Record_Or_Elementary_Input_Function
8405            (Loc, Tag_Typ, Decl, Ent);
8406          Append_To (Res, Decl);
8407       end if;
8408
8409       if Stream_Operation_OK (Tag_Typ, TSS_Stream_Output)
8410         and then No (TSS (Tag_Typ, TSS_Stream_Output))
8411       then
8412          Build_Record_Or_Elementary_Output_Procedure
8413            (Loc, Tag_Typ, Decl, Ent);
8414          Append_To (Res, Decl);
8415       end if;
8416
8417       --  Ada 2005: Generate bodies for the following primitive operations for
8418       --  limited interfaces and synchronized types that implement a limited
8419       --  interface.
8420
8421       --    disp_asynchronous_select
8422       --    disp_conditional_select
8423       --    disp_get_prim_op_kind
8424       --    disp_get_task_id
8425       --    disp_timed_select
8426
8427       --  The interface versions will have null bodies
8428
8429       --  These operations cannot be implemented on VM targets, so we simply
8430       --  disable their generation in this case. Disable the generation of
8431       --  these bodies if No_Dispatching_Calls, Ravenscar or ZFP is active.
8432
8433       if Ada_Version >= Ada_05
8434         and then VM_Target = No_VM
8435         and then not Is_Interface (Tag_Typ)
8436         and then
8437           ((Is_Interface (Etype (Tag_Typ))
8438               and then Is_Limited_Record (Etype (Tag_Typ)))
8439            or else (Is_Concurrent_Record_Type (Tag_Typ)
8440                       and then Has_Interfaces (Tag_Typ)))
8441         and then not Restriction_Active (No_Dispatching_Calls)
8442         and then not Restriction_Active (No_Select_Statements)
8443         and then RTE_Available (RE_Select_Specific_Data)
8444       then
8445          Append_To (Res, Make_Disp_Asynchronous_Select_Body (Tag_Typ));
8446          Append_To (Res, Make_Disp_Conditional_Select_Body  (Tag_Typ));
8447          Append_To (Res, Make_Disp_Get_Prim_Op_Kind_Body    (Tag_Typ));
8448          Append_To (Res, Make_Disp_Get_Task_Id_Body         (Tag_Typ));
8449          Append_To (Res, Make_Disp_Requeue_Body             (Tag_Typ));
8450          Append_To (Res, Make_Disp_Timed_Select_Body        (Tag_Typ));
8451       end if;
8452
8453       if not Is_Limited_Type (Tag_Typ)
8454         and then not Is_Interface (Tag_Typ)
8455       then
8456          --  Body for equality
8457
8458          if Eq_Needed then
8459             Decl :=
8460               Predef_Spec_Or_Body (Loc,
8461                 Tag_Typ => Tag_Typ,
8462                 Name    => Eq_Name,
8463                 Profile => New_List (
8464                   Make_Parameter_Specification (Loc,
8465                     Defining_Identifier =>
8466                       Make_Defining_Identifier (Loc, Name_X),
8467                     Parameter_Type      => New_Reference_To (Tag_Typ, Loc)),
8468
8469                   Make_Parameter_Specification (Loc,
8470                     Defining_Identifier =>
8471                       Make_Defining_Identifier (Loc, Name_Y),
8472                     Parameter_Type      => New_Reference_To (Tag_Typ, Loc))),
8473
8474                 Ret_Type => Standard_Boolean,
8475                 For_Body => True);
8476
8477             declare
8478                Def          : constant Node_Id := Parent (Tag_Typ);
8479                Stmts        : constant List_Id := New_List;
8480                Variant_Case : Boolean := Has_Discriminants (Tag_Typ);
8481                Comps        : Node_Id := Empty;
8482                Typ_Def      : Node_Id := Type_Definition (Def);
8483
8484             begin
8485                if Variant_Case then
8486                   if Nkind (Typ_Def) = N_Derived_Type_Definition then
8487                      Typ_Def := Record_Extension_Part (Typ_Def);
8488                   end if;
8489
8490                   if Present (Typ_Def) then
8491                      Comps := Component_List (Typ_Def);
8492                   end if;
8493
8494                   Variant_Case := Present (Comps)
8495                     and then Present (Variant_Part (Comps));
8496                end if;
8497
8498                if Variant_Case then
8499                   Append_To (Stmts,
8500                     Make_Eq_If (Tag_Typ, Discriminant_Specifications (Def)));
8501                   Append_List_To (Stmts, Make_Eq_Case (Tag_Typ, Comps));
8502                   Append_To (Stmts,
8503                     Make_Simple_Return_Statement (Loc,
8504                       Expression => New_Reference_To (Standard_True, Loc)));
8505
8506                else
8507                   Append_To (Stmts,
8508                     Make_Simple_Return_Statement (Loc,
8509                       Expression =>
8510                         Expand_Record_Equality (Tag_Typ,
8511                           Typ => Tag_Typ,
8512                           Lhs => Make_Identifier (Loc, Name_X),
8513                           Rhs => Make_Identifier (Loc, Name_Y),
8514                           Bodies => Declarations (Decl))));
8515                end if;
8516
8517                Set_Handled_Statement_Sequence (Decl,
8518                  Make_Handled_Sequence_Of_Statements (Loc, Stmts));
8519             end;
8520             Append_To (Res, Decl);
8521          end if;
8522
8523          --  Body for dispatching assignment
8524
8525          Decl :=
8526            Predef_Spec_Or_Body (Loc,
8527              Tag_Typ => Tag_Typ,
8528              Name    => Name_uAssign,
8529              Profile => New_List (
8530                Make_Parameter_Specification (Loc,
8531                  Defining_Identifier => Make_Defining_Identifier (Loc, Name_X),
8532                  Out_Present         => True,
8533                  Parameter_Type      => New_Reference_To (Tag_Typ, Loc)),
8534
8535                Make_Parameter_Specification (Loc,
8536                  Defining_Identifier => Make_Defining_Identifier (Loc, Name_Y),
8537                  Parameter_Type      => New_Reference_To (Tag_Typ, Loc))),
8538              For_Body => True);
8539
8540          Set_Handled_Statement_Sequence (Decl,
8541            Make_Handled_Sequence_Of_Statements (Loc, New_List (
8542              Make_Assignment_Statement (Loc,
8543                Name       => Make_Identifier (Loc, Name_X),
8544                Expression => Make_Identifier (Loc, Name_Y)))));
8545
8546          Append_To (Res, Decl);
8547       end if;
8548
8549       --  Generate dummy bodies for finalization actions of types that have
8550       --  no controlled components.
8551
8552       --  Skip this processing if we are in the finalization routine in the
8553       --  runtime itself, otherwise we get hopelessly circularly confused!
8554
8555       if In_Finalization_Root (Tag_Typ) then
8556          null;
8557
8558       --  Skip this if finalization is not available
8559
8560       elsif Restriction_Active (No_Finalization) then
8561          null;
8562
8563       elsif (Etype (Tag_Typ) = Tag_Typ
8564              or else Is_Controlled (Tag_Typ)
8565
8566                --  Ada 2005 (AI-251): We must also generate these subprograms
8567                --  if the immediate ancestor of Tag_Typ is an interface to
8568                --  ensure the correct initialization of its dispatch table.
8569
8570              or else (not Is_Interface (Tag_Typ)
8571                         and then
8572                       Is_Interface (Etype (Tag_Typ))))
8573         and then not Has_Controlled_Component (Tag_Typ)
8574       then
8575          if not Is_Limited_Type (Tag_Typ) then
8576             Decl := Predef_Deep_Spec (Loc, Tag_Typ, TSS_Deep_Adjust, True);
8577
8578             if Is_Controlled (Tag_Typ) then
8579                Set_Handled_Statement_Sequence (Decl,
8580                  Make_Handled_Sequence_Of_Statements (Loc,
8581                    Make_Adjust_Call (
8582                      Ref          => Make_Identifier (Loc, Name_V),
8583                      Typ          => Tag_Typ,
8584                      Flist_Ref    => Make_Identifier (Loc, Name_L),
8585                      With_Attach  => Make_Identifier (Loc, Name_B))));
8586
8587             else
8588                Set_Handled_Statement_Sequence (Decl,
8589                  Make_Handled_Sequence_Of_Statements (Loc, New_List (
8590                    Make_Null_Statement (Loc))));
8591             end if;
8592
8593             Append_To (Res, Decl);
8594          end if;
8595
8596          Decl := Predef_Deep_Spec (Loc, Tag_Typ, TSS_Deep_Finalize, True);
8597
8598          if Is_Controlled (Tag_Typ) then
8599             Set_Handled_Statement_Sequence (Decl,
8600               Make_Handled_Sequence_Of_Statements (Loc,
8601                 Make_Final_Call (
8602                   Ref         => Make_Identifier (Loc, Name_V),
8603                   Typ         => Tag_Typ,
8604                   With_Detach => Make_Identifier (Loc, Name_B))));
8605
8606          else
8607             Set_Handled_Statement_Sequence (Decl,
8608               Make_Handled_Sequence_Of_Statements (Loc, New_List (
8609                 Make_Null_Statement (Loc))));
8610          end if;
8611
8612          Append_To (Res, Decl);
8613       end if;
8614
8615       return Res;
8616    end Predefined_Primitive_Bodies;
8617
8618    ---------------------------------
8619    -- Predefined_Primitive_Freeze --
8620    ---------------------------------
8621
8622    function Predefined_Primitive_Freeze
8623      (Tag_Typ : Entity_Id) return List_Id
8624    is
8625       Loc     : constant Source_Ptr := Sloc (Tag_Typ);
8626       Res     : constant List_Id    := New_List;
8627       Prim    : Elmt_Id;
8628       Frnodes : List_Id;
8629
8630    begin
8631       Prim := First_Elmt (Primitive_Operations (Tag_Typ));
8632       while Present (Prim) loop
8633          if Is_Predefined_Dispatching_Operation (Node (Prim)) then
8634             Frnodes := Freeze_Entity (Node (Prim), Loc);
8635
8636             if Present (Frnodes) then
8637                Append_List_To (Res, Frnodes);
8638             end if;
8639          end if;
8640
8641          Next_Elmt (Prim);
8642       end loop;
8643
8644       return Res;
8645    end Predefined_Primitive_Freeze;
8646
8647    -------------------------
8648    -- Stream_Operation_OK --
8649    -------------------------
8650
8651    function Stream_Operation_OK
8652      (Typ       : Entity_Id;
8653       Operation : TSS_Name_Type) return Boolean
8654    is
8655       Has_Predefined_Or_Specified_Stream_Attribute : Boolean := False;
8656
8657    begin
8658       --  Special case of a limited type extension: a default implementation
8659       --  of the stream attributes Read or Write exists if that attribute
8660       --  has been specified or is available for an ancestor type; a default
8661       --  implementation of the attribute Output (resp. Input) exists if the
8662       --  attribute has been specified or Write (resp. Read) is available for
8663       --  an ancestor type. The last condition only applies under Ada 2005.
8664
8665       if Is_Limited_Type (Typ)
8666         and then Is_Tagged_Type (Typ)
8667       then
8668          if Operation = TSS_Stream_Read then
8669             Has_Predefined_Or_Specified_Stream_Attribute :=
8670               Has_Specified_Stream_Read (Typ);
8671
8672          elsif Operation = TSS_Stream_Write then
8673             Has_Predefined_Or_Specified_Stream_Attribute :=
8674               Has_Specified_Stream_Write (Typ);
8675
8676          elsif Operation = TSS_Stream_Input then
8677             Has_Predefined_Or_Specified_Stream_Attribute :=
8678               Has_Specified_Stream_Input (Typ)
8679                 or else
8680                   (Ada_Version >= Ada_05
8681                     and then Stream_Operation_OK (Typ, TSS_Stream_Read));
8682
8683          elsif Operation = TSS_Stream_Output then
8684             Has_Predefined_Or_Specified_Stream_Attribute :=
8685               Has_Specified_Stream_Output (Typ)
8686                 or else
8687                   (Ada_Version >= Ada_05
8688                     and then Stream_Operation_OK (Typ, TSS_Stream_Write));
8689          end if;
8690
8691          --  Case of inherited TSS_Stream_Read or TSS_Stream_Write
8692
8693          if not Has_Predefined_Or_Specified_Stream_Attribute
8694            and then Is_Derived_Type (Typ)
8695            and then (Operation = TSS_Stream_Read
8696                       or else Operation = TSS_Stream_Write)
8697          then
8698             Has_Predefined_Or_Specified_Stream_Attribute :=
8699               Present
8700                 (Find_Inherited_TSS (Base_Type (Etype (Typ)), Operation));
8701          end if;
8702       end if;
8703
8704       --  If the type is not limited, or else is limited but the attribute is
8705       --  explicitly specified or is predefined for the type, then return True,
8706       --  unless other conditions prevail, such as restrictions prohibiting
8707       --  streams or dispatching operations. We also return True for limited
8708       --  interfaces, because they may be extended by nonlimited types and
8709       --  permit inheritance in this case (addresses cases where an abstract
8710       --  extension doesn't get 'Input declared, as per comments below, but
8711       --  'Class'Input must still be allowed). Note that attempts to apply
8712       --  stream attributes to a limited interface or its class-wide type
8713       --  (or limited extensions thereof) will still get properly rejected
8714       --  by Check_Stream_Attribute.
8715
8716       --  We exclude the Input operation from being a predefined subprogram in
8717       --  the case where the associated type is an abstract extension, because
8718       --  the attribute is not callable in that case, per 13.13.2(49/2). Also,
8719       --  we don't want an abstract version created because types derived from
8720       --  the abstract type may not even have Input available (for example if
8721       --  derived from a private view of the abstract type that doesn't have
8722       --  a visible Input), but a VM such as .NET or the Java VM can treat the
8723       --  operation as inherited anyway, and we don't want an abstract function
8724       --  to be (implicitly) inherited in that case because it can lead to a VM
8725       --  exception.
8726
8727       return (not Is_Limited_Type (Typ)
8728                or else Is_Interface (Typ)
8729                or else Has_Predefined_Or_Specified_Stream_Attribute)
8730         and then (Operation /= TSS_Stream_Input
8731                    or else not Is_Abstract_Type (Typ)
8732                    or else not Is_Derived_Type (Typ))
8733         and then not Has_Unknown_Discriminants (Typ)
8734         and then not (Is_Interface (Typ)
8735                        and then (Is_Task_Interface (Typ)
8736                                   or else Is_Protected_Interface (Typ)
8737                                   or else Is_Synchronized_Interface (Typ)))
8738         and then not Restriction_Active (No_Streams)
8739         and then not Restriction_Active (No_Dispatch)
8740         and then not No_Run_Time_Mode
8741         and then RTE_Available (RE_Tag)
8742         and then RTE_Available (RE_Root_Stream_Type);
8743    end Stream_Operation_OK;
8744
8745 end Exp_Ch3;