OSDN Git Service

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