OSDN Git Service

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