OSDN Git Service

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