OSDN Git Service

2010-12-09 Steven G. Kargl <kargl@gcc.gnu.org>
[pf3gnuchains/gcc-fork.git] / gcc / ada / sem_ch12.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                             S E M _ C H 1 2                              --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2010, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Aspects;  use Aspects;
27 with Atree;    use Atree;
28 with Einfo;    use Einfo;
29 with Elists;   use Elists;
30 with Errout;   use Errout;
31 with Expander; use Expander;
32 with Fname;    use Fname;
33 with Fname.UF; use Fname.UF;
34 with Freeze;   use Freeze;
35 with Hostparm;
36 with Itypes;   use Itypes;
37 with Lib;      use Lib;
38 with Lib.Load; use Lib.Load;
39 with Lib.Xref; use Lib.Xref;
40 with Nlists;   use Nlists;
41 with Namet;    use Namet;
42 with Nmake;    use Nmake;
43 with Opt;      use Opt;
44 with Rident;   use Rident;
45 with Restrict; use Restrict;
46 with Rtsfind;  use Rtsfind;
47 with Sem;      use Sem;
48 with Sem_Aux;  use Sem_Aux;
49 with Sem_Cat;  use Sem_Cat;
50 with Sem_Ch3;  use Sem_Ch3;
51 with Sem_Ch6;  use Sem_Ch6;
52 with Sem_Ch7;  use Sem_Ch7;
53 with Sem_Ch8;  use Sem_Ch8;
54 with Sem_Ch10; use Sem_Ch10;
55 with Sem_Ch13; use Sem_Ch13;
56 with Sem_Disp; use Sem_Disp;
57 with Sem_Elab; use Sem_Elab;
58 with Sem_Elim; use Sem_Elim;
59 with Sem_Eval; use Sem_Eval;
60 with Sem_Res;  use Sem_Res;
61 with Sem_Type; use Sem_Type;
62 with Sem_Util; use Sem_Util;
63 with Sem_Warn; use Sem_Warn;
64 with Stand;    use Stand;
65 with Sinfo;    use Sinfo;
66 with Sinfo.CN; use Sinfo.CN;
67 with Sinput;   use Sinput;
68 with Sinput.L; use Sinput.L;
69 with Snames;   use Snames;
70 with Stringt;  use Stringt;
71 with Uname;    use Uname;
72 with Table;
73 with Tbuild;   use Tbuild;
74 with Uintp;    use Uintp;
75 with Urealp;   use Urealp;
76
77 with GNAT.HTable;
78
79 package body Sem_Ch12 is
80
81    ----------------------------------------------------------
82    -- Implementation of Generic Analysis and Instantiation --
83    ----------------------------------------------------------
84
85    --  GNAT implements generics by macro expansion. No attempt is made to share
86    --  generic instantiations (for now). Analysis of a generic definition does
87    --  not perform any expansion action, but the expander must be called on the
88    --  tree for each instantiation, because the expansion may of course depend
89    --  on the generic actuals. All of this is best achieved as follows:
90    --
91    --  a) Semantic analysis of a generic unit is performed on a copy of the
92    --  tree for the generic unit. All tree modifications that follow analysis
93    --  do not affect the original tree. Links are kept between the original
94    --  tree and the copy, in order to recognize non-local references within
95    --  the generic, and propagate them to each instance (recall that name
96    --  resolution is done on the generic declaration: generics are not really
97    --  macros!). This is summarized in the following diagram:
98
99    --              .-----------.               .----------.
100    --              |  semantic |<--------------|  generic |
101    --              |    copy   |               |    unit  |
102    --              |           |==============>|          |
103    --              |___________|    global     |__________|
104    --                             references     |   |  |
105    --                                            |   |  |
106    --                                          .-----|--|.
107    --                                          |  .-----|---.
108    --                                          |  |  .----------.
109    --                                          |  |  |  generic |
110    --                                          |__|  |          |
111    --                                             |__| instance |
112    --                                                |__________|
113
114    --  b) Each instantiation copies the original tree, and inserts into it a
115    --  series of declarations that describe the mapping between generic formals
116    --  and actuals. For example, a generic In OUT parameter is an object
117    --  renaming of the corresponding actual, etc. Generic IN parameters are
118    --  constant declarations.
119
120    --  c) In order to give the right visibility for these renamings, we use
121    --  a different scheme for package and subprogram instantiations. For
122    --  packages, the list of renamings is inserted into the package
123    --  specification, before the visible declarations of the package. The
124    --  renamings are analyzed before any of the text of the instance, and are
125    --  thus visible at the right place. Furthermore, outside of the instance,
126    --  the generic parameters are visible and denote their corresponding
127    --  actuals.
128
129    --  For subprograms, we create a container package to hold the renamings
130    --  and the subprogram instance itself. Analysis of the package makes the
131    --  renaming declarations visible to the subprogram. After analyzing the
132    --  package, the defining entity for the subprogram is touched-up so that
133    --  it appears declared in the current scope, and not inside the container
134    --  package.
135
136    --  If the instantiation is a compilation unit, the container package is
137    --  given the same name as the subprogram instance. This ensures that
138    --  the elaboration procedure called by the binder, using the compilation
139    --  unit name, calls in fact the elaboration procedure for the package.
140
141    --  Not surprisingly, private types complicate this approach. By saving in
142    --  the original generic object the non-local references, we guarantee that
143    --  the proper entities are referenced at the point of instantiation.
144    --  However, for private types, this by itself does not insure that the
145    --  proper VIEW of the entity is used (the full type may be visible at the
146    --  point of generic definition, but not at instantiation, or vice-versa).
147    --  In  order to reference the proper view, we special-case any reference
148    --  to private types in the generic object, by saving both views, one in
149    --  the generic and one in the semantic copy. At time of instantiation, we
150    --  check whether the two views are consistent, and exchange declarations if
151    --  necessary, in order to restore the correct visibility. Similarly, if
152    --  the instance view is private when the generic view was not, we perform
153    --  the exchange. After completing the instantiation, we restore the
154    --  current visibility. The flag Has_Private_View marks identifiers in the
155    --  the generic unit that require checking.
156
157    --  Visibility within nested generic units requires special handling.
158    --  Consider the following scheme:
159
160    --  type Global is ...         --  outside of generic unit.
161    --  generic ...
162    --  package Outer is
163    --     ...
164    --     type Semi_Global is ... --  global to inner.
165
166    --     generic ...                                         -- 1
167    --     procedure inner (X1 : Global;  X2 : Semi_Global);
168
169    --     procedure in2 is new inner (...);                   -- 4
170    --  end Outer;
171
172    --  package New_Outer is new Outer (...);                  -- 2
173    --  procedure New_Inner is new New_Outer.Inner (...);      -- 3
174
175    --  The semantic analysis of Outer captures all occurrences of Global.
176    --  The semantic analysis of Inner (at 1) captures both occurrences of
177    --  Global and Semi_Global.
178
179    --  At point 2 (instantiation of Outer), we also produce a generic copy
180    --  of Inner, even though Inner is, at that point, not being instantiated.
181    --  (This is just part of the semantic analysis of New_Outer).
182
183    --  Critically, references to Global within Inner must be preserved, while
184    --  references to Semi_Global should not preserved, because they must now
185    --  resolve to an entity within New_Outer. To distinguish between these, we
186    --  use a global variable, Current_Instantiated_Parent, which is set when
187    --  performing a generic copy during instantiation (at 2). This variable is
188    --  used when performing a generic copy that is not an instantiation, but
189    --  that is nested within one, as the occurrence of 1 within 2. The analysis
190    --  of a nested generic only preserves references that are global to the
191    --  enclosing Current_Instantiated_Parent. We use the Scope_Depth value to
192    --  determine whether a reference is external to the given parent.
193
194    --  The instantiation at point 3 requires no special treatment. The method
195    --  works as well for further nestings of generic units, but of course the
196    --  variable Current_Instantiated_Parent must be stacked because nested
197    --  instantiations can occur, e.g. the occurrence of 4 within 2.
198
199    --  The instantiation of package and subprogram bodies is handled in a
200    --  similar manner, except that it is delayed until after semantic
201    --  analysis is complete. In this fashion complex cross-dependencies
202    --  between several package declarations and bodies containing generics
203    --  can be compiled which otherwise would diagnose spurious circularities.
204
205    --  For example, it is possible to compile two packages A and B that
206    --  have the following structure:
207
208    --    package A is                         package B is
209    --       generic ...                          generic ...
210    --       package G_A is                       package G_B is
211
212    --    with B;                              with A;
213    --    package body A is                    package body B is
214    --       package N_B is new G_B (..)          package N_A is new G_A (..)
215
216    --  The table Pending_Instantiations in package Inline is used to keep
217    --  track of body instantiations that are delayed in this manner. Inline
218    --  handles the actual calls to do the body instantiations. This activity
219    --  is part of Inline, since the processing occurs at the same point, and
220    --  for essentially the same reason, as the handling of inlined routines.
221
222    ----------------------------------------------
223    -- Detection of Instantiation Circularities --
224    ----------------------------------------------
225
226    --  If we have a chain of instantiations that is circular, this is static
227    --  error which must be detected at compile time. The detection of these
228    --  circularities is carried out at the point that we insert a generic
229    --  instance spec or body. If there is a circularity, then the analysis of
230    --  the offending spec or body will eventually result in trying to load the
231    --  same unit again, and we detect this problem as we analyze the package
232    --  instantiation for the second time.
233
234    --  At least in some cases after we have detected the circularity, we get
235    --  into trouble if we try to keep going. The following flag is set if a
236    --  circularity is detected, and used to abandon compilation after the
237    --  messages have been posted.
238
239    Circularity_Detected : Boolean := False;
240    --  This should really be reset on encountering a new main unit, but in
241    --  practice we are not using multiple main units so it is not critical.
242
243    -------------------------------------------------
244    -- Formal packages and partial parametrization --
245    -------------------------------------------------
246
247    --  When compiling a generic, a formal package is a local instantiation. If
248    --  declared with a box, its generic formals are visible in the enclosing
249    --  generic. If declared with a partial list of actuals, those actuals that
250    --  are defaulted (covered by an Others clause, or given an explicit box
251    --  initialization) are also visible in the enclosing generic, while those
252    --  that have a corresponding actual are not.
253
254    --  In our source model of instantiation, the same visibility must be
255    --  present in the spec and body of an instance: the names of the formals
256    --  that are defaulted must be made visible within the instance, and made
257    --  invisible (hidden) after the instantiation is complete, so that they
258    --  are not accessible outside of the instance.
259
260    --  In a generic, a formal package is treated like a special instantiation.
261    --  Our Ada95 compiler handled formals with and without box in different
262    --  ways. With partial parametrization, we use a single model for both.
263    --  We create a package declaration that consists of the specification of
264    --  the generic package, and a set of declarations that map the actuals
265    --  into local renamings, just as we do for bona fide instantiations. For
266    --  defaulted parameters and formals with a box, we copy directly the
267    --  declarations of the formal into this local package. The result is a
268    --  a package whose visible declarations may include generic formals. This
269    --  package is only used for type checking and visibility analysis, and
270    --  never reaches the back-end, so it can freely violate the placement
271    --  rules for generic formal declarations.
272
273    --  The list of declarations (renamings and copies of formals) is built
274    --  by Analyze_Associations, just as for regular instantiations.
275
276    --  At the point of instantiation, conformance checking must be applied only
277    --  to those parameters that were specified in the formal. We perform this
278    --  checking by creating another internal instantiation, this one including
279    --  only the renamings and the formals (the rest of the package spec is not
280    --  relevant to conformance checking). We can then traverse two lists: the
281    --  list of actuals in the instance that corresponds to the formal package,
282    --  and the list of actuals produced for this bogus instantiation. We apply
283    --  the conformance rules to those actuals that are not defaulted (i.e.
284    --  which still appear as generic formals.
285
286    --  When we compile an instance body we must make the right parameters
287    --  visible again. The predicate Is_Generic_Formal indicates which of the
288    --  formals should have its Is_Hidden flag reset.
289
290    -----------------------
291    -- Local subprograms --
292    -----------------------
293
294    procedure Abandon_Instantiation (N : Node_Id);
295    pragma No_Return (Abandon_Instantiation);
296    --  Posts an error message "instantiation abandoned" at the indicated node
297    --  and then raises the exception Instantiation_Error to do it.
298
299    procedure Analyze_Formal_Array_Type
300      (T   : in out Entity_Id;
301       Def : Node_Id);
302    --  A formal array type is treated like an array type declaration, and
303    --  invokes Array_Type_Declaration (sem_ch3) whose first parameter is
304    --  in-out, because in the case of an anonymous type the entity is
305    --  actually created in the procedure.
306
307    --  The following procedures treat other kinds of formal parameters
308
309    procedure Analyze_Formal_Derived_Interface_Type
310      (N   : Node_Id;
311       T   : Entity_Id;
312       Def : Node_Id);
313
314    procedure Analyze_Formal_Derived_Type
315      (N   : Node_Id;
316       T   : Entity_Id;
317       Def : Node_Id);
318
319    procedure Analyze_Formal_Interface_Type
320      (N   : Node_Id;
321       T   : Entity_Id;
322       Def : Node_Id);
323
324    --  The following subprograms create abbreviated declarations for formal
325    --  scalar types. We introduce an anonymous base of the proper class for
326    --  each of them, and define the formals as constrained first subtypes of
327    --  their bases. The bounds are expressions that are non-static in the
328    --  generic.
329
330    procedure Analyze_Formal_Decimal_Fixed_Point_Type
331                                                 (T : Entity_Id; Def : Node_Id);
332    procedure Analyze_Formal_Discrete_Type       (T : Entity_Id; Def : Node_Id);
333    procedure Analyze_Formal_Floating_Type       (T : Entity_Id; Def : Node_Id);
334    procedure Analyze_Formal_Signed_Integer_Type (T : Entity_Id; Def : Node_Id);
335    procedure Analyze_Formal_Modular_Type        (T : Entity_Id; Def : Node_Id);
336    procedure Analyze_Formal_Ordinary_Fixed_Point_Type
337                                                 (T : Entity_Id; Def : Node_Id);
338
339    procedure Analyze_Formal_Private_Type
340      (N   : Node_Id;
341       T   : Entity_Id;
342       Def : Node_Id);
343    --  Creates a new private type, which does not require completion
344
345    procedure Analyze_Generic_Formal_Part (N : Node_Id);
346
347    procedure Analyze_Generic_Access_Type (T : Entity_Id; Def : Node_Id);
348    --  Create a new access type with the given designated type
349
350    function Analyze_Associations
351      (I_Node  : Node_Id;
352       Formals : List_Id;
353       F_Copy  : List_Id) return List_Id;
354    --  At instantiation time, build the list of associations between formals
355    --  and actuals. Each association becomes a renaming declaration for the
356    --  formal entity. F_Copy is the analyzed list of formals in the generic
357    --  copy. It is used to apply legality checks to the actuals. I_Node is the
358    --  instantiation node itself.
359
360    procedure Analyze_Subprogram_Instantiation
361      (N : Node_Id;
362       K : Entity_Kind);
363
364    procedure Build_Instance_Compilation_Unit_Nodes
365      (N        : Node_Id;
366       Act_Body : Node_Id;
367       Act_Decl : Node_Id);
368    --  This procedure is used in the case where the generic instance of a
369    --  subprogram body or package body is a library unit. In this case, the
370    --  original library unit node for the generic instantiation must be
371    --  replaced by the resulting generic body, and a link made to a new
372    --  compilation unit node for the generic declaration. The argument N is
373    --  the original generic instantiation. Act_Body and Act_Decl are the body
374    --  and declaration of the instance (either package body and declaration
375    --  nodes or subprogram body and declaration nodes depending on the case).
376    --  On return, the node N has been rewritten with the actual body.
377
378    procedure Check_Access_Definition (N : Node_Id);
379    --  Subsidiary routine to null exclusion processing. Perform an assertion
380    --  check on Ada version and the presence of an access definition in N.
381
382    procedure Check_Formal_Packages (P_Id : Entity_Id);
383    --  Apply the following to all formal packages in generic associations
384
385    procedure Check_Formal_Package_Instance
386      (Formal_Pack : Entity_Id;
387       Actual_Pack : Entity_Id);
388    --  Verify that the actuals of the actual instance match the actuals of
389    --  the template for a formal package that is not declared with a box.
390
391    procedure Check_Forward_Instantiation (Decl : Node_Id);
392    --  If the generic is a local entity and the corresponding body has not
393    --  been seen yet, flag enclosing packages to indicate that it will be
394    --  elaborated after the generic body. Subprograms declared in the same
395    --  package cannot be inlined by the front-end because front-end inlining
396    --  requires a strict linear order of elaboration.
397
398    procedure Check_Hidden_Child_Unit
399      (N           : Node_Id;
400       Gen_Unit    : Entity_Id;
401       Act_Decl_Id : Entity_Id);
402    --  If the generic unit is an implicit child instance within a parent
403    --  instance, we need to make an explicit test that it is not hidden by
404    --  a child instance of the same name and parent.
405
406    procedure Check_Generic_Actuals
407      (Instance      : Entity_Id;
408       Is_Formal_Box : Boolean);
409    --  Similar to previous one. Check the actuals in the instantiation,
410    --  whose views can change between the point of instantiation and the point
411    --  of instantiation of the body. In addition, mark the generic renamings
412    --  as generic actuals, so that they are not compatible with other actuals.
413    --  Recurse on an actual that is a formal package whose declaration has
414    --  a box.
415
416    function Contains_Instance_Of
417      (Inner : Entity_Id;
418       Outer : Entity_Id;
419       N     : Node_Id) return Boolean;
420    --  Inner is instantiated within the generic Outer. Check whether Inner
421    --  directly or indirectly contains an instance of Outer or of one of its
422    --  parents, in the case of a subunit. Each generic unit holds a list of
423    --  the entities instantiated within (at any depth). This procedure
424    --  determines whether the set of such lists contains a cycle, i.e. an
425    --  illegal circular instantiation.
426
427    function Denotes_Formal_Package
428      (Pack     : Entity_Id;
429       On_Exit  : Boolean := False;
430       Instance : Entity_Id := Empty) return Boolean;
431    --  Returns True if E is a formal package of an enclosing generic, or
432    --  the actual for such a formal in an enclosing instantiation. If such
433    --  a package is used as a formal in an nested generic, or as an actual
434    --  in a nested instantiation, the visibility of ITS formals should not
435    --  be modified. When called from within Restore_Private_Views, the flag
436    --  On_Exit is true, to indicate that the search for a possible enclosing
437    --  instance should ignore the current one. In that case Instance denotes
438    --  the declaration for which this is an actual. This declaration may be
439    --  an instantiation in the source, or the internal instantiation that
440    --  corresponds to the actual for a formal package.
441
442    function Find_Actual_Type
443      (Typ       : Entity_Id;
444       Gen_Type  : Entity_Id) return Entity_Id;
445    --  When validating the actual types of a child instance, check whether
446    --  the formal is a formal type of the parent unit, and retrieve the current
447    --  actual for it. Typ is the entity in the analyzed formal type declaration
448    --  (component or index type of an array type, or designated type of an
449    --  access formal) and Gen_Type is the enclosing analyzed formal array
450    --  or access type. The desired actual may be a formal of a parent, or may
451    --  be declared in a formal package of a parent. In both cases it is a
452    --  generic actual type because it appears within a visible instance.
453    --  Finally, it may be declared in a parent unit without being a formal
454    --  of that unit, in which case it must be retrieved by visibility.
455    --  Ambiguities may still arise if two homonyms are declared in two formal
456    --  packages, and the prefix of the formal type may be needed to resolve
457    --  the ambiguity in the instance ???
458
459    function In_Same_Declarative_Part
460      (F_Node : Node_Id;
461       Inst   : Node_Id) return Boolean;
462    --  True if the instantiation Inst and the given freeze_node F_Node appear
463    --  within the same declarative part, ignoring subunits, but with no inter-
464    --  vening subprograms or concurrent units. If true, the freeze node
465    --  of the instance can be placed after the freeze node of the parent,
466    --  which it itself an instance.
467
468    function In_Main_Context (E : Entity_Id) return Boolean;
469    --  Check whether an instantiation is in the context of the main unit.
470    --  Used to determine whether its body should be elaborated to allow
471    --  front-end inlining.
472
473    procedure Set_Instance_Env
474      (Gen_Unit : Entity_Id;
475       Act_Unit : Entity_Id);
476    --  Save current instance on saved environment, to be used to determine
477    --  the global status of entities in nested instances. Part of Save_Env.
478    --  called after verifying that the generic unit is legal for the instance,
479    --  The procedure also examines whether the generic unit is a predefined
480    --  unit, in order to set configuration switches accordingly. As a result
481    --  the procedure must be called after analyzing and freezing the actuals.
482
483    procedure Set_Instance_Of (A : Entity_Id; B : Entity_Id);
484    --  Associate analyzed generic parameter with corresponding
485    --  instance. Used for semantic checks at instantiation time.
486
487    function Has_Been_Exchanged (E : Entity_Id) return Boolean;
488    --  Traverse the Exchanged_Views list to see if a type was private
489    --  and has already been flipped during this phase of instantiation.
490
491    procedure Hide_Current_Scope;
492    --  When instantiating a generic child unit, the parent context must be
493    --  present, but the instance and all entities that may be generated
494    --  must be inserted in the current scope. We leave the current scope
495    --  on the stack, but make its entities invisible to avoid visibility
496    --  problems. This is reversed at the end of the instantiation. This is
497    --  not done for the instantiation of the bodies, which only require the
498    --  instances of the generic parents to be in scope.
499
500    procedure Install_Body
501      (Act_Body : Node_Id;
502       N        : Node_Id;
503       Gen_Body : Node_Id;
504       Gen_Decl : Node_Id);
505    --  If the instantiation happens textually before the body of the generic,
506    --  the instantiation of the body must be analyzed after the generic body,
507    --  and not at the point of instantiation. Such early instantiations can
508    --  happen if the generic and the instance appear in  a package declaration
509    --  because the generic body can only appear in the corresponding package
510    --  body. Early instantiations can also appear if generic, instance and
511    --  body are all in the declarative part of a subprogram or entry. Entities
512    --  of packages that are early instantiations are delayed, and their freeze
513    --  node appears after the generic body.
514
515    procedure Insert_After_Last_Decl (N : Node_Id; F_Node : Node_Id);
516    --  Insert freeze node at the end of the declarative part that includes the
517    --  instance node N. If N is in the visible part of an enclosing package
518    --  declaration, the freeze node has to be inserted at the end of the
519    --  private declarations, if any.
520
521    procedure Freeze_Subprogram_Body
522      (Inst_Node : Node_Id;
523       Gen_Body  : Node_Id;
524       Pack_Id   : Entity_Id);
525    --  The generic body may appear textually after the instance, including
526    --  in the proper body of a stub, or within a different package instance.
527    --  Given that the instance can only be elaborated after the generic, we
528    --  place freeze_nodes for the instance and/or for packages that may enclose
529    --  the instance and the generic, so that the back-end can establish the
530    --  proper order of elaboration.
531
532    procedure Init_Env;
533    --  Establish environment for subsequent instantiation. Separated from
534    --  Save_Env because data-structures for visibility handling must be
535    --  initialized before call to Check_Generic_Child_Unit.
536
537    procedure Install_Formal_Packages (Par : Entity_Id);
538    --  Install the visible part of any formal of the parent that is a formal
539    --  package. Note that for the case of a formal package with a box, this
540    --  includes the formal part of the formal package (12.7(10/2)).
541
542    procedure Install_Parent (P : Entity_Id; In_Body : Boolean := False);
543    --  When compiling an instance of a child unit the parent (which is
544    --  itself an instance) is an enclosing scope that must be made
545    --  immediately visible. This procedure is also used to install the non-
546    --  generic parent of a generic child unit when compiling its body, so
547    --  that full views of types in the parent are made visible.
548
549    procedure Remove_Parent (In_Body : Boolean := False);
550    --  Reverse effect after instantiation of child is complete
551
552    procedure Inline_Instance_Body
553      (N        : Node_Id;
554       Gen_Unit : Entity_Id;
555       Act_Decl : Node_Id);
556    --  If front-end inlining is requested, instantiate the package body,
557    --  and preserve the visibility of its compilation unit, to insure
558    --  that successive instantiations succeed.
559
560    --  The functions Instantiate_XXX perform various legality checks and build
561    --  the declarations for instantiated generic parameters. In all of these
562    --  Formal is the entity in the generic unit, Actual is the entity of
563    --  expression in the generic associations, and Analyzed_Formal is the
564    --  formal in the generic copy, which contains the semantic information to
565    --  be used to validate the actual.
566
567    function Instantiate_Object
568      (Formal          : Node_Id;
569       Actual          : Node_Id;
570       Analyzed_Formal : Node_Id) return List_Id;
571
572    function Instantiate_Type
573      (Formal          : Node_Id;
574       Actual          : Node_Id;
575       Analyzed_Formal : Node_Id;
576       Actual_Decls    : List_Id) return List_Id;
577
578    function Instantiate_Formal_Subprogram
579      (Formal          : Node_Id;
580       Actual          : Node_Id;
581       Analyzed_Formal : Node_Id) return Node_Id;
582
583    function Instantiate_Formal_Package
584      (Formal          : Node_Id;
585       Actual          : Node_Id;
586       Analyzed_Formal : Node_Id) return List_Id;
587    --  If the formal package is declared with a box, special visibility rules
588    --  apply to its formals: they are in the visible part of the package. This
589    --  is true in the declarative region of the formal package, that is to say
590    --  in the enclosing generic or instantiation. For an instantiation, the
591    --  parameters of the formal package are made visible in an explicit step.
592    --  Furthermore, if the actual has a visible USE clause, these formals must
593    --  be made potentially use-visible as well. On exit from the enclosing
594    --  instantiation, the reverse must be done.
595
596    --  For a formal package declared without a box, there are conformance rules
597    --  that apply to the actuals in the generic declaration and the actuals of
598    --  the actual package in the enclosing instantiation. The simplest way to
599    --  apply these rules is to repeat the instantiation of the formal package
600    --  in the context of the enclosing instance, and compare the generic
601    --  associations of this instantiation with those of the actual package.
602    --  This internal instantiation only needs to contain the renamings of the
603    --  formals: the visible and private declarations themselves need not be
604    --  created.
605
606    --  In Ada 2005, the formal package may be only partially parameterized.
607    --  In that case the visibility step must make visible those actuals whose
608    --  corresponding formals were given with a box. A final complication
609    --  involves inherited operations from formal derived types, which must
610    --  be visible if the type is.
611
612    function Is_In_Main_Unit (N : Node_Id) return Boolean;
613    --  Test if given node is in the main unit
614
615    procedure Load_Parent_Of_Generic
616      (N             : Node_Id;
617       Spec          : Node_Id;
618       Body_Optional : Boolean := False);
619    --  If the generic appears in a separate non-generic library unit, load the
620    --  corresponding body to retrieve the body of the generic. N is the node
621    --  for the generic instantiation, Spec is the generic package declaration.
622    --
623    --  Body_Optional is a flag that indicates that the body is being loaded to
624    --  ensure that temporaries are generated consistently when there are other
625    --  instances in the current declarative part that precede the one being
626    --  loaded. In that case a missing body is acceptable.
627
628    procedure Inherit_Context (Gen_Decl : Node_Id; Inst : Node_Id);
629    --  Add the context clause of the unit containing a generic unit to a
630    --  compilation unit that is, or contains, an instantiation.
631
632    function Get_Associated_Node (N : Node_Id) return Node_Id;
633    --  In order to propagate semantic information back from the analyzed copy
634    --  to the original generic, we maintain links between selected nodes in the
635    --  generic and their corresponding copies. At the end of generic analysis,
636    --  the routine Save_Global_References traverses the generic tree, examines
637    --  the semantic information, and preserves the links to those nodes that
638    --  contain global information. At instantiation, the information from the
639    --  associated node is placed on the new copy, so that name resolution is
640    --  not repeated.
641    --
642    --  Three kinds of source nodes have associated nodes:
643    --
644    --    a) those that can reference (denote) entities, that is identifiers,
645    --       character literals, expanded_names, operator symbols, operators,
646    --       and attribute reference nodes. These nodes have an Entity field
647    --       and are the set of nodes that are in N_Has_Entity.
648    --
649    --    b) aggregates (N_Aggregate and N_Extension_Aggregate)
650    --
651    --    c) selected components (N_Selected_Component)
652    --
653    --  For the first class, the associated node preserves the entity if it is
654    --  global. If the generic contains nested instantiations, the associated
655    --  node itself has been recopied, and a chain of them must be followed.
656    --
657    --  For aggregates, the associated node allows retrieval of the type, which
658    --  may otherwise not appear in the generic. The view of this type may be
659    --  different between generic and instantiation, and the full view can be
660    --  installed before the instantiation is analyzed. For aggregates of type
661    --  extensions, the same view exchange may have to be performed for some of
662    --  the ancestor types, if their view is private at the point of
663    --  instantiation.
664    --
665    --  Nodes that are selected components in the parse tree may be rewritten
666    --  as expanded names after resolution, and must be treated as potential
667    --  entity holders, which is why they also have an Associated_Node.
668    --
669    --  Nodes that do not come from source, such as freeze nodes, do not appear
670    --  in the generic tree, and need not have an associated node.
671    --
672    --  The associated node is stored in the Associated_Node field. Note that
673    --  this field overlaps Entity, which is fine, because the whole point is
674    --  that we don't need or want the normal Entity field in this situation.
675
676    procedure Map_Formal_Package_Entities (Form : Entity_Id; Act : Entity_Id);
677    --  Within the generic part, entities in the formal package are
678    --  visible. To validate subsequent type declarations, indicate
679    --  the correspondence between the entities in the analyzed formal,
680    --  and the entities in  the actual package. There are three packages
681    --  involved in the instantiation of a formal package: the parent
682    --  generic P1 which appears in the generic declaration, the fake
683    --  instantiation P2 which appears in the analyzed generic, and whose
684    --  visible entities may be used in subsequent formals, and the actual
685    --  P3 in the instance. To validate subsequent formals, me indicate
686    --  that the entities in P2 are mapped into those of P3. The mapping of
687    --  entities has to be done recursively for nested packages.
688
689    procedure Move_Freeze_Nodes
690      (Out_Of : Entity_Id;
691       After  : Node_Id;
692       L      : List_Id);
693    --  Freeze nodes can be generated in the analysis of a generic unit, but
694    --  will not be seen by the back-end. It is necessary to move those nodes
695    --  to the enclosing scope if they freeze an outer entity. We place them
696    --  at the end of the enclosing generic package, which is semantically
697    --  neutral.
698
699    procedure Preanalyze_Actuals (N : Node_Id);
700    --  Analyze actuals to perform name resolution. Full resolution is done
701    --  later, when the expected types are known, but names have to be captured
702    --  before installing parents of generics, that are not visible for the
703    --  actuals themselves.
704
705    procedure Valid_Default_Attribute (Nam : Entity_Id; Def : Node_Id);
706    --  Verify that an attribute that appears as the default for a formal
707    --  subprogram is a function or procedure with the correct profile.
708
709    -------------------------------------------
710    -- Data Structures for Generic Renamings --
711    -------------------------------------------
712
713    --  The map Generic_Renamings associates generic entities with their
714    --  corresponding actuals. Currently used to validate type instances. It
715    --  will eventually be used for all generic parameters to eliminate the
716    --  need for overload resolution in the instance.
717
718    type Assoc_Ptr is new Int;
719
720    Assoc_Null : constant Assoc_Ptr := -1;
721
722    type Assoc is record
723       Gen_Id         : Entity_Id;
724       Act_Id         : Entity_Id;
725       Next_In_HTable : Assoc_Ptr;
726    end record;
727
728    package Generic_Renamings is new Table.Table
729      (Table_Component_Type => Assoc,
730       Table_Index_Type     => Assoc_Ptr,
731       Table_Low_Bound      => 0,
732       Table_Initial        => 10,
733       Table_Increment      => 100,
734       Table_Name           => "Generic_Renamings");
735
736    --  Variable to hold enclosing instantiation. When the environment is
737    --  saved for a subprogram inlining, the corresponding Act_Id is empty.
738
739    Current_Instantiated_Parent : Assoc := (Empty, Empty, Assoc_Null);
740
741    --  Hash table for associations
742
743    HTable_Size : constant := 37;
744    type HTable_Range is range 0 .. HTable_Size - 1;
745
746    procedure Set_Next_Assoc (E : Assoc_Ptr; Next : Assoc_Ptr);
747    function  Next_Assoc     (E : Assoc_Ptr) return Assoc_Ptr;
748    function Get_Gen_Id      (E : Assoc_Ptr) return Entity_Id;
749    function Hash            (F : Entity_Id) return HTable_Range;
750
751    package Generic_Renamings_HTable is new GNAT.HTable.Static_HTable (
752       Header_Num => HTable_Range,
753       Element    => Assoc,
754       Elmt_Ptr   => Assoc_Ptr,
755       Null_Ptr   => Assoc_Null,
756       Set_Next   => Set_Next_Assoc,
757       Next       => Next_Assoc,
758       Key        => Entity_Id,
759       Get_Key    => Get_Gen_Id,
760       Hash       => Hash,
761       Equal      => "=");
762
763    Exchanged_Views : Elist_Id;
764    --  This list holds the private views that have been exchanged during
765    --  instantiation to restore the visibility of the generic declaration.
766    --  (see comments above). After instantiation, the current visibility is
767    --  reestablished by means of a traversal of this list.
768
769    Hidden_Entities : Elist_Id;
770    --  This list holds the entities of the current scope that are removed
771    --  from immediate visibility when instantiating a child unit. Their
772    --  visibility is restored in Remove_Parent.
773
774    --  Because instantiations can be recursive, the following must be saved
775    --  on entry and restored on exit from an instantiation (spec or body).
776    --  This is done by the two procedures Save_Env and Restore_Env. For
777    --  package and subprogram instantiations (but not for the body instances)
778    --  the action of Save_Env is done in two steps: Init_Env is called before
779    --  Check_Generic_Child_Unit, because setting the parent instances requires
780    --  that the visibility data structures be properly initialized. Once the
781    --  generic is unit is validated, Set_Instance_Env completes Save_Env.
782
783    Parent_Unit_Visible : Boolean := False;
784    --  Parent_Unit_Visible is used when the generic is a child unit, and
785    --  indicates whether the ultimate parent of the generic is visible in the
786    --  instantiation environment. It is used to reset the visibility of the
787    --  parent at the end of the instantiation (see Remove_Parent).
788
789    Instance_Parent_Unit : Entity_Id := Empty;
790    --  This records the ultimate parent unit of an instance of a generic
791    --  child unit and is used in conjunction with Parent_Unit_Visible to
792    --  indicate the unit to which the Parent_Unit_Visible flag corresponds.
793
794    type Instance_Env is record
795       Instantiated_Parent  : Assoc;
796       Exchanged_Views      : Elist_Id;
797       Hidden_Entities      : Elist_Id;
798       Current_Sem_Unit     : Unit_Number_Type;
799       Parent_Unit_Visible  : Boolean   := False;
800       Instance_Parent_Unit : Entity_Id := Empty;
801       Switches             : Config_Switches_Type;
802    end record;
803
804    package Instance_Envs is new Table.Table (
805      Table_Component_Type => Instance_Env,
806      Table_Index_Type     => Int,
807      Table_Low_Bound      => 0,
808      Table_Initial        => 32,
809      Table_Increment      => 100,
810      Table_Name           => "Instance_Envs");
811
812    procedure Restore_Private_Views
813      (Pack_Id    : Entity_Id;
814       Is_Package : Boolean := True);
815    --  Restore the private views of external types, and unmark the generic
816    --  renamings of actuals, so that they become compatible subtypes again.
817    --  For subprograms, Pack_Id is the package constructed to hold the
818    --  renamings.
819
820    procedure Switch_View (T : Entity_Id);
821    --  Switch the partial and full views of a type and its private
822    --  dependents (i.e. its subtypes and derived types).
823
824    ------------------------------------
825    -- Structures for Error Reporting --
826    ------------------------------------
827
828    Instantiation_Node : Node_Id;
829    --  Used by subprograms that validate instantiation of formal parameters
830    --  where there might be no actual on which to place the error message.
831    --  Also used to locate the instantiation node for generic subunits.
832
833    Instantiation_Error : exception;
834    --  When there is a semantic error in the generic parameter matching,
835    --  there is no point in continuing the instantiation, because the
836    --  number of cascaded errors is unpredictable. This exception aborts
837    --  the instantiation process altogether.
838
839    S_Adjustment : Sloc_Adjustment;
840    --  Offset created for each node in an instantiation, in order to keep
841    --  track of the source position of the instantiation in each of its nodes.
842    --  A subsequent semantic error or warning on a construct of the instance
843    --  points to both places: the original generic node, and the point of
844    --  instantiation. See Sinput and Sinput.L for additional details.
845
846    ------------------------------------------------------------
847    -- Data structure for keeping track when inside a Generic --
848    ------------------------------------------------------------
849
850    --  The following table is used to save values of the Inside_A_Generic
851    --  flag (see spec of Sem) when they are saved by Start_Generic.
852
853    package Generic_Flags is new Table.Table (
854      Table_Component_Type => Boolean,
855      Table_Index_Type     => Int,
856      Table_Low_Bound      => 0,
857      Table_Initial        => 32,
858      Table_Increment      => 200,
859      Table_Name           => "Generic_Flags");
860
861    ---------------------------
862    -- Abandon_Instantiation --
863    ---------------------------
864
865    procedure Abandon_Instantiation (N : Node_Id) is
866    begin
867       Error_Msg_N ("\instantiation abandoned!", N);
868       raise Instantiation_Error;
869    end Abandon_Instantiation;
870
871    --------------------------
872    -- Analyze_Associations --
873    --------------------------
874
875    function Analyze_Associations
876      (I_Node  : Node_Id;
877       Formals : List_Id;
878       F_Copy  : List_Id) return List_Id
879    is
880
881       Actual_Types    : constant Elist_Id  := New_Elmt_List;
882       Assoc           : constant List_Id   := New_List;
883       Default_Actuals : constant Elist_Id  := New_Elmt_List;
884       Gen_Unit        : constant Entity_Id :=
885                           Defining_Entity (Parent (F_Copy));
886
887       Actuals         : List_Id;
888       Actual          : Node_Id;
889       Formal          : Node_Id;
890       Next_Formal     : Node_Id;
891       Temp_Formal     : Node_Id;
892       Analyzed_Formal : Node_Id;
893       Match           : Node_Id;
894       Named           : Node_Id;
895       First_Named     : Node_Id := Empty;
896
897       Default_Formals : constant List_Id := New_List;
898       --  If an Others_Choice is present, some of the formals may be defaulted.
899       --  To simplify the treatment of visibility in an instance, we introduce
900       --  individual defaults for each such formal. These defaults are
901       --  appended to the list of associations and replace the Others_Choice.
902
903       Found_Assoc : Node_Id;
904       --  Association for the current formal being match. Empty if there are
905       --  no remaining actuals, or if there is no named association with the
906       --  name of the formal.
907
908       Is_Named_Assoc : Boolean;
909       Num_Matched    : Int := 0;
910       Num_Actuals    : Int := 0;
911
912       Others_Present : Boolean := False;
913       --  In Ada 2005, indicates partial parametrization of a formal
914       --  package. As usual an other association must be last in the list.
915
916       function Matching_Actual
917         (F   : Entity_Id;
918          A_F : Entity_Id) return Node_Id;
919       --  Find actual that corresponds to a given a formal parameter. If the
920       --  actuals are positional, return the next one, if any. If the actuals
921       --  are named, scan the parameter associations to find the right one.
922       --  A_F is the corresponding entity in the analyzed generic,which is
923       --  placed on the selector name for ASIS use.
924
925       --  In Ada 2005, a named association may be given with a box, in which
926       --  case Matching_Actual sets Found_Assoc to the generic association,
927       --  but return Empty for the actual itself. In this case the code below
928       --  creates a corresponding declaration for the formal.
929
930       function Partial_Parametrization return Boolean;
931       --  Ada 2005: if no match is found for a given formal, check if the
932       --  association for it includes a box, or whether the associations
933       --  include an Others clause.
934
935       procedure Process_Default (F : Entity_Id);
936       --  Add a copy of the declaration of generic formal  F to the list of
937       --  associations, and add an explicit box association for F  if there
938       --  is none yet, and the default comes from an Others_Choice.
939
940       procedure Set_Analyzed_Formal;
941       --  Find the node in the generic copy that corresponds to a given formal.
942       --  The semantic information on this node is used to perform legality
943       --  checks on the actuals. Because semantic analysis can introduce some
944       --  anonymous entities or modify the declaration node itself, the
945       --  correspondence between the two lists is not one-one. In addition to
946       --  anonymous types, the presence a formal equality will introduce an
947       --  implicit declaration for the corresponding inequality.
948
949       ---------------------
950       -- Matching_Actual --
951       ---------------------
952
953       function Matching_Actual
954         (F   : Entity_Id;
955          A_F : Entity_Id) return Node_Id
956       is
957          Prev  : Node_Id;
958          Act   : Node_Id;
959
960       begin
961          Is_Named_Assoc := False;
962
963          --  End of list of purely positional parameters
964
965          if No (Actual) or else Nkind (Actual) = N_Others_Choice then
966             Found_Assoc := Empty;
967             Act         := Empty;
968
969          --  Case of positional parameter corresponding to current formal
970
971          elsif No (Selector_Name (Actual)) then
972             Found_Assoc := Actual;
973             Act :=  Explicit_Generic_Actual_Parameter (Actual);
974             Num_Matched := Num_Matched + 1;
975             Next (Actual);
976
977          --  Otherwise scan list of named actuals to find the one with the
978          --  desired name. All remaining actuals have explicit names.
979
980          else
981             Is_Named_Assoc := True;
982             Found_Assoc := Empty;
983             Act         := Empty;
984             Prev        := Empty;
985
986             while Present (Actual) loop
987                if Chars (Selector_Name (Actual)) = Chars (F) then
988                   Set_Entity (Selector_Name (Actual), A_F);
989                   Set_Etype  (Selector_Name (Actual), Etype (A_F));
990                   Generate_Reference (A_F, Selector_Name (Actual));
991                   Found_Assoc := Actual;
992                   Act :=  Explicit_Generic_Actual_Parameter (Actual);
993                   Num_Matched := Num_Matched + 1;
994                   exit;
995                end if;
996
997                Prev := Actual;
998                Next (Actual);
999             end loop;
1000
1001             --  Reset for subsequent searches. In most cases the named
1002             --  associations are in order. If they are not, we reorder them
1003             --  to avoid scanning twice the same actual. This is not just a
1004             --  question of efficiency: there may be multiple defaults with
1005             --  boxes that have the same name. In a nested instantiation we
1006             --  insert actuals for those defaults, and cannot rely on their
1007             --  names to disambiguate them.
1008
1009             if Actual = First_Named  then
1010                Next (First_Named);
1011
1012             elsif Present (Actual) then
1013                Insert_Before (First_Named, Remove_Next (Prev));
1014             end if;
1015
1016             Actual := First_Named;
1017          end if;
1018
1019          if Is_Entity_Name (Act) and then Present (Entity (Act)) then
1020             Set_Used_As_Generic_Actual (Entity (Act));
1021          end if;
1022
1023          return Act;
1024       end Matching_Actual;
1025
1026       -----------------------------
1027       -- Partial_Parametrization --
1028       -----------------------------
1029
1030       function Partial_Parametrization return Boolean is
1031       begin
1032          return Others_Present
1033           or else (Present (Found_Assoc) and then Box_Present (Found_Assoc));
1034       end Partial_Parametrization;
1035
1036       ---------------------
1037       -- Process_Default --
1038       ---------------------
1039
1040       procedure Process_Default (F : Entity_Id)  is
1041          Loc     : constant Source_Ptr := Sloc (I_Node);
1042          F_Id    : constant Entity_Id  := Defining_Entity (F);
1043          Decl    : Node_Id;
1044          Default : Node_Id;
1045          Id      : Entity_Id;
1046
1047       begin
1048          --  Append copy of formal declaration to associations, and create new
1049          --  defining identifier for it.
1050
1051          Decl := New_Copy_Tree (F);
1052          Id := Make_Defining_Identifier (Sloc (F_Id), Chars (F_Id));
1053
1054          if Nkind (F) in N_Formal_Subprogram_Declaration then
1055             Set_Defining_Unit_Name (Specification (Decl), Id);
1056
1057          else
1058             Set_Defining_Identifier (Decl, Id);
1059          end if;
1060
1061          Append (Decl, Assoc);
1062
1063          if No (Found_Assoc) then
1064             Default :=
1065                Make_Generic_Association (Loc,
1066                  Selector_Name => New_Occurrence_Of (Id, Loc),
1067                  Explicit_Generic_Actual_Parameter => Empty);
1068             Set_Box_Present (Default);
1069             Append (Default, Default_Formals);
1070          end if;
1071       end Process_Default;
1072
1073       -------------------------
1074       -- Set_Analyzed_Formal --
1075       -------------------------
1076
1077       procedure Set_Analyzed_Formal is
1078          Kind : Node_Kind;
1079
1080       begin
1081          while Present (Analyzed_Formal) loop
1082             Kind := Nkind (Analyzed_Formal);
1083
1084             case Nkind (Formal) is
1085
1086                when N_Formal_Subprogram_Declaration =>
1087                   exit when Kind in N_Formal_Subprogram_Declaration
1088                     and then
1089                       Chars
1090                         (Defining_Unit_Name (Specification (Formal))) =
1091                       Chars
1092                         (Defining_Unit_Name (Specification (Analyzed_Formal)));
1093
1094                when N_Formal_Package_Declaration =>
1095                   exit when Nkind_In (Kind, N_Formal_Package_Declaration,
1096                                             N_Generic_Package_Declaration,
1097                                             N_Package_Declaration);
1098
1099                when N_Use_Package_Clause | N_Use_Type_Clause => exit;
1100
1101                when others =>
1102
1103                   --  Skip freeze nodes, and nodes inserted to replace
1104                   --  unrecognized pragmas.
1105
1106                   exit when
1107                     Kind not in N_Formal_Subprogram_Declaration
1108                       and then not Nkind_In (Kind, N_Subprogram_Declaration,
1109                                                    N_Freeze_Entity,
1110                                                    N_Null_Statement,
1111                                                    N_Itype_Reference)
1112                       and then Chars (Defining_Identifier (Formal)) =
1113                                Chars (Defining_Identifier (Analyzed_Formal));
1114             end case;
1115
1116             Next (Analyzed_Formal);
1117          end loop;
1118       end Set_Analyzed_Formal;
1119
1120    --  Start of processing for Analyze_Associations
1121
1122    begin
1123       Actuals := Generic_Associations (I_Node);
1124
1125       if Present (Actuals) then
1126
1127          --  Check for an Others choice, indicating a partial parametrization
1128          --  for a formal package.
1129
1130          Actual := First (Actuals);
1131          while Present (Actual) loop
1132             if Nkind (Actual) = N_Others_Choice then
1133                Others_Present := True;
1134
1135                if Present (Next (Actual)) then
1136                   Error_Msg_N ("others must be last association", Actual);
1137                end if;
1138
1139                --  This subprogram is used both for formal packages and for
1140                --  instantiations. For the latter, associations must all be
1141                --  explicit.
1142
1143                if Nkind (I_Node) /= N_Formal_Package_Declaration
1144                  and then Comes_From_Source (I_Node)
1145                then
1146                   Error_Msg_N
1147                     ("others association not allowed in an instance",
1148                       Actual);
1149                end if;
1150
1151                --  In any case, nothing to do after the others association
1152
1153                exit;
1154
1155             elsif Box_Present (Actual)
1156               and then Comes_From_Source (I_Node)
1157               and then Nkind (I_Node) /= N_Formal_Package_Declaration
1158             then
1159                Error_Msg_N
1160                  ("box association not allowed in an instance", Actual);
1161             end if;
1162
1163             Next (Actual);
1164          end loop;
1165
1166          --  If named associations are present, save first named association
1167          --  (it may of course be Empty) to facilitate subsequent name search.
1168
1169          First_Named := First (Actuals);
1170          while Present (First_Named)
1171            and then Nkind (First_Named) /= N_Others_Choice
1172            and then No (Selector_Name (First_Named))
1173          loop
1174             Num_Actuals := Num_Actuals + 1;
1175             Next (First_Named);
1176          end loop;
1177       end if;
1178
1179       Named := First_Named;
1180       while Present (Named) loop
1181          if Nkind (Named) /= N_Others_Choice
1182            and then  No (Selector_Name (Named))
1183          then
1184             Error_Msg_N ("invalid positional actual after named one", Named);
1185             Abandon_Instantiation (Named);
1186          end if;
1187
1188          --  A named association may lack an actual parameter, if it was
1189          --  introduced for a default subprogram that turns out to be local
1190          --  to the outer instantiation.
1191
1192          if Nkind (Named) /= N_Others_Choice
1193            and then Present (Explicit_Generic_Actual_Parameter (Named))
1194          then
1195             Num_Actuals := Num_Actuals + 1;
1196          end if;
1197
1198          Next (Named);
1199       end loop;
1200
1201       if Present (Formals) then
1202          Formal := First_Non_Pragma (Formals);
1203          Analyzed_Formal := First_Non_Pragma (F_Copy);
1204
1205          if Present (Actuals) then
1206             Actual := First (Actuals);
1207
1208          --  All formals should have default values
1209
1210          else
1211             Actual := Empty;
1212          end if;
1213
1214          while Present (Formal) loop
1215             Set_Analyzed_Formal;
1216             Next_Formal := Next_Non_Pragma (Formal);
1217
1218             case Nkind (Formal) is
1219                when N_Formal_Object_Declaration =>
1220                   Match :=
1221                     Matching_Actual (
1222                       Defining_Identifier (Formal),
1223                       Defining_Identifier (Analyzed_Formal));
1224
1225                   if No (Match) and then Partial_Parametrization then
1226                      Process_Default (Formal);
1227                   else
1228                      Append_List
1229                        (Instantiate_Object (Formal, Match, Analyzed_Formal),
1230                         Assoc);
1231                   end if;
1232
1233                when N_Formal_Type_Declaration =>
1234                   Match :=
1235                     Matching_Actual (
1236                       Defining_Identifier (Formal),
1237                       Defining_Identifier (Analyzed_Formal));
1238
1239                   if No (Match) then
1240                      if Partial_Parametrization then
1241                         Process_Default (Formal);
1242
1243                      else
1244                         Error_Msg_Sloc := Sloc (Gen_Unit);
1245                         Error_Msg_NE
1246                           ("missing actual&",
1247                             Instantiation_Node,
1248                               Defining_Identifier (Formal));
1249                         Error_Msg_NE ("\in instantiation of & declared#",
1250                             Instantiation_Node, Gen_Unit);
1251                         Abandon_Instantiation (Instantiation_Node);
1252                      end if;
1253
1254                   else
1255                      Analyze (Match);
1256                      Append_List
1257                        (Instantiate_Type
1258                          (Formal, Match, Analyzed_Formal, Assoc),
1259                        Assoc);
1260
1261                      --  An instantiation is a freeze point for the actuals,
1262                      --  unless this is a rewritten formal package.
1263
1264                      if Nkind (I_Node) /= N_Formal_Package_Declaration then
1265                         Append_Elmt (Entity (Match), Actual_Types);
1266                      end if;
1267                   end if;
1268
1269                   --  A remote access-to-class-wide type must not be an
1270                   --  actual parameter for a generic formal of an access
1271                   --  type (E.2.2 (17)).
1272
1273                   if Nkind (Analyzed_Formal) = N_Formal_Type_Declaration
1274                     and then
1275                       Nkind (Formal_Type_Definition (Analyzed_Formal)) =
1276                                             N_Access_To_Object_Definition
1277                   then
1278                      Validate_Remote_Access_To_Class_Wide_Type (Match);
1279                   end if;
1280
1281                when N_Formal_Subprogram_Declaration =>
1282                   Match :=
1283                     Matching_Actual (
1284                       Defining_Unit_Name (Specification (Formal)),
1285                       Defining_Unit_Name (Specification (Analyzed_Formal)));
1286
1287                   --  If the formal subprogram has the same name as another
1288                   --  formal subprogram of the generic, then a named
1289                   --  association is illegal (12.3(9)). Exclude named
1290                   --  associations that are generated for a nested instance.
1291
1292                   if Present (Match)
1293                     and then Is_Named_Assoc
1294                     and then Comes_From_Source (Found_Assoc)
1295                   then
1296                      Temp_Formal := First (Formals);
1297                      while Present (Temp_Formal) loop
1298                         if Nkind (Temp_Formal) in
1299                              N_Formal_Subprogram_Declaration
1300                           and then Temp_Formal /= Formal
1301                           and then
1302                             Chars (Selector_Name (Found_Assoc)) =
1303                               Chars (Defining_Unit_Name
1304                                        (Specification (Temp_Formal)))
1305                         then
1306                            Error_Msg_N
1307                              ("name not allowed for overloaded formal",
1308                               Found_Assoc);
1309                            Abandon_Instantiation (Instantiation_Node);
1310                         end if;
1311
1312                         Next (Temp_Formal);
1313                      end loop;
1314                   end if;
1315
1316                   --  If there is no corresponding actual, this may be case of
1317                   --  partial parametrization, or else the formal has a default
1318                   --  or a box.
1319
1320                   if No (Match)
1321                     and then  Partial_Parametrization
1322                   then
1323                      Process_Default (Formal);
1324                   else
1325                      Append_To (Assoc,
1326                        Instantiate_Formal_Subprogram
1327                          (Formal, Match, Analyzed_Formal));
1328                   end if;
1329
1330                   --  If this is a nested generic, preserve default for later
1331                   --  instantiations.
1332
1333                   if No (Match)
1334                     and then Box_Present (Formal)
1335                   then
1336                      Append_Elmt
1337                        (Defining_Unit_Name (Specification (Last (Assoc))),
1338                         Default_Actuals);
1339                   end if;
1340
1341                when N_Formal_Package_Declaration =>
1342                   Match :=
1343                     Matching_Actual (
1344                       Defining_Identifier (Formal),
1345                       Defining_Identifier (Original_Node (Analyzed_Formal)));
1346
1347                   if No (Match) then
1348                      if Partial_Parametrization then
1349                         Process_Default (Formal);
1350
1351                      else
1352                         Error_Msg_Sloc := Sloc (Gen_Unit);
1353                         Error_Msg_NE
1354                           ("missing actual&",
1355                             Instantiation_Node, Defining_Identifier (Formal));
1356                         Error_Msg_NE ("\in instantiation of & declared#",
1357                             Instantiation_Node, Gen_Unit);
1358
1359                         Abandon_Instantiation (Instantiation_Node);
1360                      end if;
1361
1362                   else
1363                      Analyze (Match);
1364                      Append_List
1365                        (Instantiate_Formal_Package
1366                          (Formal, Match, Analyzed_Formal),
1367                         Assoc);
1368                   end if;
1369
1370                --  For use type and use package appearing in the generic part,
1371                --  we have already copied them, so we can just move them where
1372                --  they belong (we mustn't recopy them since this would mess up
1373                --  the Sloc values).
1374
1375                when N_Use_Package_Clause |
1376                     N_Use_Type_Clause    =>
1377                   if Nkind (Original_Node (I_Node)) =
1378                                      N_Formal_Package_Declaration
1379                   then
1380                      Append (New_Copy_Tree (Formal), Assoc);
1381                   else
1382                      Remove (Formal);
1383                      Append (Formal, Assoc);
1384                   end if;
1385
1386                when others =>
1387                   raise Program_Error;
1388
1389             end case;
1390
1391             Formal := Next_Formal;
1392             Next_Non_Pragma (Analyzed_Formal);
1393          end loop;
1394
1395          if Num_Actuals > Num_Matched then
1396             Error_Msg_Sloc := Sloc (Gen_Unit);
1397
1398             if Present (Selector_Name (Actual)) then
1399                Error_Msg_NE
1400                  ("unmatched actual&",
1401                     Actual, Selector_Name (Actual));
1402                Error_Msg_NE ("\in instantiation of& declared#",
1403                     Actual, Gen_Unit);
1404             else
1405                Error_Msg_NE
1406                  ("unmatched actual in instantiation of& declared#",
1407                    Actual, Gen_Unit);
1408             end if;
1409          end if;
1410
1411       elsif Present (Actuals) then
1412          Error_Msg_N
1413            ("too many actuals in generic instantiation", Instantiation_Node);
1414       end if;
1415
1416       declare
1417          Elmt : Elmt_Id := First_Elmt (Actual_Types);
1418       begin
1419          while Present (Elmt) loop
1420             Freeze_Before (I_Node, Node (Elmt));
1421             Next_Elmt (Elmt);
1422          end loop;
1423       end;
1424
1425       --  If there are default subprograms, normalize the tree by adding
1426       --  explicit associations for them. This is required if the instance
1427       --  appears within a generic.
1428
1429       declare
1430          Elmt  : Elmt_Id;
1431          Subp  : Entity_Id;
1432          New_D : Node_Id;
1433
1434       begin
1435          Elmt := First_Elmt (Default_Actuals);
1436          while Present (Elmt) loop
1437             if No (Actuals) then
1438                Actuals := New_List;
1439                Set_Generic_Associations (I_Node, Actuals);
1440             end if;
1441
1442             Subp := Node (Elmt);
1443             New_D :=
1444               Make_Generic_Association (Sloc (Subp),
1445                 Selector_Name => New_Occurrence_Of (Subp, Sloc (Subp)),
1446                   Explicit_Generic_Actual_Parameter =>
1447                     New_Occurrence_Of (Subp, Sloc (Subp)));
1448             Mark_Rewrite_Insertion (New_D);
1449             Append_To (Actuals, New_D);
1450             Next_Elmt (Elmt);
1451          end loop;
1452       end;
1453
1454       --  If this is a formal package, normalize the parameter list by adding
1455       --  explicit box associations for the formals that are covered by an
1456       --  Others_Choice.
1457
1458       if not Is_Empty_List (Default_Formals) then
1459          Append_List (Default_Formals, Formals);
1460       end if;
1461
1462       return Assoc;
1463    end Analyze_Associations;
1464
1465    -------------------------------
1466    -- Analyze_Formal_Array_Type --
1467    -------------------------------
1468
1469    procedure Analyze_Formal_Array_Type
1470      (T   : in out Entity_Id;
1471       Def : Node_Id)
1472    is
1473       DSS : Node_Id;
1474
1475    begin
1476       --  Treated like a non-generic array declaration, with additional
1477       --  semantic checks.
1478
1479       Enter_Name (T);
1480
1481       if Nkind (Def) = N_Constrained_Array_Definition then
1482          DSS := First (Discrete_Subtype_Definitions (Def));
1483          while Present (DSS) loop
1484             if Nkind_In (DSS, N_Subtype_Indication,
1485                               N_Range,
1486                               N_Attribute_Reference)
1487             then
1488                Error_Msg_N ("only a subtype mark is allowed in a formal", DSS);
1489             end if;
1490
1491             Next (DSS);
1492          end loop;
1493       end if;
1494
1495       Array_Type_Declaration (T, Def);
1496       Set_Is_Generic_Type (Base_Type (T));
1497
1498       if Ekind (Component_Type (T)) = E_Incomplete_Type
1499         and then No (Full_View (Component_Type (T)))
1500       then
1501          Error_Msg_N ("premature usage of incomplete type", Def);
1502
1503       --  Check that range constraint is not allowed on the component type
1504       --  of a generic formal array type (AARM 12.5.3(3))
1505
1506       elsif Is_Internal (Component_Type (T))
1507         and then Present (Subtype_Indication (Component_Definition (Def)))
1508         and then Nkind (Original_Node
1509                          (Subtype_Indication (Component_Definition (Def)))) =
1510                                                          N_Subtype_Indication
1511       then
1512          Error_Msg_N
1513            ("in a formal, a subtype indication can only be "
1514              & "a subtype mark (RM 12.5.3(3))",
1515              Subtype_Indication (Component_Definition (Def)));
1516       end if;
1517
1518    end Analyze_Formal_Array_Type;
1519
1520    ---------------------------------------------
1521    -- Analyze_Formal_Decimal_Fixed_Point_Type --
1522    ---------------------------------------------
1523
1524    --  As for other generic types, we create a valid type representation with
1525    --  legal but arbitrary attributes, whose values are never considered
1526    --  static. For all scalar types we introduce an anonymous base type, with
1527    --  the same attributes. We choose the corresponding integer type to be
1528    --  Standard_Integer.
1529
1530    procedure Analyze_Formal_Decimal_Fixed_Point_Type
1531      (T   : Entity_Id;
1532       Def : Node_Id)
1533    is
1534       Loc       : constant Source_Ptr := Sloc (Def);
1535       Base      : constant Entity_Id :=
1536                     New_Internal_Entity
1537                       (E_Decimal_Fixed_Point_Type,
1538                        Current_Scope, Sloc (Def), 'G');
1539       Int_Base  : constant Entity_Id := Standard_Integer;
1540       Delta_Val : constant Ureal := Ureal_1;
1541       Digs_Val  : constant Uint  := Uint_6;
1542
1543    begin
1544       Enter_Name (T);
1545
1546       Set_Etype          (Base, Base);
1547       Set_Size_Info      (Base, Int_Base);
1548       Set_RM_Size        (Base, RM_Size (Int_Base));
1549       Set_First_Rep_Item (Base, First_Rep_Item (Int_Base));
1550       Set_Digits_Value   (Base, Digs_Val);
1551       Set_Delta_Value    (Base, Delta_Val);
1552       Set_Small_Value    (Base, Delta_Val);
1553       Set_Scalar_Range   (Base,
1554         Make_Range (Loc,
1555           Low_Bound  => Make_Real_Literal (Loc, Ureal_1),
1556           High_Bound => Make_Real_Literal (Loc, Ureal_1)));
1557
1558       Set_Is_Generic_Type (Base);
1559       Set_Parent          (Base, Parent (Def));
1560
1561       Set_Ekind          (T, E_Decimal_Fixed_Point_Subtype);
1562       Set_Etype          (T, Base);
1563       Set_Size_Info      (T, Int_Base);
1564       Set_RM_Size        (T, RM_Size (Int_Base));
1565       Set_First_Rep_Item (T, First_Rep_Item (Int_Base));
1566       Set_Digits_Value   (T, Digs_Val);
1567       Set_Delta_Value    (T, Delta_Val);
1568       Set_Small_Value    (T, Delta_Val);
1569       Set_Scalar_Range   (T, Scalar_Range (Base));
1570       Set_Is_Constrained (T);
1571
1572       Check_Restriction (No_Fixed_Point, Def);
1573    end Analyze_Formal_Decimal_Fixed_Point_Type;
1574
1575    -------------------------------------------
1576    -- Analyze_Formal_Derived_Interface_Type --
1577    -------------------------------------------
1578
1579    procedure Analyze_Formal_Derived_Interface_Type
1580      (N   : Node_Id;
1581       T   : Entity_Id;
1582       Def : Node_Id)
1583    is
1584       Loc   : constant Source_Ptr := Sloc (Def);
1585
1586    begin
1587       --  Rewrite as a type declaration of a derived type. This ensures that
1588       --  the interface list and primitive operations are properly captured.
1589
1590       Rewrite (N,
1591         Make_Full_Type_Declaration (Loc,
1592           Defining_Identifier => T,
1593           Type_Definition     => Def));
1594       Analyze (N);
1595       Set_Is_Generic_Type (T);
1596    end Analyze_Formal_Derived_Interface_Type;
1597
1598    ---------------------------------
1599    -- Analyze_Formal_Derived_Type --
1600    ---------------------------------
1601
1602    procedure Analyze_Formal_Derived_Type
1603      (N   : Node_Id;
1604       T   : Entity_Id;
1605       Def : Node_Id)
1606    is
1607       Loc      : constant Source_Ptr := Sloc (Def);
1608       Unk_Disc : constant Boolean    := Unknown_Discriminants_Present (N);
1609       New_N    : Node_Id;
1610
1611    begin
1612       Set_Is_Generic_Type (T);
1613
1614       if Private_Present (Def) then
1615          New_N :=
1616            Make_Private_Extension_Declaration (Loc,
1617              Defining_Identifier           => T,
1618              Discriminant_Specifications   => Discriminant_Specifications (N),
1619              Unknown_Discriminants_Present => Unk_Disc,
1620              Subtype_Indication            => Subtype_Mark (Def),
1621              Interface_List                => Interface_List (Def));
1622
1623          Set_Abstract_Present     (New_N, Abstract_Present     (Def));
1624          Set_Limited_Present      (New_N, Limited_Present      (Def));
1625          Set_Synchronized_Present (New_N, Synchronized_Present (Def));
1626
1627       else
1628          New_N :=
1629            Make_Full_Type_Declaration (Loc,
1630              Defining_Identifier => T,
1631              Discriminant_Specifications =>
1632                Discriminant_Specifications (Parent (T)),
1633              Type_Definition =>
1634                Make_Derived_Type_Definition (Loc,
1635                  Subtype_Indication => Subtype_Mark (Def)));
1636
1637          Set_Abstract_Present
1638            (Type_Definition (New_N), Abstract_Present (Def));
1639          Set_Limited_Present
1640            (Type_Definition (New_N), Limited_Present  (Def));
1641       end if;
1642
1643       Rewrite (N, New_N);
1644       Analyze (N);
1645
1646       if Unk_Disc then
1647          if not Is_Composite_Type (T) then
1648             Error_Msg_N
1649               ("unknown discriminants not allowed for elementary types", N);
1650          else
1651             Set_Has_Unknown_Discriminants (T);
1652             Set_Is_Constrained (T, False);
1653          end if;
1654       end if;
1655
1656       --  If the parent type has a known size, so does the formal, which makes
1657       --  legal representation clauses that involve the formal.
1658
1659       Set_Size_Known_At_Compile_Time
1660         (T, Size_Known_At_Compile_Time (Entity (Subtype_Mark (Def))));
1661    end Analyze_Formal_Derived_Type;
1662
1663    ----------------------------------
1664    -- Analyze_Formal_Discrete_Type --
1665    ----------------------------------
1666
1667    --  The operations defined for a discrete types are those of an enumeration
1668    --  type. The size is set to an arbitrary value, for use in analyzing the
1669    --  generic unit.
1670
1671    procedure Analyze_Formal_Discrete_Type (T : Entity_Id; Def : Node_Id) is
1672       Loc : constant Source_Ptr := Sloc (Def);
1673       Lo  : Node_Id;
1674       Hi  : Node_Id;
1675
1676       Base : constant Entity_Id :=
1677                New_Internal_Entity
1678                  (E_Floating_Point_Type, Current_Scope, Sloc (Def), 'G');
1679    begin
1680       Enter_Name          (T);
1681       Set_Ekind           (T, E_Enumeration_Subtype);
1682       Set_Etype           (T, Base);
1683       Init_Size           (T, 8);
1684       Init_Alignment      (T);
1685       Set_Is_Generic_Type (T);
1686       Set_Is_Constrained  (T);
1687
1688       --  For semantic analysis, the bounds of the type must be set to some
1689       --  non-static value. The simplest is to create attribute nodes for those
1690       --  bounds, that refer to the type itself. These bounds are never
1691       --  analyzed but serve as place-holders.
1692
1693       Lo :=
1694         Make_Attribute_Reference (Loc,
1695           Attribute_Name => Name_First,
1696           Prefix         => New_Reference_To (T, Loc));
1697       Set_Etype (Lo, T);
1698
1699       Hi :=
1700         Make_Attribute_Reference (Loc,
1701           Attribute_Name => Name_Last,
1702           Prefix         => New_Reference_To (T, Loc));
1703       Set_Etype (Hi, T);
1704
1705       Set_Scalar_Range (T,
1706         Make_Range (Loc,
1707           Low_Bound  => Lo,
1708           High_Bound => Hi));
1709
1710       Set_Ekind           (Base, E_Enumeration_Type);
1711       Set_Etype           (Base, Base);
1712       Init_Size           (Base, 8);
1713       Init_Alignment      (Base);
1714       Set_Is_Generic_Type (Base);
1715       Set_Scalar_Range    (Base, Scalar_Range (T));
1716       Set_Parent          (Base, Parent (Def));
1717    end Analyze_Formal_Discrete_Type;
1718
1719    ----------------------------------
1720    -- Analyze_Formal_Floating_Type --
1721    ---------------------------------
1722
1723    procedure Analyze_Formal_Floating_Type (T : Entity_Id; Def : Node_Id) is
1724       Base : constant Entity_Id :=
1725                New_Internal_Entity
1726                  (E_Floating_Point_Type, Current_Scope, Sloc (Def), 'G');
1727
1728    begin
1729       --  The various semantic attributes are taken from the predefined type
1730       --  Float, just so that all of them are initialized. Their values are
1731       --  never used because no constant folding or expansion takes place in
1732       --  the generic itself.
1733
1734       Enter_Name (T);
1735       Set_Ekind          (T, E_Floating_Point_Subtype);
1736       Set_Etype          (T, Base);
1737       Set_Size_Info      (T,              (Standard_Float));
1738       Set_RM_Size        (T, RM_Size      (Standard_Float));
1739       Set_Digits_Value   (T, Digits_Value (Standard_Float));
1740       Set_Scalar_Range   (T, Scalar_Range (Standard_Float));
1741       Set_Is_Constrained (T);
1742
1743       Set_Is_Generic_Type (Base);
1744       Set_Etype           (Base, Base);
1745       Set_Size_Info       (Base,              (Standard_Float));
1746       Set_RM_Size         (Base, RM_Size      (Standard_Float));
1747       Set_Digits_Value    (Base, Digits_Value (Standard_Float));
1748       Set_Scalar_Range    (Base, Scalar_Range (Standard_Float));
1749       Set_Parent          (Base, Parent (Def));
1750
1751       Check_Restriction (No_Floating_Point, Def);
1752    end Analyze_Formal_Floating_Type;
1753
1754    -----------------------------------
1755    -- Analyze_Formal_Interface_Type;--
1756    -----------------------------------
1757
1758    procedure Analyze_Formal_Interface_Type
1759       (N   : Node_Id;
1760        T   : Entity_Id;
1761        Def : Node_Id)
1762    is
1763       Loc   : constant Source_Ptr := Sloc (N);
1764       New_N : Node_Id;
1765
1766    begin
1767       New_N :=
1768         Make_Full_Type_Declaration (Loc,
1769           Defining_Identifier => T,
1770           Type_Definition => Def);
1771
1772       Rewrite (N, New_N);
1773       Analyze (N);
1774       Set_Is_Generic_Type (T);
1775    end Analyze_Formal_Interface_Type;
1776
1777    ---------------------------------
1778    -- Analyze_Formal_Modular_Type --
1779    ---------------------------------
1780
1781    procedure Analyze_Formal_Modular_Type (T : Entity_Id; Def : Node_Id) is
1782    begin
1783       --  Apart from their entity kind, generic modular types are treated like
1784       --  signed integer types, and have the same attributes.
1785
1786       Analyze_Formal_Signed_Integer_Type (T, Def);
1787       Set_Ekind (T, E_Modular_Integer_Subtype);
1788       Set_Ekind (Etype (T), E_Modular_Integer_Type);
1789
1790    end Analyze_Formal_Modular_Type;
1791
1792    ---------------------------------------
1793    -- Analyze_Formal_Object_Declaration --
1794    ---------------------------------------
1795
1796    procedure Analyze_Formal_Object_Declaration (N : Node_Id) is
1797       E  : constant Node_Id := Default_Expression (N);
1798       Id : constant Node_Id := Defining_Identifier (N);
1799       K  : Entity_Kind;
1800       T  : Node_Id;
1801
1802    begin
1803       Enter_Name (Id);
1804
1805       --  Determine the mode of the formal object
1806
1807       if Out_Present (N) then
1808          K := E_Generic_In_Out_Parameter;
1809
1810          if not In_Present (N) then
1811             Error_Msg_N ("formal generic objects cannot have mode OUT", N);
1812          end if;
1813
1814       else
1815          K := E_Generic_In_Parameter;
1816       end if;
1817
1818       if Present (Subtype_Mark (N)) then
1819          Find_Type (Subtype_Mark (N));
1820          T := Entity (Subtype_Mark (N));
1821
1822          --  Verify that there is no redundant null exclusion
1823
1824          if Null_Exclusion_Present (N) then
1825             if not Is_Access_Type (T) then
1826                Error_Msg_N
1827                  ("null exclusion can only apply to an access type", N);
1828
1829             elsif Can_Never_Be_Null (T) then
1830                Error_Msg_NE
1831                  ("`NOT NULL` not allowed (& already excludes null)",
1832                     N, T);
1833             end if;
1834          end if;
1835
1836       --  Ada 2005 (AI-423): Formal object with an access definition
1837
1838       else
1839          Check_Access_Definition (N);
1840          T := Access_Definition
1841                 (Related_Nod => N,
1842                  N           => Access_Definition (N));
1843       end if;
1844
1845       if Ekind (T) = E_Incomplete_Type then
1846          declare
1847             Error_Node : Node_Id;
1848
1849          begin
1850             if Present (Subtype_Mark (N)) then
1851                Error_Node := Subtype_Mark (N);
1852             else
1853                Check_Access_Definition (N);
1854                Error_Node := Access_Definition (N);
1855             end if;
1856
1857             Error_Msg_N ("premature usage of incomplete type", Error_Node);
1858          end;
1859       end if;
1860
1861       if K = E_Generic_In_Parameter then
1862
1863          --  Ada 2005 (AI-287): Limited aggregates allowed in generic formals
1864
1865          if Ada_Version < Ada_2005 and then Is_Limited_Type (T) then
1866             Error_Msg_N
1867               ("generic formal of mode IN must not be of limited type", N);
1868             Explain_Limited_Type (T, N);
1869          end if;
1870
1871          if Is_Abstract_Type (T) then
1872             Error_Msg_N
1873               ("generic formal of mode IN must not be of abstract type", N);
1874          end if;
1875
1876          if Present (E) then
1877             Preanalyze_Spec_Expression (E, T);
1878
1879             if Is_Limited_Type (T) and then not OK_For_Limited_Init (T, E) then
1880                Error_Msg_N
1881                  ("initialization not allowed for limited types", E);
1882                Explain_Limited_Type (T, E);
1883             end if;
1884          end if;
1885
1886          Set_Ekind (Id, K);
1887          Set_Etype (Id, T);
1888
1889       --  Case of generic IN OUT parameter
1890
1891       else
1892          --  If the formal has an unconstrained type, construct its actual
1893          --  subtype, as is done for subprogram formals. In this fashion, all
1894          --  its uses can refer to specific bounds.
1895
1896          Set_Ekind (Id, K);
1897          Set_Etype (Id, T);
1898
1899          if (Is_Array_Type (T)
1900               and then not Is_Constrained (T))
1901            or else
1902             (Ekind (T) = E_Record_Type
1903               and then Has_Discriminants (T))
1904          then
1905             declare
1906                Non_Freezing_Ref : constant Node_Id :=
1907                                     New_Reference_To (Id, Sloc (Id));
1908                Decl : Node_Id;
1909
1910             begin
1911                --  Make sure the actual subtype doesn't generate bogus freezing
1912
1913                Set_Must_Not_Freeze (Non_Freezing_Ref);
1914                Decl := Build_Actual_Subtype (T, Non_Freezing_Ref);
1915                Insert_Before_And_Analyze (N, Decl);
1916                Set_Actual_Subtype (Id, Defining_Identifier (Decl));
1917             end;
1918          else
1919             Set_Actual_Subtype (Id, T);
1920          end if;
1921
1922          if Present (E) then
1923             Error_Msg_N
1924               ("initialization not allowed for `IN OUT` formals", N);
1925          end if;
1926       end if;
1927
1928       Analyze_Aspect_Specifications (N, Id, Aspect_Specifications (N));
1929    end Analyze_Formal_Object_Declaration;
1930
1931    ----------------------------------------------
1932    -- Analyze_Formal_Ordinary_Fixed_Point_Type --
1933    ----------------------------------------------
1934
1935    procedure Analyze_Formal_Ordinary_Fixed_Point_Type
1936      (T   : Entity_Id;
1937       Def : Node_Id)
1938    is
1939       Loc  : constant Source_Ptr := Sloc (Def);
1940       Base : constant Entity_Id :=
1941                New_Internal_Entity
1942                  (E_Ordinary_Fixed_Point_Type, Current_Scope, Sloc (Def), 'G');
1943    begin
1944       --  The semantic attributes are set for completeness only, their values
1945       --  will never be used, since all properties of the type are non-static.
1946
1947       Enter_Name (T);
1948       Set_Ekind            (T, E_Ordinary_Fixed_Point_Subtype);
1949       Set_Etype            (T, Base);
1950       Set_Size_Info        (T, Standard_Integer);
1951       Set_RM_Size          (T, RM_Size (Standard_Integer));
1952       Set_Small_Value      (T, Ureal_1);
1953       Set_Delta_Value      (T, Ureal_1);
1954       Set_Scalar_Range     (T,
1955         Make_Range (Loc,
1956           Low_Bound  => Make_Real_Literal (Loc, Ureal_1),
1957           High_Bound => Make_Real_Literal (Loc, Ureal_1)));
1958       Set_Is_Constrained   (T);
1959
1960       Set_Is_Generic_Type (Base);
1961       Set_Etype           (Base, Base);
1962       Set_Size_Info       (Base, Standard_Integer);
1963       Set_RM_Size         (Base, RM_Size (Standard_Integer));
1964       Set_Small_Value     (Base, Ureal_1);
1965       Set_Delta_Value     (Base, Ureal_1);
1966       Set_Scalar_Range    (Base, Scalar_Range (T));
1967       Set_Parent          (Base, Parent (Def));
1968
1969       Check_Restriction (No_Fixed_Point, Def);
1970    end Analyze_Formal_Ordinary_Fixed_Point_Type;
1971
1972    ----------------------------------------
1973    -- Analyze_Formal_Package_Declaration --
1974    ----------------------------------------
1975
1976    procedure Analyze_Formal_Package_Declaration (N : Node_Id) is
1977       Loc              : constant Source_Ptr := Sloc (N);
1978       Pack_Id          : constant Entity_Id  := Defining_Identifier (N);
1979       Formal           : Entity_Id;
1980       Gen_Id           : constant Node_Id    := Name (N);
1981       Gen_Decl         : Node_Id;
1982       Gen_Unit         : Entity_Id;
1983       New_N            : Node_Id;
1984       Parent_Installed : Boolean := False;
1985       Renaming         : Node_Id;
1986       Parent_Instance  : Entity_Id;
1987       Renaming_In_Par  : Entity_Id;
1988       No_Associations  : Boolean := False;
1989
1990       function Build_Local_Package return Node_Id;
1991       --  The formal package is rewritten so that its parameters are replaced
1992       --  with corresponding declarations. For parameters with bona fide
1993       --  associations these declarations are created by Analyze_Associations
1994       --  as for a regular instantiation. For boxed parameters, we preserve
1995       --  the formal declarations and analyze them, in order to introduce
1996       --  entities of the right kind in the environment of the formal.
1997
1998       -------------------------
1999       -- Build_Local_Package --
2000       -------------------------
2001
2002       function Build_Local_Package return Node_Id is
2003          Decls     : List_Id;
2004          Pack_Decl : Node_Id;
2005
2006       begin
2007          --  Within the formal, the name of the generic package is a renaming
2008          --  of the formal (as for a regular instantiation).
2009
2010          Pack_Decl :=
2011            Make_Package_Declaration (Loc,
2012              Specification =>
2013                Copy_Generic_Node
2014                  (Specification (Original_Node (Gen_Decl)),
2015                     Empty, Instantiating => True));
2016
2017          Renaming := Make_Package_Renaming_Declaration (Loc,
2018              Defining_Unit_Name =>
2019                Make_Defining_Identifier (Loc, Chars (Gen_Unit)),
2020              Name => New_Occurrence_Of (Formal, Loc));
2021
2022          if Nkind (Gen_Id) = N_Identifier
2023            and then Chars (Gen_Id) = Chars (Pack_Id)
2024          then
2025             Error_Msg_NE
2026               ("& is hidden within declaration of instance", Gen_Id, Gen_Unit);
2027          end if;
2028
2029          --  If the formal is declared with a box, or with an others choice,
2030          --  create corresponding declarations for all entities in the formal
2031          --  part, so that names with the proper types are available in the
2032          --  specification of the formal package.
2033
2034          --  On the other hand, if there are no associations, then all the
2035          --  formals must have defaults, and this will be checked by the
2036          --  call to Analyze_Associations.
2037
2038          if Box_Present (N)
2039            or else Nkind (First (Generic_Associations (N))) = N_Others_Choice
2040          then
2041             declare
2042                Formal_Decl : Node_Id;
2043
2044             begin
2045                --  TBA : for a formal package, need to recurse ???
2046
2047                Decls := New_List;
2048                Formal_Decl :=
2049                  First
2050                    (Generic_Formal_Declarations (Original_Node (Gen_Decl)));
2051                while Present (Formal_Decl) loop
2052                   Append_To
2053                     (Decls, Copy_Generic_Node (Formal_Decl, Empty, True));
2054                   Next (Formal_Decl);
2055                end loop;
2056             end;
2057
2058          --  If generic associations are present, use Analyze_Associations to
2059          --  create the proper renaming declarations.
2060
2061          else
2062             declare
2063                Act_Tree : constant Node_Id :=
2064                             Copy_Generic_Node
2065                               (Original_Node (Gen_Decl), Empty,
2066                                Instantiating => True);
2067
2068             begin
2069                Generic_Renamings.Set_Last (0);
2070                Generic_Renamings_HTable.Reset;
2071                Instantiation_Node := N;
2072
2073                Decls :=
2074                  Analyze_Associations
2075                    (Original_Node (N),
2076                       Generic_Formal_Declarations (Act_Tree),
2077                       Generic_Formal_Declarations (Gen_Decl));
2078             end;
2079          end if;
2080
2081          Append (Renaming, To => Decls);
2082
2083          --  Add generated declarations ahead of local declarations in
2084          --  the package.
2085
2086          if No (Visible_Declarations (Specification (Pack_Decl))) then
2087             Set_Visible_Declarations (Specification (Pack_Decl), Decls);
2088          else
2089             Insert_List_Before
2090               (First (Visible_Declarations (Specification (Pack_Decl))),
2091                  Decls);
2092          end if;
2093
2094          return Pack_Decl;
2095       end Build_Local_Package;
2096
2097    --  Start of processing for Analyze_Formal_Package
2098
2099    begin
2100       Text_IO_Kludge (Gen_Id);
2101
2102       Init_Env;
2103       Check_Generic_Child_Unit (Gen_Id, Parent_Installed);
2104       Gen_Unit := Entity (Gen_Id);
2105
2106       --  Check for a formal package that is a package renaming
2107
2108       if Present (Renamed_Object (Gen_Unit)) then
2109
2110          --  Indicate that unit is used, before replacing it with renamed
2111          --  entity for use below.
2112
2113          if In_Extended_Main_Source_Unit (N) then
2114             Set_Is_Instantiated (Gen_Unit);
2115             Generate_Reference  (Gen_Unit, N);
2116          end if;
2117
2118          Gen_Unit := Renamed_Object (Gen_Unit);
2119       end if;
2120
2121       if Ekind (Gen_Unit) /= E_Generic_Package then
2122          Error_Msg_N ("expect generic package name", Gen_Id);
2123          Restore_Env;
2124          goto Leave;
2125
2126       elsif  Gen_Unit = Current_Scope then
2127          Error_Msg_N
2128            ("generic package cannot be used as a formal package of itself",
2129              Gen_Id);
2130          Restore_Env;
2131          goto Leave;
2132
2133       elsif In_Open_Scopes (Gen_Unit) then
2134          if Is_Compilation_Unit (Gen_Unit)
2135            and then Is_Child_Unit (Current_Scope)
2136          then
2137             --  Special-case the error when the formal is a parent, and
2138             --  continue analysis to minimize cascaded errors.
2139
2140             Error_Msg_N
2141               ("generic parent cannot be used as formal package "
2142                 & "of a child unit",
2143                 Gen_Id);
2144
2145          else
2146             Error_Msg_N
2147               ("generic package cannot be used as a formal package "
2148                 & "within itself",
2149                 Gen_Id);
2150             Restore_Env;
2151             goto Leave;
2152          end if;
2153       end if;
2154
2155       if Box_Present (N)
2156         or else No (Generic_Associations (N))
2157         or else Nkind (First (Generic_Associations (N))) = N_Others_Choice
2158       then
2159          No_Associations := True;
2160       end if;
2161
2162       --  If there are no generic associations, the generic parameters appear
2163       --  as local entities and are instantiated like them. We copy the generic
2164       --  package declaration as if it were an instantiation, and analyze it
2165       --  like a regular package, except that we treat the formals as
2166       --  additional visible components.
2167
2168       Gen_Decl := Unit_Declaration_Node (Gen_Unit);
2169
2170       if In_Extended_Main_Source_Unit (N) then
2171          Set_Is_Instantiated (Gen_Unit);
2172          Generate_Reference  (Gen_Unit, N);
2173       end if;
2174
2175       Formal := New_Copy (Pack_Id);
2176       Create_Instantiation_Source (N, Gen_Unit, False, S_Adjustment);
2177
2178       begin
2179          --  Make local generic without formals. The formals will be replaced
2180          --  with internal declarations.
2181
2182          New_N := Build_Local_Package;
2183
2184          --  If there are errors in the parameter list, Analyze_Associations
2185          --  raises Instantiation_Error. Patch the declaration to prevent
2186          --  further exception propagation.
2187
2188       exception
2189          when Instantiation_Error =>
2190
2191             Enter_Name (Formal);
2192             Set_Ekind  (Formal, E_Variable);
2193             Set_Etype  (Formal, Any_Type);
2194
2195             if Parent_Installed then
2196                Remove_Parent;
2197             end if;
2198
2199             goto Leave;
2200       end;
2201
2202       Rewrite (N, New_N);
2203       Set_Defining_Unit_Name (Specification (New_N), Formal);
2204       Set_Generic_Parent (Specification (N), Gen_Unit);
2205       Set_Instance_Env (Gen_Unit, Formal);
2206       Set_Is_Generic_Instance (Formal);
2207
2208       Enter_Name (Formal);
2209       Set_Ekind  (Formal, E_Package);
2210       Set_Etype  (Formal, Standard_Void_Type);
2211       Set_Inner_Instances (Formal, New_Elmt_List);
2212       Push_Scope  (Formal);
2213
2214       if Is_Child_Unit (Gen_Unit)
2215         and then Parent_Installed
2216       then
2217          --  Similarly, we have to make the name of the formal visible in the
2218          --  parent instance, to resolve properly fully qualified names that
2219          --  may appear in the generic unit. The parent instance has been
2220          --  placed on the scope stack ahead of the current scope.
2221
2222          Parent_Instance := Scope_Stack.Table (Scope_Stack.Last - 1).Entity;
2223
2224          Renaming_In_Par :=
2225            Make_Defining_Identifier (Loc, Chars (Gen_Unit));
2226          Set_Ekind (Renaming_In_Par, E_Package);
2227          Set_Etype (Renaming_In_Par, Standard_Void_Type);
2228          Set_Scope (Renaming_In_Par, Parent_Instance);
2229          Set_Parent (Renaming_In_Par, Parent (Formal));
2230          Set_Renamed_Object (Renaming_In_Par, Formal);
2231          Append_Entity (Renaming_In_Par, Parent_Instance);
2232       end if;
2233
2234       Analyze (Specification (N));
2235
2236       --  The formals for which associations are provided are not visible
2237       --  outside of the formal package. The others are still declared by a
2238       --  formal parameter declaration.
2239
2240       if not No_Associations then
2241          declare
2242             E : Entity_Id;
2243
2244          begin
2245             E := First_Entity (Formal);
2246             while Present (E) loop
2247                exit when Ekind (E) = E_Package
2248                  and then Renamed_Entity (E) = Formal;
2249
2250                if not Is_Generic_Formal (E) then
2251                   Set_Is_Hidden (E);
2252                end if;
2253
2254                Next_Entity (E);
2255             end loop;
2256          end;
2257       end if;
2258
2259       End_Package_Scope (Formal);
2260
2261       if Parent_Installed then
2262          Remove_Parent;
2263       end if;
2264
2265       Restore_Env;
2266
2267       --  Inside the generic unit, the formal package is a regular package, but
2268       --  no body is needed for it. Note that after instantiation, the defining
2269       --  unit name we need is in the new tree and not in the original (see
2270       --  Package_Instantiation). A generic formal package is an instance, and
2271       --  can be used as an actual for an inner instance.
2272
2273       Set_Has_Completion (Formal, True);
2274
2275       --  Add semantic information to the original defining identifier.
2276       --  for ASIS use.
2277
2278       Set_Ekind (Pack_Id, E_Package);
2279       Set_Etype (Pack_Id, Standard_Void_Type);
2280       Set_Scope (Pack_Id, Scope (Formal));
2281       Set_Has_Completion (Pack_Id, True);
2282
2283       <<Leave>>
2284          Analyze_Aspect_Specifications (N, Pack_Id, Aspect_Specifications (N));
2285    end Analyze_Formal_Package_Declaration;
2286
2287    ---------------------------------
2288    -- Analyze_Formal_Private_Type --
2289    ---------------------------------
2290
2291    procedure Analyze_Formal_Private_Type
2292      (N   : Node_Id;
2293       T   : Entity_Id;
2294       Def : Node_Id)
2295    is
2296    begin
2297       New_Private_Type (N, T, Def);
2298
2299       --  Set the size to an arbitrary but legal value
2300
2301       Set_Size_Info (T, Standard_Integer);
2302       Set_RM_Size   (T, RM_Size (Standard_Integer));
2303    end Analyze_Formal_Private_Type;
2304
2305    ----------------------------------------
2306    -- Analyze_Formal_Signed_Integer_Type --
2307    ----------------------------------------
2308
2309    procedure Analyze_Formal_Signed_Integer_Type
2310      (T   : Entity_Id;
2311       Def : Node_Id)
2312    is
2313       Base : constant Entity_Id :=
2314                New_Internal_Entity
2315                  (E_Signed_Integer_Type, Current_Scope, Sloc (Def), 'G');
2316
2317    begin
2318       Enter_Name (T);
2319
2320       Set_Ekind          (T, E_Signed_Integer_Subtype);
2321       Set_Etype          (T, Base);
2322       Set_Size_Info      (T, Standard_Integer);
2323       Set_RM_Size        (T, RM_Size (Standard_Integer));
2324       Set_Scalar_Range   (T, Scalar_Range (Standard_Integer));
2325       Set_Is_Constrained (T);
2326
2327       Set_Is_Generic_Type (Base);
2328       Set_Size_Info       (Base, Standard_Integer);
2329       Set_RM_Size         (Base, RM_Size (Standard_Integer));
2330       Set_Etype           (Base, Base);
2331       Set_Scalar_Range    (Base, Scalar_Range (Standard_Integer));
2332       Set_Parent          (Base, Parent (Def));
2333    end Analyze_Formal_Signed_Integer_Type;
2334
2335    -------------------------------------------
2336    -- Analyze_Formal_Subprogram_Declaration --
2337    -------------------------------------------
2338
2339    procedure Analyze_Formal_Subprogram_Declaration (N : Node_Id) is
2340       Spec : constant Node_Id   := Specification (N);
2341       Def  : constant Node_Id   := Default_Name (N);
2342       Nam  : constant Entity_Id := Defining_Unit_Name (Spec);
2343       Subp : Entity_Id;
2344
2345    begin
2346       if Nam = Error then
2347          return;
2348       end if;
2349
2350       if Nkind (Nam) = N_Defining_Program_Unit_Name then
2351          Error_Msg_N ("name of formal subprogram must be a direct name", Nam);
2352          goto Leave;
2353       end if;
2354
2355       Analyze_Subprogram_Declaration (N);
2356       Set_Is_Formal_Subprogram (Nam);
2357       Set_Has_Completion (Nam);
2358
2359       if Nkind (N) = N_Formal_Abstract_Subprogram_Declaration then
2360          Set_Is_Abstract_Subprogram (Nam);
2361          Set_Is_Dispatching_Operation (Nam);
2362
2363          declare
2364             Ctrl_Type : constant Entity_Id := Find_Dispatching_Type (Nam);
2365          begin
2366             if No (Ctrl_Type) then
2367                Error_Msg_N
2368                  ("abstract formal subprogram must have a controlling type",
2369                   N);
2370             else
2371                Check_Controlling_Formals (Ctrl_Type, Nam);
2372             end if;
2373          end;
2374       end if;
2375
2376       --  Default name is resolved at the point of instantiation
2377
2378       if Box_Present (N) then
2379          null;
2380
2381       --  Else default is bound at the point of generic declaration
2382
2383       elsif Present (Def) then
2384          if Nkind (Def) = N_Operator_Symbol then
2385             Find_Direct_Name (Def);
2386
2387          elsif Nkind (Def) /= N_Attribute_Reference then
2388             Analyze (Def);
2389
2390          else
2391             --  For an attribute reference, analyze the prefix and verify
2392             --  that it has the proper profile for the subprogram.
2393
2394             Analyze (Prefix (Def));
2395             Valid_Default_Attribute (Nam, Def);
2396             goto Leave;
2397          end if;
2398
2399          --  Default name may be overloaded, in which case the interpretation
2400          --  with the correct profile must be  selected, as for a renaming.
2401          --  If the definition is an indexed component, it must denote a
2402          --  member of an entry family. If it is a selected component, it
2403          --  can be a protected operation.
2404
2405          if Etype (Def) = Any_Type then
2406             goto Leave;
2407
2408          elsif Nkind (Def) = N_Selected_Component then
2409             if not Is_Overloadable (Entity (Selector_Name (Def))) then
2410                Error_Msg_N ("expect valid subprogram name as default", Def);
2411             end if;
2412
2413          elsif Nkind (Def) = N_Indexed_Component then
2414             if Is_Entity_Name (Prefix (Def)) then
2415                if Ekind (Entity (Prefix (Def))) /= E_Entry_Family then
2416                   Error_Msg_N ("expect valid subprogram name as default", Def);
2417                end if;
2418
2419             elsif Nkind (Prefix (Def)) = N_Selected_Component then
2420                if Ekind (Entity (Selector_Name (Prefix (Def)))) /=
2421                                                           E_Entry_Family
2422                then
2423                   Error_Msg_N ("expect valid subprogram name as default", Def);
2424                end if;
2425
2426             else
2427                Error_Msg_N ("expect valid subprogram name as default", Def);
2428                goto Leave;
2429             end if;
2430
2431          elsif Nkind (Def) = N_Character_Literal then
2432
2433             --  Needs some type checks: subprogram should be parameterless???
2434
2435             Resolve (Def, (Etype (Nam)));
2436
2437          elsif not Is_Entity_Name (Def)
2438            or else not Is_Overloadable (Entity (Def))
2439          then
2440             Error_Msg_N ("expect valid subprogram name as default", Def);
2441             goto Leave;
2442
2443          elsif not Is_Overloaded (Def) then
2444             Subp := Entity (Def);
2445
2446             if Subp = Nam then
2447                Error_Msg_N ("premature usage of formal subprogram", Def);
2448
2449             elsif not Entity_Matches_Spec (Subp, Nam) then
2450                Error_Msg_N ("no visible entity matches specification", Def);
2451             end if;
2452
2453          --  More than one interpretation, so disambiguate as for a renaming
2454
2455          else
2456             declare
2457                I   : Interp_Index;
2458                I1  : Interp_Index := 0;
2459                It  : Interp;
2460                It1 : Interp;
2461
2462             begin
2463                Subp := Any_Id;
2464                Get_First_Interp (Def, I, It);
2465                while Present (It.Nam) loop
2466                   if Entity_Matches_Spec (It.Nam, Nam) then
2467                      if Subp /= Any_Id then
2468                         It1 := Disambiguate (Def, I1, I, Etype (Subp));
2469
2470                         if It1 = No_Interp then
2471                            Error_Msg_N ("ambiguous default subprogram", Def);
2472                         else
2473                            Subp := It1.Nam;
2474                         end if;
2475
2476                         exit;
2477
2478                      else
2479                         I1  := I;
2480                         Subp := It.Nam;
2481                      end if;
2482                   end if;
2483
2484                   Get_Next_Interp (I, It);
2485                end loop;
2486             end;
2487
2488             if Subp /= Any_Id then
2489                Set_Entity (Def, Subp);
2490
2491                if Subp = Nam then
2492                   Error_Msg_N ("premature usage of formal subprogram", Def);
2493
2494                elsif Ekind (Subp) /= E_Operator then
2495                   Check_Mode_Conformant (Subp, Nam);
2496                end if;
2497
2498             else
2499                Error_Msg_N ("no visible subprogram matches specification", N);
2500             end if;
2501          end if;
2502       end if;
2503
2504       <<Leave>>
2505          Analyze_Aspect_Specifications (N, Nam, Aspect_Specifications (N));
2506    end Analyze_Formal_Subprogram_Declaration;
2507
2508    -------------------------------------
2509    -- Analyze_Formal_Type_Declaration --
2510    -------------------------------------
2511
2512    procedure Analyze_Formal_Type_Declaration (N : Node_Id) is
2513       Def : constant Node_Id := Formal_Type_Definition (N);
2514       T   : Entity_Id;
2515
2516    begin
2517       T := Defining_Identifier (N);
2518
2519       if Present (Discriminant_Specifications (N))
2520         and then Nkind (Def) /= N_Formal_Private_Type_Definition
2521       then
2522          Error_Msg_N
2523            ("discriminants not allowed for this formal type", T);
2524       end if;
2525
2526       --  Enter the new name, and branch to specific routine
2527
2528       case Nkind (Def) is
2529          when N_Formal_Private_Type_Definition         =>
2530             Analyze_Formal_Private_Type (N, T, Def);
2531
2532          when N_Formal_Derived_Type_Definition         =>
2533             Analyze_Formal_Derived_Type (N, T, Def);
2534
2535          when N_Formal_Discrete_Type_Definition        =>
2536             Analyze_Formal_Discrete_Type (T, Def);
2537
2538          when N_Formal_Signed_Integer_Type_Definition  =>
2539             Analyze_Formal_Signed_Integer_Type (T, Def);
2540
2541          when N_Formal_Modular_Type_Definition         =>
2542             Analyze_Formal_Modular_Type (T, Def);
2543
2544          when N_Formal_Floating_Point_Definition       =>
2545             Analyze_Formal_Floating_Type (T, Def);
2546
2547          when N_Formal_Ordinary_Fixed_Point_Definition =>
2548             Analyze_Formal_Ordinary_Fixed_Point_Type (T, Def);
2549
2550          when N_Formal_Decimal_Fixed_Point_Definition  =>
2551             Analyze_Formal_Decimal_Fixed_Point_Type (T, Def);
2552
2553          when N_Array_Type_Definition =>
2554             Analyze_Formal_Array_Type (T, Def);
2555
2556          when N_Access_To_Object_Definition            |
2557               N_Access_Function_Definition             |
2558               N_Access_Procedure_Definition            =>
2559             Analyze_Generic_Access_Type (T, Def);
2560
2561          --  Ada 2005: a interface declaration is encoded as an abstract
2562          --  record declaration or a abstract type derivation.
2563
2564          when N_Record_Definition                      =>
2565             Analyze_Formal_Interface_Type (N, T, Def);
2566
2567          when N_Derived_Type_Definition                =>
2568             Analyze_Formal_Derived_Interface_Type (N, T, Def);
2569
2570          when N_Error                                  =>
2571             null;
2572
2573          when others                                   =>
2574             raise Program_Error;
2575
2576       end case;
2577
2578       Set_Is_Generic_Type (T);
2579       Analyze_Aspect_Specifications (N, T, Aspect_Specifications (N));
2580    end Analyze_Formal_Type_Declaration;
2581
2582    ------------------------------------
2583    -- Analyze_Function_Instantiation --
2584    ------------------------------------
2585
2586    procedure Analyze_Function_Instantiation (N : Node_Id) is
2587    begin
2588       Analyze_Subprogram_Instantiation (N, E_Function);
2589    end Analyze_Function_Instantiation;
2590
2591    ---------------------------------
2592    -- Analyze_Generic_Access_Type --
2593    ---------------------------------
2594
2595    procedure Analyze_Generic_Access_Type (T : Entity_Id; Def : Node_Id) is
2596    begin
2597       Enter_Name (T);
2598
2599       if Nkind (Def) = N_Access_To_Object_Definition then
2600          Access_Type_Declaration (T, Def);
2601
2602          if Is_Incomplete_Or_Private_Type (Designated_Type (T))
2603            and then No (Full_View (Designated_Type (T)))
2604            and then not Is_Generic_Type (Designated_Type (T))
2605          then
2606             Error_Msg_N ("premature usage of incomplete type", Def);
2607
2608          elsif not Is_Entity_Name (Subtype_Indication (Def)) then
2609             Error_Msg_N
2610               ("only a subtype mark is allowed in a formal", Def);
2611          end if;
2612
2613       else
2614          Access_Subprogram_Declaration (T, Def);
2615       end if;
2616    end Analyze_Generic_Access_Type;
2617
2618    ---------------------------------
2619    -- Analyze_Generic_Formal_Part --
2620    ---------------------------------
2621
2622    procedure Analyze_Generic_Formal_Part (N : Node_Id) is
2623       Gen_Parm_Decl : Node_Id;
2624
2625    begin
2626       --  The generic formals are processed in the scope of the generic unit,
2627       --  where they are immediately visible. The scope is installed by the
2628       --  caller.
2629
2630       Gen_Parm_Decl := First (Generic_Formal_Declarations (N));
2631
2632       while Present (Gen_Parm_Decl) loop
2633          Analyze (Gen_Parm_Decl);
2634          Next (Gen_Parm_Decl);
2635       end loop;
2636
2637       Generate_Reference_To_Generic_Formals (Current_Scope);
2638    end Analyze_Generic_Formal_Part;
2639
2640    ------------------------------------------
2641    -- Analyze_Generic_Package_Declaration  --
2642    ------------------------------------------
2643
2644    procedure Analyze_Generic_Package_Declaration (N : Node_Id) is
2645       Loc         : constant Source_Ptr := Sloc (N);
2646       Id          : Entity_Id;
2647       New_N       : Node_Id;
2648       Save_Parent : Node_Id;
2649       Renaming    : Node_Id;
2650       Decls       : constant List_Id :=
2651                       Visible_Declarations (Specification (N));
2652       Decl        : Node_Id;
2653
2654    begin
2655       --  We introduce a renaming of the enclosing package, to have a usable
2656       --  entity as the prefix of an expanded name for a local entity of the
2657       --  form Par.P.Q, where P is the generic package. This is because a local
2658       --  entity named P may hide it, so that the usual visibility rules in
2659       --  the instance will not resolve properly.
2660
2661       Renaming :=
2662         Make_Package_Renaming_Declaration (Loc,
2663           Defining_Unit_Name =>
2664             Make_Defining_Identifier (Loc,
2665              Chars => New_External_Name (Chars (Defining_Entity (N)), "GH")),
2666           Name => Make_Identifier (Loc, Chars (Defining_Entity (N))));
2667
2668       if Present (Decls) then
2669          Decl := First (Decls);
2670          while Present (Decl)
2671            and then Nkind (Decl) = N_Pragma
2672          loop
2673             Next (Decl);
2674          end loop;
2675
2676          if Present (Decl) then
2677             Insert_Before (Decl, Renaming);
2678          else
2679             Append (Renaming, Visible_Declarations (Specification (N)));
2680          end if;
2681
2682       else
2683          Set_Visible_Declarations (Specification (N), New_List (Renaming));
2684       end if;
2685
2686       --  Create copy of generic unit, and save for instantiation. If the unit
2687       --  is a child unit, do not copy the specifications for the parent, which
2688       --  are not part of the generic tree.
2689
2690       Save_Parent := Parent_Spec (N);
2691       Set_Parent_Spec (N, Empty);
2692
2693       New_N := Copy_Generic_Node (N, Empty, Instantiating => False);
2694       Set_Parent_Spec (New_N, Save_Parent);
2695       Rewrite (N, New_N);
2696       Id := Defining_Entity (N);
2697       Generate_Definition (Id);
2698
2699       --  Expansion is not applied to generic units
2700
2701       Start_Generic;
2702
2703       Enter_Name (Id);
2704       Set_Ekind (Id, E_Generic_Package);
2705       Set_Etype (Id, Standard_Void_Type);
2706       Push_Scope (Id);
2707       Enter_Generic_Scope (Id);
2708       Set_Inner_Instances (Id, New_Elmt_List);
2709
2710       Set_Categorization_From_Pragmas (N);
2711       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2712
2713       --  Link the declaration of the generic homonym in the generic copy to
2714       --  the package it renames, so that it is always resolved properly.
2715
2716       Set_Generic_Homonym (Id, Defining_Unit_Name (Renaming));
2717       Set_Entity (Associated_Node (Name (Renaming)), Id);
2718
2719       --  For a library unit, we have reconstructed the entity for the unit,
2720       --  and must reset it in the library tables.
2721
2722       if Nkind (Parent (N)) = N_Compilation_Unit then
2723          Set_Cunit_Entity (Current_Sem_Unit, Id);
2724       end if;
2725
2726       Analyze_Generic_Formal_Part (N);
2727
2728       --  After processing the generic formals, analysis proceeds as for a
2729       --  non-generic package.
2730
2731       Analyze (Specification (N));
2732
2733       Validate_Categorization_Dependency (N, Id);
2734
2735       End_Generic;
2736
2737       End_Package_Scope (Id);
2738       Exit_Generic_Scope (Id);
2739
2740       if Nkind (Parent (N)) /= N_Compilation_Unit then
2741          Move_Freeze_Nodes (Id, N, Visible_Declarations (Specification (N)));
2742          Move_Freeze_Nodes (Id, N, Private_Declarations (Specification (N)));
2743          Move_Freeze_Nodes (Id, N, Generic_Formal_Declarations (N));
2744
2745       else
2746          Set_Body_Required (Parent (N), Unit_Requires_Body (Id));
2747          Validate_RT_RAT_Component (N);
2748
2749          --  If this is a spec without a body, check that generic parameters
2750          --  are referenced.
2751
2752          if not Body_Required (Parent (N)) then
2753             Check_References (Id);
2754          end if;
2755       end if;
2756
2757       Analyze_Aspect_Specifications (N, Id, Aspect_Specifications (N));
2758    end Analyze_Generic_Package_Declaration;
2759
2760    --------------------------------------------
2761    -- Analyze_Generic_Subprogram_Declaration --
2762    --------------------------------------------
2763
2764    procedure Analyze_Generic_Subprogram_Declaration (N : Node_Id) is
2765       Spec        : Node_Id;
2766       Id          : Entity_Id;
2767       Formals     : List_Id;
2768       New_N       : Node_Id;
2769       Result_Type : Entity_Id;
2770       Save_Parent : Node_Id;
2771       Typ         : Entity_Id;
2772
2773    begin
2774       --  Create copy of generic unit, and save for instantiation. If the unit
2775       --  is a child unit, do not copy the specifications for the parent, which
2776       --  are not part of the generic tree.
2777
2778       Save_Parent := Parent_Spec (N);
2779       Set_Parent_Spec (N, Empty);
2780
2781       New_N := Copy_Generic_Node (N, Empty, Instantiating => False);
2782       Set_Parent_Spec (New_N, Save_Parent);
2783       Rewrite (N, New_N);
2784
2785       Spec := Specification (N);
2786       Id := Defining_Entity (Spec);
2787       Generate_Definition (Id);
2788
2789       if Nkind (Id) = N_Defining_Operator_Symbol then
2790          Error_Msg_N
2791            ("operator symbol not allowed for generic subprogram", Id);
2792       end if;
2793
2794       Start_Generic;
2795
2796       Enter_Name (Id);
2797
2798       Set_Scope_Depth_Value (Id, Scope_Depth (Current_Scope) + 1);
2799       Push_Scope (Id);
2800       Enter_Generic_Scope (Id);
2801       Set_Inner_Instances (Id, New_Elmt_List);
2802       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2803
2804       Analyze_Generic_Formal_Part (N);
2805
2806       Formals := Parameter_Specifications (Spec);
2807
2808       if Present (Formals) then
2809          Process_Formals (Formals, Spec);
2810       end if;
2811
2812       if Nkind (Spec) = N_Function_Specification then
2813          Set_Ekind (Id, E_Generic_Function);
2814
2815          if Nkind (Result_Definition (Spec)) = N_Access_Definition then
2816             Result_Type := Access_Definition (Spec, Result_Definition (Spec));
2817             Set_Etype (Id, Result_Type);
2818
2819             --  Check restriction imposed by AI05-073: a generic function
2820             --  cannot return an abstract type or an access to such.
2821
2822             --  This is a binding interpreration should it apply to earlier
2823             --  versions of Ada as well as Ada 2012???
2824
2825             if Is_Abstract_Type (Designated_Type (Result_Type))
2826               and then Ada_Version >= Ada_2012
2827             then
2828                Error_Msg_N ("generic function cannot have an access result"
2829                  & " that designates an abstract type", Spec);
2830             end if;
2831
2832          else
2833             Find_Type (Result_Definition (Spec));
2834             Typ := Entity (Result_Definition (Spec));
2835
2836             if Is_Abstract_Type (Typ)
2837               and then Ada_Version >= Ada_2012
2838             then
2839                Error_Msg_N
2840                  ("generic function cannot have abstract result type", Spec);
2841             end if;
2842
2843             --  If a null exclusion is imposed on the result type, then create
2844             --  a null-excluding itype (an access subtype) and use it as the
2845             --  function's Etype.
2846
2847             if Is_Access_Type (Typ)
2848               and then Null_Exclusion_Present (Spec)
2849             then
2850                Set_Etype  (Id,
2851                  Create_Null_Excluding_Itype
2852                    (T           => Typ,
2853                     Related_Nod => Spec,
2854                     Scope_Id    => Defining_Unit_Name (Spec)));
2855             else
2856                Set_Etype (Id, Typ);
2857             end if;
2858          end if;
2859
2860       else
2861          Set_Ekind (Id, E_Generic_Procedure);
2862          Set_Etype (Id, Standard_Void_Type);
2863       end if;
2864
2865       --  For a library unit, we have reconstructed the entity for the unit,
2866       --  and must reset it in the library tables. We also make sure that
2867       --  Body_Required is set properly in the original compilation unit node.
2868
2869       if Nkind (Parent (N)) = N_Compilation_Unit then
2870          Set_Cunit_Entity (Current_Sem_Unit, Id);
2871          Set_Body_Required (Parent (N), Unit_Requires_Body (Id));
2872       end if;
2873
2874       Set_Categorization_From_Pragmas (N);
2875       Validate_Categorization_Dependency (N, Id);
2876
2877       Save_Global_References (Original_Node (N));
2878
2879       End_Generic;
2880       End_Scope;
2881       Exit_Generic_Scope (Id);
2882       Generate_Reference_To_Formals (Id);
2883
2884       List_Inherited_Pre_Post_Aspects (Id);
2885       Analyze_Aspect_Specifications (N, Id, Aspect_Specifications (N));
2886    end Analyze_Generic_Subprogram_Declaration;
2887
2888    -----------------------------------
2889    -- Analyze_Package_Instantiation --
2890    -----------------------------------
2891
2892    procedure Analyze_Package_Instantiation (N : Node_Id) is
2893       Loc    : constant Source_Ptr := Sloc (N);
2894       Gen_Id : constant Node_Id    := Name (N);
2895
2896       Act_Decl      : Node_Id;
2897       Act_Decl_Name : Node_Id;
2898       Act_Decl_Id   : Entity_Id;
2899       Act_Spec      : Node_Id;
2900       Act_Tree      : Node_Id;
2901
2902       Gen_Decl : Node_Id;
2903       Gen_Unit : Entity_Id;
2904
2905       Is_Actual_Pack : constant Boolean :=
2906                          Is_Internal (Defining_Entity (N));
2907
2908       Env_Installed    : Boolean := False;
2909       Parent_Installed : Boolean := False;
2910       Renaming_List    : List_Id;
2911       Unit_Renaming    : Node_Id;
2912       Needs_Body       : Boolean;
2913       Inline_Now       : Boolean := False;
2914
2915       procedure Delay_Descriptors (E : Entity_Id);
2916       --  Delay generation of subprogram descriptors for given entity
2917
2918       function Might_Inline_Subp return Boolean;
2919       --  If inlining is active and the generic contains inlined subprograms,
2920       --  we instantiate the body. This may cause superfluous instantiations,
2921       --  but it is simpler than detecting the need for the body at the point
2922       --  of inlining, when the context of the instance is not available.
2923
2924       -----------------------
2925       -- Delay_Descriptors --
2926       -----------------------
2927
2928       procedure Delay_Descriptors (E : Entity_Id) is
2929       begin
2930          if not Delay_Subprogram_Descriptors (E) then
2931             Set_Delay_Subprogram_Descriptors (E);
2932             Pending_Descriptor.Append (E);
2933          end if;
2934       end Delay_Descriptors;
2935
2936       -----------------------
2937       -- Might_Inline_Subp --
2938       -----------------------
2939
2940       function Might_Inline_Subp return Boolean is
2941          E : Entity_Id;
2942
2943       begin
2944          if not Inline_Processing_Required then
2945             return False;
2946
2947          else
2948             E := First_Entity (Gen_Unit);
2949             while Present (E) loop
2950                if Is_Subprogram (E)
2951                  and then Is_Inlined (E)
2952                then
2953                   return True;
2954                end if;
2955
2956                Next_Entity (E);
2957             end loop;
2958          end if;
2959
2960          return False;
2961       end Might_Inline_Subp;
2962
2963    --  Start of processing for Analyze_Package_Instantiation
2964
2965    begin
2966       --  Very first thing: apply the special kludge for Text_IO processing
2967       --  in case we are instantiating one of the children of [Wide_]Text_IO.
2968
2969       Text_IO_Kludge (Name (N));
2970
2971       --  Make node global for error reporting
2972
2973       Instantiation_Node := N;
2974
2975       --  Case of instantiation of a generic package
2976
2977       if Nkind (N) = N_Package_Instantiation then
2978          Act_Decl_Id := New_Copy (Defining_Entity (N));
2979          Set_Comes_From_Source (Act_Decl_Id, True);
2980
2981          if Nkind (Defining_Unit_Name (N)) = N_Defining_Program_Unit_Name then
2982             Act_Decl_Name :=
2983               Make_Defining_Program_Unit_Name (Loc,
2984                 Name => New_Copy_Tree (Name (Defining_Unit_Name (N))),
2985                 Defining_Identifier => Act_Decl_Id);
2986          else
2987             Act_Decl_Name :=  Act_Decl_Id;
2988          end if;
2989
2990       --  Case of instantiation of a formal package
2991
2992       else
2993          Act_Decl_Id   := Defining_Identifier (N);
2994          Act_Decl_Name := Act_Decl_Id;
2995       end if;
2996
2997       Generate_Definition (Act_Decl_Id);
2998       Preanalyze_Actuals (N);
2999
3000       Init_Env;
3001       Env_Installed := True;
3002
3003       --  Reset renaming map for formal types. The mapping is established
3004       --  when analyzing the generic associations, but some mappings are
3005       --  inherited from formal packages of parent units, and these are
3006       --  constructed when the parents are installed.
3007
3008       Generic_Renamings.Set_Last (0);
3009       Generic_Renamings_HTable.Reset;
3010
3011       Check_Generic_Child_Unit (Gen_Id, Parent_Installed);
3012       Gen_Unit := Entity (Gen_Id);
3013
3014       --  Verify that it is the name of a generic package
3015
3016       --  A visibility glitch: if the instance is a child unit and the generic
3017       --  is the generic unit of a parent instance (i.e. both the parent and
3018       --  the child units are instances of the same package) the name now
3019       --  denotes the renaming within the parent, not the intended generic
3020       --  unit. See if there is a homonym that is the desired generic. The
3021       --  renaming declaration must be visible inside the instance of the
3022       --  child, but not when analyzing the name in the instantiation itself.
3023
3024       if Ekind (Gen_Unit) = E_Package
3025         and then Present (Renamed_Entity (Gen_Unit))
3026         and then In_Open_Scopes (Renamed_Entity (Gen_Unit))
3027         and then Is_Generic_Instance (Renamed_Entity (Gen_Unit))
3028         and then Present (Homonym (Gen_Unit))
3029       then
3030          Gen_Unit := Homonym (Gen_Unit);
3031       end if;
3032
3033       if Etype (Gen_Unit) = Any_Type then
3034          Restore_Env;
3035          goto Leave;
3036
3037       elsif Ekind (Gen_Unit) /= E_Generic_Package then
3038
3039          --  Ada 2005 (AI-50217): Cannot use instance in limited with_clause
3040
3041          if From_With_Type (Gen_Unit) then
3042             Error_Msg_N
3043               ("cannot instantiate a limited withed package", Gen_Id);
3044          else
3045             Error_Msg_N
3046               ("expect name of generic package in instantiation", Gen_Id);
3047          end if;
3048
3049          Restore_Env;
3050          goto Leave;
3051       end if;
3052
3053       if In_Extended_Main_Source_Unit (N) then
3054          Set_Is_Instantiated (Gen_Unit);
3055          Generate_Reference  (Gen_Unit, N);
3056
3057          if Present (Renamed_Object (Gen_Unit)) then
3058             Set_Is_Instantiated (Renamed_Object (Gen_Unit));
3059             Generate_Reference  (Renamed_Object (Gen_Unit), N);
3060          end if;
3061       end if;
3062
3063       if Nkind (Gen_Id) = N_Identifier
3064         and then Chars (Gen_Unit) = Chars (Defining_Entity (N))
3065       then
3066          Error_Msg_NE
3067            ("& is hidden within declaration of instance", Gen_Id, Gen_Unit);
3068
3069       elsif Nkind (Gen_Id) = N_Expanded_Name
3070         and then Is_Child_Unit (Gen_Unit)
3071         and then Nkind (Prefix (Gen_Id)) = N_Identifier
3072         and then Chars (Act_Decl_Id) = Chars (Prefix (Gen_Id))
3073       then
3074          Error_Msg_N
3075            ("& is hidden within declaration of instance ", Prefix (Gen_Id));
3076       end if;
3077
3078       Set_Entity (Gen_Id, Gen_Unit);
3079
3080       --  If generic is a renaming, get original generic unit
3081
3082       if Present (Renamed_Object (Gen_Unit))
3083         and then Ekind (Renamed_Object (Gen_Unit)) = E_Generic_Package
3084       then
3085          Gen_Unit := Renamed_Object (Gen_Unit);
3086       end if;
3087
3088       --  Verify that there are no circular instantiations
3089
3090       if In_Open_Scopes (Gen_Unit) then
3091          Error_Msg_NE ("instantiation of & within itself", N, Gen_Unit);
3092          Restore_Env;
3093          goto Leave;
3094
3095       elsif Contains_Instance_Of (Gen_Unit, Current_Scope, Gen_Id) then
3096          Error_Msg_Node_2 := Current_Scope;
3097          Error_Msg_NE
3098            ("circular Instantiation: & instantiated in &!", N, Gen_Unit);
3099          Circularity_Detected := True;
3100          Restore_Env;
3101          goto Leave;
3102
3103       else
3104          Gen_Decl := Unit_Declaration_Node (Gen_Unit);
3105
3106          --  Initialize renamings map, for error checking, and the list that
3107          --  holds private entities whose views have changed between generic
3108          --  definition and instantiation. If this is the instance created to
3109          --  validate an actual package, the instantiation environment is that
3110          --  of the enclosing instance.
3111
3112          Create_Instantiation_Source (N, Gen_Unit, False, S_Adjustment);
3113
3114          --  Copy original generic tree, to produce text for instantiation
3115
3116          Act_Tree :=
3117            Copy_Generic_Node
3118              (Original_Node (Gen_Decl), Empty, Instantiating => True);
3119
3120          Act_Spec := Specification (Act_Tree);
3121
3122          --  If this is the instance created to validate an actual package,
3123          --  only the formals matter, do not examine the package spec itself.
3124
3125          if Is_Actual_Pack then
3126             Set_Visible_Declarations (Act_Spec, New_List);
3127             Set_Private_Declarations (Act_Spec, New_List);
3128          end if;
3129
3130          Renaming_List :=
3131            Analyze_Associations
3132              (N,
3133               Generic_Formal_Declarations (Act_Tree),
3134               Generic_Formal_Declarations (Gen_Decl));
3135
3136          Set_Instance_Env (Gen_Unit, Act_Decl_Id);
3137          Set_Defining_Unit_Name (Act_Spec, Act_Decl_Name);
3138          Set_Is_Generic_Instance (Act_Decl_Id);
3139
3140          Set_Generic_Parent (Act_Spec, Gen_Unit);
3141
3142          --  References to the generic in its own declaration or its body are
3143          --  references to the instance. Add a renaming declaration for the
3144          --  generic unit itself. This declaration, as well as the renaming
3145          --  declarations for the generic formals, must remain private to the
3146          --  unit: the formals, because this is the language semantics, and
3147          --  the unit because its use is an artifact of the implementation.
3148
3149          Unit_Renaming :=
3150            Make_Package_Renaming_Declaration (Loc,
3151              Defining_Unit_Name =>
3152                Make_Defining_Identifier (Loc, Chars (Gen_Unit)),
3153              Name => New_Reference_To (Act_Decl_Id, Loc));
3154
3155          Append (Unit_Renaming, Renaming_List);
3156
3157          --  The renaming declarations are the first local declarations of
3158          --  the new unit.
3159
3160          if Is_Non_Empty_List (Visible_Declarations (Act_Spec)) then
3161             Insert_List_Before
3162               (First (Visible_Declarations (Act_Spec)), Renaming_List);
3163          else
3164             Set_Visible_Declarations (Act_Spec, Renaming_List);
3165          end if;
3166
3167          Act_Decl :=
3168            Make_Package_Declaration (Loc,
3169              Specification => Act_Spec);
3170
3171          --  Save the instantiation node, for subsequent instantiation of the
3172          --  body, if there is one and we are generating code for the current
3173          --  unit. Mark the unit as having a body, to avoid a premature error
3174          --  message.
3175
3176          --  We instantiate the body if we are generating code, if we are
3177          --  generating cross-reference information, or if we are building
3178          --  trees for ASIS use.
3179
3180          declare
3181             Enclosing_Body_Present : Boolean := False;
3182             --  If the generic unit is not a compilation unit, then a body may
3183             --  be present in its parent even if none is required. We create a
3184             --  tentative pending instantiation for the body, which will be
3185             --  discarded if none is actually present.
3186
3187             Scop : Entity_Id;
3188
3189          begin
3190             if Scope (Gen_Unit) /= Standard_Standard
3191               and then not Is_Child_Unit (Gen_Unit)
3192             then
3193                Scop := Scope (Gen_Unit);
3194
3195                while Present (Scop)
3196                  and then Scop /= Standard_Standard
3197                loop
3198                   if Unit_Requires_Body (Scop) then
3199                      Enclosing_Body_Present := True;
3200                      exit;
3201
3202                   elsif In_Open_Scopes (Scop)
3203                     and then In_Package_Body (Scop)
3204                   then
3205                      Enclosing_Body_Present := True;
3206                      exit;
3207                   end if;
3208
3209                   exit when Is_Compilation_Unit (Scop);
3210                   Scop := Scope (Scop);
3211                end loop;
3212             end if;
3213
3214             --  If front-end inlining is enabled, and this is a unit for which
3215             --  code will be generated, we instantiate the body at once.
3216
3217             --  This is done if the instance is not the main unit, and if the
3218             --  generic is not a child unit of another generic, to avoid scope
3219             --  problems and the reinstallation of parent instances.
3220
3221             if Expander_Active
3222               and then (not Is_Child_Unit (Gen_Unit)
3223                          or else not Is_Generic_Unit (Scope (Gen_Unit)))
3224               and then Might_Inline_Subp
3225               and then not Is_Actual_Pack
3226             then
3227                if Front_End_Inlining
3228                  and then (Is_In_Main_Unit (N)
3229                             or else In_Main_Context (Current_Scope))
3230                  and then Nkind (Parent (N)) /= N_Compilation_Unit
3231                then
3232                   Inline_Now := True;
3233
3234                --  In configurable_run_time mode we force the inlining of
3235                --  predefined subprograms marked Inline_Always, to minimize
3236                --  the use of the run-time library.
3237
3238                elsif Is_Predefined_File_Name
3239                        (Unit_File_Name (Get_Source_Unit (Gen_Decl)))
3240                  and then Configurable_Run_Time_Mode
3241                  and then Nkind (Parent (N)) /= N_Compilation_Unit
3242                then
3243                   Inline_Now := True;
3244                end if;
3245
3246                --  If the current scope is itself an instance within a child
3247                --  unit, there will be duplications in the scope stack, and the
3248                --  unstacking mechanism in Inline_Instance_Body will fail.
3249                --  This loses some rare cases of optimization, and might be
3250                --  improved some day, if we can find a proper abstraction for
3251                --  "the complete compilation context" that can be saved and
3252                --  restored. ???
3253
3254                if Is_Generic_Instance (Current_Scope) then
3255                   declare
3256                      Curr_Unit : constant Entity_Id :=
3257                                    Cunit_Entity (Current_Sem_Unit);
3258                   begin
3259                      if Curr_Unit /= Current_Scope
3260                        and then Is_Child_Unit (Curr_Unit)
3261                      then
3262                         Inline_Now := False;
3263                      end if;
3264                   end;
3265                end if;
3266             end if;
3267
3268             Needs_Body :=
3269               (Unit_Requires_Body (Gen_Unit)
3270                   or else Enclosing_Body_Present
3271                   or else Present (Corresponding_Body (Gen_Decl)))
3272                 and then (Is_In_Main_Unit (N)
3273                            or else Might_Inline_Subp)
3274                 and then not Is_Actual_Pack
3275                 and then not Inline_Now
3276                 and then (Operating_Mode = Generate_Code
3277                             or else (Operating_Mode = Check_Semantics
3278                                       and then ASIS_Mode));
3279
3280             --  If front_end_inlining is enabled, do not instantiate body if
3281             --  within a generic context.
3282
3283             if (Front_End_Inlining
3284                   and then not Expander_Active)
3285               or else Is_Generic_Unit (Cunit_Entity (Main_Unit))
3286             then
3287                Needs_Body := False;
3288             end if;
3289
3290             --  If the current context is generic, and the package being
3291             --  instantiated is declared within a formal package, there is no
3292             --  body to instantiate until the enclosing generic is instantiated
3293             --  and there is an actual for the formal package. If the formal
3294             --  package has parameters, we build a regular package instance for
3295             --  it, that precedes the original formal package declaration.
3296
3297             if In_Open_Scopes (Scope (Scope (Gen_Unit))) then
3298                declare
3299                   Decl : constant Node_Id :=
3300                            Original_Node
3301                              (Unit_Declaration_Node (Scope (Gen_Unit)));
3302                begin
3303                   if Nkind (Decl) = N_Formal_Package_Declaration
3304                     or else (Nkind (Decl) = N_Package_Declaration
3305                                and then Is_List_Member (Decl)
3306                                and then Present (Next (Decl))
3307                                and then
3308                                  Nkind (Next (Decl)) =
3309                                                 N_Formal_Package_Declaration)
3310                   then
3311                      Needs_Body := False;
3312                   end if;
3313                end;
3314             end if;
3315          end;
3316
3317          --  If we are generating calling stubs, we never need a body for an
3318          --  instantiation from source. However normal processing occurs for
3319          --  any generic instantiation appearing in generated code, since we
3320          --  do not generate stubs in that case.
3321
3322          if Distribution_Stub_Mode = Generate_Caller_Stub_Body
3323               and then Comes_From_Source (N)
3324          then
3325             Needs_Body := False;
3326          end if;
3327
3328          if Needs_Body then
3329
3330             --  Here is a defence against a ludicrous number of instantiations
3331             --  caused by a circular set of instantiation attempts.
3332
3333             if Pending_Instantiations.Last >
3334                  Hostparm.Max_Instantiations
3335             then
3336                Error_Msg_N ("too many instantiations", N);
3337                raise Unrecoverable_Error;
3338             end if;
3339
3340             --  Indicate that the enclosing scopes contain an instantiation,
3341             --  and that cleanup actions should be delayed until after the
3342             --  instance body is expanded.
3343
3344             Check_Forward_Instantiation (Gen_Decl);
3345             if Nkind (N) = N_Package_Instantiation then
3346                declare
3347                   Enclosing_Master : Entity_Id;
3348
3349                begin
3350                   --  Loop to search enclosing masters
3351
3352                   Enclosing_Master := Current_Scope;
3353                   Scope_Loop : while Enclosing_Master /= Standard_Standard loop
3354                      if Ekind (Enclosing_Master) = E_Package then
3355                         if Is_Compilation_Unit (Enclosing_Master) then
3356                            if In_Package_Body (Enclosing_Master) then
3357                               Delay_Descriptors
3358                                 (Body_Entity (Enclosing_Master));
3359                            else
3360                               Delay_Descriptors
3361                                 (Enclosing_Master);
3362                            end if;
3363
3364                            exit Scope_Loop;
3365
3366                         else
3367                            Enclosing_Master := Scope (Enclosing_Master);
3368                         end if;
3369
3370                      elsif Ekind (Enclosing_Master) = E_Generic_Package then
3371                         Enclosing_Master := Scope (Enclosing_Master);
3372
3373                      elsif Is_Generic_Subprogram (Enclosing_Master)
3374                        or else Ekind (Enclosing_Master) = E_Void
3375                      then
3376                         --  Cleanup actions will eventually be performed on the
3377                         --  enclosing instance, if any. Enclosing scope is void
3378                         --  in the formal part of a generic subprogram.
3379
3380                         exit Scope_Loop;
3381
3382                      else
3383                         if Ekind (Enclosing_Master) = E_Entry
3384                           and then
3385                             Ekind (Scope (Enclosing_Master)) = E_Protected_Type
3386                         then
3387                            if not Expander_Active then
3388                               exit Scope_Loop;
3389                            else
3390                               Enclosing_Master :=
3391                                 Protected_Body_Subprogram (Enclosing_Master);
3392                            end if;
3393                         end if;
3394
3395                         Set_Delay_Cleanups (Enclosing_Master);
3396
3397                         while Ekind (Enclosing_Master) = E_Block loop
3398                            Enclosing_Master := Scope (Enclosing_Master);
3399                         end loop;
3400
3401                         if Is_Subprogram (Enclosing_Master) then
3402                            Delay_Descriptors (Enclosing_Master);
3403
3404                         elsif Is_Task_Type (Enclosing_Master) then
3405                            declare
3406                               TBP : constant Node_Id :=
3407                                       Get_Task_Body_Procedure
3408                                         (Enclosing_Master);
3409                            begin
3410                               if Present (TBP) then
3411                                  Delay_Descriptors  (TBP);
3412                                  Set_Delay_Cleanups (TBP);
3413                               end if;
3414                            end;
3415                         end if;
3416
3417                         exit Scope_Loop;
3418                      end if;
3419                   end loop Scope_Loop;
3420                end;
3421
3422                --  Make entry in table
3423
3424                Pending_Instantiations.Append
3425                  ((Inst_Node                => N,
3426                    Act_Decl                 => Act_Decl,
3427                    Expander_Status          => Expander_Active,
3428                    Current_Sem_Unit         => Current_Sem_Unit,
3429                    Scope_Suppress           => Scope_Suppress,
3430                    Local_Suppress_Stack_Top => Local_Suppress_Stack_Top,
3431                    Version                  => Ada_Version));
3432             end if;
3433          end if;
3434
3435          Set_Categorization_From_Pragmas (Act_Decl);
3436
3437          if Parent_Installed then
3438             Hide_Current_Scope;
3439          end if;
3440
3441          Set_Instance_Spec (N, Act_Decl);
3442
3443          --  If not a compilation unit, insert the package declaration before
3444          --  the original instantiation node.
3445
3446          if Nkind (Parent (N)) /= N_Compilation_Unit then
3447             Mark_Rewrite_Insertion (Act_Decl);
3448             Insert_Before (N, Act_Decl);
3449             Analyze (Act_Decl);
3450
3451          --  For an instantiation that is a compilation unit, place declaration
3452          --  on current node so context is complete for analysis (including
3453          --  nested instantiations). If this is the main unit, the declaration
3454          --  eventually replaces the instantiation node. If the instance body
3455          --  is created later, it replaces the instance node, and the
3456          --  declaration is attached to it (see
3457          --  Build_Instance_Compilation_Unit_Nodes).
3458
3459          else
3460             if Cunit_Entity (Current_Sem_Unit) = Defining_Entity (N) then
3461
3462                --  The entity for the current unit is the newly created one,
3463                --  and all semantic information is attached to it.
3464
3465                Set_Cunit_Entity (Current_Sem_Unit, Act_Decl_Id);
3466
3467                --  If this is the main unit, replace the main entity as well
3468
3469                if Current_Sem_Unit = Main_Unit then
3470                   Main_Unit_Entity := Act_Decl_Id;
3471                end if;
3472             end if;
3473
3474             Set_Unit (Parent (N), Act_Decl);
3475             Set_Parent_Spec (Act_Decl, Parent_Spec (N));
3476             Set_Package_Instantiation (Act_Decl_Id, N);
3477             Analyze (Act_Decl);
3478             Set_Unit (Parent (N), N);
3479             Set_Body_Required (Parent (N), False);
3480
3481             --  We never need elaboration checks on instantiations, since by
3482             --  definition, the body instantiation is elaborated at the same
3483             --  time as the spec instantiation.
3484
3485             Set_Suppress_Elaboration_Warnings (Act_Decl_Id);
3486             Set_Kill_Elaboration_Checks       (Act_Decl_Id);
3487          end if;
3488
3489          Check_Elab_Instantiation (N);
3490
3491          if ABE_Is_Certain (N) and then Needs_Body then
3492             Pending_Instantiations.Decrement_Last;
3493          end if;
3494
3495          Check_Hidden_Child_Unit (N, Gen_Unit, Act_Decl_Id);
3496
3497          Set_First_Private_Entity (Defining_Unit_Name (Unit_Renaming),
3498            First_Private_Entity (Act_Decl_Id));
3499
3500          --  If the instantiation will receive a body, the unit will be
3501          --  transformed into a package body, and receive its own elaboration
3502          --  entity. Otherwise, the nature of the unit is now a package
3503          --  declaration.
3504
3505          if Nkind (Parent (N)) = N_Compilation_Unit
3506            and then not Needs_Body
3507          then
3508             Rewrite (N, Act_Decl);
3509          end if;
3510
3511          if Present (Corresponding_Body (Gen_Decl))
3512            or else Unit_Requires_Body (Gen_Unit)
3513          then
3514             Set_Has_Completion (Act_Decl_Id);
3515          end if;
3516
3517          Check_Formal_Packages (Act_Decl_Id);
3518
3519          Restore_Private_Views (Act_Decl_Id);
3520
3521          Inherit_Context (Gen_Decl, N);
3522
3523          if Parent_Installed then
3524             Remove_Parent;
3525          end if;
3526
3527          Restore_Env;
3528          Env_Installed := False;
3529       end if;
3530
3531       Validate_Categorization_Dependency (N, Act_Decl_Id);
3532
3533       --  There used to be a check here to prevent instantiations in local
3534       --  contexts if the No_Local_Allocators restriction was active. This
3535       --  check was removed by a binding interpretation in AI-95-00130/07,
3536       --  but we retain the code for documentation purposes.
3537
3538       --  if Ekind (Act_Decl_Id) /= E_Void
3539       --    and then not Is_Library_Level_Entity (Act_Decl_Id)
3540       --  then
3541       --     Check_Restriction (No_Local_Allocators, N);
3542       --  end if;
3543
3544       if Inline_Now then
3545          Inline_Instance_Body (N, Gen_Unit, Act_Decl);
3546       end if;
3547
3548       --  The following is a tree patch for ASIS: ASIS needs separate nodes to
3549       --  be used as defining identifiers for a formal package and for the
3550       --  corresponding expanded package.
3551
3552       if Nkind (N) = N_Formal_Package_Declaration then
3553          Act_Decl_Id := New_Copy (Defining_Entity (N));
3554          Set_Comes_From_Source (Act_Decl_Id, True);
3555          Set_Is_Generic_Instance (Act_Decl_Id, False);
3556          Set_Defining_Identifier (N, Act_Decl_Id);
3557       end if;
3558
3559       <<Leave>>
3560          Analyze_Aspect_Specifications
3561            (N, Act_Decl_Id, Aspect_Specifications (N));
3562
3563    exception
3564       when Instantiation_Error =>
3565          if Parent_Installed then
3566             Remove_Parent;
3567          end if;
3568
3569          if Env_Installed then
3570             Restore_Env;
3571          end if;
3572    end Analyze_Package_Instantiation;
3573
3574    --------------------------
3575    -- Inline_Instance_Body --
3576    --------------------------
3577
3578    procedure Inline_Instance_Body
3579      (N        : Node_Id;
3580       Gen_Unit : Entity_Id;
3581       Act_Decl : Node_Id)
3582    is
3583       Vis          : Boolean;
3584       Gen_Comp     : constant Entity_Id :=
3585                       Cunit_Entity (Get_Source_Unit (Gen_Unit));
3586       Curr_Comp    : constant Node_Id := Cunit (Current_Sem_Unit);
3587       Curr_Scope   : Entity_Id := Empty;
3588       Curr_Unit    : constant Entity_Id := Cunit_Entity (Current_Sem_Unit);
3589       Removed      : Boolean := False;
3590       Num_Scopes   : Int := 0;
3591
3592       Scope_Stack_Depth : constant Int :=
3593                             Scope_Stack.Last - Scope_Stack.First + 1;
3594
3595       Use_Clauses  : array (1 .. Scope_Stack_Depth) of Node_Id;
3596       Instances    : array (1 .. Scope_Stack_Depth) of Entity_Id;
3597       Inner_Scopes : array (1 .. Scope_Stack_Depth) of Entity_Id;
3598       Num_Inner    : Int := 0;
3599       N_Instances  : Int := 0;
3600       S            : Entity_Id;
3601
3602    begin
3603       --  Case of generic unit defined in another unit. We must remove the
3604       --  complete context of the current unit to install that of the generic.
3605
3606       if Gen_Comp /= Cunit_Entity (Current_Sem_Unit) then
3607
3608          --  Add some comments for the following two loops ???
3609
3610          S := Current_Scope;
3611          while Present (S) and then S /= Standard_Standard loop
3612             loop
3613                Num_Scopes := Num_Scopes + 1;
3614
3615                Use_Clauses (Num_Scopes) :=
3616                  (Scope_Stack.Table
3617                     (Scope_Stack.Last - Num_Scopes + 1).
3618                        First_Use_Clause);
3619                End_Use_Clauses (Use_Clauses (Num_Scopes));
3620
3621                exit when Scope_Stack.Last - Num_Scopes + 1 = Scope_Stack.First
3622                  or else Scope_Stack.Table
3623                            (Scope_Stack.Last - Num_Scopes).Entity
3624                              = Scope (S);
3625             end loop;
3626
3627             exit when Is_Generic_Instance (S)
3628               and then (In_Package_Body (S)
3629                           or else Ekind (S) = E_Procedure
3630                           or else Ekind (S) = E_Function);
3631             S := Scope (S);
3632          end loop;
3633
3634          Vis := Is_Immediately_Visible (Gen_Comp);
3635
3636          --  Find and save all enclosing instances
3637
3638          S := Current_Scope;
3639
3640          while Present (S)
3641            and then S /= Standard_Standard
3642          loop
3643             if Is_Generic_Instance (S) then
3644                N_Instances := N_Instances + 1;
3645                Instances (N_Instances) := S;
3646
3647                exit when In_Package_Body (S);
3648             end if;
3649
3650             S := Scope (S);
3651          end loop;
3652
3653          --  Remove context of current compilation unit, unless we are within a
3654          --  nested package instantiation, in which case the context has been
3655          --  removed previously.
3656
3657          --  If current scope is the body of a child unit, remove context of
3658          --  spec as well. If an enclosing scope is an instance body, the
3659          --  context has already been removed, but the entities in the body
3660          --  must be made invisible as well.
3661
3662          S := Current_Scope;
3663
3664          while Present (S)
3665            and then S /= Standard_Standard
3666          loop
3667             if Is_Generic_Instance (S)
3668               and then (In_Package_Body (S)
3669                           or else Ekind (S) = E_Procedure
3670                             or else Ekind (S) = E_Function)
3671             then
3672                --  We still have to remove the entities of the enclosing
3673                --  instance from direct visibility.
3674
3675                declare
3676                   E : Entity_Id;
3677                begin
3678                   E := First_Entity (S);
3679                   while Present (E) loop
3680                      Set_Is_Immediately_Visible (E, False);
3681                      Next_Entity (E);
3682                   end loop;
3683                end;
3684
3685                exit;
3686             end if;
3687
3688             if S = Curr_Unit
3689               or else (Ekind (Curr_Unit) = E_Package_Body
3690                         and then S = Spec_Entity (Curr_Unit))
3691               or else (Ekind (Curr_Unit) = E_Subprogram_Body
3692                         and then S =
3693                           Corresponding_Spec
3694                             (Unit_Declaration_Node (Curr_Unit)))
3695             then
3696                Removed := True;
3697
3698                --  Remove entities in current scopes from visibility, so that
3699                --  instance body is compiled in a clean environment.
3700
3701                Save_Scope_Stack (Handle_Use => False);
3702
3703                if Is_Child_Unit (S) then
3704
3705                   --  Remove child unit from stack, as well as inner scopes.
3706                   --  Removing the context of a child unit removes parent units
3707                   --  as well.
3708
3709                   while Current_Scope /= S loop
3710                      Num_Inner := Num_Inner + 1;
3711                      Inner_Scopes (Num_Inner) := Current_Scope;
3712                      Pop_Scope;
3713                   end loop;
3714
3715                   Pop_Scope;
3716                   Remove_Context (Curr_Comp);
3717                   Curr_Scope := S;
3718
3719                else
3720                   Remove_Context (Curr_Comp);
3721                end if;
3722
3723                if Ekind (Curr_Unit) = E_Package_Body then
3724                   Remove_Context (Library_Unit (Curr_Comp));
3725                end if;
3726             end if;
3727
3728             S := Scope (S);
3729          end loop;
3730          pragma Assert (Num_Inner < Num_Scopes);
3731
3732          Push_Scope (Standard_Standard);
3733          Scope_Stack.Table (Scope_Stack.Last).Is_Active_Stack_Base := True;
3734          Instantiate_Package_Body
3735            (Body_Info =>
3736              ((Inst_Node                => N,
3737                Act_Decl                 => Act_Decl,
3738                Expander_Status          => Expander_Active,
3739                Current_Sem_Unit         => Current_Sem_Unit,
3740                Scope_Suppress           => Scope_Suppress,
3741                Local_Suppress_Stack_Top => Local_Suppress_Stack_Top,
3742                Version                  => Ada_Version)),
3743             Inlined_Body => True);
3744
3745          Pop_Scope;
3746
3747          --  Restore context
3748
3749          Set_Is_Immediately_Visible (Gen_Comp, Vis);
3750
3751          --  Reset Generic_Instance flag so that use clauses can be installed
3752          --  in the proper order. (See Use_One_Package for effect of enclosing
3753          --  instances on processing of use clauses).
3754
3755          for J in 1 .. N_Instances loop
3756             Set_Is_Generic_Instance (Instances (J), False);
3757          end loop;
3758
3759          if Removed then
3760             Install_Context (Curr_Comp);
3761
3762             if Present (Curr_Scope)
3763               and then Is_Child_Unit (Curr_Scope)
3764             then
3765                Push_Scope (Curr_Scope);
3766                Set_Is_Immediately_Visible (Curr_Scope);
3767
3768                --  Finally, restore inner scopes as well
3769
3770                for J in reverse 1 .. Num_Inner loop
3771                   Push_Scope (Inner_Scopes (J));
3772                end loop;
3773             end if;
3774
3775             Restore_Scope_Stack (Handle_Use => False);
3776
3777             if Present (Curr_Scope)
3778               and then
3779                 (In_Private_Part (Curr_Scope)
3780                   or else In_Package_Body (Curr_Scope))
3781             then
3782                --  Install private declaration of ancestor units, which are
3783                --  currently available. Restore_Scope_Stack and Install_Context
3784                --  only install the visible part of parents.
3785
3786                declare
3787                   Par : Entity_Id;
3788                begin
3789                   Par := Scope (Curr_Scope);
3790                   while (Present (Par))
3791                     and then Par /= Standard_Standard
3792                   loop
3793                      Install_Private_Declarations (Par);
3794                      Par := Scope (Par);
3795                   end loop;
3796                end;
3797             end if;
3798          end if;
3799
3800          --  Restore use clauses. For a child unit, use clauses in the parents
3801          --  are restored when installing the context, so only those in inner
3802          --  scopes (and those local to the child unit itself) need to be
3803          --  installed explicitly.
3804
3805          if Is_Child_Unit (Curr_Unit)
3806            and then Removed
3807          then
3808             for J in reverse 1 .. Num_Inner + 1 loop
3809                Scope_Stack.Table (Scope_Stack.Last - J + 1).First_Use_Clause :=
3810                  Use_Clauses (J);
3811                Install_Use_Clauses (Use_Clauses (J));
3812             end  loop;
3813
3814          else
3815             for J in reverse 1 .. Num_Scopes loop
3816                Scope_Stack.Table (Scope_Stack.Last - J + 1).First_Use_Clause :=
3817                  Use_Clauses (J);
3818                Install_Use_Clauses (Use_Clauses (J));
3819             end  loop;
3820          end if;
3821
3822          --  Restore status of instances. If one of them is a body, make
3823          --  its local entities visible again.
3824
3825          declare
3826             E    : Entity_Id;
3827             Inst : Entity_Id;
3828
3829          begin
3830             for J in 1 .. N_Instances loop
3831                Inst := Instances (J);
3832                Set_Is_Generic_Instance (Inst, True);
3833
3834                if In_Package_Body (Inst)
3835                  or else Ekind (S) = E_Procedure
3836                  or else Ekind (S) = E_Function
3837                then
3838                   E := First_Entity (Instances (J));
3839                   while Present (E) loop
3840                      Set_Is_Immediately_Visible (E);
3841                      Next_Entity (E);
3842                   end loop;
3843                end if;
3844             end loop;
3845          end;
3846
3847       --  If generic unit is in current unit, current context is correct
3848
3849       else
3850          Instantiate_Package_Body
3851            (Body_Info =>
3852              ((Inst_Node                => N,
3853                Act_Decl                 => Act_Decl,
3854                Expander_Status          => Expander_Active,
3855                Current_Sem_Unit         => Current_Sem_Unit,
3856                Scope_Suppress           => Scope_Suppress,
3857                Local_Suppress_Stack_Top => Local_Suppress_Stack_Top,
3858                Version                  => Ada_Version)),
3859             Inlined_Body => True);
3860       end if;
3861    end Inline_Instance_Body;
3862
3863    -------------------------------------
3864    -- Analyze_Procedure_Instantiation --
3865    -------------------------------------
3866
3867    procedure Analyze_Procedure_Instantiation (N : Node_Id) is
3868    begin
3869       Analyze_Subprogram_Instantiation (N, E_Procedure);
3870    end Analyze_Procedure_Instantiation;
3871
3872    -----------------------------------
3873    -- Need_Subprogram_Instance_Body --
3874    -----------------------------------
3875
3876    function Need_Subprogram_Instance_Body
3877      (N    : Node_Id;
3878       Subp : Entity_Id) return Boolean
3879    is
3880    begin
3881       if (Is_In_Main_Unit (N)
3882             or else Is_Inlined (Subp)
3883             or else Is_Inlined (Alias (Subp)))
3884         and then (Operating_Mode = Generate_Code
3885                     or else (Operating_Mode = Check_Semantics
3886                                and then ASIS_Mode))
3887         and then (Expander_Active or else ASIS_Mode)
3888         and then not ABE_Is_Certain (N)
3889         and then not Is_Eliminated (Subp)
3890       then
3891          Pending_Instantiations.Append
3892            ((Inst_Node                => N,
3893              Act_Decl                 => Unit_Declaration_Node (Subp),
3894              Expander_Status          => Expander_Active,
3895              Current_Sem_Unit         => Current_Sem_Unit,
3896              Scope_Suppress           => Scope_Suppress,
3897              Local_Suppress_Stack_Top => Local_Suppress_Stack_Top,
3898              Version                  => Ada_Version));
3899          return True;
3900       else
3901          return False;
3902       end if;
3903    end Need_Subprogram_Instance_Body;
3904
3905    --------------------------------------
3906    -- Analyze_Subprogram_Instantiation --
3907    --------------------------------------
3908
3909    procedure Analyze_Subprogram_Instantiation
3910      (N : Node_Id;
3911       K : Entity_Kind)
3912    is
3913       Loc    : constant Source_Ptr := Sloc (N);
3914       Gen_Id : constant Node_Id    := Name (N);
3915
3916       Anon_Id : constant Entity_Id :=
3917                   Make_Defining_Identifier (Sloc (Defining_Entity (N)),
3918                     Chars => New_External_Name
3919                                (Chars (Defining_Entity (N)), 'R'));
3920
3921       Act_Decl_Id : Entity_Id;
3922       Act_Decl    : Node_Id;
3923       Act_Spec    : Node_Id;
3924       Act_Tree    : Node_Id;
3925
3926       Env_Installed    : Boolean := False;
3927       Gen_Unit         : Entity_Id;
3928       Gen_Decl         : Node_Id;
3929       Pack_Id          : Entity_Id;
3930       Parent_Installed : Boolean := False;
3931       Renaming_List    : List_Id;
3932
3933       procedure Analyze_Instance_And_Renamings;
3934       --  The instance must be analyzed in a context that includes the mappings
3935       --  of generic parameters into actuals. We create a package declaration
3936       --  for this purpose, and a subprogram with an internal name within the
3937       --  package. The subprogram instance is simply an alias for the internal
3938       --  subprogram, declared in the current scope.
3939
3940       ------------------------------------
3941       -- Analyze_Instance_And_Renamings --
3942       ------------------------------------
3943
3944       procedure Analyze_Instance_And_Renamings is
3945          Def_Ent   : constant Entity_Id := Defining_Entity (N);
3946          Pack_Decl : Node_Id;
3947
3948       begin
3949          if Nkind (Parent (N)) = N_Compilation_Unit then
3950
3951             --  For the case of a compilation unit, the container package has
3952             --  the same name as the instantiation, to insure that the binder
3953             --  calls the elaboration procedure with the right name. Copy the
3954             --  entity of the instance, which may have compilation level flags
3955             --  (e.g. Is_Child_Unit) set.
3956
3957             Pack_Id := New_Copy (Def_Ent);
3958
3959          else
3960             --  Otherwise we use the name of the instantiation concatenated
3961             --  with its source position to ensure uniqueness if there are
3962             --  several instantiations with the same name.
3963
3964             Pack_Id :=
3965               Make_Defining_Identifier (Loc,
3966                 Chars => New_External_Name
3967                            (Related_Id   => Chars (Def_Ent),
3968                             Suffix       => "GP",
3969                             Suffix_Index => Source_Offset (Sloc (Def_Ent))));
3970          end if;
3971
3972          Pack_Decl := Make_Package_Declaration (Loc,
3973            Specification => Make_Package_Specification (Loc,
3974              Defining_Unit_Name   => Pack_Id,
3975              Visible_Declarations => Renaming_List,
3976              End_Label            => Empty));
3977
3978          Set_Instance_Spec (N, Pack_Decl);
3979          Set_Is_Generic_Instance (Pack_Id);
3980          Set_Debug_Info_Needed (Pack_Id);
3981
3982          --  Case of not a compilation unit
3983
3984          if Nkind (Parent (N)) /= N_Compilation_Unit then
3985             Mark_Rewrite_Insertion (Pack_Decl);
3986             Insert_Before (N, Pack_Decl);
3987             Set_Has_Completion (Pack_Id);
3988
3989          --  Case of an instantiation that is a compilation unit
3990
3991          --  Place declaration on current node so context is complete for
3992          --  analysis (including nested instantiations), and for use in a
3993          --  context_clause (see Analyze_With_Clause).
3994
3995          else
3996             Set_Unit (Parent (N), Pack_Decl);
3997             Set_Parent_Spec (Pack_Decl, Parent_Spec (N));
3998          end if;
3999
4000          Analyze (Pack_Decl);
4001          Check_Formal_Packages (Pack_Id);
4002          Set_Is_Generic_Instance (Pack_Id, False);
4003
4004          --  Why do we clear Is_Generic_Instance??? We set it 20 lines
4005          --  above???
4006
4007          --  Body of the enclosing package is supplied when instantiating the
4008          --  subprogram body, after semantic analysis is completed.
4009
4010          if Nkind (Parent (N)) = N_Compilation_Unit then
4011
4012             --  Remove package itself from visibility, so it does not
4013             --  conflict with subprogram.
4014
4015             Set_Name_Entity_Id (Chars (Pack_Id), Homonym (Pack_Id));
4016
4017             --  Set name and scope of internal subprogram so that the proper
4018             --  external name will be generated. The proper scope is the scope
4019             --  of the wrapper package. We need to generate debugging info for
4020             --  the internal subprogram, so set flag accordingly.
4021
4022             Set_Chars (Anon_Id, Chars (Defining_Entity (N)));
4023             Set_Scope (Anon_Id, Scope (Pack_Id));
4024
4025             --  Mark wrapper package as referenced, to avoid spurious warnings
4026             --  if the instantiation appears in various with_ clauses of
4027             --  subunits of the main unit.
4028
4029             Set_Referenced (Pack_Id);
4030          end if;
4031
4032          Set_Is_Generic_Instance (Anon_Id);
4033          Set_Debug_Info_Needed   (Anon_Id);
4034          Act_Decl_Id := New_Copy (Anon_Id);
4035
4036          Set_Parent            (Act_Decl_Id, Parent (Anon_Id));
4037          Set_Chars             (Act_Decl_Id, Chars (Defining_Entity (N)));
4038          Set_Sloc              (Act_Decl_Id, Sloc (Defining_Entity (N)));
4039          Set_Comes_From_Source (Act_Decl_Id, True);
4040
4041          --  The signature may involve types that are not frozen yet, but the
4042          --  subprogram will be frozen at the point the wrapper package is
4043          --  frozen, so it does not need its own freeze node. In fact, if one
4044          --  is created, it might conflict with the freezing actions from the
4045          --  wrapper package.
4046
4047          Set_Has_Delayed_Freeze (Anon_Id, False);
4048
4049          --  If the instance is a child unit, mark the Id accordingly. Mark
4050          --  the anonymous entity as well, which is the real subprogram and
4051          --  which is used when the instance appears in a context clause.
4052          --  Similarly, propagate the Is_Eliminated flag to handle properly
4053          --  nested eliminated subprograms.
4054
4055          Set_Is_Child_Unit (Act_Decl_Id, Is_Child_Unit (Defining_Entity (N)));
4056          Set_Is_Child_Unit (Anon_Id, Is_Child_Unit (Defining_Entity (N)));
4057          New_Overloaded_Entity (Act_Decl_Id);
4058          Check_Eliminated  (Act_Decl_Id);
4059          Set_Is_Eliminated (Anon_Id, Is_Eliminated (Act_Decl_Id));
4060
4061          --  In compilation unit case, kill elaboration checks on the
4062          --  instantiation, since they are never needed -- the body is
4063          --  instantiated at the same point as the spec.
4064
4065          if Nkind (Parent (N)) = N_Compilation_Unit then
4066             Set_Suppress_Elaboration_Warnings (Act_Decl_Id);
4067             Set_Kill_Elaboration_Checks       (Act_Decl_Id);
4068             Set_Is_Compilation_Unit (Anon_Id);
4069
4070             Set_Cunit_Entity (Current_Sem_Unit, Pack_Id);
4071          end if;
4072
4073          --  The instance is not a freezing point for the new subprogram
4074
4075          Set_Is_Frozen (Act_Decl_Id, False);
4076
4077          if Nkind (Defining_Entity (N)) = N_Defining_Operator_Symbol then
4078             Valid_Operator_Definition (Act_Decl_Id);
4079          end if;
4080
4081          Set_Alias  (Act_Decl_Id, Anon_Id);
4082          Set_Parent (Act_Decl_Id, Parent (Anon_Id));
4083          Set_Has_Completion (Act_Decl_Id);
4084          Set_Related_Instance (Pack_Id, Act_Decl_Id);
4085
4086          if Nkind (Parent (N)) = N_Compilation_Unit then
4087             Set_Body_Required (Parent (N), False);
4088          end if;
4089       end Analyze_Instance_And_Renamings;
4090
4091    --  Start of processing for Analyze_Subprogram_Instantiation
4092
4093    begin
4094       --  Very first thing: apply the special kludge for Text_IO processing
4095       --  in case we are instantiating one of the children of [Wide_]Text_IO.
4096       --  Of course such an instantiation is bogus (these are packages, not
4097       --  subprograms), but we get a better error message if we do this.
4098
4099       Text_IO_Kludge (Gen_Id);
4100
4101       --  Make node global for error reporting
4102
4103       Instantiation_Node := N;
4104       Preanalyze_Actuals (N);
4105
4106       Init_Env;
4107       Env_Installed := True;
4108       Check_Generic_Child_Unit (Gen_Id, Parent_Installed);
4109       Gen_Unit := Entity (Gen_Id);
4110
4111       Generate_Reference (Gen_Unit, Gen_Id);
4112
4113       if Nkind (Gen_Id) = N_Identifier
4114         and then Chars (Gen_Unit) = Chars (Defining_Entity (N))
4115       then
4116          Error_Msg_NE
4117            ("& is hidden within declaration of instance", Gen_Id, Gen_Unit);
4118       end if;
4119
4120       if Etype (Gen_Unit) = Any_Type then
4121          Restore_Env;
4122          return;
4123       end if;
4124
4125       --  Verify that it is a generic subprogram of the right kind, and that
4126       --  it does not lead to a circular instantiation.
4127
4128       if not Ekind_In (Gen_Unit, E_Generic_Procedure, E_Generic_Function) then
4129          Error_Msg_N ("expect generic subprogram in instantiation", Gen_Id);
4130
4131       elsif In_Open_Scopes (Gen_Unit) then
4132          Error_Msg_NE ("instantiation of & within itself", N, Gen_Unit);
4133
4134       elsif K = E_Procedure
4135         and then Ekind (Gen_Unit) /= E_Generic_Procedure
4136       then
4137          if Ekind (Gen_Unit) = E_Generic_Function then
4138             Error_Msg_N
4139               ("cannot instantiate generic function as procedure", Gen_Id);
4140          else
4141             Error_Msg_N
4142               ("expect name of generic procedure in instantiation", Gen_Id);
4143          end if;
4144
4145       elsif K = E_Function
4146         and then Ekind (Gen_Unit) /= E_Generic_Function
4147       then
4148          if Ekind (Gen_Unit) = E_Generic_Procedure then
4149             Error_Msg_N
4150               ("cannot instantiate generic procedure as function", Gen_Id);
4151          else
4152             Error_Msg_N
4153               ("expect name of generic function in instantiation", Gen_Id);
4154          end if;
4155
4156       else
4157          Set_Entity (Gen_Id, Gen_Unit);
4158          Set_Is_Instantiated (Gen_Unit);
4159
4160          if In_Extended_Main_Source_Unit (N) then
4161             Generate_Reference (Gen_Unit, N);
4162          end if;
4163
4164          --  If renaming, get original unit
4165
4166          if Present (Renamed_Object (Gen_Unit))
4167            and then (Ekind (Renamed_Object (Gen_Unit)) = E_Generic_Procedure
4168                        or else
4169                      Ekind (Renamed_Object (Gen_Unit)) = E_Generic_Function)
4170          then
4171             Gen_Unit := Renamed_Object (Gen_Unit);
4172             Set_Is_Instantiated (Gen_Unit);
4173             Generate_Reference  (Gen_Unit, N);
4174          end if;
4175
4176          if Contains_Instance_Of (Gen_Unit, Current_Scope, Gen_Id) then
4177             Error_Msg_Node_2 := Current_Scope;
4178             Error_Msg_NE
4179               ("circular Instantiation: & instantiated in &!", N, Gen_Unit);
4180             Circularity_Detected := True;
4181             goto Leave;
4182          end if;
4183
4184          Gen_Decl := Unit_Declaration_Node (Gen_Unit);
4185
4186          --  Initialize renamings map, for error checking
4187
4188          Generic_Renamings.Set_Last (0);
4189          Generic_Renamings_HTable.Reset;
4190
4191          Create_Instantiation_Source (N, Gen_Unit, False, S_Adjustment);
4192
4193          --  Copy original generic tree, to produce text for instantiation
4194
4195          Act_Tree :=
4196            Copy_Generic_Node
4197              (Original_Node (Gen_Decl), Empty, Instantiating => True);
4198
4199          --  Inherit overriding indicator from instance node
4200
4201          Act_Spec := Specification (Act_Tree);
4202          Set_Must_Override     (Act_Spec, Must_Override (N));
4203          Set_Must_Not_Override (Act_Spec, Must_Not_Override (N));
4204
4205          Renaming_List :=
4206            Analyze_Associations
4207              (N,
4208               Generic_Formal_Declarations (Act_Tree),
4209               Generic_Formal_Declarations (Gen_Decl));
4210
4211          --  The subprogram itself cannot contain a nested instance, so the
4212          --  current parent is left empty.
4213
4214          Set_Instance_Env (Gen_Unit, Empty);
4215
4216          --  Build the subprogram declaration, which does not appear in the
4217          --  generic template, and give it a sloc consistent with that of the
4218          --  template.
4219
4220          Set_Defining_Unit_Name (Act_Spec, Anon_Id);
4221          Set_Generic_Parent (Act_Spec, Gen_Unit);
4222          Act_Decl :=
4223            Make_Subprogram_Declaration (Sloc (Act_Spec),
4224              Specification => Act_Spec);
4225
4226          Set_Categorization_From_Pragmas (Act_Decl);
4227
4228          if Parent_Installed then
4229             Hide_Current_Scope;
4230          end if;
4231
4232          Append (Act_Decl, Renaming_List);
4233          Analyze_Instance_And_Renamings;
4234
4235          --  If the generic is marked Import (Intrinsic), then so is the
4236          --  instance. This indicates that there is no body to instantiate. If
4237          --  generic is marked inline, so it the instance, and the anonymous
4238          --  subprogram it renames. If inlined, or else if inlining is enabled
4239          --  for the compilation, we generate the instance body even if it is
4240          --  not within the main unit.
4241
4242          --  Any other  pragmas might also be inherited ???
4243
4244          if Is_Intrinsic_Subprogram (Gen_Unit) then
4245             Set_Is_Intrinsic_Subprogram (Anon_Id);
4246             Set_Is_Intrinsic_Subprogram (Act_Decl_Id);
4247
4248             if Chars (Gen_Unit) = Name_Unchecked_Conversion then
4249                Validate_Unchecked_Conversion (N, Act_Decl_Id);
4250             end if;
4251          end if;
4252
4253          Generate_Definition (Act_Decl_Id);
4254
4255          Set_Is_Inlined (Act_Decl_Id, Is_Inlined (Gen_Unit));
4256          Set_Is_Inlined (Anon_Id,     Is_Inlined (Gen_Unit));
4257
4258          if not Is_Intrinsic_Subprogram (Gen_Unit) then
4259             Check_Elab_Instantiation (N);
4260          end if;
4261
4262          if Is_Dispatching_Operation (Act_Decl_Id)
4263            and then Ada_Version >= Ada_2005
4264          then
4265             declare
4266                Formal : Entity_Id;
4267
4268             begin
4269                Formal := First_Formal (Act_Decl_Id);
4270                while Present (Formal) loop
4271                   if Ekind (Etype (Formal)) = E_Anonymous_Access_Type
4272                     and then Is_Controlling_Formal (Formal)
4273                     and then not Can_Never_Be_Null (Formal)
4274                   then
4275                      Error_Msg_NE ("access parameter& is controlling,",
4276                        N, Formal);
4277                      Error_Msg_NE
4278                        ("\corresponding parameter of & must be"
4279                        & " explicitly null-excluding", N, Gen_Id);
4280                   end if;
4281
4282                   Next_Formal (Formal);
4283                end loop;
4284             end;
4285          end if;
4286
4287          Check_Hidden_Child_Unit (N, Gen_Unit, Act_Decl_Id);
4288
4289          --  Subject to change, pending on if other pragmas are inherited ???
4290
4291          Validate_Categorization_Dependency (N, Act_Decl_Id);
4292
4293          if not Is_Intrinsic_Subprogram (Act_Decl_Id) then
4294             Inherit_Context (Gen_Decl, N);
4295
4296             Restore_Private_Views (Pack_Id, False);
4297
4298             --  If the context requires a full instantiation, mark node for
4299             --  subsequent construction of the body.
4300
4301             if Need_Subprogram_Instance_Body (N, Act_Decl_Id) then
4302
4303                Check_Forward_Instantiation (Gen_Decl);
4304
4305                --  The wrapper package is always delayed, because it does not
4306                --  constitute a freeze point, but to insure that the freeze
4307                --  node is placed properly, it is created directly when
4308                --  instantiating the body (otherwise the freeze node might
4309                --  appear to early for nested instantiations).
4310
4311             elsif Nkind (Parent (N)) = N_Compilation_Unit then
4312
4313                --  For ASIS purposes, indicate that the wrapper package has
4314                --  replaced the instantiation node.
4315
4316                Rewrite (N, Unit (Parent (N)));
4317                Set_Unit (Parent (N), N);
4318             end if;
4319
4320          elsif Nkind (Parent (N)) = N_Compilation_Unit then
4321
4322                --  Replace instance node for library-level instantiations of
4323                --  intrinsic subprograms, for ASIS use.
4324
4325                Rewrite (N, Unit (Parent (N)));
4326                Set_Unit (Parent (N), N);
4327          end if;
4328
4329          if Parent_Installed then
4330             Remove_Parent;
4331          end if;
4332
4333          Restore_Env;
4334          Env_Installed := False;
4335          Generic_Renamings.Set_Last (0);
4336          Generic_Renamings_HTable.Reset;
4337       end if;
4338
4339       <<Leave>>
4340          Analyze_Aspect_Specifications
4341            (N, Act_Decl_Id, Aspect_Specifications (N));
4342
4343    exception
4344       when Instantiation_Error =>
4345          if Parent_Installed then
4346             Remove_Parent;
4347          end if;
4348
4349          if Env_Installed then
4350             Restore_Env;
4351          end if;
4352    end Analyze_Subprogram_Instantiation;
4353
4354    -------------------------
4355    -- Get_Associated_Node --
4356    -------------------------
4357
4358    function Get_Associated_Node (N : Node_Id) return Node_Id is
4359       Assoc : Node_Id;
4360
4361    begin
4362       Assoc := Associated_Node (N);
4363
4364       if Nkind (Assoc) /= Nkind (N) then
4365          return Assoc;
4366
4367       elsif Nkind_In (Assoc, N_Aggregate, N_Extension_Aggregate) then
4368          return Assoc;
4369
4370       else
4371          --  If the node is part of an inner generic, it may itself have been
4372          --  remapped into a further generic copy. Associated_Node is otherwise
4373          --  used for the entity of the node, and will be of a different node
4374          --  kind, or else N has been rewritten as a literal or function call.
4375
4376          while Present (Associated_Node (Assoc))
4377            and then Nkind (Associated_Node (Assoc)) = Nkind (Assoc)
4378          loop
4379             Assoc := Associated_Node (Assoc);
4380          end loop;
4381
4382          --  Follow and additional link in case the final node was rewritten.
4383          --  This can only happen with nested generic units.
4384
4385          if (Nkind (Assoc) = N_Identifier or else Nkind (Assoc) in N_Op)
4386            and then Present (Associated_Node (Assoc))
4387            and then (Nkind_In (Associated_Node (Assoc), N_Function_Call,
4388                                                         N_Explicit_Dereference,
4389                                                         N_Integer_Literal,
4390                                                         N_Real_Literal,
4391                                                         N_String_Literal))
4392          then
4393             Assoc := Associated_Node (Assoc);
4394          end if;
4395
4396          return Assoc;
4397       end if;
4398    end Get_Associated_Node;
4399
4400    -------------------------------------------
4401    -- Build_Instance_Compilation_Unit_Nodes --
4402    -------------------------------------------
4403
4404    procedure Build_Instance_Compilation_Unit_Nodes
4405      (N        : Node_Id;
4406       Act_Body : Node_Id;
4407       Act_Decl : Node_Id)
4408    is
4409       Decl_Cunit : Node_Id;
4410       Body_Cunit : Node_Id;
4411       Citem      : Node_Id;
4412       New_Main   : constant Entity_Id := Defining_Entity (Act_Decl);
4413       Old_Main   : constant Entity_Id := Cunit_Entity (Main_Unit);
4414
4415    begin
4416       --  A new compilation unit node is built for the instance declaration
4417
4418       Decl_Cunit :=
4419         Make_Compilation_Unit (Sloc (N),
4420           Context_Items  => Empty_List,
4421           Unit           => Act_Decl,
4422           Aux_Decls_Node =>
4423             Make_Compilation_Unit_Aux (Sloc (N)));
4424
4425       Set_Parent_Spec   (Act_Decl, Parent_Spec (N));
4426
4427       --  The new compilation unit is linked to its body, but both share the
4428       --  same file, so we do not set Body_Required on the new unit so as not
4429       --  to create a spurious dependency on a non-existent body in the ali.
4430       --  This simplifies CodePeer unit traversal.
4431
4432       --  We use the original instantiation compilation unit as the resulting
4433       --  compilation unit of the instance, since this is the main unit.
4434
4435       Rewrite (N, Act_Body);
4436       Body_Cunit := Parent (N);
4437
4438       --  The two compilation unit nodes are linked by the Library_Unit field
4439
4440       Set_Library_Unit  (Decl_Cunit, Body_Cunit);
4441       Set_Library_Unit  (Body_Cunit, Decl_Cunit);
4442
4443       --  Preserve the private nature of the package if needed
4444
4445       Set_Private_Present (Decl_Cunit, Private_Present (Body_Cunit));
4446
4447       --  If the instance is not the main unit, its context, categorization
4448       --  and elaboration entity are not relevant to the compilation.
4449
4450       if Body_Cunit /= Cunit (Main_Unit) then
4451          Make_Instance_Unit (Body_Cunit, In_Main => False);
4452          return;
4453       end if;
4454
4455       --  The context clause items on the instantiation, which are now attached
4456       --  to the body compilation unit (since the body overwrote the original
4457       --  instantiation node), semantically belong on the spec, so copy them
4458       --  there. It's harmless to leave them on the body as well. In fact one
4459       --  could argue that they belong in both places.
4460
4461       Citem := First (Context_Items (Body_Cunit));
4462       while Present (Citem) loop
4463          Append (New_Copy (Citem), Context_Items (Decl_Cunit));
4464          Next (Citem);
4465       end loop;
4466
4467       --  Propagate categorization flags on packages, so that they appear in
4468       --  the ali file for the spec of the unit.
4469
4470       if Ekind (New_Main) = E_Package then
4471          Set_Is_Pure           (Old_Main, Is_Pure (New_Main));
4472          Set_Is_Preelaborated  (Old_Main, Is_Preelaborated (New_Main));
4473          Set_Is_Remote_Types   (Old_Main, Is_Remote_Types (New_Main));
4474          Set_Is_Shared_Passive (Old_Main, Is_Shared_Passive (New_Main));
4475          Set_Is_Remote_Call_Interface
4476            (Old_Main, Is_Remote_Call_Interface (New_Main));
4477       end if;
4478
4479       --  Make entry in Units table, so that binder can generate call to
4480       --  elaboration procedure for body, if any.
4481
4482       Make_Instance_Unit (Body_Cunit, In_Main => True);
4483       Main_Unit_Entity := New_Main;
4484       Set_Cunit_Entity (Main_Unit, Main_Unit_Entity);
4485
4486       --  Build elaboration entity, since the instance may certainly generate
4487       --  elaboration code requiring a flag for protection.
4488
4489       Build_Elaboration_Entity (Decl_Cunit, New_Main);
4490    end Build_Instance_Compilation_Unit_Nodes;
4491
4492    -----------------------------
4493    -- Check_Access_Definition --
4494    -----------------------------
4495
4496    procedure Check_Access_Definition (N : Node_Id) is
4497    begin
4498       pragma Assert
4499         (Ada_Version >= Ada_2005
4500            and then Present (Access_Definition (N)));
4501       null;
4502    end Check_Access_Definition;
4503
4504    -----------------------------------
4505    -- Check_Formal_Package_Instance --
4506    -----------------------------------
4507
4508    --  If the formal has specific parameters, they must match those of the
4509    --  actual. Both of them are instances, and the renaming declarations for
4510    --  their formal parameters appear in the same order in both. The analyzed
4511    --  formal has been analyzed in the context of the current instance.
4512
4513    procedure Check_Formal_Package_Instance
4514      (Formal_Pack : Entity_Id;
4515       Actual_Pack : Entity_Id)
4516    is
4517       E1 : Entity_Id := First_Entity (Actual_Pack);
4518       E2 : Entity_Id := First_Entity (Formal_Pack);
4519
4520       Expr1 : Node_Id;
4521       Expr2 : Node_Id;
4522
4523       procedure Check_Mismatch (B : Boolean);
4524       --  Common error routine for mismatch between the parameters of the
4525       --  actual instance and those of the formal package.
4526
4527       function Same_Instantiated_Constant (E1, E2 : Entity_Id) return Boolean;
4528       --  The formal may come from a nested formal package, and the actual may
4529       --  have been constant-folded. To determine whether the two denote the
4530       --  same entity we may have to traverse several definitions to recover
4531       --  the ultimate entity that they refer to.
4532
4533       function Same_Instantiated_Variable (E1, E2 : Entity_Id) return Boolean;
4534       --  Similarly, if the formal comes from a nested formal package, the
4535       --  actual may designate the formal through multiple renamings, which
4536       --  have to be followed to determine the original variable in question.
4537
4538       --------------------
4539       -- Check_Mismatch --
4540       --------------------
4541
4542       procedure Check_Mismatch (B : Boolean) is
4543          Kind : constant Node_Kind := Nkind (Parent (E2));
4544
4545       begin
4546          if Kind = N_Formal_Type_Declaration then
4547             return;
4548
4549          elsif Nkind_In (Kind, N_Formal_Object_Declaration,
4550                                N_Formal_Package_Declaration)
4551            or else Kind in N_Formal_Subprogram_Declaration
4552          then
4553             null;
4554
4555          elsif B then
4556             Error_Msg_NE
4557               ("actual for & in actual instance does not match formal",
4558                Parent (Actual_Pack), E1);
4559          end if;
4560       end Check_Mismatch;
4561
4562       --------------------------------
4563       -- Same_Instantiated_Constant --
4564       --------------------------------
4565
4566       function Same_Instantiated_Constant
4567         (E1, E2 : Entity_Id) return Boolean
4568       is
4569          Ent : Entity_Id;
4570
4571       begin
4572          Ent := E2;
4573          while Present (Ent) loop
4574             if E1 = Ent then
4575                return True;
4576
4577             elsif Ekind (Ent) /= E_Constant then
4578                return False;
4579
4580             elsif Is_Entity_Name (Constant_Value (Ent)) then
4581                if  Entity (Constant_Value (Ent)) = E1 then
4582                   return True;
4583                else
4584                   Ent := Entity (Constant_Value (Ent));
4585                end if;
4586
4587             --  The actual may be a constant that has been folded. Recover
4588             --  original name.
4589
4590             elsif Is_Entity_Name (Original_Node (Constant_Value (Ent))) then
4591                   Ent := Entity (Original_Node (Constant_Value (Ent)));
4592             else
4593                return False;
4594             end if;
4595          end loop;
4596
4597          return False;
4598       end Same_Instantiated_Constant;
4599
4600       --------------------------------
4601       -- Same_Instantiated_Variable --
4602       --------------------------------
4603
4604       function Same_Instantiated_Variable
4605         (E1, E2 : Entity_Id) return Boolean
4606       is
4607          function Original_Entity (E : Entity_Id) return Entity_Id;
4608          --  Follow chain of renamings to the ultimate ancestor
4609
4610          ---------------------
4611          -- Original_Entity --
4612          ---------------------
4613
4614          function Original_Entity (E : Entity_Id) return Entity_Id is
4615             Orig : Entity_Id;
4616
4617          begin
4618             Orig := E;
4619             while Nkind (Parent (Orig)) = N_Object_Renaming_Declaration
4620               and then Present (Renamed_Object (Orig))
4621               and then Is_Entity_Name (Renamed_Object (Orig))
4622             loop
4623                Orig := Entity (Renamed_Object (Orig));
4624             end loop;
4625
4626             return Orig;
4627          end Original_Entity;
4628
4629       --  Start of processing for Same_Instantiated_Variable
4630
4631       begin
4632          return Ekind (E1) = Ekind (E2)
4633            and then Original_Entity (E1) = Original_Entity (E2);
4634       end Same_Instantiated_Variable;
4635
4636    --  Start of processing for Check_Formal_Package_Instance
4637
4638    begin
4639       while Present (E1)
4640         and then Present (E2)
4641       loop
4642          exit when Ekind (E1) = E_Package
4643            and then Renamed_Entity (E1) = Renamed_Entity (Actual_Pack);
4644
4645          --  If the formal is the renaming of the formal package, this
4646          --  is the end of its formal part, which may occur before the
4647          --  end of the formal part in the actual in the presence of
4648          --  defaulted parameters in the formal package.
4649
4650          exit when Nkind (Parent (E2)) = N_Package_Renaming_Declaration
4651            and then Renamed_Entity (E2) = Scope (E2);
4652
4653          --  The analysis of the actual may generate additional internal
4654          --  entities. If the formal is defaulted, there is no corresponding
4655          --  analysis and the internal entities must be skipped, until we
4656          --  find corresponding entities again.
4657
4658          if Comes_From_Source (E2)
4659            and then not Comes_From_Source (E1)
4660            and then Chars (E1) /= Chars (E2)
4661          then
4662             while Present (E1)
4663               and then  Chars (E1) /= Chars (E2)
4664             loop
4665                Next_Entity (E1);
4666             end loop;
4667          end if;
4668
4669          if No (E1) then
4670             return;
4671
4672          --  If the formal entity comes from a formal declaration, it was
4673          --  defaulted in the formal package, and no check is needed on it.
4674
4675          elsif Nkind (Parent (E2)) =  N_Formal_Object_Declaration then
4676             goto Next_E;
4677
4678          elsif Is_Type (E1) then
4679
4680             --  Subtypes must statically match. E1, E2 are the local entities
4681             --  that are subtypes of the actuals. Itypes generated for other
4682             --  parameters need not be checked, the check will be performed
4683             --  on the parameters themselves.
4684
4685             --  If E2 is a formal type declaration, it is a defaulted parameter
4686             --  and needs no checking.
4687
4688             if not Is_Itype (E1)
4689               and then not Is_Itype (E2)
4690             then
4691                Check_Mismatch
4692                  (not Is_Type (E2)
4693                    or else Etype (E1) /= Etype (E2)
4694                    or else not Subtypes_Statically_Match (E1, E2));
4695             end if;
4696
4697          elsif Ekind (E1) = E_Constant then
4698
4699             --  IN parameters must denote the same static value, or the same
4700             --  constant, or the literal null.
4701
4702             Expr1 := Expression (Parent (E1));
4703
4704             if Ekind (E2) /= E_Constant then
4705                Check_Mismatch (True);
4706                goto Next_E;
4707             else
4708                Expr2 := Expression (Parent (E2));
4709             end if;
4710
4711             if Is_Static_Expression (Expr1) then
4712
4713                if not Is_Static_Expression (Expr2) then
4714                   Check_Mismatch (True);
4715
4716                elsif Is_Discrete_Type (Etype (E1)) then
4717                   declare
4718                      V1 : constant Uint := Expr_Value (Expr1);
4719                      V2 : constant Uint := Expr_Value (Expr2);
4720                   begin
4721                      Check_Mismatch (V1 /= V2);
4722                   end;
4723
4724                elsif Is_Real_Type (Etype (E1)) then
4725                   declare
4726                      V1 : constant Ureal := Expr_Value_R (Expr1);
4727                      V2 : constant Ureal := Expr_Value_R (Expr2);
4728                   begin
4729                      Check_Mismatch (V1 /= V2);
4730                   end;
4731
4732                elsif Is_String_Type (Etype (E1))
4733                  and then Nkind (Expr1) = N_String_Literal
4734                then
4735                   if Nkind (Expr2) /= N_String_Literal then
4736                      Check_Mismatch (True);
4737                   else
4738                      Check_Mismatch
4739                        (not String_Equal (Strval (Expr1), Strval (Expr2)));
4740                   end if;
4741                end if;
4742
4743             elsif Is_Entity_Name (Expr1) then
4744                if Is_Entity_Name (Expr2) then
4745                   if Entity (Expr1) = Entity (Expr2) then
4746                      null;
4747                   else
4748                      Check_Mismatch
4749                        (not Same_Instantiated_Constant
4750                          (Entity (Expr1), Entity (Expr2)));
4751                   end if;
4752                else
4753                   Check_Mismatch (True);
4754                end if;
4755
4756             elsif Is_Entity_Name (Original_Node (Expr1))
4757               and then Is_Entity_Name (Expr2)
4758             and then
4759               Same_Instantiated_Constant
4760                 (Entity (Original_Node (Expr1)), Entity (Expr2))
4761             then
4762                null;
4763
4764             elsif Nkind (Expr1) = N_Null then
4765                Check_Mismatch (Nkind (Expr1) /= N_Null);
4766
4767             else
4768                Check_Mismatch (True);
4769             end if;
4770
4771          elsif Ekind (E1) = E_Variable then
4772             Check_Mismatch (not Same_Instantiated_Variable (E1, E2));
4773
4774          elsif Ekind (E1) = E_Package then
4775             Check_Mismatch
4776               (Ekind (E1) /= Ekind (E2)
4777                 or else Renamed_Object (E1) /= Renamed_Object (E2));
4778
4779          elsif Is_Overloadable (E1) then
4780
4781             --  Verify that the actual subprograms match. Note that actuals
4782             --  that are attributes are rewritten as subprograms. If the
4783             --  subprogram in the formal package is defaulted, no check is
4784             --  needed. Note that this can only happen in Ada 2005 when the
4785             --  formal package can be partially parameterized.
4786
4787             if Nkind (Unit_Declaration_Node (E1)) =
4788                                            N_Subprogram_Renaming_Declaration
4789               and then From_Default (Unit_Declaration_Node (E1))
4790             then
4791                null;
4792
4793             else
4794                Check_Mismatch
4795                  (Ekind (E2) /= Ekind (E1) or else (Alias (E1)) /= Alias (E2));
4796             end if;
4797
4798          else
4799             raise Program_Error;
4800          end if;
4801
4802          <<Next_E>>
4803             Next_Entity (E1);
4804             Next_Entity (E2);
4805       end loop;
4806    end Check_Formal_Package_Instance;
4807
4808    ---------------------------
4809    -- Check_Formal_Packages --
4810    ---------------------------
4811
4812    procedure Check_Formal_Packages (P_Id : Entity_Id) is
4813       E        : Entity_Id;
4814       Formal_P : Entity_Id;
4815
4816    begin
4817       --  Iterate through the declarations in the instance, looking for package
4818       --  renaming declarations that denote instances of formal packages. Stop
4819       --  when we find the renaming of the current package itself. The
4820       --  declaration for a formal package without a box is followed by an
4821       --  internal entity that repeats the instantiation.
4822
4823       E := First_Entity (P_Id);
4824       while Present (E) loop
4825          if Ekind (E) = E_Package then
4826             if Renamed_Object (E) = P_Id then
4827                exit;
4828
4829             elsif Nkind (Parent (E)) /= N_Package_Renaming_Declaration then
4830                null;
4831
4832             elsif not Box_Present (Parent (Associated_Formal_Package (E))) then
4833                Formal_P := Next_Entity (E);
4834                Check_Formal_Package_Instance (Formal_P, E);
4835
4836                --  After checking, remove the internal validating package. It
4837                --  is only needed for semantic checks, and as it may contain
4838                --  generic formal declarations it should not reach gigi.
4839
4840                Remove (Unit_Declaration_Node (Formal_P));
4841             end if;
4842          end if;
4843
4844          Next_Entity (E);
4845       end loop;
4846    end Check_Formal_Packages;
4847
4848    ---------------------------------
4849    -- Check_Forward_Instantiation --
4850    ---------------------------------
4851
4852    procedure Check_Forward_Instantiation (Decl : Node_Id) is
4853       S        : Entity_Id;
4854       Gen_Comp : Entity_Id := Cunit_Entity (Get_Source_Unit (Decl));
4855
4856    begin
4857       --  The instantiation appears before the generic body if we are in the
4858       --  scope of the unit containing the generic, either in its spec or in
4859       --  the package body, and before the generic body.
4860
4861       if Ekind (Gen_Comp) = E_Package_Body then
4862          Gen_Comp := Spec_Entity (Gen_Comp);
4863       end if;
4864
4865       if In_Open_Scopes (Gen_Comp)
4866         and then No (Corresponding_Body (Decl))
4867       then
4868          S := Current_Scope;
4869
4870          while Present (S)
4871            and then not Is_Compilation_Unit (S)
4872            and then not Is_Child_Unit (S)
4873          loop
4874             if Ekind (S) = E_Package then
4875                Set_Has_Forward_Instantiation (S);
4876             end if;
4877
4878             S := Scope (S);
4879          end loop;
4880       end if;
4881    end Check_Forward_Instantiation;
4882
4883    ---------------------------
4884    -- Check_Generic_Actuals --
4885    ---------------------------
4886
4887    --  The visibility of the actuals may be different between the point of
4888    --  generic instantiation and the instantiation of the body.
4889
4890    procedure Check_Generic_Actuals
4891      (Instance      : Entity_Id;
4892       Is_Formal_Box : Boolean)
4893    is
4894       E      : Entity_Id;
4895       Astype : Entity_Id;
4896
4897       function Denotes_Previous_Actual (Typ : Entity_Id) return Boolean;
4898       --  For a formal that is an array type, the component type is often a
4899       --  previous formal in the same unit. The privacy status of the component
4900       --  type will have been examined earlier in the traversal of the
4901       --  corresponding actuals, and this status should not be modified for the
4902       --  array type itself.
4903       --
4904       --  To detect this case we have to rescan the list of formals, which
4905       --  is usually short enough to ignore the resulting inefficiency.
4906
4907       -----------------------------
4908       -- Denotes_Previous_Actual --
4909       -----------------------------
4910
4911       function Denotes_Previous_Actual (Typ : Entity_Id) return Boolean is
4912          Prev : Entity_Id;
4913
4914       begin
4915          Prev := First_Entity (Instance);
4916          while Present (Prev) loop
4917             if Is_Type (Prev)
4918               and then Nkind (Parent (Prev)) = N_Subtype_Declaration
4919               and then Is_Entity_Name (Subtype_Indication (Parent (Prev)))
4920               and then Entity (Subtype_Indication (Parent (Prev))) = Typ
4921             then
4922                return True;
4923
4924             elsif Prev = E then
4925                return False;
4926
4927             else
4928                Next_Entity (Prev);
4929             end if;
4930          end loop;
4931
4932          return False;
4933       end Denotes_Previous_Actual;
4934
4935    --  Start of processing for Check_Generic_Actuals
4936
4937    begin
4938       E := First_Entity (Instance);
4939       while Present (E) loop
4940          if Is_Type (E)
4941            and then Nkind (Parent (E)) = N_Subtype_Declaration
4942            and then Scope (Etype (E)) /= Instance
4943            and then Is_Entity_Name (Subtype_Indication (Parent (E)))
4944          then
4945             if Is_Array_Type (E)
4946               and then Denotes_Previous_Actual (Component_Type (E))
4947             then
4948                null;
4949             else
4950                Check_Private_View (Subtype_Indication (Parent (E)));
4951             end if;
4952             Set_Is_Generic_Actual_Type (E, True);
4953             Set_Is_Hidden (E, False);
4954             Set_Is_Potentially_Use_Visible (E,
4955               In_Use (Instance));
4956
4957             --  We constructed the generic actual type as a subtype of the
4958             --  supplied type. This means that it normally would not inherit
4959             --  subtype specific attributes of the actual, which is wrong for
4960             --  the generic case.
4961
4962             Astype := Ancestor_Subtype (E);
4963
4964             if No (Astype) then
4965
4966                --  This can happen when E is an itype that is the full view of
4967                --  a private type completed, e.g. with a constrained array. In
4968                --  that case, use the first subtype, which will carry size
4969                --  information. The base type itself is unconstrained and will
4970                --  not carry it.
4971
4972                Astype := First_Subtype (E);
4973             end if;
4974
4975             Set_Size_Info      (E,                (Astype));
4976             Set_RM_Size        (E, RM_Size        (Astype));
4977             Set_First_Rep_Item (E, First_Rep_Item (Astype));
4978
4979             if Is_Discrete_Or_Fixed_Point_Type (E) then
4980                Set_RM_Size (E, RM_Size (Astype));
4981
4982             --  In  nested instances, the base type of an access actual
4983             --  may itself be private, and need to be exchanged.
4984
4985             elsif Is_Access_Type (E)
4986               and then Is_Private_Type (Etype (E))
4987             then
4988                Check_Private_View
4989                  (New_Occurrence_Of (Etype (E), Sloc (Instance)));
4990             end if;
4991
4992          elsif Ekind (E) = E_Package then
4993
4994             --  If this is the renaming for the current instance, we're done.
4995             --  Otherwise it is a formal package. If the corresponding formal
4996             --  was declared with a box, the (instantiations of the) generic
4997             --  formal part are also visible. Otherwise, ignore the entity
4998             --  created to validate the actuals.
4999
5000             if Renamed_Object (E) = Instance then
5001                exit;
5002
5003             elsif Nkind (Parent (E)) /= N_Package_Renaming_Declaration then
5004                null;
5005
5006             --  The visibility of a formal of an enclosing generic is already
5007             --  correct.
5008
5009             elsif Denotes_Formal_Package (E) then
5010                null;
5011
5012             elsif Present (Associated_Formal_Package (E))
5013               and then not Is_Generic_Formal (E)
5014             then
5015                if Box_Present (Parent (Associated_Formal_Package (E))) then
5016                   Check_Generic_Actuals (Renamed_Object (E), True);
5017
5018                else
5019                   Check_Generic_Actuals (Renamed_Object (E), False);
5020                end if;
5021
5022                Set_Is_Hidden (E, False);
5023             end if;
5024
5025          --  If this is a subprogram instance (in a wrapper package) the
5026          --  actual is fully visible.
5027
5028          elsif Is_Wrapper_Package (Instance) then
5029             Set_Is_Hidden (E, False);
5030
5031          --  If the formal package is declared with a box, or if the formal
5032          --  parameter is defaulted, it is visible in the body.
5033
5034          elsif Is_Formal_Box
5035            or else Is_Visible_Formal (E)
5036          then
5037             Set_Is_Hidden (E, False);
5038          end if;
5039
5040          Next_Entity (E);
5041       end loop;
5042    end Check_Generic_Actuals;
5043
5044    ------------------------------
5045    -- Check_Generic_Child_Unit --
5046    ------------------------------
5047
5048    procedure Check_Generic_Child_Unit
5049      (Gen_Id           : Node_Id;
5050       Parent_Installed : in out Boolean)
5051    is
5052       Loc      : constant Source_Ptr := Sloc (Gen_Id);
5053       Gen_Par  : Entity_Id := Empty;
5054       E        : Entity_Id;
5055       Inst_Par : Entity_Id;
5056       S        : Node_Id;
5057
5058       function Find_Generic_Child
5059         (Scop : Entity_Id;
5060          Id   : Node_Id) return Entity_Id;
5061       --  Search generic parent for possible child unit with the given name
5062
5063       function In_Enclosing_Instance return Boolean;
5064       --  Within an instance of the parent, the child unit may be denoted
5065       --  by a simple name, or an abbreviated expanded name. Examine enclosing
5066       --  scopes to locate a possible parent instantiation.
5067
5068       ------------------------
5069       -- Find_Generic_Child --
5070       ------------------------
5071
5072       function Find_Generic_Child
5073         (Scop : Entity_Id;
5074          Id   : Node_Id) return Entity_Id
5075       is
5076          E : Entity_Id;
5077
5078       begin
5079          --  If entity of name is already set, instance has already been
5080          --  resolved, e.g. in an enclosing instantiation.
5081
5082          if Present (Entity (Id)) then
5083             if Scope (Entity (Id)) = Scop then
5084                return Entity (Id);
5085             else
5086                return Empty;
5087             end if;
5088
5089          else
5090             E := First_Entity (Scop);
5091             while Present (E) loop
5092                if Chars (E) = Chars (Id)
5093                  and then Is_Child_Unit (E)
5094                then
5095                   if Is_Child_Unit (E)
5096                     and then not Is_Visible_Child_Unit (E)
5097                   then
5098                      Error_Msg_NE
5099                        ("generic child unit& is not visible", Gen_Id, E);
5100                   end if;
5101
5102                   Set_Entity (Id, E);
5103                   return E;
5104                end if;
5105
5106                Next_Entity (E);
5107             end loop;
5108
5109             return Empty;
5110          end if;
5111       end Find_Generic_Child;
5112
5113       ---------------------------
5114       -- In_Enclosing_Instance --
5115       ---------------------------
5116
5117       function In_Enclosing_Instance return Boolean is
5118          Enclosing_Instance : Node_Id;
5119          Instance_Decl      : Node_Id;
5120
5121       begin
5122          --  We do not inline any call that contains instantiations, except
5123          --  for instantiations of Unchecked_Conversion, so if we are within
5124          --  an inlined body the current instance does not require parents.
5125
5126          if In_Inlined_Body then
5127             pragma Assert (Chars (Gen_Id) = Name_Unchecked_Conversion);
5128             return False;
5129          end if;
5130
5131          --  Loop to check enclosing scopes
5132
5133          Enclosing_Instance := Current_Scope;
5134          while Present (Enclosing_Instance) loop
5135             Instance_Decl := Unit_Declaration_Node (Enclosing_Instance);
5136
5137             if Ekind (Enclosing_Instance) = E_Package
5138               and then Is_Generic_Instance (Enclosing_Instance)
5139               and then Present
5140                 (Generic_Parent (Specification (Instance_Decl)))
5141             then
5142                --  Check whether the generic we are looking for is a child of
5143                --  this instance.
5144
5145                E := Find_Generic_Child
5146                       (Generic_Parent (Specification (Instance_Decl)), Gen_Id);
5147                exit when Present (E);
5148
5149             else
5150                E := Empty;
5151             end if;
5152
5153             Enclosing_Instance := Scope (Enclosing_Instance);
5154          end loop;
5155
5156          if No (E) then
5157
5158             --  Not a child unit
5159
5160             Analyze (Gen_Id);
5161             return False;
5162
5163          else
5164             Rewrite (Gen_Id,
5165               Make_Expanded_Name (Loc,
5166                 Chars         => Chars (E),
5167                 Prefix        => New_Occurrence_Of (Enclosing_Instance, Loc),
5168                 Selector_Name => New_Occurrence_Of (E, Loc)));
5169
5170             Set_Entity (Gen_Id, E);
5171             Set_Etype  (Gen_Id, Etype (E));
5172             Parent_Installed := False;      -- Already in scope.
5173             return True;
5174          end if;
5175       end In_Enclosing_Instance;
5176
5177    --  Start of processing for Check_Generic_Child_Unit
5178
5179    begin
5180       --  If the name of the generic is given by a selected component, it may
5181       --  be the name of a generic child unit, and the prefix is the name of an
5182       --  instance of the parent, in which case the child unit must be visible.
5183       --  If this instance is not in scope, it must be placed there and removed
5184       --  after instantiation, because what is being instantiated is not the
5185       --  original child, but the corresponding child present in the instance
5186       --  of the parent.
5187
5188       --  If the child is instantiated within the parent, it can be given by
5189       --  a simple name. In this case the instance is already in scope, but
5190       --  the child generic must be recovered from the generic parent as well.
5191
5192       if Nkind (Gen_Id) = N_Selected_Component then
5193          S := Selector_Name (Gen_Id);
5194          Analyze (Prefix (Gen_Id));
5195          Inst_Par := Entity (Prefix (Gen_Id));
5196
5197          if Ekind (Inst_Par) = E_Package
5198            and then Present (Renamed_Object (Inst_Par))
5199          then
5200             Inst_Par := Renamed_Object (Inst_Par);
5201          end if;
5202
5203          if Ekind (Inst_Par) = E_Package then
5204             if Nkind (Parent (Inst_Par)) = N_Package_Specification then
5205                Gen_Par := Generic_Parent (Parent (Inst_Par));
5206
5207             elsif Nkind (Parent (Inst_Par)) = N_Defining_Program_Unit_Name
5208               and then
5209                 Nkind (Parent (Parent (Inst_Par))) = N_Package_Specification
5210             then
5211                Gen_Par := Generic_Parent (Parent (Parent (Inst_Par)));
5212             end if;
5213
5214          elsif Ekind (Inst_Par) = E_Generic_Package
5215            and then Nkind (Parent (Gen_Id)) = N_Formal_Package_Declaration
5216          then
5217             --  A formal package may be a real child package, and not the
5218             --  implicit instance within a parent. In this case the child is
5219             --  not visible and has to be retrieved explicitly as well.
5220
5221             Gen_Par := Inst_Par;
5222          end if;
5223
5224          if Present (Gen_Par) then
5225
5226             --  The prefix denotes an instantiation. The entity itself may be a
5227             --  nested generic, or a child unit.
5228
5229             E := Find_Generic_Child (Gen_Par, S);
5230
5231             if Present (E) then
5232                Change_Selected_Component_To_Expanded_Name (Gen_Id);
5233                Set_Entity (Gen_Id, E);
5234                Set_Etype (Gen_Id, Etype (E));
5235                Set_Entity (S, E);
5236                Set_Etype (S, Etype (E));
5237
5238                --  Indicate that this is a reference to the parent
5239
5240                if In_Extended_Main_Source_Unit (Gen_Id) then
5241                   Set_Is_Instantiated (Inst_Par);
5242                end if;
5243
5244                --  A common mistake is to replicate the naming scheme of a
5245                --  hierarchy by instantiating a generic child directly, rather
5246                --  than the implicit child in a parent instance:
5247
5248                --  generic .. package Gpar is ..
5249                --  generic .. package Gpar.Child is ..
5250                --  package Par is new Gpar ();
5251
5252                --  with Gpar.Child;
5253                --  package Par.Child is new Gpar.Child ();
5254                --                           rather than Par.Child
5255
5256                --  In this case the instantiation is within Par, which is an
5257                --  instance, but Gpar does not denote Par because we are not IN
5258                --  the instance of Gpar, so this is illegal. The test below
5259                --  recognizes this particular case.
5260
5261                if Is_Child_Unit (E)
5262                  and then not Comes_From_Source (Entity (Prefix (Gen_Id)))
5263                  and then (not In_Instance
5264                              or else Nkind (Parent (Parent (Gen_Id))) =
5265                                                          N_Compilation_Unit)
5266                then
5267                   Error_Msg_N
5268                     ("prefix of generic child unit must be instance of parent",
5269                       Gen_Id);
5270                end if;
5271
5272                if not In_Open_Scopes (Inst_Par)
5273                  and then Nkind (Parent (Gen_Id)) not in
5274                                            N_Generic_Renaming_Declaration
5275                then
5276                   Install_Parent (Inst_Par);
5277                   Parent_Installed := True;
5278
5279                elsif In_Open_Scopes (Inst_Par) then
5280
5281                   --  If the parent is already installed, install the actuals
5282                   --  for its formal packages. This is necessary when the
5283                   --  child instance is a child of the parent instance:
5284                   --  in this case, the parent is placed on the scope stack
5285                   --  but the formal packages are not made visible.
5286
5287                   Install_Formal_Packages (Inst_Par);
5288                end if;
5289
5290             else
5291                --  If the generic parent does not contain an entity that
5292                --  corresponds to the selector, the instance doesn't either.
5293                --  Analyzing the node will yield the appropriate error message.
5294                --  If the entity is not a child unit, then it is an inner
5295                --  generic in the parent.
5296
5297                Analyze (Gen_Id);
5298             end if;
5299
5300          else
5301             Analyze (Gen_Id);
5302
5303             if Is_Child_Unit (Entity (Gen_Id))
5304               and then
5305                 Nkind (Parent (Gen_Id)) not in N_Generic_Renaming_Declaration
5306               and then not In_Open_Scopes (Inst_Par)
5307             then
5308                Install_Parent (Inst_Par);
5309                Parent_Installed := True;
5310
5311             --  The generic unit may be the renaming of the implicit child
5312             --  present in an instance. In that case the parent instance is
5313             --  obtained from the name of the renamed entity.
5314
5315             elsif Ekind (Entity (Gen_Id)) = E_Generic_Package
5316               and then Present (Renamed_Entity (Entity (Gen_Id)))
5317               and then Is_Child_Unit (Renamed_Entity (Entity (Gen_Id)))
5318             then
5319                declare
5320                   Renamed_Package : constant Node_Id :=
5321                                       Name (Parent (Entity (Gen_Id)));
5322                begin
5323                   if Nkind (Renamed_Package) = N_Expanded_Name then
5324                      Inst_Par := Entity (Prefix (Renamed_Package));
5325                      Install_Parent (Inst_Par);
5326                      Parent_Installed := True;
5327                   end if;
5328                end;
5329             end if;
5330          end if;
5331
5332       elsif Nkind (Gen_Id) = N_Expanded_Name then
5333
5334          --  Entity already present, analyze prefix, whose meaning may be
5335          --  an instance in the current context. If it is an instance of
5336          --  a relative within another, the proper parent may still have
5337          --  to be installed, if they are not of the same generation.
5338
5339          Analyze (Prefix (Gen_Id));
5340
5341          --  In the unlikely case that a local declaration hides the name
5342          --  of the parent package, locate it on the homonym chain. If the
5343          --  context is an instance of the parent, the renaming entity is
5344          --  flagged as such.
5345
5346          Inst_Par := Entity (Prefix (Gen_Id));
5347          while Present (Inst_Par)
5348            and then not Is_Package_Or_Generic_Package (Inst_Par)
5349          loop
5350             Inst_Par := Homonym (Inst_Par);
5351          end loop;
5352
5353          pragma Assert (Present (Inst_Par));
5354          Set_Entity (Prefix (Gen_Id), Inst_Par);
5355
5356          if In_Enclosing_Instance then
5357             null;
5358
5359          elsif Present (Entity (Gen_Id))
5360            and then Is_Child_Unit (Entity (Gen_Id))
5361            and then not In_Open_Scopes (Inst_Par)
5362          then
5363             Install_Parent (Inst_Par);
5364             Parent_Installed := True;
5365          end if;
5366
5367       elsif In_Enclosing_Instance then
5368
5369          --  The child unit is found in some enclosing scope
5370
5371          null;
5372
5373       else
5374          Analyze (Gen_Id);
5375
5376          --  If this is the renaming of the implicit child in a parent
5377          --  instance, recover the parent name and install it.
5378
5379          if Is_Entity_Name (Gen_Id) then
5380             E := Entity (Gen_Id);
5381
5382             if Is_Generic_Unit (E)
5383               and then Nkind (Parent (E)) in N_Generic_Renaming_Declaration
5384               and then Is_Child_Unit (Renamed_Object (E))
5385               and then Is_Generic_Unit (Scope (Renamed_Object (E)))
5386               and then Nkind (Name (Parent (E))) = N_Expanded_Name
5387             then
5388                Rewrite (Gen_Id,
5389                  New_Copy_Tree (Name (Parent (E))));
5390                Inst_Par := Entity (Prefix (Gen_Id));
5391
5392                if not In_Open_Scopes (Inst_Par) then
5393                   Install_Parent (Inst_Par);
5394                   Parent_Installed := True;
5395                end if;
5396
5397             --  If it is a child unit of a non-generic parent, it may be
5398             --  use-visible and given by a direct name. Install parent as
5399             --  for other cases.
5400
5401             elsif Is_Generic_Unit (E)
5402               and then Is_Child_Unit (E)
5403               and then
5404                 Nkind (Parent (Gen_Id)) not in N_Generic_Renaming_Declaration
5405               and then not Is_Generic_Unit (Scope (E))
5406             then
5407                if not In_Open_Scopes (Scope (E)) then
5408                   Install_Parent (Scope (E));
5409                   Parent_Installed := True;
5410                end if;
5411             end if;
5412          end if;
5413       end if;
5414    end Check_Generic_Child_Unit;
5415
5416    -----------------------------
5417    -- Check_Hidden_Child_Unit --
5418    -----------------------------
5419
5420    procedure Check_Hidden_Child_Unit
5421      (N           : Node_Id;
5422       Gen_Unit    : Entity_Id;
5423       Act_Decl_Id : Entity_Id)
5424    is
5425       Gen_Id : constant Node_Id := Name (N);
5426
5427    begin
5428       if Is_Child_Unit (Gen_Unit)
5429         and then Is_Child_Unit (Act_Decl_Id)
5430         and then Nkind (Gen_Id) = N_Expanded_Name
5431         and then Entity (Prefix (Gen_Id)) = Scope (Act_Decl_Id)
5432         and then Chars (Gen_Unit) = Chars (Act_Decl_Id)
5433       then
5434          Error_Msg_Node_2 := Scope (Act_Decl_Id);
5435          Error_Msg_NE
5436            ("generic unit & is implicitly declared in &",
5437              Defining_Unit_Name (N), Gen_Unit);
5438          Error_Msg_N ("\instance must have different name",
5439            Defining_Unit_Name (N));
5440       end if;
5441    end Check_Hidden_Child_Unit;
5442
5443    ------------------------
5444    -- Check_Private_View --
5445    ------------------------
5446
5447    procedure Check_Private_View (N : Node_Id) is
5448       T : constant Entity_Id := Etype (N);
5449       BT : Entity_Id;
5450
5451    begin
5452       --  Exchange views if the type was not private in the generic but is
5453       --  private at the point of instantiation. Do not exchange views if
5454       --  the scope of the type is in scope. This can happen if both generic
5455       --  and instance are sibling units, or if type is defined in a parent.
5456       --  In this case the visibility of the type will be correct for all
5457       --  semantic checks.
5458
5459       if Present (T) then
5460          BT := Base_Type (T);
5461
5462          if Is_Private_Type (T)
5463            and then not Has_Private_View (N)
5464            and then Present (Full_View (T))
5465            and then not In_Open_Scopes (Scope (T))
5466          then
5467             --  In the generic, the full type was visible. Save the private
5468             --  entity, for subsequent exchange.
5469
5470             Switch_View (T);
5471
5472          elsif Has_Private_View (N)
5473            and then not Is_Private_Type (T)
5474            and then not Has_Been_Exchanged (T)
5475            and then Etype (Get_Associated_Node (N)) /= T
5476          then
5477             --  Only the private declaration was visible in the generic. If
5478             --  the type appears in a subtype declaration, the subtype in the
5479             --  instance must have a view compatible with that of its parent,
5480             --  which must be exchanged (see corresponding code in Restore_
5481             --  Private_Views). Otherwise, if the type is defined in a parent
5482             --  unit, leave full visibility within instance, which is safe.
5483
5484             if In_Open_Scopes (Scope (Base_Type (T)))
5485               and then not Is_Private_Type (Base_Type (T))
5486               and then Comes_From_Source (Base_Type (T))
5487             then
5488                null;
5489
5490             elsif Nkind (Parent (N)) = N_Subtype_Declaration
5491               or else not In_Private_Part (Scope (Base_Type (T)))
5492             then
5493                Prepend_Elmt (T, Exchanged_Views);
5494                Exchange_Declarations (Etype (Get_Associated_Node (N)));
5495             end if;
5496
5497          --  For composite types with inconsistent representation exchange
5498          --  component types accordingly.
5499
5500          elsif Is_Access_Type (T)
5501            and then Is_Private_Type (Designated_Type (T))
5502            and then not Has_Private_View (N)
5503            and then Present (Full_View (Designated_Type (T)))
5504            and then Used_As_Generic_Actual (T)
5505          then
5506             Switch_View (Designated_Type (T));
5507
5508          elsif Is_Array_Type (T) then
5509             if Is_Private_Type (Component_Type (T))
5510               and then not Has_Private_View (N)
5511               and then Present (Full_View (Component_Type (T)))
5512             then
5513                Switch_View (Component_Type (T));
5514             end if;
5515
5516             --  The normal exchange mechanism relies on the setting of a
5517             --  flag on the reference in the generic. However, an additional
5518             --  mechanism is needed for types that are not explicitly mentioned
5519             --  in the generic, but may be needed in expanded code in the
5520             --  instance. This includes component types of arrays and
5521             --  designated types of access types. This processing must also
5522             --  include the index types of arrays which we take care of here.
5523
5524             declare
5525                Indx : Node_Id;
5526                Typ  : Entity_Id;
5527
5528             begin
5529                Indx := First_Index (T);
5530                Typ  := Base_Type (Etype (Indx));
5531                while Present (Indx) loop
5532                   if Is_Private_Type (Typ)
5533                     and then Present (Full_View (Typ))
5534                   then
5535                      Switch_View (Typ);
5536                   end if;
5537
5538                   Next_Index (Indx);
5539                end loop;
5540             end;
5541
5542          elsif Is_Private_Type (T)
5543            and then Present (Full_View (T))
5544            and then Is_Array_Type (Full_View (T))
5545            and then Is_Private_Type (Component_Type (Full_View (T)))
5546          then
5547             Switch_View (T);
5548
5549          --  Finally, a non-private subtype may have a private base type, which
5550          --  must be exchanged for consistency. This can happen when a package
5551          --  body is instantiated, when the scope stack is empty but in fact
5552          --  the subtype and the base type are declared in an enclosing scope.
5553
5554          --  Note that in this case we introduce an inconsistency in the view
5555          --  set, because we switch the base type BT, but there could be some
5556          --  private dependent subtypes of BT which remain unswitched. Such
5557          --  subtypes might need to be switched at a later point (see specific
5558          --  provision for that case in Switch_View).
5559
5560          elsif not Is_Private_Type (T)
5561            and then not Has_Private_View (N)
5562            and then Is_Private_Type (BT)
5563            and then Present (Full_View (BT))
5564            and then not Is_Generic_Type (BT)
5565            and then not In_Open_Scopes (BT)
5566          then
5567             Prepend_Elmt (Full_View (BT), Exchanged_Views);
5568             Exchange_Declarations (BT);
5569          end if;
5570       end if;
5571    end Check_Private_View;
5572
5573    --------------------------
5574    -- Contains_Instance_Of --
5575    --------------------------
5576
5577    function Contains_Instance_Of
5578      (Inner : Entity_Id;
5579       Outer : Entity_Id;
5580       N     : Node_Id) return Boolean
5581    is
5582       Elmt : Elmt_Id;
5583       Scop : Entity_Id;
5584
5585    begin
5586       Scop := Outer;
5587
5588       --  Verify that there are no circular instantiations. We check whether
5589       --  the unit contains an instance of the current scope or some enclosing
5590       --  scope (in case one of the instances appears in a subunit). Longer
5591       --  circularities involving subunits might seem too pathological to
5592       --  consider, but they were not too pathological for the authors of
5593       --  DEC bc30vsq, so we loop over all enclosing scopes, and mark all
5594       --  enclosing generic scopes as containing an instance.
5595
5596       loop
5597          --  Within a generic subprogram body, the scope is not generic, to
5598          --  allow for recursive subprograms. Use the declaration to determine
5599          --  whether this is a generic unit.
5600
5601          if Ekind (Scop) = E_Generic_Package
5602            or else (Is_Subprogram (Scop)
5603                       and then Nkind (Unit_Declaration_Node (Scop)) =
5604                                         N_Generic_Subprogram_Declaration)
5605          then
5606             Elmt := First_Elmt (Inner_Instances (Inner));
5607
5608             while Present (Elmt) loop
5609                if Node (Elmt) = Scop then
5610                   Error_Msg_Node_2 := Inner;
5611                   Error_Msg_NE
5612                     ("circular Instantiation: & instantiated within &!",
5613                        N, Scop);
5614                   return True;
5615
5616                elsif Node (Elmt) = Inner then
5617                   return True;
5618
5619                elsif Contains_Instance_Of (Node (Elmt), Scop, N) then
5620                   Error_Msg_Node_2 := Inner;
5621                   Error_Msg_NE
5622                     ("circular Instantiation: & instantiated within &!",
5623                       N, Node (Elmt));
5624                   return True;
5625                end if;
5626
5627                Next_Elmt (Elmt);
5628             end loop;
5629
5630             --  Indicate that Inner is being instantiated within Scop
5631
5632             Append_Elmt (Inner, Inner_Instances (Scop));
5633          end if;
5634
5635          if Scop = Standard_Standard then
5636             exit;
5637          else
5638             Scop := Scope (Scop);
5639          end if;
5640       end loop;
5641
5642       return False;
5643    end Contains_Instance_Of;
5644
5645    -----------------------
5646    -- Copy_Generic_Node --
5647    -----------------------
5648
5649    function Copy_Generic_Node
5650      (N             : Node_Id;
5651       Parent_Id     : Node_Id;
5652       Instantiating : Boolean) return Node_Id
5653    is
5654       Ent   : Entity_Id;
5655       New_N : Node_Id;
5656
5657       function Copy_Generic_Descendant (D : Union_Id) return Union_Id;
5658       --  Check the given value of one of the Fields referenced by the
5659       --  current node to determine whether to copy it recursively. The
5660       --  field may hold a Node_Id, a List_Id, or an Elist_Id, or a plain
5661       --  value (Sloc, Uint, Char) in which case it need not be copied.
5662
5663       procedure Copy_Descendants;
5664       --  Common utility for various nodes
5665
5666       function Copy_Generic_Elist (E : Elist_Id) return Elist_Id;
5667       --  Make copy of element list
5668
5669       function Copy_Generic_List
5670         (L         : List_Id;
5671          Parent_Id : Node_Id) return List_Id;
5672       --  Apply Copy_Node recursively to the members of a node list
5673
5674       function In_Defining_Unit_Name (Nam : Node_Id) return Boolean;
5675       --  True if an identifier is part of the defining program unit name
5676       --  of a child unit. The entity of such an identifier must be kept
5677       --  (for ASIS use) even though as the name of an enclosing generic
5678       --   it would otherwise not be preserved in the generic tree.
5679
5680       ----------------------
5681       -- Copy_Descendants --
5682       ----------------------
5683
5684       procedure Copy_Descendants is
5685
5686          use Atree.Unchecked_Access;
5687          --  This code section is part of the implementation of an untyped
5688          --  tree traversal, so it needs direct access to node fields.
5689
5690       begin
5691          Set_Field1 (New_N, Copy_Generic_Descendant (Field1 (N)));
5692          Set_Field2 (New_N, Copy_Generic_Descendant (Field2 (N)));
5693          Set_Field3 (New_N, Copy_Generic_Descendant (Field3 (N)));
5694          Set_Field4 (New_N, Copy_Generic_Descendant (Field4 (N)));
5695          Set_Field5 (New_N, Copy_Generic_Descendant (Field5 (N)));
5696       end Copy_Descendants;
5697
5698       -----------------------------
5699       -- Copy_Generic_Descendant --
5700       -----------------------------
5701
5702       function Copy_Generic_Descendant (D : Union_Id) return Union_Id is
5703       begin
5704          if D = Union_Id (Empty) then
5705             return D;
5706
5707          elsif D in Node_Range then
5708             return Union_Id
5709               (Copy_Generic_Node (Node_Id (D), New_N, Instantiating));
5710
5711          elsif D in List_Range then
5712             return Union_Id (Copy_Generic_List (List_Id (D), New_N));
5713
5714          elsif D in Elist_Range then
5715             return Union_Id (Copy_Generic_Elist (Elist_Id (D)));
5716
5717          --  Nothing else is copyable (e.g. Uint values), return as is
5718
5719          else
5720             return D;
5721          end if;
5722       end Copy_Generic_Descendant;
5723
5724       ------------------------
5725       -- Copy_Generic_Elist --
5726       ------------------------
5727
5728       function Copy_Generic_Elist (E : Elist_Id) return Elist_Id is
5729          M : Elmt_Id;
5730          L : Elist_Id;
5731
5732       begin
5733          if Present (E) then
5734             L := New_Elmt_List;
5735             M := First_Elmt (E);
5736             while Present (M) loop
5737                Append_Elmt
5738                  (Copy_Generic_Node (Node (M), Empty, Instantiating), L);
5739                Next_Elmt (M);
5740             end loop;
5741
5742             return L;
5743
5744          else
5745             return No_Elist;
5746          end if;
5747       end Copy_Generic_Elist;
5748
5749       -----------------------
5750       -- Copy_Generic_List --
5751       -----------------------
5752
5753       function Copy_Generic_List
5754         (L         : List_Id;
5755          Parent_Id : Node_Id) return List_Id
5756       is
5757          N     : Node_Id;
5758          New_L : List_Id;
5759
5760       begin
5761          if Present (L) then
5762             New_L := New_List;
5763             Set_Parent (New_L, Parent_Id);
5764
5765             N := First (L);
5766             while Present (N) loop
5767                Append (Copy_Generic_Node (N, Empty, Instantiating), New_L);
5768                Next (N);
5769             end loop;
5770
5771             return New_L;
5772
5773          else
5774             return No_List;
5775          end if;
5776       end Copy_Generic_List;
5777
5778       ---------------------------
5779       -- In_Defining_Unit_Name --
5780       ---------------------------
5781
5782       function In_Defining_Unit_Name (Nam : Node_Id) return Boolean is
5783       begin
5784          return Present (Parent (Nam))
5785            and then (Nkind (Parent (Nam)) = N_Defining_Program_Unit_Name
5786                       or else
5787                         (Nkind (Parent (Nam)) = N_Expanded_Name
5788                           and then In_Defining_Unit_Name (Parent (Nam))));
5789       end In_Defining_Unit_Name;
5790
5791    --  Start of processing for Copy_Generic_Node
5792
5793    begin
5794       if N = Empty then
5795          return N;
5796       end if;
5797
5798       New_N := New_Copy (N);
5799
5800       --  Copy aspects if present
5801
5802       if Has_Aspects (N) then
5803          Set_Has_Aspects (New_N, False);
5804          Set_Aspect_Specifications
5805            (New_N, Copy_Generic_List (Aspect_Specifications (N), Parent_Id));
5806       end if;
5807
5808       if Instantiating then
5809          Adjust_Instantiation_Sloc (New_N, S_Adjustment);
5810       end if;
5811
5812       if not Is_List_Member (N) then
5813          Set_Parent (New_N, Parent_Id);
5814       end if;
5815
5816       --  If defining identifier, then all fields have been copied already
5817
5818       if Nkind (New_N) in N_Entity then
5819          null;
5820
5821       --  Special casing for identifiers and other entity names and operators
5822
5823       elsif Nkind_In (New_N, N_Identifier,
5824                              N_Character_Literal,
5825                              N_Expanded_Name,
5826                              N_Operator_Symbol)
5827         or else Nkind (New_N) in N_Op
5828       then
5829          if not Instantiating then
5830
5831             --  Link both nodes in order to assign subsequently the entity of
5832             --  the copy to the original node, in case this is a global
5833             --  reference.
5834
5835             Set_Associated_Node (N, New_N);
5836
5837             --  If we are within an instantiation, this is a nested generic
5838             --  that has already been analyzed at the point of definition. We
5839             --  must preserve references that were global to the enclosing
5840             --  parent at that point. Other occurrences, whether global or
5841             --  local to the current generic, must be resolved anew, so we
5842             --  reset the entity in the generic copy. A global reference has a
5843             --  smaller depth than the parent, or else the same depth in case
5844             --  both are distinct compilation units.
5845             --  A child unit is implicitly declared within the enclosing parent
5846             --  but is in fact global to it, and must be preserved.
5847
5848             --  It is also possible for Current_Instantiated_Parent to be
5849             --  defined, and for this not to be a nested generic, namely if the
5850             --  unit is loaded through Rtsfind. In that case, the entity of
5851             --  New_N is only a link to the associated node, and not a defining
5852             --  occurrence.
5853
5854             --  The entities for parent units in the defining_program_unit of a
5855             --  generic child unit are established when the context of the unit
5856             --  is first analyzed, before the generic copy is made. They are
5857             --  preserved in the copy for use in ASIS queries.
5858
5859             Ent := Entity (New_N);
5860
5861             if No (Current_Instantiated_Parent.Gen_Id) then
5862                if No (Ent)
5863                  or else Nkind (Ent) /= N_Defining_Identifier
5864                  or else not In_Defining_Unit_Name (N)
5865                then
5866                   Set_Associated_Node (New_N, Empty);
5867                end if;
5868
5869             elsif No (Ent)
5870               or else
5871                 not Nkind_In (Ent, N_Defining_Identifier,
5872                                    N_Defining_Character_Literal,
5873                                    N_Defining_Operator_Symbol)
5874               or else No (Scope (Ent))
5875               or else
5876                 (Scope (Ent) = Current_Instantiated_Parent.Gen_Id
5877                   and then not Is_Child_Unit (Ent))
5878               or else
5879                 (Scope_Depth (Scope (Ent)) >
5880                              Scope_Depth (Current_Instantiated_Parent.Gen_Id)
5881                   and then
5882                     Get_Source_Unit (Ent) =
5883                     Get_Source_Unit (Current_Instantiated_Parent.Gen_Id))
5884             then
5885                Set_Associated_Node (New_N, Empty);
5886             end if;
5887
5888          --  Case of instantiating identifier or some other name or operator
5889
5890          else
5891             --  If the associated node is still defined, the entity in it is
5892             --  global, and must be copied to the instance. If this copy is
5893             --  being made for a body to inline, it is applied to an
5894             --  instantiated tree, and the entity is already present and must
5895             --  be also preserved.
5896
5897             declare
5898                Assoc : constant Node_Id := Get_Associated_Node (N);
5899
5900             begin
5901                if Present (Assoc) then
5902                   if Nkind (Assoc) = Nkind (N) then
5903                      Set_Entity (New_N, Entity (Assoc));
5904                      Check_Private_View (N);
5905
5906                   elsif Nkind (Assoc) = N_Function_Call then
5907                      Set_Entity (New_N, Entity (Name (Assoc)));
5908
5909                   elsif Nkind_In (Assoc, N_Defining_Identifier,
5910                                          N_Defining_Character_Literal,
5911                                          N_Defining_Operator_Symbol)
5912                     and then Expander_Active
5913                   then
5914                      --  Inlining case: we are copying a tree that contains
5915                      --  global entities, which are preserved in the copy to be
5916                      --  used for subsequent inlining.
5917
5918                      null;
5919
5920                   else
5921                      Set_Entity (New_N, Empty);
5922                   end if;
5923                end if;
5924             end;
5925          end if;
5926
5927          --  For expanded name, we must copy the Prefix and Selector_Name
5928
5929          if Nkind (N) = N_Expanded_Name then
5930             Set_Prefix
5931               (New_N, Copy_Generic_Node (Prefix (N), New_N, Instantiating));
5932
5933             Set_Selector_Name (New_N,
5934               Copy_Generic_Node (Selector_Name (N), New_N, Instantiating));
5935
5936          --  For operators, we must copy the right operand
5937
5938          elsif Nkind (N) in N_Op then
5939             Set_Right_Opnd (New_N,
5940               Copy_Generic_Node (Right_Opnd (N), New_N, Instantiating));
5941
5942             --  And for binary operators, the left operand as well
5943
5944             if Nkind (N) in N_Binary_Op then
5945                Set_Left_Opnd (New_N,
5946                  Copy_Generic_Node (Left_Opnd (N), New_N, Instantiating));
5947             end if;
5948          end if;
5949
5950       --  Special casing for stubs
5951
5952       elsif Nkind (N) in N_Body_Stub then
5953
5954          --  In any case, we must copy the specification or defining
5955          --  identifier as appropriate.
5956
5957          if Nkind (N) = N_Subprogram_Body_Stub then
5958             Set_Specification (New_N,
5959               Copy_Generic_Node (Specification (N), New_N, Instantiating));
5960
5961          else
5962             Set_Defining_Identifier (New_N,
5963               Copy_Generic_Node
5964                 (Defining_Identifier (N), New_N, Instantiating));
5965          end if;
5966
5967          --  If we are not instantiating, then this is where we load and
5968          --  analyze subunits, i.e. at the point where the stub occurs. A
5969          --  more permissive system might defer this analysis to the point
5970          --  of instantiation, but this seems to complicated for now.
5971
5972          if not Instantiating then
5973             declare
5974                Subunit_Name : constant Unit_Name_Type := Get_Unit_Name (N);
5975                Subunit      : Node_Id;
5976                Unum         : Unit_Number_Type;
5977                New_Body     : Node_Id;
5978
5979             begin
5980                --  Make sure that, if it is a subunit of the main unit that is
5981                --  preprocessed and if -gnateG is specified, the preprocessed
5982                --  file will be written.
5983
5984                Lib.Analysing_Subunit_Of_Main :=
5985                  Lib.In_Extended_Main_Source_Unit (N);
5986                Unum :=
5987                  Load_Unit
5988                    (Load_Name  => Subunit_Name,
5989                     Required   => False,
5990                     Subunit    => True,
5991                     Error_Node => N);
5992                Lib.Analysing_Subunit_Of_Main := False;
5993
5994                --  If the proper body is not found, a warning message will be
5995                --  emitted when analyzing the stub, or later at the point
5996                --  of instantiation. Here we just leave the stub as is.
5997
5998                if Unum = No_Unit then
5999                   Subunits_Missing := True;
6000                   goto Subunit_Not_Found;
6001                end if;
6002
6003                Subunit := Cunit (Unum);
6004
6005                if Nkind (Unit (Subunit)) /= N_Subunit then
6006                   Error_Msg_N
6007                     ("found child unit instead of expected SEPARATE subunit",
6008                      Subunit);
6009                   Error_Msg_Sloc := Sloc (N);
6010                   Error_Msg_N ("\to complete stub #", Subunit);
6011                   goto Subunit_Not_Found;
6012                end if;
6013
6014                --  We must create a generic copy of the subunit, in order to
6015                --  perform semantic analysis on it, and we must replace the
6016                --  stub in the original generic unit with the subunit, in order
6017                --  to preserve non-local references within.
6018
6019                --  Only the proper body needs to be copied. Library_Unit and
6020                --  context clause are simply inherited by the generic copy.
6021                --  Note that the copy (which may be recursive if there are
6022                --  nested subunits) must be done first, before attaching it to
6023                --  the enclosing generic.
6024
6025                New_Body :=
6026                  Copy_Generic_Node
6027                    (Proper_Body (Unit (Subunit)),
6028                     Empty, Instantiating => False);
6029
6030                --  Now place the original proper body in the original generic
6031                --  unit. This is a body, not a compilation unit.
6032
6033                Rewrite (N, Proper_Body (Unit (Subunit)));
6034                Set_Is_Compilation_Unit (Defining_Entity (N), False);
6035                Set_Was_Originally_Stub (N);
6036
6037                --  Finally replace the body of the subunit with its copy, and
6038                --  make this new subunit into the library unit of the generic
6039                --  copy, which does not have stubs any longer.
6040
6041                Set_Proper_Body (Unit (Subunit), New_Body);
6042                Set_Library_Unit (New_N, Subunit);
6043                Inherit_Context (Unit (Subunit), N);
6044             end;
6045
6046          --  If we are instantiating, this must be an error case, since
6047          --  otherwise we would have replaced the stub node by the proper body
6048          --  that corresponds. So just ignore it in the copy (i.e. we have
6049          --  copied it, and that is good enough).
6050
6051          else
6052             null;
6053          end if;
6054
6055          <<Subunit_Not_Found>> null;
6056
6057       --  If the node is a compilation unit, it is the subunit of a stub, which
6058       --  has been loaded already (see code below). In this case, the library
6059       --  unit field of N points to the parent unit (which is a compilation
6060       --  unit) and need not (and cannot!) be copied.
6061
6062       --  When the proper body of the stub is analyzed, the library_unit link
6063       --  is used to establish the proper context (see sem_ch10).
6064
6065       --  The other fields of a compilation unit are copied as usual
6066
6067       elsif Nkind (N) = N_Compilation_Unit then
6068
6069          --  This code can only be executed when not instantiating, because in
6070          --  the copy made for an instantiation, the compilation unit node has
6071          --  disappeared at the point that a stub is replaced by its proper
6072          --  body.
6073
6074          pragma Assert (not Instantiating);
6075
6076          Set_Context_Items (New_N,
6077            Copy_Generic_List (Context_Items (N), New_N));
6078
6079          Set_Unit (New_N,
6080            Copy_Generic_Node (Unit (N), New_N, False));
6081
6082          Set_First_Inlined_Subprogram (New_N,
6083            Copy_Generic_Node
6084              (First_Inlined_Subprogram (N), New_N, False));
6085
6086          Set_Aux_Decls_Node (New_N,
6087            Copy_Generic_Node (Aux_Decls_Node (N), New_N, False));
6088
6089       --  For an assignment node, the assignment is known to be semantically
6090       --  legal if we are instantiating the template. This avoids incorrect
6091       --  diagnostics in generated code.
6092
6093       elsif Nkind (N) = N_Assignment_Statement then
6094
6095          --  Copy name and expression fields in usual manner
6096
6097          Set_Name (New_N,
6098            Copy_Generic_Node (Name (N), New_N, Instantiating));
6099
6100          Set_Expression (New_N,
6101            Copy_Generic_Node (Expression (N), New_N, Instantiating));
6102
6103          if Instantiating then
6104             Set_Assignment_OK (Name (New_N), True);
6105          end if;
6106
6107       elsif Nkind_In (N, N_Aggregate, N_Extension_Aggregate) then
6108          if not Instantiating then
6109             Set_Associated_Node (N, New_N);
6110
6111          else
6112             if Present (Get_Associated_Node (N))
6113               and then Nkind (Get_Associated_Node (N)) = Nkind (N)
6114             then
6115                --  In the generic the aggregate has some composite type. If at
6116                --  the point of instantiation the type has a private view,
6117                --  install the full view (and that of its ancestors, if any).
6118
6119                declare
6120                   T   : Entity_Id := (Etype (Get_Associated_Node (New_N)));
6121                   Rt  : Entity_Id;
6122
6123                begin
6124                   if Present (T)
6125                     and then Is_Private_Type (T)
6126                   then
6127                      Switch_View (T);
6128                   end if;
6129
6130                   if Present (T)
6131                     and then Is_Tagged_Type (T)
6132                     and then Is_Derived_Type (T)
6133                   then
6134                      Rt := Root_Type (T);
6135
6136                      loop
6137                         T := Etype (T);
6138
6139                         if Is_Private_Type (T) then
6140                            Switch_View (T);
6141                         end if;
6142
6143                         exit when T = Rt;
6144                      end loop;
6145                   end if;
6146                end;
6147             end if;
6148          end if;
6149
6150          --  Do not copy the associated node, which points to
6151          --  the generic copy of the aggregate.
6152
6153          declare
6154             use Atree.Unchecked_Access;
6155             --  This code section is part of the implementation of an untyped
6156             --  tree traversal, so it needs direct access to node fields.
6157
6158          begin
6159             Set_Field1 (New_N, Copy_Generic_Descendant (Field1 (N)));
6160             Set_Field2 (New_N, Copy_Generic_Descendant (Field2 (N)));
6161             Set_Field3 (New_N, Copy_Generic_Descendant (Field3 (N)));
6162             Set_Field5 (New_N, Copy_Generic_Descendant (Field5 (N)));
6163          end;
6164
6165       --  Allocators do not have an identifier denoting the access type,
6166       --  so we must locate it through the expression to check whether
6167       --  the views are consistent.
6168
6169       elsif Nkind (N) = N_Allocator
6170         and then Nkind (Expression (N)) = N_Qualified_Expression
6171         and then Is_Entity_Name (Subtype_Mark (Expression (N)))
6172         and then Instantiating
6173       then
6174          declare
6175             T     : constant Node_Id :=
6176                       Get_Associated_Node (Subtype_Mark (Expression (N)));
6177             Acc_T : Entity_Id;
6178
6179          begin
6180             if Present (T) then
6181
6182                --  Retrieve the allocator node in the generic copy
6183
6184                Acc_T := Etype (Parent (Parent (T)));
6185                if Present (Acc_T)
6186                  and then Is_Private_Type (Acc_T)
6187                then
6188                   Switch_View (Acc_T);
6189                end if;
6190             end if;
6191
6192             Copy_Descendants;
6193          end;
6194
6195       --  For a proper body, we must catch the case of a proper body that
6196       --  replaces a stub. This represents the point at which a separate
6197       --  compilation unit, and hence template file, may be referenced, so we
6198       --  must make a new source instantiation entry for the template of the
6199       --  subunit, and ensure that all nodes in the subunit are adjusted using
6200       --  this new source instantiation entry.
6201
6202       elsif Nkind (N) in N_Proper_Body then
6203          declare
6204             Save_Adjustment : constant Sloc_Adjustment := S_Adjustment;
6205
6206          begin
6207             if Instantiating and then Was_Originally_Stub (N) then
6208                Create_Instantiation_Source
6209                  (Instantiation_Node,
6210                   Defining_Entity (N),
6211                   False,
6212                   S_Adjustment);
6213             end if;
6214
6215             --  Now copy the fields of the proper body, using the new
6216             --  adjustment factor if one was needed as per test above.
6217
6218             Copy_Descendants;
6219
6220             --  Restore the original adjustment factor in case changed
6221
6222             S_Adjustment := Save_Adjustment;
6223          end;
6224
6225       --  Don't copy Ident or Comment pragmas, since the comment belongs to the
6226       --  generic unit, not to the instantiating unit.
6227
6228       elsif Nkind (N) = N_Pragma
6229         and then Instantiating
6230       then
6231          declare
6232             Prag_Id : constant Pragma_Id := Get_Pragma_Id (N);
6233          begin
6234             if Prag_Id = Pragma_Ident
6235               or else Prag_Id = Pragma_Comment
6236             then
6237                New_N := Make_Null_Statement (Sloc (N));
6238             else
6239                Copy_Descendants;
6240             end if;
6241          end;
6242
6243       elsif Nkind_In (N, N_Integer_Literal, N_Real_Literal) then
6244
6245          --  No descendant fields need traversing
6246
6247          null;
6248
6249       elsif Nkind (N) = N_String_Literal
6250         and then Present (Etype (N))
6251         and then Instantiating
6252       then
6253          --  If the string is declared in an outer scope, the string_literal
6254          --  subtype created for it may have the wrong scope. We force the
6255          --  reanalysis of the constant to generate a new itype in the proper
6256          --  context.
6257
6258          Set_Etype (New_N, Empty);
6259          Set_Analyzed (New_N, False);
6260
6261       --  For the remaining nodes, copy their descendants recursively
6262
6263       else
6264          Copy_Descendants;
6265
6266          if Instantiating
6267            and then Nkind (N) = N_Subprogram_Body
6268          then
6269             Set_Generic_Parent (Specification (New_N), N);
6270          end if;
6271       end if;
6272
6273       return New_N;
6274    end Copy_Generic_Node;
6275
6276    ----------------------------
6277    -- Denotes_Formal_Package --
6278    ----------------------------
6279
6280    function Denotes_Formal_Package
6281      (Pack     : Entity_Id;
6282       On_Exit  : Boolean := False;
6283       Instance : Entity_Id := Empty) return Boolean
6284    is
6285       Par  : Entity_Id;
6286       Scop : constant Entity_Id := Scope (Pack);
6287       E    : Entity_Id;
6288
6289       function Is_Actual_Of_Previous_Formal (P : Entity_Id) return Boolean;
6290       --  The package in question may be an actual for a previous formal
6291       --  package P of the current instance, so examine its actuals as well.
6292       --  This must be recursive over other formal packages.
6293
6294       ----------------------------------
6295       -- Is_Actual_Of_Previous_Formal --
6296       ----------------------------------
6297
6298       function Is_Actual_Of_Previous_Formal (P : Entity_Id) return Boolean is
6299          E1 : Entity_Id;
6300
6301       begin
6302          E1 := First_Entity (P);
6303          while Present (E1) and then  E1 /= Instance loop
6304             if Ekind (E1) = E_Package
6305               and then Nkind (Parent (E1)) = N_Package_Renaming_Declaration
6306             then
6307                if Renamed_Object (E1) = Pack then
6308                   return True;
6309
6310                elsif E1 = P
6311                  or else  Renamed_Object (E1) = P
6312                then
6313                   return False;
6314
6315                elsif Is_Actual_Of_Previous_Formal (E1) then
6316                   return True;
6317                end if;
6318             end if;
6319
6320             Next_Entity (E1);
6321          end loop;
6322
6323          return False;
6324       end Is_Actual_Of_Previous_Formal;
6325
6326    --  Start of processing for Denotes_Formal_Package
6327
6328    begin
6329       if On_Exit then
6330          Par :=
6331            Instance_Envs.Table
6332              (Instance_Envs.Last).Instantiated_Parent.Act_Id;
6333       else
6334          Par  := Current_Instantiated_Parent.Act_Id;
6335       end if;
6336
6337       if Ekind (Scop) = E_Generic_Package
6338         or else Nkind (Unit_Declaration_Node (Scop)) =
6339                                          N_Generic_Subprogram_Declaration
6340       then
6341          return True;
6342
6343       elsif Nkind (Original_Node (Unit_Declaration_Node (Pack))) =
6344         N_Formal_Package_Declaration
6345       then
6346          return True;
6347
6348       elsif No (Par) then
6349          return False;
6350
6351       else
6352          --  Check whether this package is associated with a formal package of
6353          --  the enclosing instantiation. Iterate over the list of renamings.
6354
6355          E := First_Entity (Par);
6356          while Present (E) loop
6357             if Ekind (E) /= E_Package
6358               or else Nkind (Parent (E)) /= N_Package_Renaming_Declaration
6359             then
6360                null;
6361
6362             elsif Renamed_Object (E) = Par then
6363                return False;
6364
6365             elsif Renamed_Object (E) = Pack then
6366                return True;
6367
6368             elsif Is_Actual_Of_Previous_Formal (E) then
6369                return True;
6370
6371             end if;
6372
6373             Next_Entity (E);
6374          end loop;
6375
6376          return False;
6377       end if;
6378    end Denotes_Formal_Package;
6379
6380    -----------------
6381    -- End_Generic --
6382    -----------------
6383
6384    procedure End_Generic is
6385    begin
6386       --  ??? More things could be factored out in this routine. Should
6387       --  probably be done at a later stage.
6388
6389       Inside_A_Generic := Generic_Flags.Table (Generic_Flags.Last);
6390       Generic_Flags.Decrement_Last;
6391
6392       Expander_Mode_Restore;
6393    end End_Generic;
6394
6395    ----------------------
6396    -- Find_Actual_Type --
6397    ----------------------
6398
6399    function Find_Actual_Type
6400      (Typ      : Entity_Id;
6401       Gen_Type : Entity_Id) return Entity_Id
6402    is
6403       Gen_Scope : constant Entity_Id := Scope (Gen_Type);
6404       T         : Entity_Id;
6405
6406    begin
6407       --  Special processing only applies to child units
6408
6409       if not Is_Child_Unit (Gen_Scope) then
6410          return Get_Instance_Of (Typ);
6411
6412       --  If designated or component type is itself a formal of the child unit,
6413       --  its instance is available.
6414
6415       elsif Scope (Typ) = Gen_Scope then
6416          return Get_Instance_Of (Typ);
6417
6418       --  If the array or access type is not declared in the parent unit,
6419       --  no special processing needed.
6420
6421       elsif not Is_Generic_Type (Typ)
6422         and then Scope (Gen_Scope) /= Scope (Typ)
6423       then
6424          return Get_Instance_Of (Typ);
6425
6426       --  Otherwise, retrieve designated or component type by visibility
6427
6428       else
6429          T := Current_Entity (Typ);
6430          while Present (T) loop
6431             if In_Open_Scopes (Scope (T)) then
6432                return T;
6433
6434             elsif Is_Generic_Actual_Type (T) then
6435                return T;
6436             end if;
6437
6438             T := Homonym (T);
6439          end loop;
6440
6441          return Typ;
6442       end if;
6443    end Find_Actual_Type;
6444
6445    ----------------------------
6446    -- Freeze_Subprogram_Body --
6447    ----------------------------
6448
6449    procedure Freeze_Subprogram_Body
6450      (Inst_Node : Node_Id;
6451       Gen_Body  : Node_Id;
6452       Pack_Id   : Entity_Id)
6453   is
6454       F_Node   : Node_Id;
6455       Gen_Unit : constant Entity_Id := Get_Generic_Entity (Inst_Node);
6456       Par      : constant Entity_Id := Scope (Gen_Unit);
6457       Enc_G    : Entity_Id;
6458       Enc_I    : Node_Id;
6459       E_G_Id   : Entity_Id;
6460
6461       function Earlier (N1, N2 : Node_Id) return Boolean;
6462       --  Yields True if N1 and N2 appear in the same compilation unit,
6463       --  ignoring subunits, and if N1 is to the left of N2 in a left-to-right
6464       --  traversal of the tree for the unit.
6465
6466       function Enclosing_Body (N : Node_Id) return Node_Id;
6467       --  Find innermost package body that encloses the given node, and which
6468       --  is not a compilation unit. Freeze nodes for the instance, or for its
6469       --  enclosing body, may be inserted after the enclosing_body of the
6470       --  generic unit.
6471
6472       function Package_Freeze_Node (B : Node_Id) return Node_Id;
6473       --  Find entity for given package body, and locate or create a freeze
6474       --  node for it.
6475
6476       function True_Parent (N : Node_Id) return Node_Id;
6477       --  For a subunit, return parent of corresponding stub
6478
6479       -------------
6480       -- Earlier --
6481       -------------
6482
6483       function Earlier (N1, N2 : Node_Id) return Boolean is
6484          D1 : Integer := 0;
6485          D2 : Integer := 0;
6486          P1 : Node_Id := N1;
6487          P2 : Node_Id := N2;
6488
6489          procedure Find_Depth (P : in out Node_Id; D : in out Integer);
6490          --  Find distance from given node to enclosing compilation unit
6491
6492          ----------------
6493          -- Find_Depth --
6494          ----------------
6495
6496          procedure Find_Depth (P : in out Node_Id; D : in out Integer) is
6497          begin
6498             while Present (P)
6499               and then Nkind (P) /= N_Compilation_Unit
6500             loop
6501                P := True_Parent (P);
6502                D := D + 1;
6503             end loop;
6504          end Find_Depth;
6505
6506       --  Start of processing for Earlier
6507
6508       begin
6509          Find_Depth (P1, D1);
6510          Find_Depth (P2, D2);
6511
6512          if P1 /= P2 then
6513             return False;
6514          else
6515             P1 := N1;
6516             P2 := N2;
6517          end if;
6518
6519          while D1 > D2 loop
6520             P1 := True_Parent (P1);
6521             D1 := D1 - 1;
6522          end loop;
6523
6524          while D2 > D1 loop
6525             P2 := True_Parent (P2);
6526             D2 := D2 - 1;
6527          end loop;
6528
6529          --  At this point P1 and P2 are at the same distance from the root.
6530          --  We examine their parents until we find a common declarative
6531          --  list, at which point we can establish their relative placement
6532          --  by comparing their ultimate slocs. If we reach the root,
6533          --  N1 and N2 do not descend from the same declarative list (e.g.
6534          --  one is nested in the declarative part and the other is in a block
6535          --  in the statement part) and the earlier one is already frozen.
6536
6537          while not Is_List_Member (P1)
6538            or else not Is_List_Member (P2)
6539            or else List_Containing (P1) /= List_Containing (P2)
6540          loop
6541             P1 := True_Parent (P1);
6542             P2 := True_Parent (P2);
6543
6544             if Nkind (Parent (P1)) = N_Subunit then
6545                P1 := Corresponding_Stub (Parent (P1));
6546             end if;
6547
6548             if Nkind (Parent (P2)) = N_Subunit then
6549                P2 := Corresponding_Stub (Parent (P2));
6550             end if;
6551
6552             if P1 = P2 then
6553                return False;
6554             end if;
6555          end loop;
6556
6557          return
6558            Top_Level_Location (Sloc (P1)) < Top_Level_Location (Sloc (P2));
6559       end Earlier;
6560
6561       --------------------
6562       -- Enclosing_Body --
6563       --------------------
6564
6565       function Enclosing_Body (N : Node_Id) return Node_Id is
6566          P : Node_Id := Parent (N);
6567
6568       begin
6569          while Present (P)
6570            and then Nkind (Parent (P)) /= N_Compilation_Unit
6571          loop
6572             if Nkind (P) = N_Package_Body then
6573
6574                if Nkind (Parent (P)) = N_Subunit then
6575                   return Corresponding_Stub (Parent (P));
6576                else
6577                   return P;
6578                end if;
6579             end if;
6580
6581             P := True_Parent (P);
6582          end loop;
6583
6584          return Empty;
6585       end Enclosing_Body;
6586
6587       -------------------------
6588       -- Package_Freeze_Node --
6589       -------------------------
6590
6591       function Package_Freeze_Node (B : Node_Id) return Node_Id is
6592          Id : Entity_Id;
6593
6594       begin
6595          if Nkind (B) = N_Package_Body then
6596             Id := Corresponding_Spec (B);
6597
6598          else pragma Assert (Nkind (B) = N_Package_Body_Stub);
6599             Id := Corresponding_Spec (Proper_Body (Unit (Library_Unit (B))));
6600          end if;
6601
6602          Ensure_Freeze_Node (Id);
6603          return Freeze_Node (Id);
6604       end Package_Freeze_Node;
6605
6606       -----------------
6607       -- True_Parent --
6608       -----------------
6609
6610       function True_Parent (N : Node_Id) return Node_Id is
6611       begin
6612          if Nkind (Parent (N)) = N_Subunit then
6613             return Parent (Corresponding_Stub (Parent (N)));
6614          else
6615             return Parent (N);
6616          end if;
6617       end True_Parent;
6618
6619    --  Start of processing of Freeze_Subprogram_Body
6620
6621    begin
6622       --  If the instance and the generic body appear within the same unit, and
6623       --  the instance precedes the generic, the freeze node for the instance
6624       --  must appear after that of the generic. If the generic is nested
6625       --  within another instance I2, then current instance must be frozen
6626       --  after I2. In both cases, the freeze nodes are those of enclosing
6627       --  packages. Otherwise, the freeze node is placed at the end of the
6628       --  current declarative part.
6629
6630       Enc_G  := Enclosing_Body (Gen_Body);
6631       Enc_I  := Enclosing_Body (Inst_Node);
6632       Ensure_Freeze_Node (Pack_Id);
6633       F_Node := Freeze_Node (Pack_Id);
6634
6635       if Is_Generic_Instance (Par)
6636         and then Present (Freeze_Node (Par))
6637         and then
6638           In_Same_Declarative_Part (Freeze_Node (Par), Inst_Node)
6639       then
6640          if ABE_Is_Certain (Get_Package_Instantiation_Node (Par)) then
6641
6642             --  The parent was a premature instantiation. Insert freeze node at
6643             --  the end the current declarative part.
6644
6645             Insert_After_Last_Decl (Inst_Node, F_Node);
6646
6647          else
6648             Insert_After (Freeze_Node (Par), F_Node);
6649          end if;
6650
6651       --  The body enclosing the instance should be frozen after the body that
6652       --  includes the generic, because the body of the instance may make
6653       --  references to entities therein. If the two are not in the same
6654       --  declarative part, or if the one enclosing the instance is frozen
6655       --  already, freeze the instance at the end of the current declarative
6656       --  part.
6657
6658       elsif Is_Generic_Instance (Par)
6659         and then Present (Freeze_Node (Par))
6660         and then Present (Enc_I)
6661       then
6662          if In_Same_Declarative_Part (Freeze_Node (Par), Enc_I)
6663            or else
6664              (Nkind (Enc_I) = N_Package_Body
6665                and then
6666                  In_Same_Declarative_Part (Freeze_Node (Par), Parent (Enc_I)))
6667          then
6668             --  The enclosing package may contain several instances. Rather
6669             --  than computing the earliest point at which to insert its
6670             --  freeze node, we place it at the end of the declarative part
6671             --  of the parent of the generic.
6672
6673             Insert_After_Last_Decl
6674               (Freeze_Node (Par), Package_Freeze_Node (Enc_I));
6675          end if;
6676
6677          Insert_After_Last_Decl (Inst_Node, F_Node);
6678
6679       elsif Present (Enc_G)
6680         and then Present (Enc_I)
6681         and then Enc_G /= Enc_I
6682         and then Earlier (Inst_Node, Gen_Body)
6683       then
6684          if Nkind (Enc_G) = N_Package_Body then
6685             E_G_Id := Corresponding_Spec (Enc_G);
6686          else pragma Assert (Nkind (Enc_G) = N_Package_Body_Stub);
6687             E_G_Id :=
6688               Corresponding_Spec (Proper_Body (Unit (Library_Unit (Enc_G))));
6689          end if;
6690
6691          --  Freeze package that encloses instance, and place node after
6692          --  package that encloses generic. If enclosing package is already
6693          --  frozen we have to assume it is at the proper place. This may be
6694          --  a potential ABE that requires dynamic checking. Do not add a
6695          --  freeze node if the package that encloses the generic is inside
6696          --  the body that encloses the instance, because the freeze node
6697          --  would be in the wrong scope. Additional contortions needed if
6698          --  the bodies are within a subunit.
6699
6700          declare
6701             Enclosing_Body : Node_Id;
6702
6703          begin
6704             if Nkind (Enc_I) = N_Package_Body_Stub then
6705                Enclosing_Body := Proper_Body (Unit (Library_Unit (Enc_I)));
6706             else
6707                Enclosing_Body := Enc_I;
6708             end if;
6709
6710             if Parent (List_Containing (Enc_G)) /= Enclosing_Body then
6711                Insert_After_Last_Decl (Enc_G, Package_Freeze_Node (Enc_I));
6712             end if;
6713          end;
6714
6715          --  Freeze enclosing subunit before instance
6716
6717          Ensure_Freeze_Node (E_G_Id);
6718
6719          if not Is_List_Member (Freeze_Node (E_G_Id)) then
6720             Insert_After (Enc_G, Freeze_Node (E_G_Id));
6721          end if;
6722
6723          Insert_After_Last_Decl (Inst_Node, F_Node);
6724
6725       else
6726          --  If none of the above, insert freeze node at the end of the current
6727          --  declarative part.
6728
6729          Insert_After_Last_Decl (Inst_Node, F_Node);
6730       end if;
6731    end Freeze_Subprogram_Body;
6732
6733    ----------------
6734    -- Get_Gen_Id --
6735    ----------------
6736
6737    function Get_Gen_Id (E : Assoc_Ptr) return Entity_Id is
6738    begin
6739       return Generic_Renamings.Table (E).Gen_Id;
6740    end Get_Gen_Id;
6741
6742    ---------------------
6743    -- Get_Instance_Of --
6744    ---------------------
6745
6746    function Get_Instance_Of (A : Entity_Id) return Entity_Id is
6747       Res : constant Assoc_Ptr := Generic_Renamings_HTable.Get (A);
6748
6749    begin
6750       if Res /= Assoc_Null then
6751          return Generic_Renamings.Table (Res).Act_Id;
6752       else
6753          --  On exit, entity is not instantiated: not a generic parameter, or
6754          --  else parameter of an inner generic unit.
6755
6756          return A;
6757       end if;
6758    end Get_Instance_Of;
6759
6760    ------------------------------------
6761    -- Get_Package_Instantiation_Node --
6762    ------------------------------------
6763
6764    function Get_Package_Instantiation_Node (A : Entity_Id) return Node_Id is
6765       Decl : Node_Id := Unit_Declaration_Node (A);
6766       Inst : Node_Id;
6767
6768    begin
6769       --  If the Package_Instantiation attribute has been set on the package
6770       --  entity, then use it directly when it (or its Original_Node) refers
6771       --  to an N_Package_Instantiation node. In principle it should be
6772       --  possible to have this field set in all cases, which should be
6773       --  investigated, and would allow this function to be significantly
6774       --  simplified. ???
6775
6776       if Present (Package_Instantiation (A)) then
6777          if Nkind (Package_Instantiation (A)) = N_Package_Instantiation then
6778             return Package_Instantiation (A);
6779
6780          elsif Nkind (Original_Node (Package_Instantiation (A))) =
6781                                                    N_Package_Instantiation
6782          then
6783             return Original_Node (Package_Instantiation (A));
6784          end if;
6785       end if;
6786
6787       --  If the instantiation is a compilation unit that does not need body
6788       --  then the instantiation node has been rewritten as a package
6789       --  declaration for the instance, and we return the original node.
6790
6791       --  If it is a compilation unit and the instance node has not been
6792       --  rewritten, then it is still the unit of the compilation. Finally, if
6793       --  a body is present, this is a parent of the main unit whose body has
6794       --  been compiled for inlining purposes, and the instantiation node has
6795       --  been rewritten with the instance body.
6796
6797       --  Otherwise the instantiation node appears after the declaration. If
6798       --  the entity is a formal package, the declaration may have been
6799       --  rewritten as a generic declaration (in the case of a formal with box)
6800       --  or left as a formal package declaration if it has actuals, and is
6801       --  found with a forward search.
6802
6803       if Nkind (Parent (Decl)) = N_Compilation_Unit then
6804          if Nkind (Decl) = N_Package_Declaration
6805            and then Present (Corresponding_Body (Decl))
6806          then
6807             Decl := Unit_Declaration_Node (Corresponding_Body (Decl));
6808          end if;
6809
6810          if Nkind (Original_Node (Decl)) = N_Package_Instantiation then
6811             return Original_Node (Decl);
6812          else
6813             return Unit (Parent (Decl));
6814          end if;
6815
6816       elsif Nkind (Decl) = N_Package_Declaration
6817         and then Nkind (Original_Node (Decl)) = N_Formal_Package_Declaration
6818       then
6819          return Original_Node (Decl);
6820
6821       else
6822          Inst := Next (Decl);
6823          while not Nkind_In (Inst, N_Package_Instantiation,
6824                                    N_Formal_Package_Declaration)
6825          loop
6826             Next (Inst);
6827          end loop;
6828
6829          return Inst;
6830       end if;
6831    end Get_Package_Instantiation_Node;
6832
6833    ------------------------
6834    -- Has_Been_Exchanged --
6835    ------------------------
6836
6837    function Has_Been_Exchanged (E : Entity_Id) return Boolean is
6838       Next : Elmt_Id;
6839
6840    begin
6841       Next := First_Elmt (Exchanged_Views);
6842       while Present (Next) loop
6843          if Full_View (Node (Next)) = E then
6844             return True;
6845          end if;
6846
6847          Next_Elmt (Next);
6848       end loop;
6849
6850       return False;
6851    end Has_Been_Exchanged;
6852
6853    ----------
6854    -- Hash --
6855    ----------
6856
6857    function Hash (F : Entity_Id) return HTable_Range is
6858    begin
6859       return HTable_Range (F mod HTable_Size);
6860    end Hash;
6861
6862    ------------------------
6863    -- Hide_Current_Scope --
6864    ------------------------
6865
6866    procedure Hide_Current_Scope is
6867       C : constant Entity_Id := Current_Scope;
6868       E : Entity_Id;
6869
6870    begin
6871       Set_Is_Hidden_Open_Scope (C);
6872
6873       E := First_Entity (C);
6874       while Present (E) loop
6875          if Is_Immediately_Visible (E) then
6876             Set_Is_Immediately_Visible (E, False);
6877             Append_Elmt (E, Hidden_Entities);
6878          end if;
6879
6880          Next_Entity (E);
6881       end loop;
6882
6883       --  Make the scope name invisible as well. This is necessary, but might
6884       --  conflict with calls to Rtsfind later on, in case the scope is a
6885       --  predefined one. There is no clean solution to this problem, so for
6886       --  now we depend on the user not redefining Standard itself in one of
6887       --  the parent units.
6888
6889       if Is_Immediately_Visible (C)
6890         and then C /= Standard_Standard
6891       then
6892          Set_Is_Immediately_Visible (C, False);
6893          Append_Elmt (C, Hidden_Entities);
6894       end if;
6895
6896    end Hide_Current_Scope;
6897
6898    --------------
6899    -- Init_Env --
6900    --------------
6901
6902    procedure Init_Env is
6903       Saved : Instance_Env;
6904
6905    begin
6906       Saved.Instantiated_Parent  := Current_Instantiated_Parent;
6907       Saved.Exchanged_Views      := Exchanged_Views;
6908       Saved.Hidden_Entities      := Hidden_Entities;
6909       Saved.Current_Sem_Unit     := Current_Sem_Unit;
6910       Saved.Parent_Unit_Visible  := Parent_Unit_Visible;
6911       Saved.Instance_Parent_Unit := Instance_Parent_Unit;
6912
6913       --  Save configuration switches. These may be reset if the unit is a
6914       --  predefined unit, and the current mode is not Ada 2005.
6915
6916       Save_Opt_Config_Switches (Saved.Switches);
6917
6918       Instance_Envs.Append (Saved);
6919
6920       Exchanged_Views := New_Elmt_List;
6921       Hidden_Entities := New_Elmt_List;
6922
6923       --  Make dummy entry for Instantiated parent. If generic unit is legal,
6924       --  this is set properly in Set_Instance_Env.
6925
6926       Current_Instantiated_Parent :=
6927         (Current_Scope, Current_Scope, Assoc_Null);
6928    end Init_Env;
6929
6930    ------------------------------
6931    -- In_Same_Declarative_Part --
6932    ------------------------------
6933
6934    function In_Same_Declarative_Part
6935      (F_Node : Node_Id;
6936       Inst   : Node_Id) return Boolean
6937    is
6938       Decls : constant Node_Id := Parent (F_Node);
6939       Nod   : Node_Id := Parent (Inst);
6940
6941    begin
6942       while Present (Nod) loop
6943          if Nod = Decls then
6944             return True;
6945
6946          elsif Nkind_In (Nod, N_Subprogram_Body,
6947                               N_Package_Body,
6948                               N_Task_Body,
6949                               N_Protected_Body,
6950                               N_Block_Statement)
6951          then
6952             return False;
6953
6954          elsif Nkind (Nod) = N_Subunit then
6955             Nod :=  Corresponding_Stub (Nod);
6956
6957          elsif Nkind (Nod) = N_Compilation_Unit then
6958             return False;
6959
6960          else
6961             Nod := Parent (Nod);
6962          end if;
6963       end loop;
6964
6965       return False;
6966    end In_Same_Declarative_Part;
6967
6968    ---------------------
6969    -- In_Main_Context --
6970    ---------------------
6971
6972    function In_Main_Context (E : Entity_Id) return Boolean is
6973       Context : List_Id;
6974       Clause  : Node_Id;
6975       Nam     : Node_Id;
6976
6977    begin
6978       if not Is_Compilation_Unit (E)
6979         or else Ekind (E) /= E_Package
6980         or else In_Private_Part (E)
6981       then
6982          return False;
6983       end if;
6984
6985       Context := Context_Items (Cunit (Main_Unit));
6986
6987       Clause  := First (Context);
6988       while Present (Clause) loop
6989          if Nkind (Clause) = N_With_Clause then
6990             Nam := Name (Clause);
6991
6992             --  If the current scope is part of the context of the main unit,
6993             --  analysis of the corresponding with_clause is not complete, and
6994             --  the entity is not set. We use the Chars field directly, which
6995             --  might produce false positives in rare cases, but guarantees
6996             --  that we produce all the instance bodies we will need.
6997
6998             if (Is_Entity_Name (Nam)
6999                  and then Chars (Nam) = Chars (E))
7000               or else (Nkind (Nam) = N_Selected_Component
7001                         and then Chars (Selector_Name (Nam)) = Chars (E))
7002             then
7003                return True;
7004             end if;
7005          end if;
7006
7007          Next (Clause);
7008       end loop;
7009
7010       return False;
7011    end In_Main_Context;
7012
7013    ---------------------
7014    -- Inherit_Context --
7015    ---------------------
7016
7017    procedure Inherit_Context (Gen_Decl : Node_Id; Inst : Node_Id) is
7018       Current_Context : List_Id;
7019       Current_Unit    : Node_Id;
7020       Item            : Node_Id;
7021       New_I           : Node_Id;
7022
7023    begin
7024       if Nkind (Parent (Gen_Decl)) = N_Compilation_Unit then
7025
7026          --  The inherited context is attached to the enclosing compilation
7027          --  unit. This is either the main unit, or the declaration for the
7028          --  main unit (in case the instantiation appears within the package
7029          --  declaration and the main unit is its body).
7030
7031          Current_Unit := Parent (Inst);
7032          while Present (Current_Unit)
7033            and then Nkind (Current_Unit) /= N_Compilation_Unit
7034          loop
7035             Current_Unit := Parent (Current_Unit);
7036          end loop;
7037
7038          Current_Context := Context_Items (Current_Unit);
7039
7040          Item := First (Context_Items (Parent (Gen_Decl)));
7041          while Present (Item) loop
7042             if Nkind (Item) = N_With_Clause then
7043
7044                --  Take care to prevent direct cyclic with's, which can happen
7045                --  if the generic body with's the current unit. Such a case
7046                --  would result in binder errors (or run-time errors if the
7047                --  -gnatE switch is in effect), but we want to prevent it here,
7048                --  because Sem.Walk_Library_Items doesn't like cycles. Note
7049                --  that we don't bother to detect indirect cycles.
7050
7051                if Library_Unit (Item) /= Current_Unit then
7052                   New_I := New_Copy (Item);
7053                   Set_Implicit_With (New_I, True);
7054                   Append (New_I, Current_Context);
7055                end if;
7056             end if;
7057
7058             Next (Item);
7059          end loop;
7060       end if;
7061    end Inherit_Context;
7062
7063    ----------------
7064    -- Initialize --
7065    ----------------
7066
7067    procedure Initialize is
7068    begin
7069       Generic_Renamings.Init;
7070       Instance_Envs.Init;
7071       Generic_Flags.Init;
7072       Generic_Renamings_HTable.Reset;
7073       Circularity_Detected := False;
7074       Exchanged_Views      := No_Elist;
7075       Hidden_Entities      := No_Elist;
7076    end Initialize;
7077
7078    ----------------------------
7079    -- Insert_After_Last_Decl --
7080    ----------------------------
7081
7082    procedure Insert_After_Last_Decl (N : Node_Id; F_Node : Node_Id) is
7083       L : List_Id          := List_Containing (N);
7084       P : constant Node_Id := Parent (L);
7085
7086    begin
7087       if not Is_List_Member (F_Node) then
7088          if Nkind (P) = N_Package_Specification
7089            and then L = Visible_Declarations (P)
7090            and then Present (Private_Declarations (P))
7091            and then not Is_Empty_List (Private_Declarations (P))
7092          then
7093             L := Private_Declarations (P);
7094          end if;
7095
7096          Insert_After (Last (L), F_Node);
7097       end if;
7098    end Insert_After_Last_Decl;
7099
7100    ------------------
7101    -- Install_Body --
7102    ------------------
7103
7104    procedure Install_Body
7105      (Act_Body : Node_Id;
7106       N        : Node_Id;
7107       Gen_Body : Node_Id;
7108       Gen_Decl : Node_Id)
7109    is
7110       Act_Id    : constant Entity_Id := Corresponding_Spec (Act_Body);
7111       Act_Unit  : constant Node_Id   := Unit (Cunit (Get_Source_Unit (N)));
7112       Gen_Id    : constant Entity_Id := Corresponding_Spec (Gen_Body);
7113       Par       : constant Entity_Id := Scope (Gen_Id);
7114       Gen_Unit  : constant Node_Id   :=
7115                     Unit (Cunit (Get_Source_Unit (Gen_Decl)));
7116       Orig_Body : Node_Id := Gen_Body;
7117       F_Node    : Node_Id;
7118       Body_Unit : Node_Id;
7119
7120       Must_Delay : Boolean;
7121
7122       function Enclosing_Subp (Id : Entity_Id) return Entity_Id;
7123       --  Find subprogram (if any) that encloses instance and/or generic body
7124
7125       function True_Sloc (N : Node_Id) return Source_Ptr;
7126       --  If the instance is nested inside a generic unit, the Sloc of the
7127       --  instance indicates the place of the original definition, not the
7128       --  point of the current enclosing instance. Pending a better usage of
7129       --  Slocs to indicate instantiation places, we determine the place of
7130       --  origin of a node by finding the maximum sloc of any ancestor node.
7131       --  Why is this not equivalent to Top_Level_Location ???
7132
7133       --------------------
7134       -- Enclosing_Subp --
7135       --------------------
7136
7137       function Enclosing_Subp (Id : Entity_Id) return Entity_Id is
7138          Scop : Entity_Id := Scope (Id);
7139
7140       begin
7141          while Scop /= Standard_Standard
7142            and then not Is_Overloadable (Scop)
7143          loop
7144             Scop := Scope (Scop);
7145          end loop;
7146
7147          return Scop;
7148       end Enclosing_Subp;
7149
7150       ---------------
7151       -- True_Sloc --
7152       ---------------
7153
7154       function True_Sloc (N : Node_Id) return Source_Ptr is
7155          Res : Source_Ptr;
7156          N1  : Node_Id;
7157
7158       begin
7159          Res := Sloc (N);
7160          N1 := N;
7161          while Present (N1) and then N1 /= Act_Unit loop
7162             if Sloc (N1) > Res then
7163                Res := Sloc (N1);
7164             end if;
7165
7166             N1 := Parent (N1);
7167          end loop;
7168
7169          return Res;
7170       end True_Sloc;
7171
7172    --  Start of processing for Install_Body
7173
7174    begin
7175
7176       --  If the body is a subunit, the freeze point is the corresponding
7177       --  stub in the current compilation, not the subunit itself.
7178
7179       if Nkind (Parent (Gen_Body)) = N_Subunit then
7180          Orig_Body := Corresponding_Stub (Parent (Gen_Body));
7181       else
7182          Orig_Body := Gen_Body;
7183       end if;
7184
7185       Body_Unit := Unit (Cunit (Get_Source_Unit (Orig_Body)));
7186
7187       --  If the instantiation and the generic definition appear in the same
7188       --  package declaration, this is an early instantiation. If they appear
7189       --  in the same declarative part, it is an early instantiation only if
7190       --  the generic body appears textually later, and the generic body is
7191       --  also in the main unit.
7192
7193       --  If instance is nested within a subprogram, and the generic body is
7194       --  not, the instance is delayed because the enclosing body is. If
7195       --  instance and body are within the same scope, or the same sub-
7196       --  program body, indicate explicitly that the instance is delayed.
7197
7198       Must_Delay :=
7199         (Gen_Unit = Act_Unit
7200           and then (Nkind_In (Gen_Unit, N_Package_Declaration,
7201                                         N_Generic_Package_Declaration)
7202                       or else (Gen_Unit = Body_Unit
7203                                 and then True_Sloc (N) < Sloc (Orig_Body)))
7204           and then Is_In_Main_Unit (Gen_Unit)
7205           and then (Scope (Act_Id) = Scope (Gen_Id)
7206                       or else
7207                     Enclosing_Subp (Act_Id) = Enclosing_Subp (Gen_Id)));
7208
7209       --  If this is an early instantiation, the freeze node is placed after
7210       --  the generic body. Otherwise, if the generic appears in an instance,
7211       --  we cannot freeze the current instance until the outer one is frozen.
7212       --  This is only relevant if the current instance is nested within some
7213       --  inner scope not itself within the outer instance. If this scope is
7214       --  a package body in the same declarative part as the outer instance,
7215       --  then that body needs to be frozen after the outer instance. Finally,
7216       --  if no delay is needed, we place the freeze node at the end of the
7217       --  current declarative part.
7218
7219       if Expander_Active then
7220          Ensure_Freeze_Node (Act_Id);
7221          F_Node := Freeze_Node (Act_Id);
7222
7223          if Must_Delay then
7224             Insert_After (Orig_Body, F_Node);
7225
7226          elsif Is_Generic_Instance (Par)
7227            and then Present (Freeze_Node (Par))
7228            and then Scope (Act_Id) /= Par
7229          then
7230             --  Freeze instance of inner generic after instance of enclosing
7231             --  generic.
7232
7233             if In_Same_Declarative_Part (Freeze_Node (Par), N) then
7234                Insert_After (Freeze_Node (Par), F_Node);
7235
7236             --  Freeze package enclosing instance of inner generic after
7237             --  instance of enclosing generic.
7238
7239             elsif Nkind (Parent (N)) = N_Package_Body
7240               and then In_Same_Declarative_Part (Freeze_Node (Par), Parent (N))
7241             then
7242
7243                declare
7244                   Enclosing : constant Entity_Id :=
7245                                 Corresponding_Spec (Parent (N));
7246
7247                begin
7248                   Insert_After_Last_Decl (N, F_Node);
7249                   Ensure_Freeze_Node (Enclosing);
7250
7251                   if not Is_List_Member (Freeze_Node (Enclosing)) then
7252                      Insert_After (Freeze_Node (Par), Freeze_Node (Enclosing));
7253                   end if;
7254                end;
7255
7256             else
7257                Insert_After_Last_Decl (N, F_Node);
7258             end if;
7259
7260          else
7261             Insert_After_Last_Decl (N, F_Node);
7262          end if;
7263       end if;
7264
7265       Set_Is_Frozen (Act_Id);
7266       Insert_Before (N, Act_Body);
7267       Mark_Rewrite_Insertion (Act_Body);
7268    end Install_Body;
7269
7270    -----------------------------
7271    -- Install_Formal_Packages --
7272    -----------------------------
7273
7274    procedure Install_Formal_Packages (Par : Entity_Id) is
7275       E     : Entity_Id;
7276       Gen   : Entity_Id;
7277       Gen_E : Entity_Id := Empty;
7278
7279    begin
7280       E := First_Entity (Par);
7281
7282       --  In we are installing an instance parent, locate the formal packages
7283       --  of its generic parent.
7284
7285       if Is_Generic_Instance (Par) then
7286          Gen   := Generic_Parent (Specification (Unit_Declaration_Node (Par)));
7287          Gen_E := First_Entity (Gen);
7288       end if;
7289
7290       while Present (E) loop
7291          if Ekind (E) = E_Package
7292            and then Nkind (Parent (E)) = N_Package_Renaming_Declaration
7293          then
7294             --  If this is the renaming for the parent instance, done
7295
7296             if Renamed_Object (E) = Par then
7297                exit;
7298
7299             --  The visibility of a formal of an enclosing generic is already
7300             --  correct.
7301
7302             elsif Denotes_Formal_Package (E) then
7303                null;
7304
7305             elsif Present (Associated_Formal_Package (E)) then
7306                Check_Generic_Actuals (Renamed_Object (E), True);
7307                Set_Is_Hidden (E, False);
7308
7309                --  Find formal package in generic unit that corresponds to
7310                --  (instance of) formal package in instance.
7311
7312                while Present (Gen_E) and then Chars (Gen_E) /= Chars (E) loop
7313                   Next_Entity (Gen_E);
7314                end loop;
7315
7316                if Present (Gen_E) then
7317                   Map_Formal_Package_Entities (Gen_E, E);
7318                end if;
7319             end if;
7320          end if;
7321
7322          Next_Entity (E);
7323          if Present (Gen_E) then
7324             Next_Entity (Gen_E);
7325          end if;
7326       end loop;
7327    end Install_Formal_Packages;
7328
7329    --------------------
7330    -- Install_Parent --
7331    --------------------
7332
7333    procedure Install_Parent (P : Entity_Id; In_Body : Boolean := False) is
7334       Ancestors : constant Elist_Id  := New_Elmt_List;
7335       S         : constant Entity_Id := Current_Scope;
7336       Inst_Par  : Entity_Id;
7337       First_Par : Entity_Id;
7338       Inst_Node : Node_Id;
7339       Gen_Par   : Entity_Id;
7340       First_Gen : Entity_Id;
7341       Elmt      : Elmt_Id;
7342
7343       procedure Install_Noninstance_Specs (Par : Entity_Id);
7344       --  Install the scopes of noninstance parent units ending with Par
7345
7346       procedure Install_Spec (Par : Entity_Id);
7347       --  The child unit is within the declarative part of the parent, so
7348       --  the declarations within the parent are immediately visible.
7349
7350       -------------------------------
7351       -- Install_Noninstance_Specs --
7352       -------------------------------
7353
7354       procedure Install_Noninstance_Specs (Par : Entity_Id) is
7355       begin
7356          if Present (Par)
7357            and then Par /= Standard_Standard
7358            and then not In_Open_Scopes (Par)
7359          then
7360             Install_Noninstance_Specs (Scope (Par));
7361             Install_Spec (Par);
7362          end if;
7363       end Install_Noninstance_Specs;
7364
7365       ------------------
7366       -- Install_Spec --
7367       ------------------
7368
7369       procedure Install_Spec (Par : Entity_Id) is
7370          Spec : constant Node_Id :=
7371                   Specification (Unit_Declaration_Node (Par));
7372
7373       begin
7374          --  If this parent of the child instance is a top-level unit,
7375          --  then record the unit and its visibility for later resetting
7376          --  in Remove_Parent. We exclude units that are generic instances,
7377          --  as we only want to record this information for the ultimate
7378          --  top-level noninstance parent (is that always correct???).
7379
7380          if Scope (Par) = Standard_Standard
7381            and then not Is_Generic_Instance (Par)
7382          then
7383             Parent_Unit_Visible := Is_Immediately_Visible (Par);
7384             Instance_Parent_Unit := Par;
7385          end if;
7386
7387          --  Open the parent scope and make it and its declarations visible.
7388          --  If this point is not within a body, then only the visible
7389          --  declarations should be made visible, and installation of the
7390          --  private declarations is deferred until the appropriate point
7391          --  within analysis of the spec being instantiated (see the handling
7392          --  of parent visibility in Analyze_Package_Specification). This is
7393          --  relaxed in the case where the parent unit is Ada.Tags, to avoid
7394          --  private view problems that occur when compiling instantiations of
7395          --  a generic child of that package (Generic_Dispatching_Constructor).
7396          --  If the instance freezes a tagged type, inlinings of operations
7397          --  from Ada.Tags may need the full view of type Tag. If inlining took
7398          --  proper account of establishing visibility of inlined subprograms'
7399          --  parents then it should be possible to remove this
7400          --  special check. ???
7401
7402          Push_Scope (Par);
7403          Set_Is_Immediately_Visible   (Par);
7404          Install_Visible_Declarations (Par);
7405          Set_Use (Visible_Declarations (Spec));
7406
7407          if In_Body or else Is_RTU (Par, Ada_Tags) then
7408             Install_Private_Declarations (Par);
7409             Set_Use (Private_Declarations (Spec));
7410          end if;
7411       end Install_Spec;
7412
7413    --  Start of processing for Install_Parent
7414
7415    begin
7416       --  We need to install the parent instance to compile the instantiation
7417       --  of the child, but the child instance must appear in the current
7418       --  scope. Given that we cannot place the parent above the current scope
7419       --  in the scope stack, we duplicate the current scope and unstack both
7420       --  after the instantiation is complete.
7421
7422       --  If the parent is itself the instantiation of a child unit, we must
7423       --  also stack the instantiation of its parent, and so on. Each such
7424       --  ancestor is the prefix of the name in a prior instantiation.
7425
7426       --  If this is a nested instance, the parent unit itself resolves to
7427       --  a renaming of the parent instance, whose declaration we need.
7428
7429       --  Finally, the parent may be a generic (not an instance) when the
7430       --  child unit appears as a formal package.
7431
7432       Inst_Par := P;
7433
7434       if Present (Renamed_Entity (Inst_Par)) then
7435          Inst_Par := Renamed_Entity (Inst_Par);
7436       end if;
7437
7438       First_Par := Inst_Par;
7439
7440       Gen_Par :=
7441         Generic_Parent (Specification (Unit_Declaration_Node (Inst_Par)));
7442
7443       First_Gen := Gen_Par;
7444
7445       while Present (Gen_Par)
7446         and then Is_Child_Unit (Gen_Par)
7447       loop
7448          --  Load grandparent instance as well
7449
7450          Inst_Node := Get_Package_Instantiation_Node (Inst_Par);
7451
7452          if Nkind (Name (Inst_Node)) = N_Expanded_Name then
7453             Inst_Par := Entity (Prefix (Name (Inst_Node)));
7454
7455             if Present (Renamed_Entity (Inst_Par)) then
7456                Inst_Par := Renamed_Entity (Inst_Par);
7457             end if;
7458
7459             Gen_Par :=
7460               Generic_Parent
7461                 (Specification (Unit_Declaration_Node (Inst_Par)));
7462
7463             if Present (Gen_Par) then
7464                Prepend_Elmt (Inst_Par, Ancestors);
7465
7466             else
7467                --  Parent is not the name of an instantiation
7468
7469                Install_Noninstance_Specs (Inst_Par);
7470
7471                exit;
7472             end if;
7473
7474          else
7475             --  Previous error
7476
7477             exit;
7478          end if;
7479       end loop;
7480
7481       if Present (First_Gen) then
7482          Append_Elmt (First_Par, Ancestors);
7483
7484       else
7485          Install_Noninstance_Specs (First_Par);
7486       end if;
7487
7488       if not Is_Empty_Elmt_List (Ancestors) then
7489          Elmt := First_Elmt (Ancestors);
7490
7491          while Present (Elmt) loop
7492             Install_Spec (Node (Elmt));
7493             Install_Formal_Packages (Node (Elmt));
7494
7495             Next_Elmt (Elmt);
7496          end loop;
7497       end if;
7498
7499       if not In_Body then
7500          Push_Scope (S);
7501       end if;
7502    end Install_Parent;
7503
7504    --------------------------------
7505    -- Instantiate_Formal_Package --
7506    --------------------------------
7507
7508    function Instantiate_Formal_Package
7509      (Formal          : Node_Id;
7510       Actual          : Node_Id;
7511       Analyzed_Formal : Node_Id) return List_Id
7512    is
7513       Loc         : constant Source_Ptr := Sloc (Actual);
7514       Actual_Pack : Entity_Id;
7515       Formal_Pack : Entity_Id;
7516       Gen_Parent  : Entity_Id;
7517       Decls       : List_Id;
7518       Nod         : Node_Id;
7519       Parent_Spec : Node_Id;
7520
7521       procedure Find_Matching_Actual
7522        (F    : Node_Id;
7523         Act  : in out Entity_Id);
7524       --  We need to associate each formal entity in the formal package
7525       --  with the corresponding entity in the actual package. The actual
7526       --  package has been analyzed and possibly expanded, and as a result
7527       --  there is no one-to-one correspondence between the two lists (for
7528       --  example, the actual may include subtypes, itypes, and inherited
7529       --  primitive operations, interspersed among the renaming declarations
7530       --  for the actuals) . We retrieve the corresponding actual by name
7531       --  because each actual has the same name as the formal, and they do
7532       --  appear in the same order.
7533
7534       function Get_Formal_Entity (N : Node_Id) return Entity_Id;
7535       --  Retrieve entity of defining entity of  generic formal parameter.
7536       --  Only the declarations of formals need to be considered when
7537       --  linking them to actuals, but the declarative list may include
7538       --  internal entities generated during analysis, and those are ignored.
7539
7540       procedure Match_Formal_Entity
7541         (Formal_Node : Node_Id;
7542          Formal_Ent  : Entity_Id;
7543          Actual_Ent  : Entity_Id);
7544       --  Associates the formal entity with the actual. In the case
7545       --  where Formal_Ent is a formal package, this procedure iterates
7546       --  through all of its formals and enters associations between the
7547       --  actuals occurring in the formal package's corresponding actual
7548       --  package (given by Actual_Ent) and the formal package's formal
7549       --  parameters. This procedure recurses if any of the parameters is
7550       --  itself a package.
7551
7552       function Is_Instance_Of
7553         (Act_Spec : Entity_Id;
7554          Gen_Anc  : Entity_Id) return Boolean;
7555       --  The actual can be an instantiation of a generic within another
7556       --  instance, in which case there is no direct link from it to the
7557       --  original generic ancestor. In that case, we recognize that the
7558       --  ultimate ancestor is the same by examining names and scopes.
7559
7560       procedure Process_Nested_Formal (Formal : Entity_Id);
7561       --  If the current formal is declared with a box, its own formals are
7562       --  visible in the instance, as they were in the generic, and their
7563       --  Hidden flag must be reset. If some of these formals are themselves
7564       --  packages declared with a box, the processing must be recursive.
7565
7566       --------------------------
7567       -- Find_Matching_Actual --
7568       --------------------------
7569
7570       procedure Find_Matching_Actual
7571         (F   : Node_Id;
7572          Act : in out Entity_Id)
7573      is
7574          Formal_Ent : Entity_Id;
7575
7576       begin
7577          case Nkind (Original_Node (F)) is
7578             when N_Formal_Object_Declaration |
7579                  N_Formal_Type_Declaration   =>
7580                Formal_Ent := Defining_Identifier (F);
7581
7582                while Chars (Act) /= Chars (Formal_Ent) loop
7583                   Next_Entity (Act);
7584                end loop;
7585
7586             when N_Formal_Subprogram_Declaration |
7587                  N_Formal_Package_Declaration    |
7588                  N_Package_Declaration           |
7589                  N_Generic_Package_Declaration   =>
7590                Formal_Ent := Defining_Entity (F);
7591
7592                while Chars (Act) /= Chars (Formal_Ent) loop
7593                   Next_Entity (Act);
7594                end loop;
7595
7596             when others =>
7597                raise Program_Error;
7598          end case;
7599       end Find_Matching_Actual;
7600
7601       -------------------------
7602       -- Match_Formal_Entity --
7603       -------------------------
7604
7605       procedure Match_Formal_Entity
7606         (Formal_Node : Node_Id;
7607          Formal_Ent  : Entity_Id;
7608          Actual_Ent  : Entity_Id)
7609       is
7610          Act_Pkg   : Entity_Id;
7611
7612       begin
7613          Set_Instance_Of (Formal_Ent, Actual_Ent);
7614
7615          if Ekind (Actual_Ent) = E_Package then
7616
7617             --  Record associations for each parameter
7618
7619             Act_Pkg := Actual_Ent;
7620
7621             declare
7622                A_Ent  : Entity_Id := First_Entity (Act_Pkg);
7623                F_Ent  : Entity_Id;
7624                F_Node : Node_Id;
7625
7626                Gen_Decl : Node_Id;
7627                Formals  : List_Id;
7628                Actual   : Entity_Id;
7629
7630             begin
7631                --  Retrieve the actual given in the formal package declaration
7632
7633                Actual := Entity (Name (Original_Node (Formal_Node)));
7634
7635                --  The actual in the formal package declaration  may be a
7636                --  renamed generic package, in which case we want to retrieve
7637                --  the original generic in order to traverse its formal part.
7638
7639                if Present (Renamed_Entity (Actual)) then
7640                   Gen_Decl := Unit_Declaration_Node (Renamed_Entity (Actual));
7641                else
7642                   Gen_Decl := Unit_Declaration_Node (Actual);
7643                end if;
7644
7645                Formals := Generic_Formal_Declarations (Gen_Decl);
7646
7647                if Present (Formals) then
7648                   F_Node := First_Non_Pragma (Formals);
7649                else
7650                   F_Node := Empty;
7651                end if;
7652
7653                while Present (A_Ent)
7654                  and then Present (F_Node)
7655                  and then A_Ent /= First_Private_Entity (Act_Pkg)
7656                loop
7657                   F_Ent := Get_Formal_Entity (F_Node);
7658
7659                   if Present (F_Ent) then
7660
7661                      --  This is a formal of the original package. Record
7662                      --  association and recurse.
7663
7664                      Find_Matching_Actual (F_Node, A_Ent);
7665                      Match_Formal_Entity (F_Node, F_Ent, A_Ent);
7666                      Next_Entity (A_Ent);
7667                   end if;
7668
7669                   Next_Non_Pragma (F_Node);
7670                end loop;
7671             end;
7672          end if;
7673       end Match_Formal_Entity;
7674
7675       -----------------------
7676       -- Get_Formal_Entity --
7677       -----------------------
7678
7679       function Get_Formal_Entity (N : Node_Id) return Entity_Id is
7680          Kind : constant Node_Kind := Nkind (Original_Node (N));
7681       begin
7682          case Kind is
7683             when N_Formal_Object_Declaration     =>
7684                return Defining_Identifier (N);
7685
7686             when N_Formal_Type_Declaration       =>
7687                return Defining_Identifier (N);
7688
7689             when N_Formal_Subprogram_Declaration =>
7690                return Defining_Unit_Name (Specification (N));
7691
7692             when N_Formal_Package_Declaration    =>
7693                return Defining_Identifier (Original_Node (N));
7694
7695             when N_Generic_Package_Declaration   =>
7696                return Defining_Identifier (Original_Node (N));
7697
7698             --  All other declarations are introduced by semantic analysis and
7699             --  have no match in the actual.
7700
7701             when others =>
7702                return Empty;
7703          end case;
7704       end Get_Formal_Entity;
7705
7706       --------------------
7707       -- Is_Instance_Of --
7708       --------------------
7709
7710       function Is_Instance_Of
7711         (Act_Spec : Entity_Id;
7712          Gen_Anc  : Entity_Id) return Boolean
7713       is
7714          Gen_Par : constant Entity_Id := Generic_Parent (Act_Spec);
7715
7716       begin
7717          if No (Gen_Par) then
7718             return False;
7719
7720          --  Simplest case: the generic parent of the actual is the formal
7721
7722          elsif Gen_Par = Gen_Anc then
7723             return True;
7724
7725          elsif Chars (Gen_Par) /= Chars (Gen_Anc) then
7726             return False;
7727
7728          --  The actual may be obtained through several instantiations. Its
7729          --  scope must itself be an instance of a generic declared in the
7730          --  same scope as the formal. Any other case is detected above.
7731
7732          elsif not Is_Generic_Instance (Scope (Gen_Par)) then
7733             return False;
7734
7735          else
7736             return Generic_Parent (Parent (Scope (Gen_Par))) = Scope (Gen_Anc);
7737          end if;
7738       end Is_Instance_Of;
7739
7740       ---------------------------
7741       -- Process_Nested_Formal --
7742       ---------------------------
7743
7744       procedure Process_Nested_Formal (Formal : Entity_Id) is
7745          Ent : Entity_Id;
7746
7747       begin
7748          if Present (Associated_Formal_Package (Formal))
7749            and then Box_Present (Parent (Associated_Formal_Package (Formal)))
7750          then
7751             Ent := First_Entity (Formal);
7752             while Present (Ent) loop
7753                Set_Is_Hidden (Ent, False);
7754                Set_Is_Visible_Formal (Ent);
7755                Set_Is_Potentially_Use_Visible
7756                  (Ent, Is_Potentially_Use_Visible (Formal));
7757
7758                if Ekind (Ent) = E_Package then
7759                   exit when Renamed_Entity (Ent) = Renamed_Entity (Formal);
7760                   Process_Nested_Formal (Ent);
7761                end if;
7762
7763                Next_Entity (Ent);
7764             end loop;
7765          end if;
7766       end Process_Nested_Formal;
7767
7768    --  Start of processing for Instantiate_Formal_Package
7769
7770    begin
7771       Analyze (Actual);
7772
7773       if not Is_Entity_Name (Actual)
7774         or else  Ekind (Entity (Actual)) /= E_Package
7775       then
7776          Error_Msg_N
7777            ("expect package instance to instantiate formal", Actual);
7778          Abandon_Instantiation (Actual);
7779          raise Program_Error;
7780
7781       else
7782          Actual_Pack := Entity (Actual);
7783          Set_Is_Instantiated (Actual_Pack);
7784
7785          --  The actual may be a renamed package, or an outer generic formal
7786          --  package whose instantiation is converted into a renaming.
7787
7788          if Present (Renamed_Object (Actual_Pack)) then
7789             Actual_Pack := Renamed_Object (Actual_Pack);
7790          end if;
7791
7792          if Nkind (Analyzed_Formal) = N_Formal_Package_Declaration then
7793             Gen_Parent  := Get_Instance_Of (Entity (Name (Analyzed_Formal)));
7794             Formal_Pack := Defining_Identifier (Analyzed_Formal);
7795          else
7796             Gen_Parent :=
7797               Generic_Parent (Specification (Analyzed_Formal));
7798             Formal_Pack :=
7799               Defining_Unit_Name (Specification (Analyzed_Formal));
7800          end if;
7801
7802          if Nkind (Parent (Actual_Pack)) = N_Defining_Program_Unit_Name then
7803             Parent_Spec := Specification (Unit_Declaration_Node (Actual_Pack));
7804          else
7805             Parent_Spec := Parent (Actual_Pack);
7806          end if;
7807
7808          if Gen_Parent = Any_Id then
7809             Error_Msg_N
7810               ("previous error in declaration of formal package", Actual);
7811             Abandon_Instantiation (Actual);
7812
7813          elsif
7814            Is_Instance_Of (Parent_Spec, Get_Instance_Of (Gen_Parent))
7815          then
7816             null;
7817
7818          else
7819             Error_Msg_NE
7820               ("actual parameter must be instance of&", Actual, Gen_Parent);
7821             Abandon_Instantiation (Actual);
7822          end if;
7823
7824          Set_Instance_Of (Defining_Identifier (Formal), Actual_Pack);
7825          Map_Formal_Package_Entities (Formal_Pack, Actual_Pack);
7826
7827          Nod :=
7828            Make_Package_Renaming_Declaration (Loc,
7829              Defining_Unit_Name => New_Copy (Defining_Identifier (Formal)),
7830              Name               => New_Reference_To (Actual_Pack, Loc));
7831
7832          Set_Associated_Formal_Package (Defining_Unit_Name (Nod),
7833            Defining_Identifier (Formal));
7834          Decls := New_List (Nod);
7835
7836          --  If the formal F has a box, then the generic declarations are
7837          --  visible in the generic G. In an instance of G, the corresponding
7838          --  entities in the actual for F (which are the actuals for the
7839          --  instantiation of the generic that F denotes) must also be made
7840          --  visible for analysis of the current instance. On exit from the
7841          --  current instance, those entities are made private again. If the
7842          --  actual is currently in use, these entities are also use-visible.
7843
7844          --  The loop through the actual entities also steps through the formal
7845          --  entities and enters associations from formals to actuals into the
7846          --  renaming map. This is necessary to properly handle checking of
7847          --  actual parameter associations for later formals that depend on
7848          --  actuals declared in the formal package.
7849
7850          --  In Ada 2005, partial parametrization requires that we make visible
7851          --  the actuals corresponding to formals that were defaulted in the
7852          --  formal package. There formals are identified because they remain
7853          --  formal generics within the formal package, rather than being
7854          --  renamings of the actuals supplied.
7855
7856          declare
7857             Gen_Decl : constant Node_Id :=
7858                          Unit_Declaration_Node (Gen_Parent);
7859             Formals  : constant List_Id :=
7860                          Generic_Formal_Declarations (Gen_Decl);
7861
7862             Actual_Ent       : Entity_Id;
7863             Actual_Of_Formal : Node_Id;
7864             Formal_Node      : Node_Id;
7865             Formal_Ent       : Entity_Id;
7866
7867          begin
7868             if Present (Formals) then
7869                Formal_Node := First_Non_Pragma (Formals);
7870             else
7871                Formal_Node := Empty;
7872             end if;
7873
7874             Actual_Ent := First_Entity (Actual_Pack);
7875             Actual_Of_Formal :=
7876                First (Visible_Declarations (Specification (Analyzed_Formal)));
7877             while Present (Actual_Ent)
7878               and then Actual_Ent /= First_Private_Entity (Actual_Pack)
7879             loop
7880                if Present (Formal_Node) then
7881                   Formal_Ent := Get_Formal_Entity (Formal_Node);
7882
7883                   if Present (Formal_Ent) then
7884                      Find_Matching_Actual (Formal_Node, Actual_Ent);
7885                      Match_Formal_Entity
7886                        (Formal_Node, Formal_Ent, Actual_Ent);
7887
7888                      --  We iterate at the same time over the actuals of the
7889                      --  local package created for the formal, to determine
7890                      --  which one of the formals of the original generic were
7891                      --  defaulted in the formal. The corresponding actual
7892                      --  entities are visible in the enclosing instance.
7893
7894                      if Box_Present (Formal)
7895                        or else
7896                          (Present (Actual_Of_Formal)
7897                            and then
7898                              Is_Generic_Formal
7899                                (Get_Formal_Entity (Actual_Of_Formal)))
7900                      then
7901                         Set_Is_Hidden (Actual_Ent, False);
7902                         Set_Is_Visible_Formal (Actual_Ent);
7903                         Set_Is_Potentially_Use_Visible
7904                           (Actual_Ent, In_Use (Actual_Pack));
7905
7906                         if Ekind (Actual_Ent) = E_Package then
7907                            Process_Nested_Formal (Actual_Ent);
7908                         end if;
7909
7910                      else
7911                         Set_Is_Hidden (Actual_Ent);
7912                         Set_Is_Potentially_Use_Visible (Actual_Ent, False);
7913                      end if;
7914                   end if;
7915
7916                   Next_Non_Pragma (Formal_Node);
7917                   Next (Actual_Of_Formal);
7918
7919                else
7920                   --  No further formals to match, but the generic part may
7921                   --  contain inherited operation that are not hidden in the
7922                   --  enclosing instance.
7923
7924                   Next_Entity (Actual_Ent);
7925                end if;
7926             end loop;
7927
7928             --  Inherited subprograms generated by formal derived types are
7929             --  also visible if the types are.
7930
7931             Actual_Ent := First_Entity (Actual_Pack);
7932             while Present (Actual_Ent)
7933               and then Actual_Ent /= First_Private_Entity (Actual_Pack)
7934             loop
7935                if Is_Overloadable (Actual_Ent)
7936                  and then
7937                    Nkind (Parent (Actual_Ent)) = N_Subtype_Declaration
7938                  and then
7939                    not Is_Hidden (Defining_Identifier (Parent (Actual_Ent)))
7940                then
7941                   Set_Is_Hidden (Actual_Ent, False);
7942                   Set_Is_Potentially_Use_Visible
7943                     (Actual_Ent, In_Use (Actual_Pack));
7944                end if;
7945
7946                Next_Entity (Actual_Ent);
7947             end loop;
7948          end;
7949
7950          --  If the formal is not declared with a box, reanalyze it as an
7951          --  abbreviated instantiation, to verify the matching rules of 12.7.
7952          --  The actual checks are performed after the generic associations
7953          --  have been analyzed, to guarantee the same visibility for this
7954          --  instantiation and for the actuals.
7955
7956          --  In Ada 2005, the generic associations for the formal can include
7957          --  defaulted parameters. These are ignored during check. This
7958          --  internal instantiation is removed from the tree after conformance
7959          --  checking, because it contains formal declarations for those
7960          --  defaulted parameters, and those should not reach the back-end.
7961
7962          if not Box_Present (Formal) then
7963             declare
7964                I_Pack : constant Entity_Id :=
7965                           Make_Temporary (Sloc (Actual), 'P');
7966
7967             begin
7968                Set_Is_Internal (I_Pack);
7969
7970                Append_To (Decls,
7971                  Make_Package_Instantiation (Sloc (Actual),
7972                    Defining_Unit_Name => I_Pack,
7973                    Name =>
7974                      New_Occurrence_Of
7975                        (Get_Instance_Of (Gen_Parent), Sloc (Actual)),
7976                    Generic_Associations =>
7977                      Generic_Associations (Formal)));
7978             end;
7979          end if;
7980
7981          return Decls;
7982       end if;
7983    end Instantiate_Formal_Package;
7984
7985    -----------------------------------
7986    -- Instantiate_Formal_Subprogram --
7987    -----------------------------------
7988
7989    function Instantiate_Formal_Subprogram
7990      (Formal          : Node_Id;
7991       Actual          : Node_Id;
7992       Analyzed_Formal : Node_Id) return Node_Id
7993    is
7994       Loc        : Source_Ptr;
7995       Formal_Sub : constant Entity_Id :=
7996                      Defining_Unit_Name (Specification (Formal));
7997       Analyzed_S : constant Entity_Id :=
7998                      Defining_Unit_Name (Specification (Analyzed_Formal));
7999       Decl_Node  : Node_Id;
8000       Nam        : Node_Id;
8001       New_Spec   : Node_Id;
8002
8003       function From_Parent_Scope (Subp : Entity_Id) return Boolean;
8004       --  If the generic is a child unit, the parent has been installed on the
8005       --  scope stack, but a default subprogram cannot resolve to something on
8006       --  the parent because that parent is not really part of the visible
8007       --  context (it is there to resolve explicit local entities). If the
8008       --  default has resolved in this way, we remove the entity from
8009       --  immediate visibility and analyze the node again to emit an error
8010       --  message or find another visible candidate.
8011
8012       procedure Valid_Actual_Subprogram (Act : Node_Id);
8013       --  Perform legality check and raise exception on failure
8014
8015       -----------------------
8016       -- From_Parent_Scope --
8017       -----------------------
8018
8019       function From_Parent_Scope (Subp : Entity_Id) return Boolean is
8020          Gen_Scope : Node_Id;
8021
8022       begin
8023          Gen_Scope := Scope (Analyzed_S);
8024          while Present (Gen_Scope)
8025            and then  Is_Child_Unit (Gen_Scope)
8026          loop
8027             if Scope (Subp) = Scope (Gen_Scope) then
8028                return True;
8029             end if;
8030
8031             Gen_Scope := Scope (Gen_Scope);
8032          end loop;
8033
8034          return False;
8035       end From_Parent_Scope;
8036
8037       -----------------------------
8038       -- Valid_Actual_Subprogram --
8039       -----------------------------
8040
8041       procedure Valid_Actual_Subprogram (Act : Node_Id) is
8042          Act_E : Entity_Id;
8043
8044       begin
8045          if Is_Entity_Name (Act) then
8046             Act_E := Entity (Act);
8047
8048          elsif Nkind (Act) = N_Selected_Component
8049            and then Is_Entity_Name (Selector_Name (Act))
8050          then
8051             Act_E := Entity (Selector_Name (Act));
8052
8053          else
8054             Act_E := Empty;
8055          end if;
8056
8057          if (Present (Act_E) and then Is_Overloadable (Act_E))
8058            or else Nkind_In (Act, N_Attribute_Reference,
8059                                   N_Indexed_Component,
8060                                   N_Character_Literal,
8061                                   N_Explicit_Dereference)
8062          then
8063             return;
8064          end if;
8065
8066          Error_Msg_NE
8067            ("expect subprogram or entry name in instantiation of&",
8068             Instantiation_Node, Formal_Sub);
8069          Abandon_Instantiation (Instantiation_Node);
8070
8071       end Valid_Actual_Subprogram;
8072
8073    --  Start of processing for Instantiate_Formal_Subprogram
8074
8075    begin
8076       New_Spec := New_Copy_Tree (Specification (Formal));
8077
8078       --  The tree copy has created the proper instantiation sloc for the
8079       --  new specification. Use this location for all other constructed
8080       --  declarations.
8081
8082       Loc := Sloc (Defining_Unit_Name (New_Spec));
8083
8084       --  Create new entity for the actual (New_Copy_Tree does not)
8085
8086       Set_Defining_Unit_Name
8087         (New_Spec, Make_Defining_Identifier (Loc, Chars (Formal_Sub)));
8088
8089       --  Create new entities for the each of the formals in the
8090       --  specification of the renaming declaration built for the actual.
8091
8092       if Present (Parameter_Specifications (New_Spec)) then
8093          declare
8094             F : Node_Id;
8095          begin
8096             F := First (Parameter_Specifications (New_Spec));
8097             while Present (F) loop
8098                Set_Defining_Identifier (F,
8099                   Make_Defining_Identifier (Sloc (F),
8100                     Chars => Chars (Defining_Identifier (F))));
8101                Next (F);
8102             end loop;
8103          end;
8104       end if;
8105
8106       --  Find entity of actual. If the actual is an attribute reference, it
8107       --  cannot be resolved here (its formal is missing) but is handled
8108       --  instead in Attribute_Renaming. If the actual is overloaded, it is
8109       --  fully resolved subsequently, when the renaming declaration for the
8110       --  formal is analyzed. If it is an explicit dereference, resolve the
8111       --  prefix but not the actual itself, to prevent interpretation as call.
8112
8113       if Present (Actual) then
8114          Loc := Sloc (Actual);
8115          Set_Sloc (New_Spec, Loc);
8116
8117          if Nkind (Actual) = N_Operator_Symbol then
8118             Find_Direct_Name (Actual);
8119
8120          elsif Nkind (Actual) = N_Explicit_Dereference then
8121             Analyze (Prefix (Actual));
8122
8123          elsif Nkind (Actual) /= N_Attribute_Reference then
8124             Analyze (Actual);
8125          end if;
8126
8127          Valid_Actual_Subprogram (Actual);
8128          Nam := Actual;
8129
8130       elsif Present (Default_Name (Formal)) then
8131          if not Nkind_In (Default_Name (Formal), N_Attribute_Reference,
8132                                                  N_Selected_Component,
8133                                                  N_Indexed_Component,
8134                                                  N_Character_Literal)
8135            and then Present (Entity (Default_Name (Formal)))
8136          then
8137             Nam := New_Occurrence_Of (Entity (Default_Name (Formal)), Loc);
8138          else
8139             Nam := New_Copy (Default_Name (Formal));
8140             Set_Sloc (Nam, Loc);
8141          end if;
8142
8143       elsif Box_Present (Formal) then
8144
8145          --  Actual is resolved at the point of instantiation. Create an
8146          --  identifier or operator with the same name as the formal.
8147
8148          if Nkind (Formal_Sub) = N_Defining_Operator_Symbol then
8149             Nam := Make_Operator_Symbol (Loc,
8150               Chars =>  Chars (Formal_Sub),
8151               Strval => No_String);
8152          else
8153             Nam := Make_Identifier (Loc, Chars (Formal_Sub));
8154          end if;
8155
8156       elsif Nkind (Specification (Formal)) = N_Procedure_Specification
8157         and then Null_Present (Specification (Formal))
8158       then
8159          --  Generate null body for procedure, for use in the instance
8160
8161          Decl_Node :=
8162            Make_Subprogram_Body (Loc,
8163              Specification              => New_Spec,
8164              Declarations               => New_List,
8165              Handled_Statement_Sequence =>
8166                Make_Handled_Sequence_Of_Statements (Loc,
8167                  Statements => New_List (Make_Null_Statement (Loc))));
8168
8169          Set_Is_Intrinsic_Subprogram (Defining_Unit_Name (New_Spec));
8170          return Decl_Node;
8171
8172       else
8173          Error_Msg_Sloc := Sloc (Scope (Analyzed_S));
8174          Error_Msg_NE
8175            ("missing actual&", Instantiation_Node, Formal_Sub);
8176          Error_Msg_NE
8177            ("\in instantiation of & declared#",
8178               Instantiation_Node, Scope (Analyzed_S));
8179          Abandon_Instantiation (Instantiation_Node);
8180       end if;
8181
8182       Decl_Node :=
8183         Make_Subprogram_Renaming_Declaration (Loc,
8184           Specification => New_Spec,
8185           Name          => Nam);
8186
8187       --  If we do not have an actual and the formal specified <> then set to
8188       --  get proper default.
8189
8190       if No (Actual) and then Box_Present (Formal) then
8191          Set_From_Default (Decl_Node);
8192       end if;
8193
8194       --  Gather possible interpretations for the actual before analyzing the
8195       --  instance. If overloaded, it will be resolved when analyzing the
8196       --  renaming declaration.
8197
8198       if Box_Present (Formal)
8199         and then No (Actual)
8200       then
8201          Analyze (Nam);
8202
8203          if Is_Child_Unit (Scope (Analyzed_S))
8204            and then Present (Entity (Nam))
8205          then
8206             if not Is_Overloaded (Nam) then
8207
8208                if From_Parent_Scope (Entity (Nam)) then
8209                   Set_Is_Immediately_Visible (Entity (Nam), False);
8210                   Set_Entity (Nam, Empty);
8211                   Set_Etype (Nam, Empty);
8212
8213                   Analyze (Nam);
8214
8215                   Set_Is_Immediately_Visible (Entity (Nam));
8216                end if;
8217
8218             else
8219                declare
8220                   I  : Interp_Index;
8221                   It : Interp;
8222
8223                begin
8224                   Get_First_Interp (Nam, I, It);
8225
8226                   while Present (It.Nam) loop
8227                      if From_Parent_Scope (It.Nam) then
8228                         Remove_Interp (I);
8229                      end if;
8230
8231                      Get_Next_Interp (I, It);
8232                   end loop;
8233                end;
8234             end if;
8235          end if;
8236       end if;
8237
8238       --  The generic instantiation freezes the actual. This can only be done
8239       --  once the actual is resolved, in the analysis of the renaming
8240       --  declaration. To make the formal subprogram entity available, we set
8241       --  Corresponding_Formal_Spec to point to the formal subprogram entity.
8242       --  This is also needed in Analyze_Subprogram_Renaming for the processing
8243       --  of formal abstract subprograms.
8244
8245       Set_Corresponding_Formal_Spec (Decl_Node, Analyzed_S);
8246
8247       --  We cannot analyze the renaming declaration, and thus find the actual,
8248       --  until all the actuals are assembled in the instance. For subsequent
8249       --  checks of other actuals, indicate the node that will hold the
8250       --  instance of this formal.
8251
8252       Set_Instance_Of (Analyzed_S, Nam);
8253
8254       if Nkind (Actual) = N_Selected_Component
8255         and then Is_Task_Type (Etype (Prefix (Actual)))
8256         and then not Is_Frozen (Etype (Prefix (Actual)))
8257       then
8258          --  The renaming declaration will create a body, which must appear
8259          --  outside of the instantiation, We move the renaming declaration
8260          --  out of the instance, and create an additional renaming inside,
8261          --  to prevent freezing anomalies.
8262
8263          declare
8264             Anon_Id : constant Entity_Id := Make_Temporary (Loc, 'E');
8265
8266          begin
8267             Set_Defining_Unit_Name (New_Spec, Anon_Id);
8268             Insert_Before (Instantiation_Node, Decl_Node);
8269             Analyze (Decl_Node);
8270
8271             --  Now create renaming within the instance
8272
8273             Decl_Node :=
8274               Make_Subprogram_Renaming_Declaration (Loc,
8275                 Specification => New_Copy_Tree (New_Spec),
8276                 Name => New_Occurrence_Of (Anon_Id, Loc));
8277
8278             Set_Defining_Unit_Name (Specification (Decl_Node),
8279               Make_Defining_Identifier (Loc, Chars (Formal_Sub)));
8280          end;
8281       end if;
8282
8283       return Decl_Node;
8284    end Instantiate_Formal_Subprogram;
8285
8286    ------------------------
8287    -- Instantiate_Object --
8288    ------------------------
8289
8290    function Instantiate_Object
8291      (Formal          : Node_Id;
8292       Actual          : Node_Id;
8293       Analyzed_Formal : Node_Id) return List_Id
8294    is
8295       Gen_Obj     : constant Entity_Id  := Defining_Identifier (Formal);
8296       A_Gen_Obj   : constant Entity_Id  :=
8297                       Defining_Identifier (Analyzed_Formal);
8298       Acc_Def     : Node_Id             := Empty;
8299       Act_Assoc   : constant Node_Id    := Parent (Actual);
8300       Actual_Decl : Node_Id             := Empty;
8301       Decl_Node   : Node_Id;
8302       Def         : Node_Id;
8303       Ftyp        : Entity_Id;
8304       List        : constant List_Id    := New_List;
8305       Loc         : constant Source_Ptr := Sloc (Actual);
8306       Orig_Ftyp   : constant Entity_Id  := Etype (A_Gen_Obj);
8307       Subt_Decl   : Node_Id             := Empty;
8308       Subt_Mark   : Node_Id             := Empty;
8309
8310    begin
8311       if Present (Subtype_Mark (Formal)) then
8312          Subt_Mark := Subtype_Mark (Formal);
8313       else
8314          Check_Access_Definition (Formal);
8315          Acc_Def := Access_Definition (Formal);
8316       end if;
8317
8318       --  Sloc for error message on missing actual
8319
8320       Error_Msg_Sloc := Sloc (Scope (A_Gen_Obj));
8321
8322       if Get_Instance_Of (Gen_Obj) /= Gen_Obj then
8323          Error_Msg_N ("duplicate instantiation of generic parameter", Actual);
8324       end if;
8325
8326       Set_Parent (List, Parent (Actual));
8327
8328       --  OUT present
8329
8330       if Out_Present (Formal) then
8331
8332          --  An IN OUT generic actual must be a name. The instantiation is a
8333          --  renaming declaration. The actual is the name being renamed. We
8334          --  use the actual directly, rather than a copy, because it is not
8335          --  used further in the list of actuals, and because a copy or a use
8336          --  of relocate_node is incorrect if the instance is nested within a
8337          --  generic. In order to simplify ASIS searches, the Generic_Parent
8338          --  field links the declaration to the generic association.
8339
8340          if No (Actual) then
8341             Error_Msg_NE
8342               ("missing actual&",
8343                Instantiation_Node, Gen_Obj);
8344             Error_Msg_NE
8345               ("\in instantiation of & declared#",
8346                  Instantiation_Node, Scope (A_Gen_Obj));
8347             Abandon_Instantiation (Instantiation_Node);
8348          end if;
8349
8350          if Present (Subt_Mark) then
8351             Decl_Node :=
8352               Make_Object_Renaming_Declaration (Loc,
8353                 Defining_Identifier => New_Copy (Gen_Obj),
8354                 Subtype_Mark        => New_Copy_Tree (Subt_Mark),
8355                 Name                => Actual);
8356
8357          else pragma Assert (Present (Acc_Def));
8358             Decl_Node :=
8359               Make_Object_Renaming_Declaration (Loc,
8360                 Defining_Identifier => New_Copy (Gen_Obj),
8361                 Access_Definition   => New_Copy_Tree (Acc_Def),
8362                 Name                => Actual);
8363          end if;
8364
8365          Set_Corresponding_Generic_Association (Decl_Node, Act_Assoc);
8366
8367          --  The analysis of the actual may produce insert_action nodes, so
8368          --  the declaration must have a context in which to attach them.
8369
8370          Append (Decl_Node, List);
8371          Analyze (Actual);
8372
8373          --  Return if the analysis of the actual reported some error
8374
8375          if Etype (Actual) = Any_Type then
8376             return List;
8377          end if;
8378
8379          --  This check is performed here because Analyze_Object_Renaming will
8380          --  not check it when Comes_From_Source is False. Note though that the
8381          --  check for the actual being the name of an object will be performed
8382          --  in Analyze_Object_Renaming.
8383
8384          if Is_Object_Reference (Actual)
8385            and then Is_Dependent_Component_Of_Mutable_Object (Actual)
8386          then
8387             Error_Msg_N
8388               ("illegal discriminant-dependent component for in out parameter",
8389                Actual);
8390          end if;
8391
8392          --  The actual has to be resolved in order to check that it is a
8393          --  variable (due to cases such as F (1), where F returns access to an
8394          --  array, and for overloaded prefixes).
8395
8396          Ftyp := Get_Instance_Of (Etype (A_Gen_Obj));
8397
8398          --  If the type of the formal is not itself a formal, and the
8399          --  current unit is a child unit, the formal type must be declared
8400          --  in a parent, and must be retrieved by visibility.
8401
8402          if Ftyp = Orig_Ftyp
8403            and then Is_Generic_Unit (Scope (Ftyp))
8404            and then Is_Child_Unit (Scope (A_Gen_Obj))
8405          then
8406             declare
8407                Temp : constant Node_Id :=
8408                         New_Copy_Tree (Subtype_Mark (Analyzed_Formal));
8409             begin
8410                Set_Entity (Temp, Empty);
8411                Find_Type (Temp);
8412                Ftyp := Entity (Temp);
8413             end;
8414          end if;
8415
8416          if Is_Private_Type (Ftyp)
8417            and then not Is_Private_Type (Etype (Actual))
8418            and then (Base_Type (Full_View (Ftyp)) = Base_Type (Etype (Actual))
8419                       or else Base_Type (Etype (Actual)) = Ftyp)
8420          then
8421             --  If the actual has the type of the full view of the formal, or
8422             --  else a non-private subtype of the formal, then the visibility
8423             --  of the formal type has changed. Add to the actuals a subtype
8424             --  declaration that will force the exchange of views in the body
8425             --  of the instance as well.
8426
8427             Subt_Decl :=
8428               Make_Subtype_Declaration (Loc,
8429                  Defining_Identifier => Make_Temporary (Loc, 'P'),
8430                  Subtype_Indication  => New_Occurrence_Of (Ftyp, Loc));
8431
8432             Prepend (Subt_Decl, List);
8433
8434             Prepend_Elmt (Full_View (Ftyp), Exchanged_Views);
8435             Exchange_Declarations (Ftyp);
8436          end if;
8437
8438          Resolve (Actual, Ftyp);
8439
8440          if not Denotes_Variable (Actual) then
8441             Error_Msg_NE
8442               ("actual for& must be a variable", Actual, Gen_Obj);
8443
8444          elsif Base_Type (Ftyp) /= Base_Type (Etype (Actual)) then
8445
8446             --  Ada 2005 (AI-423): For a generic formal object of mode in out,
8447             --  the type of the actual shall resolve to a specific anonymous
8448             --  access type.
8449
8450             if Ada_Version < Ada_2005
8451               or else
8452                 Ekind (Base_Type (Ftyp)) /=
8453                   E_Anonymous_Access_Type
8454               or else
8455                 Ekind (Base_Type (Etype (Actual))) /=
8456                   E_Anonymous_Access_Type
8457             then
8458                Error_Msg_NE ("type of actual does not match type of&",
8459                              Actual, Gen_Obj);
8460             end if;
8461          end if;
8462
8463          Note_Possible_Modification (Actual, Sure => True);
8464
8465          --  Check for instantiation of atomic/volatile actual for
8466          --  non-atomic/volatile formal (RM C.6 (12)).
8467
8468          if Is_Atomic_Object (Actual)
8469            and then not Is_Atomic (Orig_Ftyp)
8470          then
8471             Error_Msg_N
8472               ("cannot instantiate non-atomic formal object " &
8473                "with atomic actual", Actual);
8474
8475          elsif Is_Volatile_Object (Actual)
8476            and then not Is_Volatile (Orig_Ftyp)
8477          then
8478             Error_Msg_N
8479               ("cannot instantiate non-volatile formal object " &
8480                "with volatile actual", Actual);
8481          end if;
8482
8483       --  Formal in-parameter
8484
8485       else
8486          --  The instantiation of a generic formal in-parameter is constant
8487          --  declaration. The actual is the expression for that declaration.
8488
8489          if Present (Actual) then
8490             if Present (Subt_Mark) then
8491                Def := Subt_Mark;
8492             else pragma Assert (Present (Acc_Def));
8493                Def := Acc_Def;
8494             end if;
8495
8496             Decl_Node :=
8497               Make_Object_Declaration (Loc,
8498                 Defining_Identifier    => New_Copy (Gen_Obj),
8499                 Constant_Present       => True,
8500                 Null_Exclusion_Present => Null_Exclusion_Present (Formal),
8501                 Object_Definition      => New_Copy_Tree (Def),
8502                 Expression             => Actual);
8503
8504             Set_Corresponding_Generic_Association (Decl_Node, Act_Assoc);
8505
8506             --  A generic formal object of a tagged type is defined to be
8507             --  aliased so the new constant must also be treated as aliased.
8508
8509             if Is_Tagged_Type (Etype (A_Gen_Obj)) then
8510                Set_Aliased_Present (Decl_Node);
8511             end if;
8512
8513             Append (Decl_Node, List);
8514
8515             --  No need to repeat (pre-)analysis of some expression nodes
8516             --  already handled in Preanalyze_Actuals.
8517
8518             if Nkind (Actual) /= N_Allocator then
8519                Analyze (Actual);
8520
8521                --  Return if the analysis of the actual reported some error
8522
8523                if Etype (Actual) = Any_Type then
8524                   return List;
8525                end if;
8526             end if;
8527
8528             declare
8529                Formal_Type : constant Entity_Id := Etype (A_Gen_Obj);
8530                Typ         : Entity_Id;
8531
8532             begin
8533                Typ := Get_Instance_Of (Formal_Type);
8534
8535                Freeze_Before (Instantiation_Node, Typ);
8536
8537                --  If the actual is an aggregate, perform name resolution on
8538                --  its components (the analysis of an aggregate does not do it)
8539                --  to capture local names that may be hidden if the generic is
8540                --  a child unit.
8541
8542                if Nkind (Actual) = N_Aggregate then
8543                   Preanalyze_And_Resolve (Actual, Typ);
8544                end if;
8545
8546                if Is_Limited_Type (Typ)
8547                  and then not OK_For_Limited_Init (Typ, Actual)
8548                then
8549                   Error_Msg_N
8550                     ("initialization not allowed for limited types", Actual);
8551                   Explain_Limited_Type (Typ, Actual);
8552                end if;
8553             end;
8554
8555          elsif Present (Default_Expression (Formal)) then
8556
8557             --  Use default to construct declaration
8558
8559             if Present (Subt_Mark) then
8560                Def := Subt_Mark;
8561             else pragma Assert (Present (Acc_Def));
8562                Def := Acc_Def;
8563             end if;
8564
8565             Decl_Node :=
8566               Make_Object_Declaration (Sloc (Formal),
8567                 Defining_Identifier    => New_Copy (Gen_Obj),
8568                 Constant_Present       => True,
8569                 Null_Exclusion_Present => Null_Exclusion_Present (Formal),
8570                 Object_Definition      => New_Copy (Def),
8571                 Expression             => New_Copy_Tree
8572                                             (Default_Expression (Formal)));
8573
8574             Append (Decl_Node, List);
8575             Set_Analyzed (Expression (Decl_Node), False);
8576
8577          else
8578             Error_Msg_NE
8579               ("missing actual&",
8580                 Instantiation_Node, Gen_Obj);
8581             Error_Msg_NE ("\in instantiation of & declared#",
8582               Instantiation_Node, Scope (A_Gen_Obj));
8583
8584             if Is_Scalar_Type (Etype (A_Gen_Obj)) then
8585
8586                --  Create dummy constant declaration so that instance can be
8587                --  analyzed, to minimize cascaded visibility errors.
8588
8589                if Present (Subt_Mark) then
8590                   Def := Subt_Mark;
8591                else pragma Assert (Present (Acc_Def));
8592                   Def := Acc_Def;
8593                end if;
8594
8595                Decl_Node :=
8596                  Make_Object_Declaration (Loc,
8597                    Defining_Identifier    => New_Copy (Gen_Obj),
8598                    Constant_Present       => True,
8599                    Null_Exclusion_Present => Null_Exclusion_Present (Formal),
8600                    Object_Definition      => New_Copy (Def),
8601                    Expression             =>
8602                      Make_Attribute_Reference (Sloc (Gen_Obj),
8603                        Attribute_Name => Name_First,
8604                        Prefix         => New_Copy (Def)));
8605
8606                Append (Decl_Node, List);
8607
8608             else
8609                Abandon_Instantiation (Instantiation_Node);
8610             end if;
8611          end if;
8612       end if;
8613
8614       if Nkind (Actual) in N_Has_Entity then
8615          Actual_Decl := Parent (Entity (Actual));
8616       end if;
8617
8618       --  Ada 2005 (AI-423): For a formal object declaration with a null
8619       --  exclusion or an access definition that has a null exclusion: If the
8620       --  actual matching the formal object declaration denotes a generic
8621       --  formal object of another generic unit G, and the instantiation
8622       --  containing the actual occurs within the body of G or within the body
8623       --  of a generic unit declared within the declarative region of G, then
8624       --  the declaration of the formal object of G must have a null exclusion.
8625       --  Otherwise, the subtype of the actual matching the formal object
8626       --  declaration shall exclude null.
8627
8628       if Ada_Version >= Ada_2005
8629         and then Present (Actual_Decl)
8630         and then
8631           Nkind_In (Actual_Decl, N_Formal_Object_Declaration,
8632                                  N_Object_Declaration)
8633         and then Nkind (Analyzed_Formal) = N_Formal_Object_Declaration
8634         and then not Has_Null_Exclusion (Actual_Decl)
8635         and then Has_Null_Exclusion (Analyzed_Formal)
8636       then
8637          Error_Msg_Sloc := Sloc (Analyzed_Formal);
8638          Error_Msg_N
8639            ("actual must exclude null to match generic formal#", Actual);
8640       end if;
8641
8642       return List;
8643    end Instantiate_Object;
8644
8645    ------------------------------
8646    -- Instantiate_Package_Body --
8647    ------------------------------
8648
8649    procedure Instantiate_Package_Body
8650      (Body_Info     : Pending_Body_Info;
8651       Inlined_Body  : Boolean := False;
8652       Body_Optional : Boolean := False)
8653    is
8654       Act_Decl    : constant Node_Id    := Body_Info.Act_Decl;
8655       Inst_Node   : constant Node_Id    := Body_Info.Inst_Node;
8656       Loc         : constant Source_Ptr := Sloc (Inst_Node);
8657
8658       Gen_Id      : constant Node_Id    := Name (Inst_Node);
8659       Gen_Unit    : constant Entity_Id  := Get_Generic_Entity (Inst_Node);
8660       Gen_Decl    : constant Node_Id    := Unit_Declaration_Node (Gen_Unit);
8661       Act_Spec    : constant Node_Id    := Specification (Act_Decl);
8662       Act_Decl_Id : constant Entity_Id  := Defining_Entity (Act_Spec);
8663
8664       Act_Body_Name : Node_Id;
8665       Gen_Body      : Node_Id;
8666       Gen_Body_Id   : Node_Id;
8667       Act_Body      : Node_Id;
8668       Act_Body_Id   : Entity_Id;
8669
8670       Parent_Installed : Boolean := False;
8671       Save_Style_Check : constant Boolean := Style_Check;
8672
8673       Par_Ent : Entity_Id := Empty;
8674       Par_Vis : Boolean   := False;
8675
8676    begin
8677       Gen_Body_Id := Corresponding_Body (Gen_Decl);
8678
8679       --  The instance body may already have been processed, as the parent of
8680       --  another instance that is inlined (Load_Parent_Of_Generic).
8681
8682       if Present (Corresponding_Body (Instance_Spec (Inst_Node))) then
8683          return;
8684       end if;
8685
8686       Expander_Mode_Save_And_Set (Body_Info.Expander_Status);
8687
8688       --  Re-establish the state of information on which checks are suppressed.
8689       --  This information was set in Body_Info at the point of instantiation,
8690       --  and now we restore it so that the instance is compiled using the
8691       --  check status at the instantiation (RM 11.5 (7.2/2), AI95-00224-01).
8692
8693       Local_Suppress_Stack_Top := Body_Info.Local_Suppress_Stack_Top;
8694       Scope_Suppress           := Body_Info.Scope_Suppress;
8695       Opt.Ada_Version          := Body_Info.Version;
8696
8697       if No (Gen_Body_Id) then
8698          Load_Parent_Of_Generic
8699            (Inst_Node, Specification (Gen_Decl), Body_Optional);
8700          Gen_Body_Id := Corresponding_Body (Gen_Decl);
8701       end if;
8702
8703       --  Establish global variable for sloc adjustment and for error recovery
8704
8705       Instantiation_Node := Inst_Node;
8706
8707       if Present (Gen_Body_Id) then
8708          Save_Env (Gen_Unit, Act_Decl_Id);
8709          Style_Check := False;
8710          Current_Sem_Unit := Body_Info.Current_Sem_Unit;
8711
8712          Gen_Body := Unit_Declaration_Node (Gen_Body_Id);
8713
8714          Create_Instantiation_Source
8715            (Inst_Node, Gen_Body_Id, False, S_Adjustment);
8716
8717          Act_Body :=
8718            Copy_Generic_Node
8719              (Original_Node (Gen_Body), Empty, Instantiating => True);
8720
8721          --  Build new name (possibly qualified) for body declaration
8722
8723          Act_Body_Id := New_Copy (Act_Decl_Id);
8724
8725          --  Some attributes of spec entity are not inherited by body entity
8726
8727          Set_Handler_Records (Act_Body_Id, No_List);
8728
8729          if Nkind (Defining_Unit_Name (Act_Spec)) =
8730                                            N_Defining_Program_Unit_Name
8731          then
8732             Act_Body_Name :=
8733               Make_Defining_Program_Unit_Name (Loc,
8734                 Name => New_Copy_Tree (Name (Defining_Unit_Name (Act_Spec))),
8735                 Defining_Identifier => Act_Body_Id);
8736          else
8737             Act_Body_Name :=  Act_Body_Id;
8738          end if;
8739
8740          Set_Defining_Unit_Name (Act_Body, Act_Body_Name);
8741
8742          Set_Corresponding_Spec (Act_Body, Act_Decl_Id);
8743          Check_Generic_Actuals (Act_Decl_Id, False);
8744
8745          --  If it is a child unit, make the parent instance (which is an
8746          --  instance of the parent of the generic) visible. The parent
8747          --  instance is the prefix of the name of the generic unit.
8748
8749          if Ekind (Scope (Gen_Unit)) = E_Generic_Package
8750            and then Nkind (Gen_Id) = N_Expanded_Name
8751          then
8752             Par_Ent := Entity (Prefix (Gen_Id));
8753             Par_Vis := Is_Immediately_Visible (Par_Ent);
8754             Install_Parent (Par_Ent, In_Body => True);
8755             Parent_Installed := True;
8756
8757          elsif Is_Child_Unit (Gen_Unit) then
8758             Par_Ent := Scope (Gen_Unit);
8759             Par_Vis := Is_Immediately_Visible (Par_Ent);
8760             Install_Parent (Par_Ent, In_Body => True);
8761             Parent_Installed := True;
8762          end if;
8763
8764          --  If the instantiation is a library unit, and this is the main unit,
8765          --  then build the resulting compilation unit nodes for the instance.
8766          --  If this is a compilation unit but it is not the main unit, then it
8767          --  is the body of a unit in the context, that is being compiled
8768          --  because it is encloses some inlined unit or another generic unit
8769          --  being instantiated. In that case, this body is not part of the
8770          --  current compilation, and is not attached to the tree, but its
8771          --  parent must be set for analysis.
8772
8773          if Nkind (Parent (Inst_Node)) = N_Compilation_Unit then
8774
8775             --  Replace instance node with body of instance, and create new
8776             --  node for corresponding instance declaration.
8777
8778             Build_Instance_Compilation_Unit_Nodes
8779               (Inst_Node, Act_Body, Act_Decl);
8780             Analyze (Inst_Node);
8781
8782             if Parent (Inst_Node) = Cunit (Main_Unit) then
8783
8784                --  If the instance is a child unit itself, then set the scope
8785                --  of the expanded body to be the parent of the instantiation
8786                --  (ensuring that the fully qualified name will be generated
8787                --  for the elaboration subprogram).
8788
8789                if Nkind (Defining_Unit_Name (Act_Spec)) =
8790                                               N_Defining_Program_Unit_Name
8791                then
8792                   Set_Scope
8793                     (Defining_Entity (Inst_Node), Scope (Act_Decl_Id));
8794                end if;
8795             end if;
8796
8797          --  Case where instantiation is not a library unit
8798
8799          else
8800             --  If this is an early instantiation, i.e. appears textually
8801             --  before the corresponding body and must be elaborated first,
8802             --  indicate that the body instance is to be delayed.
8803
8804             Install_Body (Act_Body, Inst_Node, Gen_Body, Gen_Decl);
8805
8806             --  Now analyze the body. We turn off all checks if this is an
8807             --  internal unit, since there is no reason to have checks on for
8808             --  any predefined run-time library code. All such code is designed
8809             --  to be compiled with checks off.
8810
8811             --  Note that we do NOT apply this criterion to children of GNAT
8812             --  (or on VMS, children of DEC). The latter units must suppress
8813             --  checks explicitly if this is needed.
8814
8815             if Is_Predefined_File_Name
8816                  (Unit_File_Name (Get_Source_Unit (Gen_Decl)))
8817             then
8818                Analyze (Act_Body, Suppress => All_Checks);
8819             else
8820                Analyze (Act_Body);
8821             end if;
8822          end if;
8823
8824          Inherit_Context (Gen_Body, Inst_Node);
8825
8826          --  Remove the parent instances if they have been placed on the scope
8827          --  stack to compile the body.
8828
8829          if Parent_Installed then
8830             Remove_Parent (In_Body => True);
8831
8832             --  Restore the previous visibility of the parent
8833
8834             Set_Is_Immediately_Visible (Par_Ent, Par_Vis);
8835          end if;
8836
8837          Restore_Private_Views (Act_Decl_Id);
8838
8839          --  Remove the current unit from visibility if this is an instance
8840          --  that is not elaborated on the fly for inlining purposes.
8841
8842          if not Inlined_Body then
8843             Set_Is_Immediately_Visible (Act_Decl_Id, False);
8844          end if;
8845
8846          Restore_Env;
8847          Style_Check := Save_Style_Check;
8848
8849       --  If we have no body, and the unit requires a body, then complain. This
8850       --  complaint is suppressed if we have detected other errors (since a
8851       --  common reason for missing the body is that it had errors).
8852       --  In CodePeer mode, a warning has been emitted already, no need for
8853       --  further messages.
8854
8855       elsif Unit_Requires_Body (Gen_Unit)
8856         and then not Body_Optional
8857       then
8858          if CodePeer_Mode then
8859             null;
8860
8861          elsif Serious_Errors_Detected = 0 then
8862             Error_Msg_NE
8863               ("cannot find body of generic package &", Inst_Node, Gen_Unit);
8864
8865          --  Don't attempt to perform any cleanup actions if some other error
8866          --  was already detected, since this can cause blowups.
8867
8868          else
8869             return;
8870          end if;
8871
8872       --  Case of package that does not need a body
8873
8874       else
8875          --  If the instantiation of the declaration is a library unit, rewrite
8876          --  the original package instantiation as a package declaration in the
8877          --  compilation unit node.
8878
8879          if Nkind (Parent (Inst_Node)) = N_Compilation_Unit then
8880             Set_Parent_Spec (Act_Decl, Parent_Spec (Inst_Node));
8881             Rewrite (Inst_Node, Act_Decl);
8882
8883             --  Generate elaboration entity, in case spec has elaboration code.
8884             --  This cannot be done when the instance is analyzed, because it
8885             --  is not known yet whether the body exists.
8886
8887             Set_Elaboration_Entity_Required (Act_Decl_Id, False);
8888             Build_Elaboration_Entity (Parent (Inst_Node), Act_Decl_Id);
8889
8890          --  If the instantiation is not a library unit, then append the
8891          --  declaration to the list of implicitly generated entities, unless
8892          --  it is already a list member which means that it was already
8893          --  processed
8894
8895          elsif not Is_List_Member (Act_Decl) then
8896             Mark_Rewrite_Insertion (Act_Decl);
8897             Insert_Before (Inst_Node, Act_Decl);
8898          end if;
8899       end if;
8900
8901       Expander_Mode_Restore;
8902    end Instantiate_Package_Body;
8903
8904    ---------------------------------
8905    -- Instantiate_Subprogram_Body --
8906    ---------------------------------
8907
8908    procedure Instantiate_Subprogram_Body
8909      (Body_Info     : Pending_Body_Info;
8910       Body_Optional : Boolean := False)
8911    is
8912       Act_Decl      : constant Node_Id    := Body_Info.Act_Decl;
8913       Inst_Node     : constant Node_Id    := Body_Info.Inst_Node;
8914       Loc           : constant Source_Ptr := Sloc (Inst_Node);
8915       Gen_Id        : constant Node_Id    := Name (Inst_Node);
8916       Gen_Unit      : constant Entity_Id  := Get_Generic_Entity (Inst_Node);
8917       Gen_Decl      : constant Node_Id    := Unit_Declaration_Node (Gen_Unit);
8918       Anon_Id       : constant Entity_Id  :=
8919                         Defining_Unit_Name (Specification (Act_Decl));
8920       Pack_Id       : constant Entity_Id  :=
8921                         Defining_Unit_Name (Parent (Act_Decl));
8922       Decls         : List_Id;
8923       Gen_Body      : Node_Id;
8924       Gen_Body_Id   : Node_Id;
8925       Act_Body      : Node_Id;
8926       Pack_Body     : Node_Id;
8927       Prev_Formal   : Entity_Id;
8928       Ret_Expr      : Node_Id;
8929       Unit_Renaming : Node_Id;
8930
8931       Parent_Installed : Boolean := False;
8932       Save_Style_Check : constant Boolean := Style_Check;
8933
8934       Par_Ent : Entity_Id := Empty;
8935       Par_Vis : Boolean   := False;
8936
8937    begin
8938       Gen_Body_Id := Corresponding_Body (Gen_Decl);
8939
8940       --  Subprogram body may have been created already because of an inline
8941       --  pragma, or because of multiple elaborations of the enclosing package
8942       --  when several instances of the subprogram appear in the main unit.
8943
8944       if Present (Corresponding_Body (Act_Decl)) then
8945          return;
8946       end if;
8947
8948       Expander_Mode_Save_And_Set (Body_Info.Expander_Status);
8949
8950       --  Re-establish the state of information on which checks are suppressed.
8951       --  This information was set in Body_Info at the point of instantiation,
8952       --  and now we restore it so that the instance is compiled using the
8953       --  check status at the instantiation (RM 11.5 (7.2/2), AI95-00224-01).
8954
8955       Local_Suppress_Stack_Top := Body_Info.Local_Suppress_Stack_Top;
8956       Scope_Suppress           := Body_Info.Scope_Suppress;
8957       Opt.Ada_Version          := Body_Info.Version;
8958
8959       if No (Gen_Body_Id) then
8960
8961          --  For imported generic subprogram, no body to compile, complete
8962          --  the spec entity appropriately.
8963
8964          if Is_Imported (Gen_Unit) then
8965             Set_Is_Imported (Anon_Id);
8966             Set_First_Rep_Item (Anon_Id, First_Rep_Item (Gen_Unit));
8967             Set_Interface_Name (Anon_Id, Interface_Name (Gen_Unit));
8968             Set_Convention     (Anon_Id, Convention     (Gen_Unit));
8969             Set_Has_Completion (Anon_Id);
8970             return;
8971
8972          --  For other cases, compile the body
8973
8974          else
8975             Load_Parent_Of_Generic
8976               (Inst_Node, Specification (Gen_Decl), Body_Optional);
8977             Gen_Body_Id := Corresponding_Body (Gen_Decl);
8978          end if;
8979       end if;
8980
8981       Instantiation_Node := Inst_Node;
8982
8983       if Present (Gen_Body_Id) then
8984          Gen_Body := Unit_Declaration_Node (Gen_Body_Id);
8985
8986          if Nkind (Gen_Body) = N_Subprogram_Body_Stub then
8987
8988             --  Either body is not present, or context is non-expanding, as
8989             --  when compiling a subunit. Mark the instance as completed, and
8990             --  diagnose a missing body when needed.
8991
8992             if Expander_Active
8993               and then Operating_Mode = Generate_Code
8994             then
8995                Error_Msg_N
8996                  ("missing proper body for instantiation", Gen_Body);
8997             end if;
8998
8999             Set_Has_Completion (Anon_Id);
9000             return;
9001          end if;
9002
9003          Save_Env (Gen_Unit, Anon_Id);
9004          Style_Check := False;
9005          Current_Sem_Unit := Body_Info.Current_Sem_Unit;
9006          Create_Instantiation_Source
9007            (Inst_Node,
9008             Gen_Body_Id,
9009             False,
9010             S_Adjustment);
9011
9012          Act_Body :=
9013            Copy_Generic_Node
9014              (Original_Node (Gen_Body), Empty, Instantiating => True);
9015
9016          --  Create proper defining name for the body, to correspond to
9017          --  the one in the spec.
9018
9019          Set_Defining_Unit_Name (Specification (Act_Body),
9020            Make_Defining_Identifier
9021              (Sloc (Defining_Entity (Inst_Node)), Chars (Anon_Id)));
9022          Set_Corresponding_Spec (Act_Body, Anon_Id);
9023          Set_Has_Completion (Anon_Id);
9024          Check_Generic_Actuals (Pack_Id, False);
9025
9026          --  Generate a reference to link the visible subprogram instance to
9027          --  the generic body, which for navigation purposes is the only
9028          --  available source for the instance.
9029
9030          Generate_Reference
9031            (Related_Instance (Pack_Id),
9032              Gen_Body_Id, 'b', Set_Ref => False, Force => True);
9033
9034          --  If it is a child unit, make the parent instance (which is an
9035          --  instance of the parent of the generic) visible. The parent
9036          --  instance is the prefix of the name of the generic unit.
9037
9038          if Ekind (Scope (Gen_Unit)) = E_Generic_Package
9039            and then Nkind (Gen_Id) = N_Expanded_Name
9040          then
9041             Par_Ent := Entity (Prefix (Gen_Id));
9042             Par_Vis := Is_Immediately_Visible (Par_Ent);
9043             Install_Parent (Par_Ent, In_Body => True);
9044             Parent_Installed := True;
9045
9046          elsif Is_Child_Unit (Gen_Unit) then
9047             Par_Ent := Scope (Gen_Unit);
9048             Par_Vis := Is_Immediately_Visible (Par_Ent);
9049             Install_Parent (Par_Ent, In_Body => True);
9050             Parent_Installed := True;
9051          end if;
9052
9053          --  Inside its body, a reference to the generic unit is a reference
9054          --  to the instance. The corresponding renaming is the first
9055          --  declaration in the body.
9056
9057          Unit_Renaming :=
9058            Make_Subprogram_Renaming_Declaration (Loc,
9059              Specification =>
9060                Copy_Generic_Node (
9061                  Specification (Original_Node (Gen_Body)),
9062                  Empty,
9063                  Instantiating => True),
9064              Name => New_Occurrence_Of (Anon_Id, Loc));
9065
9066          --  If there is a formal subprogram with the same name as the unit
9067          --  itself, do not add this renaming declaration. This is a temporary
9068          --  fix for one ACVC test. ???
9069
9070          Prev_Formal := First_Entity (Pack_Id);
9071          while Present (Prev_Formal) loop
9072             if Chars (Prev_Formal) = Chars (Gen_Unit)
9073               and then Is_Overloadable (Prev_Formal)
9074             then
9075                exit;
9076             end if;
9077
9078             Next_Entity (Prev_Formal);
9079          end loop;
9080
9081          if Present (Prev_Formal) then
9082             Decls :=  New_List (Act_Body);
9083          else
9084             Decls :=  New_List (Unit_Renaming, Act_Body);
9085          end if;
9086
9087          --  The subprogram body is placed in the body of a dummy package body,
9088          --  whose spec contains the subprogram declaration as well as the
9089          --  renaming declarations for the generic parameters.
9090
9091          Pack_Body := Make_Package_Body (Loc,
9092            Defining_Unit_Name => New_Copy (Pack_Id),
9093            Declarations       => Decls);
9094
9095          Set_Corresponding_Spec (Pack_Body, Pack_Id);
9096
9097          --  If the instantiation is a library unit, then build resulting
9098          --  compilation unit nodes for the instance. The declaration of
9099          --  the enclosing package is the grandparent of the subprogram
9100          --  declaration. First replace the instantiation node as the unit
9101          --  of the corresponding compilation.
9102
9103          if Nkind (Parent (Inst_Node)) = N_Compilation_Unit then
9104             if Parent (Inst_Node) = Cunit (Main_Unit) then
9105                Set_Unit (Parent (Inst_Node), Inst_Node);
9106                Build_Instance_Compilation_Unit_Nodes
9107                  (Inst_Node, Pack_Body, Parent (Parent (Act_Decl)));
9108                Analyze (Inst_Node);
9109             else
9110                Set_Parent (Pack_Body, Parent (Inst_Node));
9111                Analyze (Pack_Body);
9112             end if;
9113
9114          else
9115             Insert_Before (Inst_Node, Pack_Body);
9116             Mark_Rewrite_Insertion (Pack_Body);
9117             Analyze (Pack_Body);
9118
9119             if Expander_Active then
9120                Freeze_Subprogram_Body (Inst_Node, Gen_Body, Pack_Id);
9121             end if;
9122          end if;
9123
9124          Inherit_Context (Gen_Body, Inst_Node);
9125
9126          Restore_Private_Views (Pack_Id, False);
9127
9128          if Parent_Installed then
9129             Remove_Parent (In_Body => True);
9130
9131             --  Restore the previous visibility of the parent
9132
9133             Set_Is_Immediately_Visible (Par_Ent, Par_Vis);
9134          end if;
9135
9136          Restore_Env;
9137          Style_Check := Save_Style_Check;
9138
9139       --  Body not found. Error was emitted already. If there were no previous
9140       --  errors, this may be an instance whose scope is a premature instance.
9141       --  In that case we must insure that the (legal) program does raise
9142       --  program error if executed. We generate a subprogram body for this
9143       --  purpose. See DEC ac30vso.
9144
9145       --  Should not reference proprietary DEC tests in comments ???
9146
9147       elsif Serious_Errors_Detected = 0
9148         and then Nkind (Parent (Inst_Node)) /= N_Compilation_Unit
9149       then
9150          if Body_Optional then
9151             return;
9152
9153          elsif Ekind (Anon_Id) = E_Procedure then
9154             Act_Body :=
9155               Make_Subprogram_Body (Loc,
9156                  Specification              =>
9157                    Make_Procedure_Specification (Loc,
9158                      Defining_Unit_Name         =>
9159                        Make_Defining_Identifier (Loc, Chars (Anon_Id)),
9160                        Parameter_Specifications =>
9161                        New_Copy_List
9162                          (Parameter_Specifications (Parent (Anon_Id)))),
9163
9164                  Declarations               => Empty_List,
9165                  Handled_Statement_Sequence =>
9166                    Make_Handled_Sequence_Of_Statements (Loc,
9167                      Statements =>
9168                        New_List (
9169                          Make_Raise_Program_Error (Loc,
9170                            Reason =>
9171                              PE_Access_Before_Elaboration))));
9172
9173          else
9174             Ret_Expr :=
9175               Make_Raise_Program_Error (Loc,
9176                 Reason => PE_Access_Before_Elaboration);
9177
9178             Set_Etype (Ret_Expr, (Etype (Anon_Id)));
9179             Set_Analyzed (Ret_Expr);
9180
9181             Act_Body :=
9182               Make_Subprogram_Body (Loc,
9183                 Specification =>
9184                   Make_Function_Specification (Loc,
9185                      Defining_Unit_Name         =>
9186                        Make_Defining_Identifier (Loc, Chars (Anon_Id)),
9187                        Parameter_Specifications =>
9188                        New_Copy_List
9189                          (Parameter_Specifications (Parent (Anon_Id))),
9190                      Result_Definition =>
9191                        New_Occurrence_Of (Etype (Anon_Id), Loc)),
9192
9193                   Declarations               => Empty_List,
9194                   Handled_Statement_Sequence =>
9195                     Make_Handled_Sequence_Of_Statements (Loc,
9196                       Statements =>
9197                         New_List
9198                           (Make_Simple_Return_Statement (Loc, Ret_Expr))));
9199          end if;
9200
9201          Pack_Body := Make_Package_Body (Loc,
9202            Defining_Unit_Name => New_Copy (Pack_Id),
9203            Declarations       => New_List (Act_Body));
9204
9205          Insert_After (Inst_Node, Pack_Body);
9206          Set_Corresponding_Spec (Pack_Body, Pack_Id);
9207          Analyze (Pack_Body);
9208       end if;
9209
9210       Expander_Mode_Restore;
9211    end Instantiate_Subprogram_Body;
9212
9213    ----------------------
9214    -- Instantiate_Type --
9215    ----------------------
9216
9217    function Instantiate_Type
9218      (Formal          : Node_Id;
9219       Actual          : Node_Id;
9220       Analyzed_Formal : Node_Id;
9221       Actual_Decls    : List_Id) return List_Id
9222    is
9223       Gen_T      : constant Entity_Id  := Defining_Identifier (Formal);
9224       A_Gen_T    : constant Entity_Id  :=
9225                      Defining_Identifier (Analyzed_Formal);
9226       Ancestor   : Entity_Id := Empty;
9227       Def        : constant Node_Id    := Formal_Type_Definition (Formal);
9228       Act_T      : Entity_Id;
9229       Decl_Node  : Node_Id;
9230       Decl_Nodes : List_Id;
9231       Loc        : Source_Ptr;
9232       Subt       : Entity_Id;
9233
9234       procedure Validate_Array_Type_Instance;
9235       procedure Validate_Access_Subprogram_Instance;
9236       procedure Validate_Access_Type_Instance;
9237       procedure Validate_Derived_Type_Instance;
9238       procedure Validate_Derived_Interface_Type_Instance;
9239       procedure Validate_Interface_Type_Instance;
9240       procedure Validate_Private_Type_Instance;
9241       --  These procedures perform validation tests for the named case
9242
9243       function Subtypes_Match (Gen_T, Act_T : Entity_Id) return Boolean;
9244       --  Check that base types are the same and that the subtypes match
9245       --  statically. Used in several of the above.
9246
9247       --------------------
9248       -- Subtypes_Match --
9249       --------------------
9250
9251       function Subtypes_Match (Gen_T, Act_T : Entity_Id) return Boolean is
9252          T : constant Entity_Id := Get_Instance_Of (Gen_T);
9253
9254       begin
9255          return (Base_Type (T) = Base_Type (Act_T)
9256                   and then Subtypes_Statically_Match (T, Act_T))
9257
9258            or else (Is_Class_Wide_Type (Gen_T)
9259                      and then Is_Class_Wide_Type (Act_T)
9260                      and then
9261                        Subtypes_Match
9262                         (Get_Instance_Of (Root_Type (Gen_T)),
9263                          Root_Type (Act_T)))
9264
9265            or else
9266              ((Ekind (Gen_T) = E_Anonymous_Access_Subprogram_Type
9267                  or else Ekind (Gen_T) = E_Anonymous_Access_Type)
9268                and then Ekind (Act_T) = Ekind (Gen_T)
9269                and then
9270                  Subtypes_Statically_Match
9271                    (Designated_Type (Gen_T), Designated_Type (Act_T)));
9272       end Subtypes_Match;
9273
9274       -----------------------------------------
9275       -- Validate_Access_Subprogram_Instance --
9276       -----------------------------------------
9277
9278       procedure Validate_Access_Subprogram_Instance is
9279       begin
9280          if not Is_Access_Type (Act_T)
9281            or else Ekind (Designated_Type (Act_T)) /= E_Subprogram_Type
9282          then
9283             Error_Msg_NE
9284               ("expect access type in instantiation of &", Actual, Gen_T);
9285             Abandon_Instantiation (Actual);
9286          end if;
9287
9288          Check_Mode_Conformant
9289            (Designated_Type (Act_T),
9290             Designated_Type (A_Gen_T),
9291             Actual,
9292             Get_Inst => True);
9293
9294          if Ekind (Base_Type (Act_T)) = E_Access_Protected_Subprogram_Type then
9295             if Ekind (A_Gen_T) = E_Access_Subprogram_Type then
9296                Error_Msg_NE
9297                  ("protected access type not allowed for formal &",
9298                   Actual, Gen_T);
9299             end if;
9300
9301          elsif Ekind (A_Gen_T) = E_Access_Protected_Subprogram_Type then
9302             Error_Msg_NE
9303               ("expect protected access type for formal &",
9304                Actual, Gen_T);
9305          end if;
9306       end Validate_Access_Subprogram_Instance;
9307
9308       -----------------------------------
9309       -- Validate_Access_Type_Instance --
9310       -----------------------------------
9311
9312       procedure Validate_Access_Type_Instance is
9313          Desig_Type : constant Entity_Id :=
9314                         Find_Actual_Type (Designated_Type (A_Gen_T), A_Gen_T);
9315          Desig_Act  : Entity_Id;
9316
9317       begin
9318          if not Is_Access_Type (Act_T) then
9319             Error_Msg_NE
9320               ("expect access type in instantiation of &", Actual, Gen_T);
9321             Abandon_Instantiation (Actual);
9322          end if;
9323
9324          if Is_Access_Constant (A_Gen_T) then
9325             if not Is_Access_Constant (Act_T) then
9326                Error_Msg_N
9327                  ("actual type must be access-to-constant type", Actual);
9328                Abandon_Instantiation (Actual);
9329             end if;
9330          else
9331             if Is_Access_Constant (Act_T) then
9332                Error_Msg_N
9333                  ("actual type must be access-to-variable type", Actual);
9334                Abandon_Instantiation (Actual);
9335
9336             elsif Ekind (A_Gen_T) = E_General_Access_Type
9337               and then Ekind (Base_Type (Act_T)) /= E_General_Access_Type
9338             then
9339                Error_Msg_N -- CODEFIX
9340                  ("actual must be general access type!", Actual);
9341                Error_Msg_NE -- CODEFIX
9342                  ("add ALL to }!", Actual, Act_T);
9343                Abandon_Instantiation (Actual);
9344             end if;
9345          end if;
9346
9347          --  The designated subtypes, that is to say the subtypes introduced
9348          --  by an access type declaration (and not by a subtype declaration)
9349          --  must match.
9350
9351          Desig_Act := Designated_Type (Base_Type (Act_T));
9352
9353          --  The designated type may have been introduced through a limited_
9354          --  with clause, in which case retrieve the non-limited view. This
9355          --  applies to incomplete types as well as to class-wide types.
9356
9357          if From_With_Type (Desig_Act) then
9358             Desig_Act := Available_View (Desig_Act);
9359          end if;
9360
9361          if not Subtypes_Match
9362            (Desig_Type, Desig_Act) then
9363             Error_Msg_NE
9364               ("designated type of actual does not match that of formal &",
9365                  Actual, Gen_T);
9366             Abandon_Instantiation (Actual);
9367
9368          elsif Is_Access_Type (Designated_Type (Act_T))
9369            and then Is_Constrained (Designated_Type (Designated_Type (Act_T)))
9370                       /=
9371                   Is_Constrained (Designated_Type (Desig_Type))
9372          then
9373             Error_Msg_NE
9374               ("designated type of actual does not match that of formal &",
9375                  Actual, Gen_T);
9376             Abandon_Instantiation (Actual);
9377          end if;
9378
9379          --  Ada 2005: null-exclusion indicators of the two types must agree
9380
9381          if Can_Never_Be_Null (A_Gen_T) /=  Can_Never_Be_Null (Act_T) then
9382             Error_Msg_NE
9383               ("non null exclusion of actual and formal & do not match",
9384                  Actual, Gen_T);
9385          end if;
9386       end Validate_Access_Type_Instance;
9387
9388       ----------------------------------
9389       -- Validate_Array_Type_Instance --
9390       ----------------------------------
9391
9392       procedure Validate_Array_Type_Instance is
9393          I1 : Node_Id;
9394          I2 : Node_Id;
9395          T2 : Entity_Id;
9396
9397          function Formal_Dimensions return Int;
9398          --  Count number of dimensions in array type formal
9399
9400          -----------------------
9401          -- Formal_Dimensions --
9402          -----------------------
9403
9404          function Formal_Dimensions return Int is
9405             Num   : Int := 0;
9406             Index : Node_Id;
9407
9408          begin
9409             if Nkind (Def) = N_Constrained_Array_Definition then
9410                Index := First (Discrete_Subtype_Definitions (Def));
9411             else
9412                Index := First (Subtype_Marks (Def));
9413             end if;
9414
9415             while Present (Index) loop
9416                Num := Num + 1;
9417                Next_Index (Index);
9418             end loop;
9419
9420             return Num;
9421          end Formal_Dimensions;
9422
9423       --  Start of processing for Validate_Array_Type_Instance
9424
9425       begin
9426          if not Is_Array_Type (Act_T) then
9427             Error_Msg_NE
9428               ("expect array type in instantiation of &", Actual, Gen_T);
9429             Abandon_Instantiation (Actual);
9430
9431          elsif Nkind (Def) = N_Constrained_Array_Definition then
9432             if not (Is_Constrained (Act_T)) then
9433                Error_Msg_NE
9434                  ("expect constrained array in instantiation of &",
9435                   Actual, Gen_T);
9436                Abandon_Instantiation (Actual);
9437             end if;
9438
9439          else
9440             if Is_Constrained (Act_T) then
9441                Error_Msg_NE
9442                  ("expect unconstrained array in instantiation of &",
9443                   Actual, Gen_T);
9444                Abandon_Instantiation (Actual);
9445             end if;
9446          end if;
9447
9448          if Formal_Dimensions /= Number_Dimensions (Act_T) then
9449             Error_Msg_NE
9450               ("dimensions of actual do not match formal &", Actual, Gen_T);
9451             Abandon_Instantiation (Actual);
9452          end if;
9453
9454          I1 := First_Index (A_Gen_T);
9455          I2 := First_Index (Act_T);
9456          for J in 1 .. Formal_Dimensions loop
9457
9458             --  If the indexes of the actual were given by a subtype_mark,
9459             --  the index was transformed into a range attribute. Retrieve
9460             --  the original type mark for checking.
9461
9462             if Is_Entity_Name (Original_Node (I2)) then
9463                T2 := Entity (Original_Node (I2));
9464             else
9465                T2 := Etype (I2);
9466             end if;
9467
9468             if not Subtypes_Match
9469                      (Find_Actual_Type (Etype (I1), A_Gen_T), T2)
9470             then
9471                Error_Msg_NE
9472                  ("index types of actual do not match those of formal &",
9473                   Actual, Gen_T);
9474                Abandon_Instantiation (Actual);
9475             end if;
9476
9477             Next_Index (I1);
9478             Next_Index (I2);
9479          end loop;
9480
9481          --  Check matching subtypes. Note that there are complex visibility
9482          --  issues when the generic is a child unit and some aspect of the
9483          --  generic type is declared in a parent unit of the generic. We do
9484          --  the test to handle this special case only after a direct check
9485          --  for static matching has failed.
9486
9487          if Subtypes_Match
9488            (Component_Type (A_Gen_T), Component_Type (Act_T))
9489              or else Subtypes_Match
9490                       (Find_Actual_Type (Component_Type (A_Gen_T), A_Gen_T),
9491                        Component_Type (Act_T))
9492          then
9493             null;
9494          else
9495             Error_Msg_NE
9496               ("component subtype of actual does not match that of formal &",
9497                Actual, Gen_T);
9498             Abandon_Instantiation (Actual);
9499          end if;
9500
9501          if Has_Aliased_Components (A_Gen_T)
9502            and then not Has_Aliased_Components (Act_T)
9503          then
9504             Error_Msg_NE
9505               ("actual must have aliased components to match formal type &",
9506                Actual, Gen_T);
9507          end if;
9508       end Validate_Array_Type_Instance;
9509
9510       -----------------------------------------------
9511       --  Validate_Derived_Interface_Type_Instance --
9512       -----------------------------------------------
9513
9514       procedure Validate_Derived_Interface_Type_Instance is
9515          Par  : constant Entity_Id := Entity (Subtype_Indication (Def));
9516          Elmt : Elmt_Id;
9517
9518       begin
9519          --  First apply interface instance checks
9520
9521          Validate_Interface_Type_Instance;
9522
9523          --  Verify that immediate parent interface is an ancestor of
9524          --  the actual.
9525
9526          if Present (Par)
9527            and then not Interface_Present_In_Ancestor (Act_T, Par)
9528          then
9529             Error_Msg_NE
9530               ("interface actual must include progenitor&", Actual, Par);
9531          end if;
9532
9533          --  Now verify that the actual includes all other ancestors of
9534          --  the formal.
9535
9536          Elmt := First_Elmt (Interfaces (A_Gen_T));
9537          while Present (Elmt) loop
9538             if not Interface_Present_In_Ancestor
9539                      (Act_T, Get_Instance_Of (Node (Elmt)))
9540             then
9541                Error_Msg_NE
9542                  ("interface actual must include progenitor&",
9543                     Actual, Node (Elmt));
9544             end if;
9545
9546             Next_Elmt (Elmt);
9547          end loop;
9548       end Validate_Derived_Interface_Type_Instance;
9549
9550       ------------------------------------
9551       -- Validate_Derived_Type_Instance --
9552       ------------------------------------
9553
9554       procedure Validate_Derived_Type_Instance is
9555          Actual_Discr   : Entity_Id;
9556          Ancestor_Discr : Entity_Id;
9557
9558       begin
9559          --  If the parent type in the generic declaration is itself a previous
9560          --  formal type, then it is local to the generic and absent from the
9561          --  analyzed generic definition. In that case the ancestor is the
9562          --  instance of the formal (which must have been instantiated
9563          --  previously), unless the ancestor is itself a formal derived type.
9564          --  In this latter case (which is the subject of Corrigendum 8652/0038
9565          --  (AI-202) the ancestor of the formals is the ancestor of its
9566          --  parent. Otherwise, the analyzed generic carries the parent type.
9567          --  If the parent type is defined in a previous formal package, then
9568          --  the scope of that formal package is that of the generic type
9569          --  itself, and it has already been mapped into the corresponding type
9570          --  in the actual package.
9571
9572          --  Common case: parent type defined outside of the generic
9573
9574          if Is_Entity_Name (Subtype_Mark (Def))
9575            and then Present (Entity (Subtype_Mark (Def)))
9576          then
9577             Ancestor := Get_Instance_Of (Entity (Subtype_Mark (Def)));
9578
9579          --  Check whether parent is defined in a previous formal package
9580
9581          elsif
9582            Scope (Scope (Base_Type (Etype (A_Gen_T)))) = Scope (A_Gen_T)
9583          then
9584             Ancestor :=
9585               Get_Instance_Of (Base_Type (Etype (A_Gen_T)));
9586
9587          --  The type may be a local derivation, or a type extension of a
9588          --  previous formal, or of a formal of a parent package.
9589
9590          elsif Is_Derived_Type (Get_Instance_Of (A_Gen_T))
9591           or else
9592             Ekind (Get_Instance_Of (A_Gen_T)) = E_Record_Type_With_Private
9593          then
9594             --  Check whether the parent is another derived formal type in the
9595             --  same generic unit.
9596
9597             if Etype (A_Gen_T) /= A_Gen_T
9598               and then Is_Generic_Type (Etype (A_Gen_T))
9599               and then Scope (Etype (A_Gen_T)) = Scope (A_Gen_T)
9600               and then Etype (Etype (A_Gen_T)) /= Etype (A_Gen_T)
9601             then
9602                --  Locate ancestor of parent from the subtype declaration
9603                --  created for the actual.
9604
9605                declare
9606                   Decl : Node_Id;
9607
9608                begin
9609                   Decl := First (Actual_Decls);
9610                   while Present (Decl) loop
9611                      if Nkind (Decl) = N_Subtype_Declaration
9612                        and then Chars (Defining_Identifier (Decl)) =
9613                                                     Chars (Etype (A_Gen_T))
9614                      then
9615                         Ancestor := Generic_Parent_Type (Decl);
9616                         exit;
9617                      else
9618                         Next (Decl);
9619                      end if;
9620                   end loop;
9621                end;
9622
9623                pragma Assert (Present (Ancestor));
9624
9625             else
9626                Ancestor :=
9627                  Get_Instance_Of (Base_Type (Get_Instance_Of (A_Gen_T)));
9628             end if;
9629
9630          else
9631             Ancestor := Get_Instance_Of (Etype (Base_Type (A_Gen_T)));
9632          end if;
9633
9634          --  If the formal derived type has pragma Preelaborable_Initialization
9635          --  then the actual type must have preelaborable initialization.
9636
9637          if Known_To_Have_Preelab_Init (A_Gen_T)
9638            and then not Has_Preelaborable_Initialization (Act_T)
9639          then
9640             Error_Msg_NE
9641               ("actual for & must have preelaborable initialization",
9642                Actual, Gen_T);
9643          end if;
9644
9645          --  Ada 2005 (AI-251)
9646
9647          if Ada_Version >= Ada_2005
9648            and then Is_Interface (Ancestor)
9649          then
9650             if not Interface_Present_In_Ancestor (Act_T, Ancestor) then
9651                Error_Msg_NE
9652                  ("(Ada 2005) expected type implementing & in instantiation",
9653                   Actual, Ancestor);
9654             end if;
9655
9656          elsif not Is_Ancestor (Base_Type (Ancestor), Act_T) then
9657             Error_Msg_NE
9658               ("expect type derived from & in instantiation",
9659                Actual, First_Subtype (Ancestor));
9660             Abandon_Instantiation (Actual);
9661          end if;
9662
9663          --  Ada 2005 (AI-443): Synchronized formal derived type checks. Note
9664          --  that the formal type declaration has been rewritten as a private
9665          --  extension.
9666
9667          if Ada_Version >= Ada_2005
9668            and then Nkind (Parent (A_Gen_T)) = N_Private_Extension_Declaration
9669            and then Synchronized_Present (Parent (A_Gen_T))
9670          then
9671             --  The actual must be a synchronized tagged type
9672
9673             if not Is_Tagged_Type (Act_T) then
9674                Error_Msg_N
9675                  ("actual of synchronized type must be tagged", Actual);
9676                Abandon_Instantiation (Actual);
9677
9678             elsif Nkind (Parent (Act_T)) = N_Full_Type_Declaration
9679               and then Nkind (Type_Definition (Parent (Act_T))) =
9680                          N_Derived_Type_Definition
9681               and then not Synchronized_Present (Type_Definition
9682                              (Parent (Act_T)))
9683             then
9684                Error_Msg_N
9685                  ("actual of synchronized type must be synchronized", Actual);
9686                Abandon_Instantiation (Actual);
9687             end if;
9688          end if;
9689
9690          --  Perform atomic/volatile checks (RM C.6(12))
9691
9692          if Is_Atomic (Act_T) and then not Is_Atomic (Ancestor) then
9693             Error_Msg_N
9694               ("cannot have atomic actual type for non-atomic formal type",
9695                Actual);
9696
9697          elsif Is_Volatile (Act_T)
9698            and then not Is_Volatile (Ancestor)
9699            and then Is_By_Reference_Type (Ancestor)
9700          then
9701             Error_Msg_N
9702               ("cannot have volatile actual type for non-volatile formal type",
9703                Actual);
9704          end if;
9705
9706          --  It should not be necessary to check for unknown discriminants on
9707          --  Formal, but for some reason Has_Unknown_Discriminants is false for
9708          --  A_Gen_T, so Is_Indefinite_Subtype incorrectly returns False. This
9709          --  needs fixing. ???
9710
9711          if not Is_Indefinite_Subtype (A_Gen_T)
9712            and then not Unknown_Discriminants_Present (Formal)
9713            and then Is_Indefinite_Subtype (Act_T)
9714          then
9715             Error_Msg_N
9716               ("actual subtype must be constrained", Actual);
9717             Abandon_Instantiation (Actual);
9718          end if;
9719
9720          if not Unknown_Discriminants_Present (Formal) then
9721             if Is_Constrained (Ancestor) then
9722                if not Is_Constrained (Act_T) then
9723                   Error_Msg_N
9724                     ("actual subtype must be constrained", Actual);
9725                   Abandon_Instantiation (Actual);
9726                end if;
9727
9728             --  Ancestor is unconstrained, Check if generic formal and actual
9729             --  agree on constrainedness. The check only applies to array types
9730             --  and discriminated types.
9731
9732             elsif Is_Constrained (Act_T) then
9733                if Ekind (Ancestor) = E_Access_Type
9734                  or else
9735                    (not Is_Constrained (A_Gen_T)
9736                      and then Is_Composite_Type (A_Gen_T))
9737                then
9738                   Error_Msg_N
9739                     ("actual subtype must be unconstrained", Actual);
9740                   Abandon_Instantiation (Actual);
9741                end if;
9742
9743             --  A class-wide type is only allowed if the formal has unknown
9744             --  discriminants.
9745
9746             elsif Is_Class_Wide_Type (Act_T)
9747               and then not Has_Unknown_Discriminants (Ancestor)
9748             then
9749                Error_Msg_NE
9750                  ("actual for & cannot be a class-wide type", Actual, Gen_T);
9751                Abandon_Instantiation (Actual);
9752
9753             --  Otherwise, the formal and actual shall have the same number
9754             --  of discriminants and each discriminant of the actual must
9755             --  correspond to a discriminant of the formal.
9756
9757             elsif Has_Discriminants (Act_T)
9758               and then not Has_Unknown_Discriminants (Act_T)
9759               and then Has_Discriminants (Ancestor)
9760             then
9761                Actual_Discr   := First_Discriminant (Act_T);
9762                Ancestor_Discr := First_Discriminant (Ancestor);
9763                while Present (Actual_Discr)
9764                  and then Present (Ancestor_Discr)
9765                loop
9766                   if Base_Type (Act_T) /= Base_Type (Ancestor) and then
9767                     No (Corresponding_Discriminant (Actual_Discr))
9768                   then
9769                      Error_Msg_NE
9770                        ("discriminant & does not correspond " &
9771                         "to ancestor discriminant", Actual, Actual_Discr);
9772                      Abandon_Instantiation (Actual);
9773                   end if;
9774
9775                   Next_Discriminant (Actual_Discr);
9776                   Next_Discriminant (Ancestor_Discr);
9777                end loop;
9778
9779                if Present (Actual_Discr) or else Present (Ancestor_Discr) then
9780                   Error_Msg_NE
9781                     ("actual for & must have same number of discriminants",
9782                      Actual, Gen_T);
9783                   Abandon_Instantiation (Actual);
9784                end if;
9785
9786             --  This case should be caught by the earlier check for
9787             --  constrainedness, but the check here is added for completeness.
9788
9789             elsif Has_Discriminants (Act_T)
9790               and then not Has_Unknown_Discriminants (Act_T)
9791             then
9792                Error_Msg_NE
9793                  ("actual for & must not have discriminants", Actual, Gen_T);
9794                Abandon_Instantiation (Actual);
9795
9796             elsif Has_Discriminants (Ancestor) then
9797                Error_Msg_NE
9798                  ("actual for & must have known discriminants", Actual, Gen_T);
9799                Abandon_Instantiation (Actual);
9800             end if;
9801
9802             if not Subtypes_Statically_Compatible (Act_T, Ancestor) then
9803                Error_Msg_N
9804                  ("constraint on actual is incompatible with formal", Actual);
9805                Abandon_Instantiation (Actual);
9806             end if;
9807          end if;
9808
9809          --  If the formal and actual types are abstract, check that there
9810          --  are no abstract primitives of the actual type that correspond to
9811          --  nonabstract primitives of the formal type (second sentence of
9812          --  RM95-3.9.3(9)).
9813
9814          if Is_Abstract_Type (A_Gen_T) and then Is_Abstract_Type (Act_T) then
9815             Check_Abstract_Primitives : declare
9816                Gen_Prims  : constant Elist_Id :=
9817                              Primitive_Operations (A_Gen_T);
9818                Gen_Elmt   : Elmt_Id;
9819                Gen_Subp   : Entity_Id;
9820                Anc_Subp   : Entity_Id;
9821                Anc_Formal : Entity_Id;
9822                Anc_F_Type : Entity_Id;
9823
9824                Act_Prims  : constant Elist_Id  := Primitive_Operations (Act_T);
9825                Act_Elmt   : Elmt_Id;
9826                Act_Subp   : Entity_Id;
9827                Act_Formal : Entity_Id;
9828                Act_F_Type : Entity_Id;
9829
9830                Subprograms_Correspond : Boolean;
9831
9832                function Is_Tagged_Ancestor (T1, T2 : Entity_Id) return Boolean;
9833                --  Returns true if T2 is derived directly or indirectly from
9834                --  T1, including derivations from interfaces. T1 and T2 are
9835                --  required to be specific tagged base types.
9836
9837                ------------------------
9838                -- Is_Tagged_Ancestor --
9839                ------------------------
9840
9841                function Is_Tagged_Ancestor (T1, T2 : Entity_Id) return Boolean
9842                is
9843                   Intfc_Elmt : Elmt_Id;
9844
9845                begin
9846                   --  The predicate is satisfied if the types are the same
9847
9848                   if T1 = T2 then
9849                      return True;
9850
9851                   --  If we've reached the top of the derivation chain then
9852                   --  we know that T1 is not an ancestor of T2.
9853
9854                   elsif Etype (T2) = T2 then
9855                      return False;
9856
9857                   --  Proceed to check T2's immediate parent
9858
9859                   elsif Is_Ancestor (T1, Base_Type (Etype (T2))) then
9860                      return True;
9861
9862                   --  Finally, check to see if T1 is an ancestor of any of T2's
9863                   --  progenitors.
9864
9865                   else
9866                      Intfc_Elmt := First_Elmt (Interfaces (T2));
9867                      while Present (Intfc_Elmt) loop
9868                         if Is_Ancestor (T1, Node (Intfc_Elmt)) then
9869                            return True;
9870                         end if;
9871
9872                         Next_Elmt (Intfc_Elmt);
9873                      end loop;
9874                   end if;
9875
9876                   return False;
9877                end Is_Tagged_Ancestor;
9878
9879             --  Start of processing for Check_Abstract_Primitives
9880
9881             begin
9882                --  Loop over all of the formal derived type's primitives
9883
9884                Gen_Elmt := First_Elmt (Gen_Prims);
9885                while Present (Gen_Elmt) loop
9886                   Gen_Subp := Node (Gen_Elmt);
9887
9888                   --  If the primitive of the formal is not abstract, then
9889                   --  determine whether there is a corresponding primitive of
9890                   --  the actual type that's abstract.
9891
9892                   if not Is_Abstract_Subprogram (Gen_Subp) then
9893                      Act_Elmt := First_Elmt (Act_Prims);
9894                      while Present (Act_Elmt) loop
9895                         Act_Subp := Node (Act_Elmt);
9896
9897                         --  If we find an abstract primitive of the actual,
9898                         --  then we need to test whether it corresponds to the
9899                         --  subprogram from which the generic formal primitive
9900                         --  is inherited.
9901
9902                         if Is_Abstract_Subprogram (Act_Subp) then
9903                            Anc_Subp := Alias (Gen_Subp);
9904
9905                            --  Test whether we have a corresponding primitive
9906                            --  by comparing names, kinds, formal types, and
9907                            --  result types.
9908
9909                            if Chars (Anc_Subp) = Chars (Act_Subp)
9910                              and then Ekind (Anc_Subp) = Ekind (Act_Subp)
9911                            then
9912                               Anc_Formal := First_Formal (Anc_Subp);
9913                               Act_Formal := First_Formal (Act_Subp);
9914                               while Present (Anc_Formal)
9915                                 and then Present (Act_Formal)
9916                               loop
9917                                  Anc_F_Type := Etype (Anc_Formal);
9918                                  Act_F_Type := Etype (Act_Formal);
9919
9920                                  if Ekind (Anc_F_Type)
9921                                       = E_Anonymous_Access_Type
9922                                  then
9923                                     Anc_F_Type := Designated_Type (Anc_F_Type);
9924
9925                                     if Ekind (Act_F_Type)
9926                                          = E_Anonymous_Access_Type
9927                                     then
9928                                        Act_F_Type :=
9929                                          Designated_Type (Act_F_Type);
9930                                     else
9931                                        exit;
9932                                     end if;
9933
9934                                  elsif
9935                                    Ekind (Act_F_Type) = E_Anonymous_Access_Type
9936                                  then
9937                                     exit;
9938                                  end if;
9939
9940                                  Anc_F_Type := Base_Type (Anc_F_Type);
9941                                  Act_F_Type := Base_Type (Act_F_Type);
9942
9943                                  --  If the formal is controlling, then the
9944                                  --  the type of the actual primitive's formal
9945                                  --  must be derived directly or indirectly
9946                                  --  from the type of the ancestor primitive's
9947                                  --  formal.
9948
9949                                  if Is_Controlling_Formal (Anc_Formal) then
9950                                     if not Is_Tagged_Ancestor
9951                                              (Anc_F_Type, Act_F_Type)
9952                                     then
9953                                        exit;
9954                                     end if;
9955
9956                                  --  Otherwise the types of the formals must
9957                                  --  be the same.
9958
9959                                  elsif Anc_F_Type /= Act_F_Type then
9960                                     exit;
9961                                  end if;
9962
9963                                  Next_Entity (Anc_Formal);
9964                                  Next_Entity (Act_Formal);
9965                               end loop;
9966
9967                               --  If we traversed through all of the formals
9968                               --  then so far the subprograms correspond, so
9969                               --  now check that any result types correspond.
9970
9971                               if No (Anc_Formal) and then No (Act_Formal) then
9972                                  Subprograms_Correspond := True;
9973
9974                                  if Ekind (Act_Subp) = E_Function then
9975                                     Anc_F_Type := Etype (Anc_Subp);
9976                                     Act_F_Type := Etype (Act_Subp);
9977
9978                                     if Ekind (Anc_F_Type)
9979                                          = E_Anonymous_Access_Type
9980                                     then
9981                                        Anc_F_Type :=
9982                                          Designated_Type (Anc_F_Type);
9983
9984                                        if Ekind (Act_F_Type)
9985                                             = E_Anonymous_Access_Type
9986                                        then
9987                                           Act_F_Type :=
9988                                             Designated_Type (Act_F_Type);
9989                                        else
9990                                           Subprograms_Correspond := False;
9991                                        end if;
9992
9993                                     elsif
9994                                       Ekind (Act_F_Type)
9995                                         = E_Anonymous_Access_Type
9996                                     then
9997                                        Subprograms_Correspond := False;
9998                                     end if;
9999
10000                                     Anc_F_Type := Base_Type (Anc_F_Type);
10001                                     Act_F_Type := Base_Type (Act_F_Type);
10002
10003                                     --  Now either the result types must be
10004                                     --  the same or, if the result type is
10005                                     --  controlling, the result type of the
10006                                     --  actual primitive must descend from the
10007                                     --  result type of the ancestor primitive.
10008
10009                                     if Subprograms_Correspond
10010                                       and then Anc_F_Type /= Act_F_Type
10011                                       and then
10012                                         Has_Controlling_Result (Anc_Subp)
10013                                       and then
10014                                         not Is_Tagged_Ancestor
10015                                               (Anc_F_Type, Act_F_Type)
10016                                     then
10017                                        Subprograms_Correspond := False;
10018                                     end if;
10019                                  end if;
10020
10021                                  --  Found a matching subprogram belonging to
10022                                  --  formal ancestor type, so actual subprogram
10023                                  --  corresponds and this violates 3.9.3(9).
10024
10025                                  if Subprograms_Correspond then
10026                                     Error_Msg_NE
10027                                       ("abstract subprogram & overrides " &
10028                                        "nonabstract subprogram of ancestor",
10029                                        Actual,
10030                                        Act_Subp);
10031                                  end if;
10032                               end if;
10033                            end if;
10034                         end if;
10035
10036                         Next_Elmt (Act_Elmt);
10037                      end loop;
10038                   end if;
10039
10040                   Next_Elmt (Gen_Elmt);
10041                end loop;
10042             end Check_Abstract_Primitives;
10043          end if;
10044
10045          --  Verify that limitedness matches. If parent is a limited
10046          --  interface then  the generic formal is not unless declared
10047          --  explicitly so. If not declared limited, the actual cannot be
10048          --  limited (see AI05-0087).
10049
10050          --  Even though this AI is a binding interpretation, we enable the
10051          --  check only in Ada 2012 mode, because this improper construct
10052          --  shows up in user code and in existing B-tests.
10053
10054          if Is_Limited_Type (Act_T)
10055            and then not Is_Limited_Type (A_Gen_T)
10056            and then Ada_Version >= Ada_2012
10057          then
10058             Error_Msg_NE
10059               ("actual for non-limited & cannot be a limited type", Actual,
10060                Gen_T);
10061             Explain_Limited_Type (Act_T, Actual);
10062             Abandon_Instantiation (Actual);
10063          end if;
10064       end Validate_Derived_Type_Instance;
10065
10066       --------------------------------------
10067       -- Validate_Interface_Type_Instance --
10068       --------------------------------------
10069
10070       procedure Validate_Interface_Type_Instance is
10071       begin
10072          if not Is_Interface (Act_T) then
10073             Error_Msg_NE
10074               ("actual for formal interface type must be an interface",
10075                 Actual, Gen_T);
10076
10077          elsif Is_Limited_Type (Act_T) /= Is_Limited_Type (A_Gen_T)
10078            or else
10079              Is_Task_Interface (A_Gen_T) /= Is_Task_Interface (Act_T)
10080            or else
10081              Is_Protected_Interface (A_Gen_T) /=
10082                Is_Protected_Interface (Act_T)
10083            or else
10084              Is_Synchronized_Interface (A_Gen_T) /=
10085                Is_Synchronized_Interface (Act_T)
10086          then
10087             Error_Msg_NE
10088               ("actual for interface& does not match (RM 12.5.5(4))",
10089                Actual, Gen_T);
10090          end if;
10091       end Validate_Interface_Type_Instance;
10092
10093       ------------------------------------
10094       -- Validate_Private_Type_Instance --
10095       ------------------------------------
10096
10097       procedure Validate_Private_Type_Instance is
10098          Formal_Discr : Entity_Id;
10099          Actual_Discr : Entity_Id;
10100          Formal_Subt  : Entity_Id;
10101
10102       begin
10103          if Is_Limited_Type (Act_T)
10104            and then not Is_Limited_Type (A_Gen_T)
10105          then
10106             Error_Msg_NE
10107               ("actual for non-limited & cannot be a limited type", Actual,
10108                Gen_T);
10109             Explain_Limited_Type (Act_T, Actual);
10110             Abandon_Instantiation (Actual);
10111
10112          elsif Known_To_Have_Preelab_Init (A_Gen_T)
10113            and then not Has_Preelaborable_Initialization (Act_T)
10114          then
10115             Error_Msg_NE
10116               ("actual for & must have preelaborable initialization", Actual,
10117                Gen_T);
10118
10119          elsif Is_Indefinite_Subtype (Act_T)
10120             and then not Is_Indefinite_Subtype (A_Gen_T)
10121             and then Ada_Version >= Ada_95
10122          then
10123             Error_Msg_NE
10124               ("actual for & must be a definite subtype", Actual, Gen_T);
10125
10126          elsif not Is_Tagged_Type (Act_T)
10127            and then Is_Tagged_Type (A_Gen_T)
10128          then
10129             Error_Msg_NE
10130               ("actual for & must be a tagged type", Actual, Gen_T);
10131
10132          elsif Has_Discriminants (A_Gen_T) then
10133             if not Has_Discriminants (Act_T) then
10134                Error_Msg_NE
10135                  ("actual for & must have discriminants", Actual, Gen_T);
10136                Abandon_Instantiation (Actual);
10137
10138             elsif Is_Constrained (Act_T) then
10139                Error_Msg_NE
10140                  ("actual for & must be unconstrained", Actual, Gen_T);
10141                Abandon_Instantiation (Actual);
10142
10143             else
10144                Formal_Discr := First_Discriminant (A_Gen_T);
10145                Actual_Discr := First_Discriminant (Act_T);
10146                while Formal_Discr /= Empty loop
10147                   if Actual_Discr = Empty then
10148                      Error_Msg_NE
10149                        ("discriminants on actual do not match formal",
10150                         Actual, Gen_T);
10151                      Abandon_Instantiation (Actual);
10152                   end if;
10153
10154                   Formal_Subt := Get_Instance_Of (Etype (Formal_Discr));
10155
10156                   --  Access discriminants match if designated types do
10157
10158                   if Ekind (Base_Type (Formal_Subt)) = E_Anonymous_Access_Type
10159                     and then (Ekind (Base_Type (Etype (Actual_Discr)))) =
10160                                 E_Anonymous_Access_Type
10161                     and then
10162                       Get_Instance_Of
10163                         (Designated_Type (Base_Type (Formal_Subt))) =
10164                            Designated_Type (Base_Type (Etype (Actual_Discr)))
10165                   then
10166                      null;
10167
10168                   elsif Base_Type (Formal_Subt) /=
10169                           Base_Type (Etype (Actual_Discr))
10170                   then
10171                      Error_Msg_NE
10172                        ("types of actual discriminants must match formal",
10173                         Actual, Gen_T);
10174                      Abandon_Instantiation (Actual);
10175
10176                   elsif not Subtypes_Statically_Match
10177                               (Formal_Subt, Etype (Actual_Discr))
10178                     and then Ada_Version >= Ada_95
10179                   then
10180                      Error_Msg_NE
10181                        ("subtypes of actual discriminants must match formal",
10182                         Actual, Gen_T);
10183                      Abandon_Instantiation (Actual);
10184                   end if;
10185
10186                   Next_Discriminant (Formal_Discr);
10187                   Next_Discriminant (Actual_Discr);
10188                end loop;
10189
10190                if Actual_Discr /= Empty then
10191                   Error_Msg_NE
10192                     ("discriminants on actual do not match formal",
10193                      Actual, Gen_T);
10194                   Abandon_Instantiation (Actual);
10195                end if;
10196             end if;
10197
10198          end if;
10199
10200          Ancestor := Gen_T;
10201       end Validate_Private_Type_Instance;
10202
10203    --  Start of processing for Instantiate_Type
10204
10205    begin
10206       if Get_Instance_Of (A_Gen_T) /= A_Gen_T then
10207          Error_Msg_N ("duplicate instantiation of generic type", Actual);
10208          return New_List (Error);
10209
10210       elsif not Is_Entity_Name (Actual)
10211         or else not Is_Type (Entity (Actual))
10212       then
10213          Error_Msg_NE
10214            ("expect valid subtype mark to instantiate &", Actual, Gen_T);
10215          Abandon_Instantiation (Actual);
10216
10217       else
10218          Act_T := Entity (Actual);
10219
10220          --  Ada 2005 (AI-216): An Unchecked_Union subtype shall only be passed
10221          --  as a generic actual parameter if the corresponding formal type
10222          --  does not have a known_discriminant_part, or is a formal derived
10223          --  type that is an Unchecked_Union type.
10224
10225          if Is_Unchecked_Union (Base_Type (Act_T)) then
10226             if not Has_Discriminants (A_Gen_T)
10227                      or else
10228                    (Is_Derived_Type (A_Gen_T)
10229                      and then
10230                     Is_Unchecked_Union (A_Gen_T))
10231             then
10232                null;
10233             else
10234                Error_Msg_N ("Unchecked_Union cannot be the actual for a" &
10235                  " discriminated formal type", Act_T);
10236
10237             end if;
10238          end if;
10239
10240          --  Deal with fixed/floating restrictions
10241
10242          if Is_Floating_Point_Type (Act_T) then
10243             Check_Restriction (No_Floating_Point, Actual);
10244          elsif Is_Fixed_Point_Type (Act_T) then
10245             Check_Restriction (No_Fixed_Point, Actual);
10246          end if;
10247
10248          --  Deal with error of using incomplete type as generic actual.
10249          --  This includes limited views of a type, even if the non-limited
10250          --  view may be available.
10251
10252          if Ekind (Act_T) = E_Incomplete_Type
10253            or else (Is_Class_Wide_Type (Act_T)
10254                       and then
10255                          Ekind (Root_Type (Act_T)) = E_Incomplete_Type)
10256          then
10257             if Is_Class_Wide_Type (Act_T)
10258               or else No (Full_View (Act_T))
10259             then
10260                Error_Msg_N ("premature use of incomplete type", Actual);
10261                Abandon_Instantiation (Actual);
10262             else
10263                Act_T := Full_View (Act_T);
10264                Set_Entity (Actual, Act_T);
10265
10266                if Has_Private_Component (Act_T) then
10267                   Error_Msg_N
10268                     ("premature use of type with private component", Actual);
10269                end if;
10270             end if;
10271
10272          --  Deal with error of premature use of private type as generic actual
10273
10274          elsif Is_Private_Type (Act_T)
10275            and then Is_Private_Type (Base_Type (Act_T))
10276            and then not Is_Generic_Type (Act_T)
10277            and then not Is_Derived_Type (Act_T)
10278            and then No (Full_View (Root_Type (Act_T)))
10279          then
10280             Error_Msg_N ("premature use of private type", Actual);
10281
10282          elsif Has_Private_Component (Act_T) then
10283             Error_Msg_N
10284               ("premature use of type with private component", Actual);
10285          end if;
10286
10287          Set_Instance_Of (A_Gen_T, Act_T);
10288
10289          --  If the type is generic, the class-wide type may also be used
10290
10291          if Is_Tagged_Type (A_Gen_T)
10292            and then Is_Tagged_Type (Act_T)
10293            and then not Is_Class_Wide_Type (A_Gen_T)
10294          then
10295             Set_Instance_Of (Class_Wide_Type (A_Gen_T),
10296               Class_Wide_Type (Act_T));
10297          end if;
10298
10299          if not Is_Abstract_Type (A_Gen_T)
10300            and then Is_Abstract_Type (Act_T)
10301          then
10302             Error_Msg_N
10303               ("actual of non-abstract formal cannot be abstract", Actual);
10304          end if;
10305
10306          --  A generic scalar type is a first subtype for which we generate
10307          --  an anonymous base type. Indicate that the instance of this base
10308          --  is the base type of the actual.
10309
10310          if Is_Scalar_Type (A_Gen_T) then
10311             Set_Instance_Of (Etype (A_Gen_T), Etype (Act_T));
10312          end if;
10313       end if;
10314
10315       if Error_Posted (Act_T) then
10316          null;
10317       else
10318          case Nkind (Def) is
10319             when N_Formal_Private_Type_Definition =>
10320                Validate_Private_Type_Instance;
10321
10322             when N_Formal_Derived_Type_Definition =>
10323                Validate_Derived_Type_Instance;
10324
10325             when N_Formal_Discrete_Type_Definition =>
10326                if not Is_Discrete_Type (Act_T) then
10327                   Error_Msg_NE
10328                     ("expect discrete type in instantiation of&",
10329                        Actual, Gen_T);
10330                   Abandon_Instantiation (Actual);
10331                end if;
10332
10333             when N_Formal_Signed_Integer_Type_Definition =>
10334                if not Is_Signed_Integer_Type (Act_T) then
10335                   Error_Msg_NE
10336                     ("expect signed integer type in instantiation of&",
10337                      Actual, Gen_T);
10338                   Abandon_Instantiation (Actual);
10339                end if;
10340
10341             when N_Formal_Modular_Type_Definition =>
10342                if not Is_Modular_Integer_Type (Act_T) then
10343                   Error_Msg_NE
10344                     ("expect modular type in instantiation of &",
10345                        Actual, Gen_T);
10346                   Abandon_Instantiation (Actual);
10347                end if;
10348
10349             when N_Formal_Floating_Point_Definition =>
10350                if not Is_Floating_Point_Type (Act_T) then
10351                   Error_Msg_NE
10352                     ("expect float type in instantiation of &", Actual, Gen_T);
10353                   Abandon_Instantiation (Actual);
10354                end if;
10355
10356             when N_Formal_Ordinary_Fixed_Point_Definition =>
10357                if not Is_Ordinary_Fixed_Point_Type (Act_T) then
10358                   Error_Msg_NE
10359                     ("expect ordinary fixed point type in instantiation of &",
10360                      Actual, Gen_T);
10361                   Abandon_Instantiation (Actual);
10362                end if;
10363
10364             when N_Formal_Decimal_Fixed_Point_Definition =>
10365                if not Is_Decimal_Fixed_Point_Type (Act_T) then
10366                   Error_Msg_NE
10367                     ("expect decimal type in instantiation of &",
10368                      Actual, Gen_T);
10369                   Abandon_Instantiation (Actual);
10370                end if;
10371
10372             when N_Array_Type_Definition =>
10373                Validate_Array_Type_Instance;
10374
10375             when N_Access_To_Object_Definition =>
10376                Validate_Access_Type_Instance;
10377
10378             when N_Access_Function_Definition |
10379                  N_Access_Procedure_Definition =>
10380                Validate_Access_Subprogram_Instance;
10381
10382             when N_Record_Definition           =>
10383                Validate_Interface_Type_Instance;
10384
10385             when N_Derived_Type_Definition     =>
10386                Validate_Derived_Interface_Type_Instance;
10387
10388             when others =>
10389                raise Program_Error;
10390
10391          end case;
10392       end if;
10393
10394       Subt := New_Copy (Gen_T);
10395
10396       --  Use adjusted sloc of subtype name as the location for other nodes in
10397       --  the subtype declaration.
10398
10399       Loc  := Sloc (Subt);
10400
10401       Decl_Node :=
10402         Make_Subtype_Declaration (Loc,
10403           Defining_Identifier => Subt,
10404           Subtype_Indication  => New_Reference_To (Act_T, Loc));
10405
10406       if Is_Private_Type (Act_T) then
10407          Set_Has_Private_View (Subtype_Indication (Decl_Node));
10408
10409       elsif Is_Access_Type (Act_T)
10410         and then Is_Private_Type (Designated_Type (Act_T))
10411       then
10412          Set_Has_Private_View (Subtype_Indication (Decl_Node));
10413       end if;
10414
10415       Decl_Nodes := New_List (Decl_Node);
10416
10417       --  Flag actual derived types so their elaboration produces the
10418       --  appropriate renamings for the primitive operations of the ancestor.
10419       --  Flag actual for formal private types as well, to determine whether
10420       --  operations in the private part may override inherited operations.
10421       --  If the formal has an interface list, the ancestor is not the
10422       --  parent, but the analyzed formal that includes the interface
10423       --  operations of all its progenitors.
10424
10425       --  Same treatment for formal private types, so we can check whether the
10426       --  type is tagged limited when validating derivations in the private
10427       --  part. (See AI05-096).
10428
10429       if Nkind (Def) = N_Formal_Derived_Type_Definition then
10430          if Present (Interface_List (Def)) then
10431             Set_Generic_Parent_Type (Decl_Node, A_Gen_T);
10432          else
10433             Set_Generic_Parent_Type (Decl_Node, Ancestor);
10434          end if;
10435
10436       elsif Nkind (Def) = N_Formal_Private_Type_Definition then
10437          Set_Generic_Parent_Type (Decl_Node, A_Gen_T);
10438       end if;
10439
10440       --  If the actual is a synchronized type that implements an interface,
10441       --  the primitive operations are attached to the corresponding record,
10442       --  and we have to treat it as an additional generic actual, so that its
10443       --  primitive operations become visible in the instance. The task or
10444       --  protected type itself does not carry primitive operations.
10445
10446       if Is_Concurrent_Type (Act_T)
10447         and then Is_Tagged_Type (Act_T)
10448         and then Present (Corresponding_Record_Type (Act_T))
10449         and then Present (Ancestor)
10450         and then Is_Interface (Ancestor)
10451       then
10452          declare
10453             Corr_Rec  : constant Entity_Id :=
10454                           Corresponding_Record_Type (Act_T);
10455             New_Corr  : Entity_Id;
10456             Corr_Decl : Node_Id;
10457
10458          begin
10459             New_Corr := Make_Temporary (Loc, 'S');
10460             Corr_Decl :=
10461               Make_Subtype_Declaration (Loc,
10462                 Defining_Identifier => New_Corr,
10463                 Subtype_Indication  =>
10464                   New_Reference_To (Corr_Rec, Loc));
10465             Append_To (Decl_Nodes, Corr_Decl);
10466
10467             if Ekind (Act_T) = E_Task_Type then
10468                Set_Ekind (Subt, E_Task_Subtype);
10469             else
10470                Set_Ekind (Subt, E_Protected_Subtype);
10471             end if;
10472
10473             Set_Corresponding_Record_Type (Subt, Corr_Rec);
10474             Set_Generic_Parent_Type (Corr_Decl, Ancestor);
10475             Set_Generic_Parent_Type (Decl_Node, Empty);
10476          end;
10477       end if;
10478
10479       return Decl_Nodes;
10480    end Instantiate_Type;
10481
10482    ---------------------
10483    -- Is_In_Main_Unit --
10484    ---------------------
10485
10486    function Is_In_Main_Unit (N : Node_Id) return Boolean is
10487       Unum         : constant Unit_Number_Type := Get_Source_Unit (N);
10488       Current_Unit : Node_Id;
10489
10490    begin
10491       if Unum = Main_Unit then
10492          return True;
10493
10494       --  If the current unit is a subunit then it is either the main unit or
10495       --  is being compiled as part of the main unit.
10496
10497       elsif Nkind (N) = N_Compilation_Unit then
10498          return Nkind (Unit (N)) = N_Subunit;
10499       end if;
10500
10501       Current_Unit := Parent (N);
10502       while Present (Current_Unit)
10503         and then Nkind (Current_Unit) /= N_Compilation_Unit
10504       loop
10505          Current_Unit := Parent (Current_Unit);
10506       end loop;
10507
10508       --  The instantiation node is in the main unit, or else the current node
10509       --  (perhaps as the result of nested instantiations) is in the main unit,
10510       --  or in the declaration of the main unit, which in this last case must
10511       --  be a body.
10512
10513       return Unum = Main_Unit
10514         or else Current_Unit = Cunit (Main_Unit)
10515         or else Current_Unit = Library_Unit (Cunit (Main_Unit))
10516         or else (Present (Library_Unit (Current_Unit))
10517                   and then Is_In_Main_Unit (Library_Unit (Current_Unit)));
10518    end Is_In_Main_Unit;
10519
10520    ----------------------------
10521    -- Load_Parent_Of_Generic --
10522    ----------------------------
10523
10524    procedure Load_Parent_Of_Generic
10525      (N             : Node_Id;
10526       Spec          : Node_Id;
10527       Body_Optional : Boolean := False)
10528    is
10529       Comp_Unit          : constant Node_Id := Cunit (Get_Source_Unit (Spec));
10530       Save_Style_Check   : constant Boolean := Style_Check;
10531       True_Parent        : Node_Id;
10532       Inst_Node          : Node_Id;
10533       OK                 : Boolean;
10534       Previous_Instances : constant Elist_Id := New_Elmt_List;
10535
10536       procedure Collect_Previous_Instances (Decls : List_Id);
10537       --  Collect all instantiations in the given list of declarations, that
10538       --  precede the generic that we need to load. If the bodies of these
10539       --  instantiations are available, we must analyze them, to ensure that
10540       --  the public symbols generated are the same when the unit is compiled
10541       --  to generate code, and when it is compiled in the context of a unit
10542       --  that needs a particular nested instance. This process is applied to
10543       --  both package and subprogram instances.
10544
10545       --------------------------------
10546       -- Collect_Previous_Instances --
10547       --------------------------------
10548
10549       procedure Collect_Previous_Instances (Decls : List_Id) is
10550          Decl : Node_Id;
10551
10552       begin
10553          Decl := First (Decls);
10554          while Present (Decl) loop
10555             if Sloc (Decl) >= Sloc (Inst_Node) then
10556                return;
10557
10558             --  If Decl is an instantiation, then record it as requiring
10559             --  instantiation of the corresponding body, except if it is an
10560             --  abbreviated instantiation generated internally for conformance
10561             --  checking purposes only for the case of a formal package
10562             --  declared without a box (see Instantiate_Formal_Package). Such
10563             --  an instantiation does not generate any code (the actual code
10564             --  comes from actual) and thus does not need to be analyzed here.
10565             --  If the instantiation appears with a generic package body it is
10566             --  not analyzed here either.
10567
10568             elsif Nkind (Decl) = N_Package_Instantiation
10569               and then not Is_Internal (Defining_Entity (Decl))
10570             then
10571                Append_Elmt (Decl, Previous_Instances);
10572
10573             --  For a subprogram instantiation, omit instantiations intrinsic
10574             --  operations (Unchecked_Conversions, etc.) that have no bodies.
10575
10576             elsif Nkind_In (Decl, N_Function_Instantiation,
10577                                   N_Procedure_Instantiation)
10578               and then not Is_Intrinsic_Subprogram (Entity (Name (Decl)))
10579             then
10580                Append_Elmt (Decl, Previous_Instances);
10581
10582             elsif Nkind (Decl) = N_Package_Declaration then
10583                Collect_Previous_Instances
10584                  (Visible_Declarations (Specification (Decl)));
10585                Collect_Previous_Instances
10586                  (Private_Declarations (Specification (Decl)));
10587
10588             --  Previous non-generic bodies may contain instances as well
10589
10590             elsif Nkind (Decl) = N_Package_Body
10591               and then Ekind (Corresponding_Spec (Decl)) /= E_Generic_Package
10592             then
10593                Collect_Previous_Instances (Declarations (Decl));
10594
10595             elsif Nkind (Decl) = N_Subprogram_Body
10596               and then not Acts_As_Spec (Decl)
10597               and then not Is_Generic_Subprogram (Corresponding_Spec (Decl))
10598             then
10599                Collect_Previous_Instances (Declarations (Decl));
10600             end if;
10601
10602             Next (Decl);
10603          end loop;
10604       end Collect_Previous_Instances;
10605
10606    --  Start of processing for Load_Parent_Of_Generic
10607
10608    begin
10609       if not In_Same_Source_Unit (N, Spec)
10610         or else Nkind (Unit (Comp_Unit)) = N_Package_Declaration
10611         or else (Nkind (Unit (Comp_Unit)) = N_Package_Body
10612                    and then not Is_In_Main_Unit (Spec))
10613       then
10614          --  Find body of parent of spec, and analyze it. A special case arises
10615          --  when the parent is an instantiation, that is to say when we are
10616          --  currently instantiating a nested generic. In that case, there is
10617          --  no separate file for the body of the enclosing instance. Instead,
10618          --  the enclosing body must be instantiated as if it were a pending
10619          --  instantiation, in order to produce the body for the nested generic
10620          --  we require now. Note that in that case the generic may be defined
10621          --  in a package body, the instance defined in the same package body,
10622          --  and the original enclosing body may not be in the main unit.
10623
10624          Inst_Node := Empty;
10625
10626          True_Parent := Parent (Spec);
10627          while Present (True_Parent)
10628            and then Nkind (True_Parent) /= N_Compilation_Unit
10629          loop
10630             if Nkind (True_Parent) = N_Package_Declaration
10631                  and then
10632                Nkind (Original_Node (True_Parent)) = N_Package_Instantiation
10633             then
10634                --  Parent is a compilation unit that is an instantiation.
10635                --  Instantiation node has been replaced with package decl.
10636
10637                Inst_Node := Original_Node (True_Parent);
10638                exit;
10639
10640             elsif Nkind (True_Parent) = N_Package_Declaration
10641               and then Present (Generic_Parent (Specification (True_Parent)))
10642               and then Nkind (Parent (True_Parent)) /= N_Compilation_Unit
10643             then
10644                --  Parent is an instantiation within another specification.
10645                --  Declaration for instance has been inserted before original
10646                --  instantiation node. A direct link would be preferable?
10647
10648                Inst_Node := Next (True_Parent);
10649                while Present (Inst_Node)
10650                  and then Nkind (Inst_Node) /= N_Package_Instantiation
10651                loop
10652                   Next (Inst_Node);
10653                end loop;
10654
10655                --  If the instance appears within a generic, and the generic
10656                --  unit is defined within a formal package of the enclosing
10657                --  generic, there is no generic body available, and none
10658                --  needed. A more precise test should be used ???
10659
10660                if No (Inst_Node) then
10661                   return;
10662                end if;
10663
10664                exit;
10665
10666             else
10667                True_Parent := Parent (True_Parent);
10668             end if;
10669          end loop;
10670
10671          --  Case where we are currently instantiating a nested generic
10672
10673          if Present (Inst_Node) then
10674             if Nkind (Parent (True_Parent)) = N_Compilation_Unit then
10675
10676                --  Instantiation node and declaration of instantiated package
10677                --  were exchanged when only the declaration was needed.
10678                --  Restore instantiation node before proceeding with body.
10679
10680                Set_Unit (Parent (True_Parent), Inst_Node);
10681             end if;
10682
10683             --  Now complete instantiation of enclosing body, if it appears in
10684             --  some other unit. If it appears in the current unit, the body
10685             --  will have been instantiated already.
10686
10687             if No (Corresponding_Body (Instance_Spec (Inst_Node))) then
10688
10689                --  We need to determine the expander mode to instantiate the
10690                --  enclosing body. Because the generic body we need may use
10691                --  global entities declared in the enclosing package (including
10692                --  aggregates) it is in general necessary to compile this body
10693                --  with expansion enabled, except if we are within a generic
10694                --  package, in which case the usual generic rule applies.
10695
10696                declare
10697                   Exp_Status         : Boolean := True;
10698                   Scop               : Entity_Id;
10699
10700                begin
10701                   --  Loop through scopes looking for generic package
10702
10703                   Scop := Scope (Defining_Entity (Instance_Spec (Inst_Node)));
10704                   while Present (Scop)
10705                     and then Scop /= Standard_Standard
10706                   loop
10707                      if Ekind (Scop) = E_Generic_Package then
10708                         Exp_Status := False;
10709                         exit;
10710                      end if;
10711
10712                      Scop := Scope (Scop);
10713                   end loop;
10714
10715                   --  Collect previous instantiations in the unit that contains
10716                   --  the desired generic.
10717
10718                   if Nkind (Parent (True_Parent)) /= N_Compilation_Unit
10719                     and then not Body_Optional
10720                   then
10721                      declare
10722                         Decl : Elmt_Id;
10723                         Info : Pending_Body_Info;
10724                         Par  : Node_Id;
10725
10726                      begin
10727                         Par := Parent (Inst_Node);
10728                         while Present (Par) loop
10729                            exit when Nkind (Parent (Par)) = N_Compilation_Unit;
10730                            Par := Parent (Par);
10731                         end loop;
10732
10733                         pragma Assert (Present (Par));
10734
10735                         if Nkind (Par) = N_Package_Body then
10736                            Collect_Previous_Instances (Declarations (Par));
10737
10738                         elsif Nkind (Par) = N_Package_Declaration then
10739                            Collect_Previous_Instances
10740                              (Visible_Declarations (Specification (Par)));
10741                            Collect_Previous_Instances
10742                              (Private_Declarations (Specification (Par)));
10743
10744                         else
10745                            --  Enclosing unit is a subprogram body. In this
10746                            --  case all instance bodies are processed in order
10747                            --  and there is no need to collect them separately.
10748
10749                            null;
10750                         end if;
10751
10752                         Decl := First_Elmt (Previous_Instances);
10753                         while Present (Decl) loop
10754                            Info :=
10755                              (Inst_Node                => Node (Decl),
10756                               Act_Decl                 =>
10757                                 Instance_Spec (Node (Decl)),
10758                               Expander_Status          => Exp_Status,
10759                               Current_Sem_Unit         =>
10760                                 Get_Code_Unit (Sloc (Node (Decl))),
10761                               Scope_Suppress           => Scope_Suppress,
10762                               Local_Suppress_Stack_Top =>
10763                                 Local_Suppress_Stack_Top,
10764                               Version                  => Ada_Version);
10765
10766                            --  Package instance
10767
10768                            if
10769                              Nkind (Node (Decl)) = N_Package_Instantiation
10770                            then
10771                               Instantiate_Package_Body
10772                                 (Info, Body_Optional => True);
10773
10774                            --  Subprogram instance
10775
10776                            else
10777                               --  The instance_spec is the wrapper package,
10778                               --  and the subprogram declaration is the last
10779                               --  declaration in the wrapper.
10780
10781                               Info.Act_Decl :=
10782                                 Last
10783                                   (Visible_Declarations
10784                                     (Specification (Info.Act_Decl)));
10785
10786                               Instantiate_Subprogram_Body
10787                                 (Info, Body_Optional => True);
10788                            end if;
10789
10790                            Next_Elmt (Decl);
10791                         end loop;
10792                      end;
10793                   end if;
10794
10795                   Instantiate_Package_Body
10796                     (Body_Info =>
10797                        ((Inst_Node                => Inst_Node,
10798                          Act_Decl                 => True_Parent,
10799                          Expander_Status          => Exp_Status,
10800                          Current_Sem_Unit         =>
10801                            Get_Code_Unit (Sloc (Inst_Node)),
10802                          Scope_Suppress           => Scope_Suppress,
10803                          Local_Suppress_Stack_Top =>
10804                            Local_Suppress_Stack_Top,
10805                            Version                => Ada_Version)),
10806                      Body_Optional => Body_Optional);
10807                end;
10808             end if;
10809
10810          --  Case where we are not instantiating a nested generic
10811
10812          else
10813             Opt.Style_Check := False;
10814             Expander_Mode_Save_And_Set (True);
10815             Load_Needed_Body (Comp_Unit, OK);
10816             Opt.Style_Check := Save_Style_Check;
10817             Expander_Mode_Restore;
10818
10819             if not OK
10820               and then Unit_Requires_Body (Defining_Entity (Spec))
10821               and then not Body_Optional
10822             then
10823                declare
10824                   Bname : constant Unit_Name_Type :=
10825                             Get_Body_Name (Get_Unit_Name (Unit (Comp_Unit)));
10826
10827                begin
10828                   --  In CodePeer mode, the missing body may make the analysis
10829                   --  incomplete, but we do not treat it as fatal.
10830
10831                   if CodePeer_Mode then
10832                      return;
10833
10834                   else
10835                      Error_Msg_Unit_1 := Bname;
10836                      Error_Msg_N ("this instantiation requires$!", N);
10837                      Error_Msg_File_1 :=
10838                        Get_File_Name (Bname, Subunit => False);
10839                      Error_Msg_N ("\but file{ was not found!", N);
10840                      raise Unrecoverable_Error;
10841                   end if;
10842                end;
10843             end if;
10844          end if;
10845       end if;
10846
10847       --  If loading parent of the generic caused an instantiation circularity,
10848       --  we abandon compilation at this point, because otherwise in some cases
10849       --  we get into trouble with infinite recursions after this point.
10850
10851       if Circularity_Detected then
10852          raise Unrecoverable_Error;
10853       end if;
10854    end Load_Parent_Of_Generic;
10855
10856    ---------------------------------
10857    -- Map_Formal_Package_Entities --
10858    ---------------------------------
10859
10860    procedure Map_Formal_Package_Entities (Form : Entity_Id; Act : Entity_Id) is
10861       E1 : Entity_Id;
10862       E2 : Entity_Id;
10863
10864    begin
10865       Set_Instance_Of (Form, Act);
10866
10867       --  Traverse formal and actual package to map the corresponding entities.
10868       --  We skip over internal entities that may be generated during semantic
10869       --  analysis, and find the matching entities by name, given that they
10870       --  must appear in the same order.
10871
10872       E1 := First_Entity (Form);
10873       E2 := First_Entity (Act);
10874       while Present (E1) and then E1 /= First_Private_Entity (Form) loop
10875          --  Could this test be a single condition???
10876          --  Seems like it could, and isn't FPE (Form) a constant anyway???
10877
10878          if not Is_Internal (E1)
10879            and then Present (Parent (E1))
10880            and then not Is_Class_Wide_Type (E1)
10881            and then not Is_Internal_Name (Chars (E1))
10882          then
10883             while Present (E2) and then Chars (E2) /= Chars (E1) loop
10884                Next_Entity (E2);
10885             end loop;
10886
10887             if No (E2) then
10888                exit;
10889             else
10890                Set_Instance_Of (E1, E2);
10891
10892                if Is_Type (E1) and then Is_Tagged_Type (E2) then
10893                   Set_Instance_Of (Class_Wide_Type (E1), Class_Wide_Type (E2));
10894                end if;
10895
10896                if Is_Constrained (E1) then
10897                   Set_Instance_Of (Base_Type (E1), Base_Type (E2));
10898                end if;
10899
10900                if Ekind (E1) = E_Package and then No (Renamed_Object (E1)) then
10901                   Map_Formal_Package_Entities (E1, E2);
10902                end if;
10903             end if;
10904          end if;
10905
10906          Next_Entity (E1);
10907       end loop;
10908    end Map_Formal_Package_Entities;
10909
10910    -----------------------
10911    -- Move_Freeze_Nodes --
10912    -----------------------
10913
10914    procedure Move_Freeze_Nodes
10915      (Out_Of : Entity_Id;
10916       After  : Node_Id;
10917       L      : List_Id)
10918    is
10919       Decl      : Node_Id;
10920       Next_Decl : Node_Id;
10921       Next_Node : Node_Id := After;
10922       Spec      : Node_Id;
10923
10924       function Is_Outer_Type (T : Entity_Id) return Boolean;
10925       --  Check whether entity is declared in a scope external to that of the
10926       --  generic unit.
10927
10928       -------------------
10929       -- Is_Outer_Type --
10930       -------------------
10931
10932       function Is_Outer_Type (T : Entity_Id) return Boolean is
10933          Scop : Entity_Id := Scope (T);
10934
10935       begin
10936          if Scope_Depth (Scop) < Scope_Depth (Out_Of) then
10937             return True;
10938
10939          else
10940             while Scop /= Standard_Standard loop
10941                if Scop = Out_Of then
10942                   return False;
10943                else
10944                   Scop := Scope (Scop);
10945                end if;
10946             end loop;
10947
10948             return True;
10949          end if;
10950       end Is_Outer_Type;
10951
10952    --  Start of processing for Move_Freeze_Nodes
10953
10954    begin
10955       if No (L) then
10956          return;
10957       end if;
10958
10959       --  First remove the freeze nodes that may appear before all other
10960       --  declarations.
10961
10962       Decl := First (L);
10963       while Present (Decl)
10964         and then Nkind (Decl) = N_Freeze_Entity
10965         and then Is_Outer_Type (Entity (Decl))
10966       loop
10967          Decl := Remove_Head (L);
10968          Insert_After (Next_Node, Decl);
10969          Set_Analyzed (Decl, False);
10970          Next_Node := Decl;
10971          Decl := First (L);
10972       end loop;
10973
10974       --  Next scan the list of declarations and remove each freeze node that
10975       --  appears ahead of the current node.
10976
10977       while Present (Decl) loop
10978          while Present (Next (Decl))
10979            and then Nkind (Next (Decl)) = N_Freeze_Entity
10980            and then Is_Outer_Type (Entity (Next (Decl)))
10981          loop
10982             Next_Decl := Remove_Next (Decl);
10983             Insert_After (Next_Node, Next_Decl);
10984             Set_Analyzed (Next_Decl, False);
10985             Next_Node := Next_Decl;
10986          end loop;
10987
10988          --  If the declaration is a nested package or concurrent type, then
10989          --  recurse. Nested generic packages will have been processed from the
10990          --  inside out.
10991
10992          case Nkind (Decl) is
10993             when N_Package_Declaration =>
10994                Spec := Specification (Decl);
10995
10996             when N_Task_Type_Declaration =>
10997                Spec := Task_Definition (Decl);
10998
10999             when N_Protected_Type_Declaration =>
11000                Spec := Protected_Definition (Decl);
11001
11002             when others =>
11003                Spec := Empty;
11004          end case;
11005
11006          if Present (Spec) then
11007             Move_Freeze_Nodes (Out_Of, Next_Node, Visible_Declarations (Spec));
11008             Move_Freeze_Nodes (Out_Of, Next_Node, Private_Declarations (Spec));
11009          end if;
11010
11011          Next (Decl);
11012       end loop;
11013    end Move_Freeze_Nodes;
11014
11015    ----------------
11016    -- Next_Assoc --
11017    ----------------
11018
11019    function Next_Assoc (E : Assoc_Ptr) return Assoc_Ptr is
11020    begin
11021       return Generic_Renamings.Table (E).Next_In_HTable;
11022    end Next_Assoc;
11023
11024    ------------------------
11025    -- Preanalyze_Actuals --
11026    ------------------------
11027
11028    procedure Preanalyze_Actuals (N : Node_Id) is
11029       Assoc : Node_Id;
11030       Act   : Node_Id;
11031       Errs  : constant Int := Serious_Errors_Detected;
11032
11033       Cur : Entity_Id := Empty;
11034       --  Current homograph of the instance name
11035
11036       Vis : Boolean;
11037       --  Saved visibility status of the current homograph
11038
11039    begin
11040       Assoc := First (Generic_Associations (N));
11041
11042       --  If the instance is a child unit, its name may hide an outer homonym,
11043       --  so make it invisible to perform name resolution on the actuals.
11044
11045       if Nkind (Defining_Unit_Name (N)) = N_Defining_Program_Unit_Name
11046         and then Present
11047           (Current_Entity (Defining_Identifier (Defining_Unit_Name (N))))
11048       then
11049          Cur := Current_Entity (Defining_Identifier (Defining_Unit_Name (N)));
11050
11051          if Is_Compilation_Unit (Cur) then
11052             Vis := Is_Immediately_Visible (Cur);
11053             Set_Is_Immediately_Visible (Cur, False);
11054          else
11055             Cur := Empty;
11056          end if;
11057       end if;
11058
11059       while Present (Assoc) loop
11060          if Nkind (Assoc) /= N_Others_Choice then
11061             Act := Explicit_Generic_Actual_Parameter (Assoc);
11062
11063             --  Within a nested instantiation, a defaulted actual is an empty
11064             --  association, so nothing to analyze. If the subprogram actual
11065             --  is an attribute, analyze prefix only, because actual is not a
11066             --  complete attribute reference.
11067
11068             --  If actual is an allocator, analyze expression only. The full
11069             --  analysis can generate code, and if instance is a compilation
11070             --  unit we have to wait until the package instance is installed
11071             --  to have a proper place to insert this code.
11072
11073             --  String literals may be operators, but at this point we do not
11074             --  know whether the actual is a formal subprogram or a string.
11075
11076             if No (Act) then
11077                null;
11078
11079             elsif Nkind (Act) = N_Attribute_Reference then
11080                Analyze (Prefix (Act));
11081
11082             elsif Nkind (Act) = N_Explicit_Dereference then
11083                Analyze (Prefix (Act));
11084
11085             elsif Nkind (Act) = N_Allocator then
11086                declare
11087                   Expr : constant Node_Id := Expression (Act);
11088
11089                begin
11090                   if Nkind (Expr) = N_Subtype_Indication then
11091                      Analyze (Subtype_Mark (Expr));
11092
11093                      --  Analyze separately each discriminant constraint, when
11094                      --  given with a named association.
11095
11096                      declare
11097                         Constr : Node_Id;
11098
11099                      begin
11100                         Constr := First (Constraints (Constraint (Expr)));
11101                         while Present (Constr) loop
11102                            if Nkind (Constr) = N_Discriminant_Association then
11103                               Analyze (Expression (Constr));
11104                            else
11105                               Analyze (Constr);
11106                            end if;
11107
11108                            Next (Constr);
11109                         end loop;
11110                      end;
11111
11112                   else
11113                      Analyze (Expr);
11114                   end if;
11115                end;
11116
11117             elsif Nkind (Act) /= N_Operator_Symbol then
11118                Analyze (Act);
11119             end if;
11120
11121             if Errs /= Serious_Errors_Detected then
11122
11123                --  Do a minimal analysis of the generic, to prevent spurious
11124                --  warnings complaining about the generic being unreferenced,
11125                --  before abandoning the instantiation.
11126
11127                Analyze (Name (N));
11128
11129                if Is_Entity_Name (Name (N))
11130                  and then Etype (Name (N)) /= Any_Type
11131                then
11132                   Generate_Reference  (Entity (Name (N)), Name (N));
11133                   Set_Is_Instantiated (Entity (Name (N)));
11134                end if;
11135
11136                if Present (Cur) then
11137
11138                   --  For the case of a child instance hiding an outer homonym,
11139                   --  provide additional warning which might explain the error.
11140
11141                   Set_Is_Immediately_Visible (Cur, Vis);
11142                   Error_Msg_NE ("& hides outer unit with the same name?",
11143                     N, Defining_Unit_Name (N));
11144                end if;
11145
11146                Abandon_Instantiation (Act);
11147             end if;
11148          end if;
11149
11150          Next (Assoc);
11151       end loop;
11152
11153       if Present (Cur) then
11154          Set_Is_Immediately_Visible (Cur, Vis);
11155       end if;
11156    end Preanalyze_Actuals;
11157
11158    -------------------
11159    -- Remove_Parent --
11160    -------------------
11161
11162    procedure Remove_Parent (In_Body : Boolean := False) is
11163       S : Entity_Id := Current_Scope;
11164       --  S is the scope containing the instantiation just completed. The scope
11165       --  stack contains the parent instances of the instantiation, followed by
11166       --  the original S.
11167
11168       Cur_P  : Entity_Id;
11169       E      : Entity_Id;
11170       P      : Entity_Id;
11171       Hidden : Elmt_Id;
11172
11173    begin
11174       --  After child instantiation is complete, remove from scope stack the
11175       --  extra copy of the current scope, and then remove parent instances.
11176
11177       if not In_Body then
11178          Pop_Scope;
11179
11180          while Current_Scope /= S loop
11181             P := Current_Scope;
11182             End_Package_Scope (Current_Scope);
11183
11184             if In_Open_Scopes (P) then
11185                E := First_Entity (P);
11186                while Present (E) loop
11187                   Set_Is_Immediately_Visible (E, True);
11188                   Next_Entity (E);
11189                end loop;
11190
11191                --  If instantiation is declared in a block, it is the enclosing
11192                --  scope that might be a parent instance. Note that only one
11193                --  block can be involved, because the parent instances have
11194                --  been installed within it.
11195
11196                if Ekind (P) = E_Block then
11197                   Cur_P := Scope (P);
11198                else
11199                   Cur_P := P;
11200                end if;
11201
11202                if Is_Generic_Instance (Cur_P) and then P /= Current_Scope then
11203                   --  We are within an instance of some sibling. Retain
11204                   --  visibility of parent, for proper subsequent cleanup, and
11205                   --  reinstall private declarations as well.
11206
11207                   Set_In_Private_Part (P);
11208                   Install_Private_Declarations (P);
11209                end if;
11210
11211             --  If the ultimate parent is a top-level unit recorded in
11212             --  Instance_Parent_Unit, then reset its visibility to what it was
11213             --  before instantiation. (It's not clear what the purpose is of
11214             --  testing whether Scope (P) is In_Open_Scopes, but that test was
11215             --  present before the ultimate parent test was added.???)
11216
11217             elsif not In_Open_Scopes (Scope (P))
11218               or else (P = Instance_Parent_Unit
11219                         and then not Parent_Unit_Visible)
11220             then
11221                Set_Is_Immediately_Visible (P, False);
11222
11223             --  If the current scope is itself an instantiation of a generic
11224             --  nested within P, and we are in the private part of body of this
11225             --  instantiation, restore the full views of P, that were removed
11226             --  in End_Package_Scope above. This obscure case can occur when a
11227             --  subunit of a generic contains an instance of a child unit of
11228             --  its generic parent unit.
11229
11230             elsif S = Current_Scope and then Is_Generic_Instance (S) then
11231                declare
11232                   Par : constant Entity_Id :=
11233                           Generic_Parent
11234                             (Specification (Unit_Declaration_Node (S)));
11235                begin
11236                   if Present (Par)
11237                     and then P = Scope (Par)
11238                     and then (In_Package_Body (S) or else In_Private_Part (S))
11239                   then
11240                      Set_In_Private_Part (P);
11241                      Install_Private_Declarations (P);
11242                   end if;
11243                end;
11244             end if;
11245          end loop;
11246
11247          --  Reset visibility of entities in the enclosing scope
11248
11249          Set_Is_Hidden_Open_Scope (Current_Scope, False);
11250
11251          Hidden := First_Elmt (Hidden_Entities);
11252          while Present (Hidden) loop
11253             Set_Is_Immediately_Visible (Node (Hidden), True);
11254             Next_Elmt (Hidden);
11255          end loop;
11256
11257       else
11258          --  Each body is analyzed separately, and there is no context that
11259          --  needs preserving from one body instance to the next, so remove all
11260          --  parent scopes that have been installed.
11261
11262          while Present (S) loop
11263             End_Package_Scope (S);
11264             Set_Is_Immediately_Visible (S, False);
11265             S := Current_Scope;
11266             exit when S = Standard_Standard;
11267          end loop;
11268       end if;
11269    end Remove_Parent;
11270
11271    -----------------
11272    -- Restore_Env --
11273    -----------------
11274
11275    procedure Restore_Env is
11276       Saved : Instance_Env renames Instance_Envs.Table (Instance_Envs.Last);
11277
11278    begin
11279       if No (Current_Instantiated_Parent.Act_Id) then
11280          --  Restore environment after subprogram inlining
11281
11282          Restore_Private_Views (Empty);
11283       end if;
11284
11285       Current_Instantiated_Parent := Saved.Instantiated_Parent;
11286       Exchanged_Views             := Saved.Exchanged_Views;
11287       Hidden_Entities             := Saved.Hidden_Entities;
11288       Current_Sem_Unit            := Saved.Current_Sem_Unit;
11289       Parent_Unit_Visible         := Saved.Parent_Unit_Visible;
11290       Instance_Parent_Unit        := Saved.Instance_Parent_Unit;
11291
11292       Restore_Opt_Config_Switches (Saved.Switches);
11293
11294       Instance_Envs.Decrement_Last;
11295    end Restore_Env;
11296
11297    ---------------------------
11298    -- Restore_Private_Views --
11299    ---------------------------
11300
11301    procedure Restore_Private_Views
11302      (Pack_Id    : Entity_Id;
11303       Is_Package : Boolean := True)
11304    is
11305       M        : Elmt_Id;
11306       E        : Entity_Id;
11307       Typ      : Entity_Id;
11308       Dep_Elmt : Elmt_Id;
11309       Dep_Typ  : Node_Id;
11310
11311       procedure Restore_Nested_Formal (Formal : Entity_Id);
11312       --  Hide the generic formals of formal packages declared with box which
11313       --  were reachable in the current instantiation.
11314
11315       ---------------------------
11316       -- Restore_Nested_Formal --
11317       ---------------------------
11318
11319       procedure Restore_Nested_Formal (Formal : Entity_Id) is
11320          Ent : Entity_Id;
11321
11322       begin
11323          if Present (Renamed_Object (Formal))
11324            and then Denotes_Formal_Package (Renamed_Object (Formal), True)
11325          then
11326             return;
11327
11328          elsif Present (Associated_Formal_Package (Formal)) then
11329             Ent := First_Entity (Formal);
11330             while Present (Ent) loop
11331                exit when Ekind (Ent) = E_Package
11332                  and then Renamed_Entity (Ent) = Renamed_Entity (Formal);
11333
11334                Set_Is_Hidden (Ent);
11335                Set_Is_Potentially_Use_Visible (Ent, False);
11336
11337                --  If package, then recurse
11338
11339                if Ekind (Ent) = E_Package then
11340                   Restore_Nested_Formal (Ent);
11341                end if;
11342
11343                Next_Entity (Ent);
11344             end loop;
11345          end if;
11346       end Restore_Nested_Formal;
11347
11348    --  Start of processing for Restore_Private_Views
11349
11350    begin
11351       M := First_Elmt (Exchanged_Views);
11352       while Present (M) loop
11353          Typ := Node (M);
11354
11355          --  Subtypes of types whose views have been exchanged, and that are
11356          --  defined within the instance, were not on the Private_Dependents
11357          --  list on entry to the instance, so they have to be exchanged
11358          --  explicitly now, in order to remain consistent with the view of the
11359          --  parent type.
11360
11361          if Ekind_In (Typ, E_Private_Type,
11362                            E_Limited_Private_Type,
11363                            E_Record_Type_With_Private)
11364          then
11365             Dep_Elmt := First_Elmt (Private_Dependents (Typ));
11366             while Present (Dep_Elmt) loop
11367                Dep_Typ := Node (Dep_Elmt);
11368
11369                if Scope (Dep_Typ) = Pack_Id
11370                  and then Present (Full_View (Dep_Typ))
11371                then
11372                   Replace_Elmt (Dep_Elmt, Full_View (Dep_Typ));
11373                   Exchange_Declarations (Dep_Typ);
11374                end if;
11375
11376                Next_Elmt (Dep_Elmt);
11377             end loop;
11378          end if;
11379
11380          Exchange_Declarations (Node (M));
11381          Next_Elmt (M);
11382       end loop;
11383
11384       if No (Pack_Id) then
11385          return;
11386       end if;
11387
11388       --  Make the generic formal parameters private, and make the formal types
11389       --  into subtypes of the actuals again.
11390
11391       E := First_Entity (Pack_Id);
11392       while Present (E) loop
11393          Set_Is_Hidden (E, True);
11394
11395          if Is_Type (E)
11396            and then Nkind (Parent (E)) = N_Subtype_Declaration
11397          then
11398             Set_Is_Generic_Actual_Type (E, False);
11399
11400             --  An unusual case of aliasing: the actual may also be directly
11401             --  visible in the generic, and be private there, while it is fully
11402             --  visible in the context of the instance. The internal subtype
11403             --  is private in the instance but has full visibility like its
11404             --  parent in the enclosing scope. This enforces the invariant that
11405             --  the privacy status of all private dependents of a type coincide
11406             --  with that of the parent type. This can only happen when a
11407             --  generic child unit is instantiated within a sibling.
11408
11409             if Is_Private_Type (E)
11410               and then not Is_Private_Type (Etype (E))
11411             then
11412                Exchange_Declarations (E);
11413             end if;
11414
11415          elsif Ekind (E) = E_Package then
11416
11417             --  The end of the renaming list is the renaming of the generic
11418             --  package itself. If the instance is a subprogram, all entities
11419             --  in the corresponding package are renamings. If this entity is
11420             --  a formal package, make its own formals private as well. The
11421             --  actual in this case is itself the renaming of an instantiation.
11422             --  If the entity is not a package renaming, it is the entity
11423             --  created to validate formal package actuals: ignore it.
11424
11425             --  If the actual is itself a formal package for the enclosing
11426             --  generic, or the actual for such a formal package, it remains
11427             --  visible on exit from the instance, and therefore nothing needs
11428             --  to be done either, except to keep it accessible.
11429
11430             if Is_Package and then Renamed_Object (E) = Pack_Id then
11431                exit;
11432
11433             elsif Nkind (Parent (E)) /= N_Package_Renaming_Declaration then
11434                null;
11435
11436             elsif
11437               Denotes_Formal_Package (Renamed_Object (E), True, Pack_Id)
11438             then
11439                Set_Is_Hidden (E, False);
11440
11441             else
11442                declare
11443                   Act_P : constant Entity_Id := Renamed_Object (E);
11444                   Id    : Entity_Id;
11445
11446                begin
11447                   Id := First_Entity (Act_P);
11448                   while Present (Id)
11449                     and then Id /= First_Private_Entity (Act_P)
11450                   loop
11451                      exit when Ekind (Id) = E_Package
11452                                  and then Renamed_Object (Id) = Act_P;
11453
11454                      Set_Is_Hidden (Id, True);
11455                      Set_Is_Potentially_Use_Visible (Id, In_Use (Act_P));
11456
11457                      if Ekind (Id) = E_Package then
11458                         Restore_Nested_Formal (Id);
11459                      end if;
11460
11461                      Next_Entity (Id);
11462                   end loop;
11463                end;
11464             end if;
11465          end if;
11466
11467          Next_Entity (E);
11468       end loop;
11469    end Restore_Private_Views;
11470
11471    --------------
11472    -- Save_Env --
11473    --------------
11474
11475    procedure Save_Env
11476      (Gen_Unit : Entity_Id;
11477       Act_Unit : Entity_Id)
11478    is
11479    begin
11480       Init_Env;
11481       Set_Instance_Env (Gen_Unit, Act_Unit);
11482    end Save_Env;
11483
11484    ----------------------------
11485    -- Save_Global_References --
11486    ----------------------------
11487
11488    procedure Save_Global_References (N : Node_Id) is
11489       Gen_Scope : Entity_Id;
11490       E         : Entity_Id;
11491       N2        : Node_Id;
11492
11493       function Is_Global (E : Entity_Id) return Boolean;
11494       --  Check whether entity is defined outside of generic unit. Examine the
11495       --  scope of an entity, and the scope of the scope, etc, until we find
11496       --  either Standard, in which case the entity is global, or the generic
11497       --  unit itself, which indicates that the entity is local. If the entity
11498       --  is the generic unit itself, as in the case of a recursive call, or
11499       --  the enclosing generic unit, if different from the current scope, then
11500       --  it is local as well, because it will be replaced at the point of
11501       --  instantiation. On the other hand, if it is a reference to a child
11502       --  unit of a common ancestor, which appears in an instantiation, it is
11503       --  global because it is used to denote a specific compilation unit at
11504       --  the time the instantiations will be analyzed.
11505
11506       procedure Reset_Entity (N : Node_Id);
11507       --  Save semantic information on global entity so that it is not resolved
11508       --  again at instantiation time.
11509
11510       procedure Save_Entity_Descendants (N : Node_Id);
11511       --  Apply Save_Global_References to the two syntactic descendants of
11512       --  non-terminal nodes that carry an Associated_Node and are processed
11513       --  through Reset_Entity. Once the global entity (if any) has been
11514       --  captured together with its type, only two syntactic descendants need
11515       --  to be traversed to complete the processing of the tree rooted at N.
11516       --  This applies to Selected_Components, Expanded_Names, and to Operator
11517       --  nodes. N can also be a character literal, identifier, or operator
11518       --  symbol node, but the call has no effect in these cases.
11519
11520       procedure Save_Global_Defaults (N1, N2 : Node_Id);
11521       --  Default actuals in nested instances must be handled specially
11522       --  because there is no link to them from the original tree. When an
11523       --  actual subprogram is given by a default, we add an explicit generic
11524       --  association for it in the instantiation node. When we save the
11525       --  global references on the name of the instance, we recover the list
11526       --  of generic associations, and add an explicit one to the original
11527       --  generic tree, through which a global actual can be preserved.
11528       --  Similarly, if a child unit is instantiated within a sibling, in the
11529       --  context of the parent, we must preserve the identifier of the parent
11530       --  so that it can be properly resolved in a subsequent instantiation.
11531
11532       procedure Save_Global_Descendant (D : Union_Id);
11533       --  Apply Save_Global_References recursively to the descendents of the
11534       --  current node.
11535
11536       procedure Save_References (N : Node_Id);
11537       --  This is the recursive procedure that does the work, once the
11538       --  enclosing generic scope has been established.
11539
11540       ---------------
11541       -- Is_Global --
11542       ---------------
11543
11544       function Is_Global (E : Entity_Id) return Boolean is
11545          Se : Entity_Id;
11546
11547          function Is_Instance_Node (Decl : Node_Id) return Boolean;
11548          --  Determine whether the parent node of a reference to a child unit
11549          --  denotes an instantiation or a formal package, in which case the
11550          --  reference to the child unit is global, even if it appears within
11551          --  the current scope (e.g. when the instance appears within the body
11552          --  of an ancestor).
11553
11554          ----------------------
11555          -- Is_Instance_Node --
11556          ----------------------
11557
11558          function Is_Instance_Node (Decl : Node_Id) return Boolean is
11559          begin
11560             return Nkind (Decl) in N_Generic_Instantiation
11561                      or else
11562                    Nkind (Original_Node (Decl)) = N_Formal_Package_Declaration;
11563          end Is_Instance_Node;
11564
11565       --  Start of processing for Is_Global
11566
11567       begin
11568          if E = Gen_Scope then
11569             return False;
11570
11571          elsif E = Standard_Standard then
11572             return True;
11573
11574          elsif Is_Child_Unit (E)
11575            and then (Is_Instance_Node (Parent (N2))
11576                       or else (Nkind (Parent (N2)) = N_Expanded_Name
11577                                 and then N2 = Selector_Name (Parent (N2))
11578                                 and then
11579                                   Is_Instance_Node (Parent (Parent (N2)))))
11580          then
11581             return True;
11582
11583          else
11584             Se := Scope (E);
11585             while Se /= Gen_Scope loop
11586                if Se = Standard_Standard then
11587                   return True;
11588                else
11589                   Se := Scope (Se);
11590                end if;
11591             end loop;
11592
11593             return False;
11594          end if;
11595       end Is_Global;
11596
11597       ------------------
11598       -- Reset_Entity --
11599       ------------------
11600
11601       procedure Reset_Entity (N : Node_Id) is
11602
11603          procedure Set_Global_Type (N : Node_Id; N2 : Node_Id);
11604          --  If the type of N2 is global to the generic unit. Save the type in
11605          --  the generic node.
11606          --  What does this comment mean???
11607
11608          function Top_Ancestor (E : Entity_Id) return Entity_Id;
11609          --  Find the ultimate ancestor of the current unit. If it is not a
11610          --  generic unit, then the name of the current unit in the prefix of
11611          --  an expanded name must be replaced with its generic homonym to
11612          --  ensure that it will be properly resolved in an instance.
11613
11614          ---------------------
11615          -- Set_Global_Type --
11616          ---------------------
11617
11618          procedure Set_Global_Type (N : Node_Id; N2 : Node_Id) is
11619             Typ : constant Entity_Id := Etype (N2);
11620
11621          begin
11622             Set_Etype (N, Typ);
11623
11624             if Entity (N) /= N2
11625               and then Has_Private_View (Entity (N))
11626             then
11627                --  If the entity of N is not the associated node, this is a
11628                --  nested generic and it has an associated node as well, whose
11629                --  type is already the full view (see below). Indicate that the
11630                --  original node has a private view.
11631
11632                Set_Has_Private_View (N);
11633             end if;
11634
11635             --  If not a private type, nothing else to do
11636
11637             if not Is_Private_Type (Typ) then
11638                if Is_Array_Type (Typ)
11639                  and then Is_Private_Type (Component_Type (Typ))
11640                then
11641                   Set_Has_Private_View (N);
11642                end if;
11643
11644             --  If it is a derivation of a private type in a context where no
11645             --  full view is needed, nothing to do either.
11646
11647             elsif No (Full_View (Typ)) and then Typ /= Etype (Typ) then
11648                null;
11649
11650             --  Otherwise mark the type for flipping and use the full view when
11651             --  available.
11652
11653             else
11654                Set_Has_Private_View (N);
11655
11656                if Present (Full_View (Typ)) then
11657                   Set_Etype (N2, Full_View (Typ));
11658                end if;
11659             end if;
11660          end Set_Global_Type;
11661
11662          ------------------
11663          -- Top_Ancestor --
11664          ------------------
11665
11666          function Top_Ancestor (E : Entity_Id) return Entity_Id is
11667             Par : Entity_Id;
11668
11669          begin
11670             Par := E;
11671             while Is_Child_Unit (Par) loop
11672                Par := Scope (Par);
11673             end loop;
11674
11675             return Par;
11676          end Top_Ancestor;
11677
11678       --  Start of processing for Reset_Entity
11679
11680       begin
11681          N2 := Get_Associated_Node (N);
11682          E := Entity (N2);
11683
11684          --  If the entity is an itype created as a subtype of an access type
11685          --  with a null exclusion restore source entity for proper visibility.
11686          --  The itype will be created anew in the instance.
11687
11688          if Present (E) then
11689             if Is_Itype (E)
11690               and then Ekind (E) = E_Access_Subtype
11691               and then Is_Entity_Name (N)
11692               and then Chars (Etype (E)) = Chars (N)
11693             then
11694                E := Etype (E);
11695                Set_Entity (N2, E);
11696                Set_Etype  (N2, E);
11697             end if;
11698
11699             if Is_Global (E) then
11700                Set_Global_Type (N, N2);
11701
11702             elsif Nkind (N) = N_Op_Concat
11703               and then Is_Generic_Type (Etype (N2))
11704               and then (Base_Type (Etype (Right_Opnd (N2))) = Etype (N2)
11705                          or else
11706                         Base_Type (Etype (Left_Opnd (N2)))  = Etype (N2))
11707               and then Is_Intrinsic_Subprogram (E)
11708             then
11709                null;
11710
11711             else
11712                --  Entity is local. Mark generic node as unresolved.
11713                --  Note that now it does not have an entity.
11714
11715                Set_Associated_Node (N, Empty);
11716                Set_Etype  (N, Empty);
11717             end if;
11718
11719             if Nkind (Parent (N)) in N_Generic_Instantiation
11720               and then N = Name (Parent (N))
11721             then
11722                Save_Global_Defaults (Parent (N), Parent (N2));
11723             end if;
11724
11725          elsif Nkind (Parent (N)) = N_Selected_Component
11726            and then Nkind (Parent (N2)) = N_Expanded_Name
11727          then
11728             if Is_Global (Entity (Parent (N2))) then
11729                Change_Selected_Component_To_Expanded_Name (Parent (N));
11730                Set_Associated_Node (Parent (N), Parent (N2));
11731                Set_Global_Type (Parent (N), Parent (N2));
11732                Save_Entity_Descendants (N);
11733
11734             --  If this is a reference to the current generic entity, replace
11735             --  by the name of the generic homonym of the current package. This
11736             --  is because in an instantiation Par.P.Q will not resolve to the
11737             --  name of the instance, whose enclosing scope is not necessarily
11738             --  Par. We use the generic homonym rather that the name of the
11739             --  generic itself because it may be hidden by a local declaration.
11740
11741             elsif In_Open_Scopes (Entity (Parent (N2)))
11742               and then not
11743                 Is_Generic_Unit (Top_Ancestor (Entity (Prefix (Parent (N2)))))
11744             then
11745                if Ekind (Entity (Parent (N2))) = E_Generic_Package then
11746                   Rewrite (Parent (N),
11747                     Make_Identifier (Sloc (N),
11748                       Chars =>
11749                         Chars (Generic_Homonym (Entity (Parent (N2))))));
11750                else
11751                   Rewrite (Parent (N),
11752                     Make_Identifier (Sloc (N),
11753                       Chars => Chars (Selector_Name (Parent (N2)))));
11754                end if;
11755             end if;
11756
11757             if Nkind (Parent (Parent (N))) in N_Generic_Instantiation
11758               and then Parent (N) = Name (Parent (Parent (N)))
11759             then
11760                Save_Global_Defaults
11761                  (Parent (Parent (N)), Parent (Parent ((N2))));
11762             end if;
11763
11764          --  A selected component may denote a static constant that has been
11765          --  folded. If the static constant is global to the generic, capture
11766          --  its value. Otherwise the folding will happen in any instantiation.
11767
11768          elsif Nkind (Parent (N)) = N_Selected_Component
11769            and then Nkind_In (Parent (N2), N_Integer_Literal, N_Real_Literal)
11770          then
11771             if Present (Entity (Original_Node (Parent (N2))))
11772               and then Is_Global (Entity (Original_Node (Parent (N2))))
11773             then
11774                Rewrite (Parent (N), New_Copy (Parent (N2)));
11775                Set_Analyzed (Parent (N), False);
11776
11777             else
11778                null;
11779             end if;
11780
11781          --  A selected component may be transformed into a parameterless
11782          --  function call. If the called entity is global, rewrite the node
11783          --  appropriately, i.e. as an extended name for the global entity.
11784
11785          elsif Nkind (Parent (N)) = N_Selected_Component
11786            and then Nkind (Parent (N2)) = N_Function_Call
11787            and then N = Selector_Name (Parent (N))
11788          then
11789             if No (Parameter_Associations (Parent (N2))) then
11790                if Is_Global (Entity (Name (Parent (N2)))) then
11791                   Change_Selected_Component_To_Expanded_Name (Parent (N));
11792                   Set_Associated_Node (Parent (N), Name (Parent (N2)));
11793                   Set_Global_Type (Parent (N), Name (Parent (N2)));
11794                   Save_Entity_Descendants (N);
11795
11796                else
11797                   Set_Associated_Node (N, Empty);
11798                   Set_Etype (N, Empty);
11799                end if;
11800
11801             --  In Ada 2005, X.F may be a call to a primitive operation,
11802             --  rewritten as F (X). This rewriting will be done again in an
11803             --  instance, so keep the original node. Global entities will be
11804             --  captured as for other constructs.
11805
11806             else
11807                null;
11808             end if;
11809
11810          --  Entity is local. Reset in generic unit, so that node is resolved
11811          --  anew at the point of instantiation.
11812
11813          else
11814             Set_Associated_Node (N, Empty);
11815             Set_Etype (N, Empty);
11816          end if;
11817       end Reset_Entity;
11818
11819       -----------------------------
11820       -- Save_Entity_Descendants --
11821       -----------------------------
11822
11823       procedure Save_Entity_Descendants (N : Node_Id) is
11824       begin
11825          case Nkind (N) is
11826             when N_Binary_Op =>
11827                Save_Global_Descendant (Union_Id (Left_Opnd (N)));
11828                Save_Global_Descendant (Union_Id (Right_Opnd (N)));
11829
11830             when N_Unary_Op =>
11831                Save_Global_Descendant (Union_Id (Right_Opnd (N)));
11832
11833             when N_Expanded_Name | N_Selected_Component =>
11834                Save_Global_Descendant (Union_Id (Prefix (N)));
11835                Save_Global_Descendant (Union_Id (Selector_Name (N)));
11836
11837             when N_Identifier | N_Character_Literal | N_Operator_Symbol =>
11838                null;
11839
11840             when others =>
11841                raise Program_Error;
11842          end case;
11843       end Save_Entity_Descendants;
11844
11845       --------------------------
11846       -- Save_Global_Defaults --
11847       --------------------------
11848
11849       procedure Save_Global_Defaults (N1, N2 : Node_Id) is
11850          Loc    : constant Source_Ptr := Sloc (N1);
11851          Assoc2 : constant List_Id    := Generic_Associations (N2);
11852          Gen_Id : constant Entity_Id  := Get_Generic_Entity (N2);
11853          Assoc1 : List_Id;
11854          Act1   : Node_Id;
11855          Act2   : Node_Id;
11856          Def    : Node_Id;
11857          Ndec   : Node_Id;
11858          Subp   : Entity_Id;
11859          Actual : Entity_Id;
11860
11861       begin
11862          Assoc1 := Generic_Associations (N1);
11863
11864          if Present (Assoc1) then
11865             Act1 := First (Assoc1);
11866          else
11867             Act1 := Empty;
11868             Set_Generic_Associations (N1, New_List);
11869             Assoc1 := Generic_Associations (N1);
11870          end if;
11871
11872          if Present (Assoc2) then
11873             Act2 := First (Assoc2);
11874          else
11875             return;
11876          end if;
11877
11878          while Present (Act1) and then Present (Act2) loop
11879             Next (Act1);
11880             Next (Act2);
11881          end loop;
11882
11883          --  Find the associations added for default subprograms
11884
11885          if Present (Act2) then
11886             while Nkind (Act2) /= N_Generic_Association
11887               or else No (Entity (Selector_Name (Act2)))
11888               or else not Is_Overloadable (Entity (Selector_Name (Act2)))
11889             loop
11890                Next (Act2);
11891             end loop;
11892
11893             --  Add a similar association if the default is global. The
11894             --  renaming declaration for the actual has been analyzed, and
11895             --  its alias is the program it renames. Link the actual in the
11896             --  original generic tree with the node in the analyzed tree.
11897
11898             while Present (Act2) loop
11899                Subp := Entity (Selector_Name (Act2));
11900                Def  := Explicit_Generic_Actual_Parameter (Act2);
11901
11902                --  Following test is defence against rubbish errors
11903
11904                if No (Alias (Subp)) then
11905                   return;
11906                end if;
11907
11908                --  Retrieve the resolved actual from the renaming declaration
11909                --  created for the instantiated formal.
11910
11911                Actual := Entity (Name (Parent (Parent (Subp))));
11912                Set_Entity (Def, Actual);
11913                Set_Etype (Def, Etype (Actual));
11914
11915                if Is_Global (Actual) then
11916                   Ndec :=
11917                     Make_Generic_Association (Loc,
11918                       Selector_Name => New_Occurrence_Of (Subp, Loc),
11919                         Explicit_Generic_Actual_Parameter =>
11920                           New_Occurrence_Of (Actual, Loc));
11921
11922                   Set_Associated_Node
11923                     (Explicit_Generic_Actual_Parameter (Ndec), Def);
11924
11925                   Append (Ndec, Assoc1);
11926
11927                --  If there are other defaults, add a dummy association in case
11928                --  there are other defaulted formals with the same name.
11929
11930                elsif Present (Next (Act2)) then
11931                   Ndec :=
11932                     Make_Generic_Association (Loc,
11933                       Selector_Name => New_Occurrence_Of (Subp, Loc),
11934                         Explicit_Generic_Actual_Parameter => Empty);
11935
11936                   Append (Ndec, Assoc1);
11937                end if;
11938
11939                Next (Act2);
11940             end loop;
11941          end if;
11942
11943          if Nkind (Name (N1)) = N_Identifier
11944            and then Is_Child_Unit (Gen_Id)
11945            and then Is_Global (Gen_Id)
11946            and then Is_Generic_Unit (Scope (Gen_Id))
11947            and then In_Open_Scopes (Scope (Gen_Id))
11948          then
11949             --  This is an instantiation of a child unit within a sibling, so
11950             --  that the generic parent is in scope. An eventual instance must
11951             --  occur within the scope of an instance of the parent. Make name
11952             --  in instance into an expanded name, to preserve the identifier
11953             --  of the parent, so it can be resolved subsequently.
11954
11955             Rewrite (Name (N2),
11956               Make_Expanded_Name (Loc,
11957                 Chars         => Chars (Gen_Id),
11958                 Prefix        => New_Occurrence_Of (Scope (Gen_Id), Loc),
11959                 Selector_Name => New_Occurrence_Of (Gen_Id, Loc)));
11960             Set_Entity (Name (N2), Gen_Id);
11961
11962             Rewrite (Name (N1),
11963                Make_Expanded_Name (Loc,
11964                 Chars         => Chars (Gen_Id),
11965                 Prefix        => New_Occurrence_Of (Scope (Gen_Id), Loc),
11966                 Selector_Name => New_Occurrence_Of (Gen_Id, Loc)));
11967
11968             Set_Associated_Node (Name (N1), Name (N2));
11969             Set_Associated_Node (Prefix (Name (N1)), Empty);
11970             Set_Associated_Node
11971               (Selector_Name (Name (N1)), Selector_Name (Name (N2)));
11972             Set_Etype (Name (N1), Etype (Gen_Id));
11973          end if;
11974
11975       end Save_Global_Defaults;
11976
11977       ----------------------------
11978       -- Save_Global_Descendant --
11979       ----------------------------
11980
11981       procedure Save_Global_Descendant (D : Union_Id) is
11982          N1 : Node_Id;
11983
11984       begin
11985          if D in Node_Range then
11986             if D = Union_Id (Empty) then
11987                null;
11988
11989             elsif Nkind (Node_Id (D)) /= N_Compilation_Unit then
11990                Save_References (Node_Id (D));
11991             end if;
11992
11993          elsif D in List_Range then
11994             if D = Union_Id (No_List)
11995               or else Is_Empty_List (List_Id (D))
11996             then
11997                null;
11998
11999             else
12000                N1 := First (List_Id (D));
12001                while Present (N1) loop
12002                   Save_References (N1);
12003                   Next (N1);
12004                end loop;
12005             end if;
12006
12007          --  Element list or other non-node field, nothing to do
12008
12009          else
12010             null;
12011          end if;
12012       end Save_Global_Descendant;
12013
12014       ---------------------
12015       -- Save_References --
12016       ---------------------
12017
12018       --  This is the recursive procedure that does the work once the enclosing
12019       --  generic scope has been established. We have to treat specially a
12020       --  number of node rewritings that are required by semantic processing
12021       --  and which change the kind of nodes in the generic copy: typically
12022       --  constant-folding, replacing an operator node by a string literal, or
12023       --  a selected component by an expanded name. In each of those cases, the
12024       --  transformation is propagated to the generic unit.
12025
12026       procedure Save_References (N : Node_Id) is
12027          Loc : constant Source_Ptr := Sloc (N);
12028
12029       begin
12030          if N = Empty then
12031             null;
12032
12033          elsif Nkind_In (N, N_Character_Literal, N_Operator_Symbol) then
12034             if Nkind (N) = Nkind (Get_Associated_Node (N)) then
12035                Reset_Entity (N);
12036
12037             elsif Nkind (N) = N_Operator_Symbol
12038               and then Nkind (Get_Associated_Node (N)) = N_String_Literal
12039             then
12040                Change_Operator_Symbol_To_String_Literal (N);
12041             end if;
12042
12043          elsif Nkind (N) in N_Op then
12044             if Nkind (N) = Nkind (Get_Associated_Node (N)) then
12045                if Nkind (N) = N_Op_Concat then
12046                   Set_Is_Component_Left_Opnd (N,
12047                     Is_Component_Left_Opnd (Get_Associated_Node (N)));
12048
12049                   Set_Is_Component_Right_Opnd (N,
12050                     Is_Component_Right_Opnd (Get_Associated_Node (N)));
12051                end if;
12052
12053                Reset_Entity (N);
12054
12055             else
12056                --  Node may be transformed into call to a user-defined operator
12057
12058                N2 := Get_Associated_Node (N);
12059
12060                if Nkind (N2) = N_Function_Call then
12061                   E := Entity (Name (N2));
12062
12063                   if Present (E)
12064                     and then Is_Global (E)
12065                   then
12066                      Set_Etype (N, Etype (N2));
12067                   else
12068                      Set_Associated_Node (N, Empty);
12069                      Set_Etype (N, Empty);
12070                   end if;
12071
12072                elsif Nkind_In (N2, N_Integer_Literal,
12073                                    N_Real_Literal,
12074                                    N_String_Literal)
12075                then
12076                   if Present (Original_Node (N2))
12077                     and then Nkind (Original_Node (N2)) = Nkind (N)
12078                   then
12079
12080                      --  Operation was constant-folded. Whenever possible,
12081                      --  recover semantic information from unfolded node,
12082                      --  for ASIS use.
12083
12084                      Set_Associated_Node (N, Original_Node (N2));
12085
12086                      if Nkind (N) = N_Op_Concat then
12087                         Set_Is_Component_Left_Opnd (N,
12088                           Is_Component_Left_Opnd  (Get_Associated_Node (N)));
12089                         Set_Is_Component_Right_Opnd (N,
12090                           Is_Component_Right_Opnd (Get_Associated_Node (N)));
12091                      end if;
12092
12093                      Reset_Entity (N);
12094
12095                   else
12096                      --  If original node is already modified, propagate
12097                      --  constant-folding to template.
12098
12099                      Rewrite (N, New_Copy (N2));
12100                      Set_Analyzed (N, False);
12101                   end if;
12102
12103                elsif Nkind (N2) = N_Identifier
12104                  and then Ekind (Entity (N2)) = E_Enumeration_Literal
12105                then
12106                   --  Same if call was folded into a literal, but in this case
12107                   --  retain the entity to avoid spurious ambiguities if it is
12108                   --  overloaded at the point of instantiation or inlining.
12109
12110                   Rewrite (N, New_Copy (N2));
12111                   Set_Analyzed (N, False);
12112                end if;
12113             end if;
12114
12115             --  Complete operands check if node has not been constant-folded
12116
12117             if Nkind (N) in N_Op then
12118                Save_Entity_Descendants (N);
12119             end if;
12120
12121          elsif Nkind (N) = N_Identifier then
12122             if Nkind (N) = Nkind (Get_Associated_Node (N)) then
12123
12124                --  If this is a discriminant reference, always save it. It is
12125                --  used in the instance to find the corresponding discriminant
12126                --  positionally rather than by name.
12127
12128                Set_Original_Discriminant
12129                  (N, Original_Discriminant (Get_Associated_Node (N)));
12130                Reset_Entity (N);
12131
12132             else
12133                N2 := Get_Associated_Node (N);
12134
12135                if Nkind (N2) = N_Function_Call then
12136                   E := Entity (Name (N2));
12137
12138                   --  Name resolves to a call to parameterless function. If
12139                   --  original entity is global, mark node as resolved.
12140
12141                   if Present (E)
12142                     and then Is_Global (E)
12143                   then
12144                      Set_Etype (N, Etype (N2));
12145                   else
12146                      Set_Associated_Node (N, Empty);
12147                      Set_Etype (N, Empty);
12148                   end if;
12149
12150                elsif Nkind_In (N2, N_Integer_Literal, N_Real_Literal)
12151                  and then Is_Entity_Name (Original_Node (N2))
12152                then
12153                   --  Name resolves to named number that is constant-folded,
12154                   --  We must preserve the original name for ASIS use, and
12155                   --  undo the constant-folding, which will be repeated in
12156                   --  each instance.
12157
12158                   Set_Associated_Node (N, Original_Node (N2));
12159                   Reset_Entity (N);
12160
12161                elsif Nkind (N2) = N_String_Literal then
12162
12163                   --  Name resolves to string literal. Perform the same
12164                   --  replacement in generic.
12165
12166                   Rewrite (N, New_Copy (N2));
12167
12168                elsif Nkind (N2) = N_Explicit_Dereference then
12169
12170                   --  An identifier is rewritten as a dereference if it is the
12171                   --  prefix in an implicit dereference (call or attribute).
12172                   --  The analysis of an instantiation will expand the node
12173                   --  again, so we preserve the original tree but link it to
12174                   --  the resolved entity in case it is global.
12175
12176                   if Is_Entity_Name (Prefix (N2))
12177                     and then Present (Entity (Prefix (N2)))
12178                     and then Is_Global (Entity (Prefix (N2)))
12179                   then
12180                      Set_Associated_Node (N, Prefix (N2));
12181
12182                   elsif Nkind (Prefix (N2)) = N_Function_Call
12183                     and then Is_Global (Entity (Name (Prefix (N2))))
12184                   then
12185                      Rewrite (N,
12186                        Make_Explicit_Dereference (Loc,
12187                           Prefix => Make_Function_Call (Loc,
12188                             Name =>
12189                               New_Occurrence_Of (Entity (Name (Prefix (N2))),
12190                                                  Loc))));
12191
12192                   else
12193                      Set_Associated_Node (N, Empty);
12194                      Set_Etype (N, Empty);
12195                   end if;
12196
12197                --  The subtype mark of a nominally unconstrained object is
12198                --  rewritten as a subtype indication using the bounds of the
12199                --  expression. Recover the original subtype mark.
12200
12201                elsif Nkind (N2) = N_Subtype_Indication
12202                  and then Is_Entity_Name (Original_Node (N2))
12203                then
12204                   Set_Associated_Node (N, Original_Node (N2));
12205                   Reset_Entity (N);
12206
12207                else
12208                   null;
12209                end if;
12210             end if;
12211
12212          elsif Nkind (N) in N_Entity then
12213             null;
12214
12215          else
12216             declare
12217                Qual : Node_Id := Empty;
12218                Typ  : Entity_Id := Empty;
12219                Nam  : Node_Id;
12220
12221                use Atree.Unchecked_Access;
12222                --  This code section is part of implementing an untyped tree
12223                --  traversal, so it needs direct access to node fields.
12224
12225             begin
12226                if Nkind_In (N, N_Aggregate, N_Extension_Aggregate) then
12227                   N2 := Get_Associated_Node (N);
12228
12229                   if No (N2) then
12230                      Typ := Empty;
12231                   else
12232                      Typ := Etype (N2);
12233
12234                      --  In an instance within a generic, use the name of the
12235                      --  actual and not the original generic parameter. If the
12236                      --  actual is global in the current generic it must be
12237                      --  preserved for its instantiation.
12238
12239                      if Nkind (Parent (Typ)) = N_Subtype_Declaration
12240                        and then
12241                          Present (Generic_Parent_Type (Parent (Typ)))
12242                      then
12243                         Typ := Base_Type (Typ);
12244                         Set_Etype (N2, Typ);
12245                      end if;
12246                   end if;
12247
12248                   if No (N2)
12249                     or else No (Typ)
12250                     or else not Is_Global (Typ)
12251                   then
12252                      Set_Associated_Node (N, Empty);
12253
12254                      --  If the aggregate is an actual in a call, it has been
12255                      --  resolved in the current context, to some local type.
12256                      --  The enclosing call may have been disambiguated by the
12257                      --  aggregate, and this disambiguation might fail at
12258                      --  instantiation time because the type to which the
12259                      --  aggregate did resolve is not preserved. In order to
12260                      --  preserve some of this information, we wrap the
12261                      --  aggregate in a qualified expression, using the id of
12262                      --  its type. For further disambiguation we qualify the
12263                      --  type name with its scope (if visible) because both
12264                      --  id's will have corresponding entities in an instance.
12265                      --  This resolves most of the problems with missing type
12266                      --  information on aggregates in instances.
12267
12268                      if Nkind (N2) = Nkind (N)
12269                        and then
12270                          Nkind_In (Parent (N2), N_Procedure_Call_Statement,
12271                                                 N_Function_Call)
12272                        and then Comes_From_Source (Typ)
12273                      then
12274                         if Is_Immediately_Visible (Scope (Typ)) then
12275                            Nam := Make_Selected_Component (Loc,
12276                              Prefix =>
12277                                Make_Identifier (Loc, Chars (Scope (Typ))),
12278                              Selector_Name =>
12279                                Make_Identifier (Loc, Chars (Typ)));
12280                         else
12281                            Nam := Make_Identifier (Loc, Chars (Typ));
12282                         end if;
12283
12284                         Qual :=
12285                           Make_Qualified_Expression (Loc,
12286                             Subtype_Mark => Nam,
12287                             Expression => Relocate_Node (N));
12288                      end if;
12289                   end if;
12290
12291                   Save_Global_Descendant (Field1 (N));
12292                   Save_Global_Descendant (Field2 (N));
12293                   Save_Global_Descendant (Field3 (N));
12294                   Save_Global_Descendant (Field5 (N));
12295
12296                   if Present (Qual) then
12297                      Rewrite (N, Qual);
12298                   end if;
12299
12300                --  All other cases than aggregates
12301
12302                else
12303                   --  For pragmas, we propagate the Enabled status for the
12304                   --  relevant pragmas to the original generic tree. This was
12305                   --  originally needed for SCO generation. It is no longer
12306                   --  needed there (since we use the Sloc value in calls to
12307                   --  Set_SCO_Pragma_Enabled), but it seems a generally good
12308                   --  idea to have this flag set properly.
12309
12310                   if Nkind (N) = N_Pragma
12311                     and then
12312                       (Pragma_Name (N) = Name_Assert       or else
12313                        Pragma_Name (N) = Name_Check        or else
12314                        Pragma_Name (N) = Name_Precondition or else
12315                        Pragma_Name (N) = Name_Postcondition)
12316                     and then Present (Associated_Node (Pragma_Identifier (N)))
12317                   then
12318                      Set_Pragma_Enabled (N,
12319                        Pragma_Enabled
12320                          (Parent (Associated_Node (Pragma_Identifier (N)))));
12321                   end if;
12322
12323                   Save_Global_Descendant (Field1 (N));
12324                   Save_Global_Descendant (Field2 (N));
12325                   Save_Global_Descendant (Field3 (N));
12326                   Save_Global_Descendant (Field4 (N));
12327                   Save_Global_Descendant (Field5 (N));
12328                end if;
12329             end;
12330          end if;
12331       end Save_References;
12332
12333    --  Start of processing for Save_Global_References
12334
12335    begin
12336       Gen_Scope := Current_Scope;
12337
12338       --  If the generic unit is a child unit, references to entities in the
12339       --  parent are treated as local, because they will be resolved anew in
12340       --  the context of the instance of the parent.
12341
12342       while Is_Child_Unit (Gen_Scope)
12343         and then Ekind (Scope (Gen_Scope)) = E_Generic_Package
12344       loop
12345          Gen_Scope := Scope (Gen_Scope);
12346       end loop;
12347
12348       Save_References (N);
12349    end Save_Global_References;
12350
12351    --------------------------------------
12352    -- Set_Copied_Sloc_For_Inlined_Body --
12353    --------------------------------------
12354
12355    procedure Set_Copied_Sloc_For_Inlined_Body (N : Node_Id; E : Entity_Id) is
12356    begin
12357       Create_Instantiation_Source (N, E, True, S_Adjustment);
12358    end Set_Copied_Sloc_For_Inlined_Body;
12359
12360    ---------------------
12361    -- Set_Instance_Of --
12362    ---------------------
12363
12364    procedure Set_Instance_Of (A : Entity_Id; B : Entity_Id) is
12365    begin
12366       Generic_Renamings.Table (Generic_Renamings.Last) := (A, B, Assoc_Null);
12367       Generic_Renamings_HTable.Set (Generic_Renamings.Last);
12368       Generic_Renamings.Increment_Last;
12369    end Set_Instance_Of;
12370
12371    --------------------
12372    -- Set_Next_Assoc --
12373    --------------------
12374
12375    procedure Set_Next_Assoc (E : Assoc_Ptr; Next : Assoc_Ptr) is
12376    begin
12377       Generic_Renamings.Table (E).Next_In_HTable := Next;
12378    end Set_Next_Assoc;
12379
12380    -------------------
12381    -- Start_Generic --
12382    -------------------
12383
12384    procedure Start_Generic is
12385    begin
12386       --  ??? More things could be factored out in this routine.
12387       --  Should probably be done at a later stage.
12388
12389       Generic_Flags.Append (Inside_A_Generic);
12390       Inside_A_Generic := True;
12391
12392       Expander_Mode_Save_And_Set (False);
12393    end Start_Generic;
12394
12395    ----------------------
12396    -- Set_Instance_Env --
12397    ----------------------
12398
12399    procedure Set_Instance_Env
12400      (Gen_Unit : Entity_Id;
12401       Act_Unit : Entity_Id)
12402    is
12403    begin
12404       --  Regardless of the current mode, predefined units are analyzed in the
12405       --  most current Ada mode, and earlier version Ada checks do not apply
12406       --  to predefined units. Nothing needs to be done for non-internal units.
12407       --  These are always analyzed in the current mode.
12408
12409       if Is_Internal_File_Name
12410            (Fname              => Unit_File_Name (Get_Source_Unit (Gen_Unit)),
12411             Renamings_Included => True)
12412       then
12413          Set_Opt_Config_Switches (True, Current_Sem_Unit = Main_Unit);
12414       end if;
12415
12416       Current_Instantiated_Parent :=
12417         (Gen_Id         => Gen_Unit,
12418          Act_Id         => Act_Unit,
12419          Next_In_HTable => Assoc_Null);
12420    end Set_Instance_Env;
12421
12422    -----------------
12423    -- Switch_View --
12424    -----------------
12425
12426    procedure Switch_View (T : Entity_Id) is
12427       BT        : constant Entity_Id := Base_Type (T);
12428       Priv_Elmt : Elmt_Id := No_Elmt;
12429       Priv_Sub  : Entity_Id;
12430
12431    begin
12432       --  T may be private but its base type may have been exchanged through
12433       --  some other occurrence, in which case there is nothing to switch
12434       --  besides T itself. Note that a private dependent subtype of a private
12435       --  type might not have been switched even if the base type has been,
12436       --  because of the last branch of Check_Private_View (see comment there).
12437
12438       if not Is_Private_Type (BT) then
12439          Prepend_Elmt (Full_View (T), Exchanged_Views);
12440          Exchange_Declarations (T);
12441          return;
12442       end if;
12443
12444       Priv_Elmt := First_Elmt (Private_Dependents (BT));
12445
12446       if Present (Full_View (BT)) then
12447          Prepend_Elmt (Full_View (BT), Exchanged_Views);
12448          Exchange_Declarations (BT);
12449       end if;
12450
12451       while Present (Priv_Elmt) loop
12452          Priv_Sub := (Node (Priv_Elmt));
12453
12454          --  We avoid flipping the subtype if the Etype of its full view is
12455          --  private because this would result in a malformed subtype. This
12456          --  occurs when the Etype of the subtype full view is the full view of
12457          --  the base type (and since the base types were just switched, the
12458          --  subtype is pointing to the wrong view). This is currently the case
12459          --  for tagged record types, access types (maybe more?) and needs to
12460          --  be resolved. ???
12461
12462          if Present (Full_View (Priv_Sub))
12463            and then not Is_Private_Type (Etype (Full_View (Priv_Sub)))
12464          then
12465             Prepend_Elmt (Full_View (Priv_Sub), Exchanged_Views);
12466             Exchange_Declarations (Priv_Sub);
12467          end if;
12468
12469          Next_Elmt (Priv_Elmt);
12470       end loop;
12471    end Switch_View;
12472
12473    -----------------------------
12474    -- Valid_Default_Attribute --
12475    -----------------------------
12476
12477    procedure Valid_Default_Attribute (Nam : Entity_Id; Def : Node_Id) is
12478       Attr_Id : constant Attribute_Id :=
12479                   Get_Attribute_Id (Attribute_Name (Def));
12480       T       : constant Entity_Id := Entity (Prefix (Def));
12481       Is_Fun  : constant Boolean := (Ekind (Nam) = E_Function);
12482       F       : Entity_Id;
12483       Num_F   : Int;
12484       OK      : Boolean;
12485
12486    begin
12487       if No (T)
12488         or else T = Any_Id
12489       then
12490          return;
12491       end if;
12492
12493       Num_F := 0;
12494       F := First_Formal (Nam);
12495       while Present (F) loop
12496          Num_F := Num_F + 1;
12497          Next_Formal (F);
12498       end loop;
12499
12500       case Attr_Id is
12501          when Attribute_Adjacent |  Attribute_Ceiling   | Attribute_Copy_Sign |
12502               Attribute_Floor    |  Attribute_Fraction  | Attribute_Machine   |
12503               Attribute_Model    |  Attribute_Remainder | Attribute_Rounding  |
12504               Attribute_Unbiased_Rounding  =>
12505             OK := Is_Fun
12506                     and then Num_F = 1
12507                     and then Is_Floating_Point_Type (T);
12508
12509          when Attribute_Image    | Attribute_Pred       | Attribute_Succ |
12510               Attribute_Value    | Attribute_Wide_Image |
12511               Attribute_Wide_Value  =>
12512             OK := (Is_Fun and then Num_F = 1 and then Is_Scalar_Type (T));
12513
12514          when Attribute_Max      |  Attribute_Min  =>
12515             OK := (Is_Fun and then Num_F = 2 and then Is_Scalar_Type (T));
12516
12517          when Attribute_Input =>
12518             OK := (Is_Fun and then Num_F = 1);
12519
12520          when Attribute_Output | Attribute_Read | Attribute_Write =>
12521             OK := (not Is_Fun and then Num_F = 2);
12522
12523          when others =>
12524             OK := False;
12525       end case;
12526
12527       if not OK then
12528          Error_Msg_N ("attribute reference has wrong profile for subprogram",
12529            Def);
12530       end if;
12531    end Valid_Default_Attribute;
12532
12533 end Sem_Ch12;