OSDN Git Service

2004-05-17 Steve Kargl <kargls@comcast.net>
[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-2004, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 2,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT;  see file COPYING.  If not, write --
19 -- to  the Free Software Foundation,  59 Temple Place - Suite 330,  Boston, --
20 -- MA 02111-1307, USA.                                                      --
21 --                                                                          --
22 -- GNAT was originally developed  by the GNAT team at  New York University. --
23 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
24 --                                                                          --
25 ------------------------------------------------------------------------------
26
27 with Atree;    use Atree;
28 with 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 Inline;   use Inline;
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 Nmake;    use Nmake;
42 with Opt;      use Opt;
43 with Rident;   use Rident;
44 with Restrict; use Restrict;
45 with Rtsfind;  use Rtsfind;
46 with Sem;      use Sem;
47 with Sem_Cat;  use Sem_Cat;
48 with Sem_Ch3;  use Sem_Ch3;
49 with Sem_Ch6;  use Sem_Ch6;
50 with Sem_Ch7;  use Sem_Ch7;
51 with Sem_Ch8;  use Sem_Ch8;
52 with Sem_Ch10; use Sem_Ch10;
53 with Sem_Ch13; use Sem_Ch13;
54 with Sem_Elab; use Sem_Elab;
55 with Sem_Elim; use Sem_Elim;
56 with Sem_Eval; use Sem_Eval;
57 with Sem_Res;  use Sem_Res;
58 with Sem_Type; use Sem_Type;
59 with Sem_Util; use Sem_Util;
60 with Sem_Warn; use Sem_Warn;
61 with Stand;    use Stand;
62 with Sinfo;    use Sinfo;
63 with Sinfo.CN; use Sinfo.CN;
64 with Sinput;   use Sinput;
65 with Sinput.L; use Sinput.L;
66 with Snames;   use Snames;
67 with Stringt;  use Stringt;
68 with Uname;    use Uname;
69 with Table;
70 with Tbuild;   use Tbuild;
71 with Uintp;    use Uintp;
72 with Urealp;   use Urealp;
73
74 with GNAT.HTable;
75
76 package body Sem_Ch12 is
77
78    ----------------------------------------------------------
79    -- Implementation of Generic Analysis and Instantiation --
80    -----------------------------------------------------------
81
82    --  GNAT implements generics by macro expansion. No attempt is made to
83    --  share generic instantiations (for now). Analysis of a generic definition
84    --  does not perform any expansion action, but the expander must be called
85    --  on the tree for each instantiation, because the expansion may of course
86    --  depend on the generic actuals. All of this is best achieved as follows:
87    --
88    --  a) Semantic analysis of a generic unit is performed on a copy of the
89    --  tree for the generic unit. All tree modifications that follow analysis
90    --  do not affect the original tree. Links are kept between the original
91    --  tree and the copy, in order to recognize non-local references within
92    --  the generic, and propagate them to each instance (recall that name
93    --  resolution is done on the generic declaration: generics are not really
94    --  macros!). This is summarized in the following diagram:
95    --
96    --              .-----------.               .----------.
97    --              |  semantic |<--------------|  generic |
98    --              |    copy   |               |    unit  |
99    --              |           |==============>|          |
100    --              |___________|    global     |__________|
101    --                             references     |   |  |
102    --                                            |   |  |
103    --                                          .-----|--|.
104    --                                          |  .-----|---.
105    --                                          |  |  .----------.
106    --                                          |  |  |  generic |
107    --                                          |__|  |          |
108    --                                             |__| instance |
109    --                                                |__________|
110    --
111    --  b) Each instantiation copies the original tree, and inserts into it a
112    --  series of declarations that describe the mapping between generic formals
113    --  and actuals. For example, a generic In OUT parameter is an object
114    --  renaming of the corresponing actual, etc. Generic IN parameters are
115    --  constant declarations.
116    --
117    --  c) In order to give the right visibility for these renamings, we use
118    --  a different scheme for package and subprogram instantiations. For
119    --  packages, the list of renamings is inserted into the package
120    --  specification, before the visible declarations of the package. The
121    --  renamings are analyzed before any of the text of the instance, and are
122    --  thus visible at the right place. Furthermore, outside of the instance,
123    --  the generic parameters are visible and denote their corresponding
124    --  actuals.
125
126    --  For subprograms, we create a container package to hold the renamings
127    --  and the subprogram instance itself. Analysis of the package makes the
128    --  renaming declarations visible to the subprogram. After analyzing the
129    --  package, the defining entity for the subprogram is touched-up so that
130    --  it appears declared in the current scope, and not inside the container
131    --  package.
132
133    --  If the instantiation is a compilation unit, the container package is
134    --  given the same name as the subprogram instance. This ensures that
135    --  the elaboration procedure called by the binder, using the compilation
136    --  unit name, calls in fact the elaboration procedure for the package.
137
138    --  Not surprisingly, private types complicate this approach. By saving in
139    --  the original generic object the non-local references, we guarantee that
140    --  the proper entities are referenced at the point of instantiation.
141    --  However, for private types, this by itself does not insure that the
142    --  proper VIEW of the entity is used (the full type may be visible at the
143    --  point of generic definition, but not at instantiation, or vice-versa).
144    --  In  order to reference the proper view, we special-case any reference
145    --  to private types in the generic object, by saving both views, one in
146    --  the generic and one in the semantic copy. At time of instantiation, we
147    --  check whether the two views are consistent, and exchange declarations if
148    --  necessary, in order to restore the correct visibility. Similarly, if
149    --  the instance view is private when the generic view was not, we perform
150    --  the exchange. After completing the instantiation, we restore the
151    --  current visibility. The flag Has_Private_View marks identifiers in the
152    --  the generic unit that require checking.
153
154    --  Visibility within nested generic units requires special handling.
155    --  Consider the following scheme:
156    --
157    --  type Global is ...         --  outside of generic unit.
158    --  generic ...
159    --  package Outer is
160    --     ...
161    --     type Semi_Global is ... --  global to inner.
162    --
163    --     generic ...                                         -- 1
164    --     procedure inner (X1 : Global;  X2 : Semi_Global);
165    --
166    --     procedure in2 is new inner (...);                   -- 4
167    --  end Outer;
168
169    --  package New_Outer is new Outer (...);                  -- 2
170    --  procedure New_Inner is new New_Outer.Inner (...);      -- 3
171
172    --  The semantic analysis of Outer captures all occurrences of Global.
173    --  The semantic analysis of Inner (at 1) captures both occurrences of
174    --  Global and Semi_Global.
175
176    --  At point 2 (instantiation of Outer), we also produce a generic copy
177    --  of Inner, even though Inner is, at that point, not being instantiated.
178    --  (This is just part of the semantic analysis of New_Outer).
179
180    --  Critically, references to Global within Inner must be preserved, while
181    --  references to Semi_Global should not preserved, because they must now
182    --  resolve to an entity within New_Outer. To distinguish between these, we
183    --  use a global variable, Current_Instantiated_Parent, which is set when
184    --  performing a generic copy during instantiation (at 2). This variable is
185    --  used when performing a generic copy that is not an instantiation, but
186    --  that is nested within one, as the occurrence of 1 within 2. The analysis
187    --  of a nested generic only preserves references that are global to the
188    --  enclosing Current_Instantiated_Parent. We use the Scope_Depth value to
189    --  determine whether a reference is external to the given parent.
190
191    --  The instantiation at point 3 requires no special treatment. The method
192    --  works as well for further nestings of generic units, but of course the
193    --  variable Current_Instantiated_Parent must be stacked because nested
194    --  instantiations can occur, e.g. the occurrence of 4 within 2.
195
196    --  The instantiation of package and subprogram bodies is handled in a
197    --  similar manner, except that it is delayed until after semantic
198    --  analysis is complete. In this fashion complex cross-dependencies
199    --  between several package declarations and bodies containing generics
200    --  can be compiled which otherwise would diagnose spurious circularities.
201
202    --  For example, it is possible to compile two packages A and B that
203    --  have the following structure:
204
205    --    package A is                         package B is
206    --       generic ...                          generic ...
207    --       package G_A is                       package G_B is
208
209    --    with B;                              with A;
210    --    package body A is                    package body B is
211    --       package N_B is new G_B (..)          package N_A is new G_A (..)
212
213    --  The table Pending_Instantiations in package Inline is used to keep
214    --  track of body instantiations that are delayed in this manner. Inline
215    --  handles the actual calls to do the body instantiations. This activity
216    --  is part of Inline, since the processing occurs at the same point, and
217    --  for essentially the same reason, as the handling of inlined routines.
218
219    ----------------------------------------------
220    -- Detection of Instantiation Circularities --
221    ----------------------------------------------
222
223    --  If we have a chain of instantiations that is circular, this is a
224    --  static error which must be detected at compile time. The detection
225    --  of these circularities is carried out at the point that we insert
226    --  a generic instance spec or body. If there is a circularity, then
227    --  the analysis of the offending spec or body will eventually result
228    --  in trying to load the same unit again, and we detect this problem
229    --  as we analyze the package instantiation for the second time.
230
231    --  At least in some cases after we have detected the circularity, we
232    --  get into trouble if we try to keep going. The following flag is
233    --  set if a circularity is detected, and used to abandon compilation
234    --  after the messages have been posted.
235
236    Circularity_Detected : Boolean := False;
237    --  This should really be reset on encountering a new main unit, but in
238    --  practice we are not using multiple main units so it is not critical.
239
240    -----------------------
241    -- Local subprograms --
242    -----------------------
243
244    procedure Abandon_Instantiation (N : Node_Id);
245    pragma No_Return (Abandon_Instantiation);
246    --  Posts an error message "instantiation abandoned" at the indicated
247    --  node and then raises the exception Instantiation_Error to do it.
248
249    procedure Analyze_Formal_Array_Type
250      (T   : in out Entity_Id;
251       Def : Node_Id);
252    --  A formal array type is treated like an array type declaration, and
253    --  invokes Array_Type_Declaration (sem_ch3) whose first parameter is
254    --  in-out, because in the case of an anonymous type the entity is
255    --  actually created in the procedure.
256
257    --  The following procedures treat other kinds of formal parameters.
258
259    procedure Analyze_Formal_Derived_Type
260      (N   : Node_Id;
261       T   : Entity_Id;
262       Def : Node_Id);
263
264    --  All the following need comments???
265
266    procedure Analyze_Formal_Decimal_Fixed_Point_Type
267                                                 (T : Entity_Id; Def : Node_Id);
268    procedure Analyze_Formal_Discrete_Type       (T : Entity_Id; Def : Node_Id);
269    procedure Analyze_Formal_Floating_Type       (T : Entity_Id; Def : Node_Id);
270    procedure Analyze_Formal_Signed_Integer_Type (T : Entity_Id; Def : Node_Id);
271    procedure Analyze_Formal_Modular_Type        (T : Entity_Id; Def : Node_Id);
272    procedure Analyze_Formal_Ordinary_Fixed_Point_Type
273                                                 (T : Entity_Id; Def : Node_Id);
274
275    procedure Analyze_Formal_Private_Type
276      (N   : Node_Id;
277       T   : Entity_Id;
278       Def : Node_Id);
279    --  This needs comments???
280
281    procedure Analyze_Generic_Formal_Part (N : Node_Id);
282
283    procedure Analyze_Generic_Access_Type (T : Entity_Id; Def : Node_Id);
284    --  This needs comments ???
285
286    function Analyze_Associations
287      (I_Node  : Node_Id;
288       Formals : List_Id;
289       F_Copy  : List_Id)
290       return    List_Id;
291    --  At instantiation time, build the list of associations between formals
292    --  and actuals. Each association becomes a renaming declaration for the
293    --  formal entity. F_Copy is the analyzed list of formals in the generic
294    --  copy. It is used to apply legality checks to the actuals. I_Node is the
295    --  instantiation node itself.
296
297    procedure Analyze_Subprogram_Instantiation
298      (N : Node_Id;
299       K : Entity_Kind);
300
301    procedure Build_Instance_Compilation_Unit_Nodes
302      (N        : Node_Id;
303       Act_Body : Node_Id;
304       Act_Decl : Node_Id);
305    --  This procedure is used in the case where the generic instance of a
306    --  subprogram body or package body is a library unit. In this case, the
307    --  original library unit node for the generic instantiation must be
308    --  replaced by the resulting generic body, and a link made to a new
309    --  compilation unit node for the generic declaration. The argument N is
310    --  the original generic instantiation. Act_Body and Act_Decl are the body
311    --  and declaration of the instance (either package body and declaration
312    --  nodes or subprogram body and declaration nodes depending on the case).
313    --  On return, the node N has been rewritten with the actual body.
314
315    procedure Check_Formal_Packages (P_Id : Entity_Id);
316    --  Apply the following to all formal packages in generic associations.
317
318    procedure Check_Formal_Package_Instance
319      (Formal_Pack : Entity_Id;
320       Actual_Pack : Entity_Id);
321    --  Verify that the actuals of the actual instance match the actuals of
322    --  the template for a formal package that is not declared with a box.
323
324    procedure Check_Forward_Instantiation (Decl : Node_Id);
325    --  If the generic is a local entity and the corresponding body has not
326    --  been seen yet, flag enclosing packages to indicate that it will be
327    --  elaborated after the generic body. Subprograms declared in the same
328    --  package cannot be inlined by the front-end because front-end inlining
329    --  requires a strict linear order of elaboration.
330
331    procedure Check_Hidden_Child_Unit
332      (N           : Node_Id;
333       Gen_Unit    : Entity_Id;
334       Act_Decl_Id : Entity_Id);
335    --  If the generic unit is an implicit child instance within a parent
336    --  instance, we need to make an explicit test that it is not hidden by
337    --  a child instance of the same name and parent.
338
339    procedure Check_Private_View (N : Node_Id);
340    --  Check whether the type of a generic entity has a different view between
341    --  the point of generic analysis and the point of instantiation. If the
342    --  view has changed, then at the point of instantiation we restore the
343    --  correct view to perform semantic analysis of the instance, and reset
344    --  the current view after instantiation. The processing is driven by the
345    --  current private status of the type of the node, and Has_Private_View,
346    --  a flag that is set at the point of generic compilation. If view and
347    --  flag are inconsistent then the type is updated appropriately.
348
349    procedure Check_Generic_Actuals
350      (Instance      : Entity_Id;
351       Is_Formal_Box : Boolean);
352    --  Similar to previous one. Check the actuals in the instantiation,
353    --  whose views can change between the point of instantiation and the point
354    --  of instantiation of the body. In addition, mark the generic renamings
355    --  as generic actuals, so that they are not compatible with other actuals.
356    --  Recurse on an actual that is a formal package whose declaration has
357    --  a box.
358
359    function Contains_Instance_Of
360      (Inner : Entity_Id;
361       Outer : Entity_Id;
362       N     : Node_Id)
363       return  Boolean;
364    --  Inner is instantiated within the generic Outer. Check whether Inner
365    --  directly or indirectly contains an instance of Outer or of one of its
366    --  parents, in the case of a subunit. Each generic unit holds a list of
367    --  the entities instantiated within (at any depth). This procedure
368    --  determines whether the set of such lists contains a cycle, i.e. an
369    --  illegal circular instantiation.
370
371    function Denotes_Formal_Package (Pack : Entity_Id) return Boolean;
372    --  Returns True if E is a formal package of an enclosing generic, or
373    --  the actual for such a formal in an enclosing instantiation. Used in
374    --  Restore_Private_Views, to keep the formals of such a package visible
375    --  on exit from an inner instantiation.
376
377    function Find_Actual_Type
378      (Typ       : Entity_Id;
379       Gen_Scope : Entity_Id)
380       return      Entity_Id;
381    --  When validating the actual types of a child instance, check whether
382    --  the formal is a formal type of the parent unit, and retrieve the current
383    --  actual for it. Typ is the entity in the analyzed formal type declaration
384    --  (component or index type of an array type) and Gen_Scope is the scope of
385    --  the analyzed formal array type.
386
387    function Get_Package_Instantiation_Node (A : Entity_Id) return Node_Id;
388    --  Given the entity of a unit that is an instantiation, retrieve the
389    --  original instance node. This is used when loading the instantiations
390    --  of the ancestors of a child generic that is being instantiated.
391
392    function In_Same_Declarative_Part
393      (F_Node : Node_Id;
394       Inst   : Node_Id)
395       return   Boolean;
396    --  True if the instantiation Inst and the given freeze_node F_Node appear
397    --  within the same declarative part, ignoring subunits, but with no inter-
398    --  vening suprograms or concurrent units. If true, the freeze node
399    --  of the instance can be placed after the freeze node of the parent,
400    --  which it itself an instance.
401
402    procedure Set_Instance_Env
403      (Gen_Unit : Entity_Id;
404       Act_Unit : Entity_Id);
405    --  Save current instance on saved environment, to be used to determine
406    --  the global status of entities in nested instances. Part of Save_Env.
407    --  called after verifying that the generic unit is legal for the instance.
408
409    procedure Set_Instance_Of (A : Entity_Id; B : Entity_Id);
410    --  Associate analyzed generic parameter with corresponding
411    --  instance. Used for semantic checks at instantiation time.
412
413    function Has_Been_Exchanged (E : Entity_Id) return Boolean;
414    --  Traverse the Exchanged_Views list to see if a type was private
415    --  and has already been flipped during this phase of instantiation.
416
417    procedure Hide_Current_Scope;
418    --  When compiling a generic child unit, the parent context must be
419    --  present, but the instance and all entities that may be generated
420    --  must be inserted in the current scope. We leave the current scope
421    --  on the stack, but make its entities invisible to avoid visibility
422    --  problems. This is reversed at the end of instantiations. This is
423    --  not done for the instantiation of the bodies, which only require the
424    --  instances of the generic parents to be in scope.
425
426    procedure Install_Body
427      (Act_Body : Node_Id;
428       N        : Node_Id;
429       Gen_Body : Node_Id;
430       Gen_Decl : Node_Id);
431    --  If the instantiation happens textually before the body of the generic,
432    --  the instantiation of the body must be analyzed after the generic body,
433    --  and not at the point of instantiation. Such early instantiations can
434    --  happen if the generic and the instance appear in  a package declaration
435    --  because the generic body can only appear in the corresponding package
436    --  body. Early instantiations can also appear if generic, instance and
437    --  body are all in the declarative part of a subprogram or entry. Entities
438    --  of packages that are early instantiations are delayed, and their freeze
439    --  node appears after the generic body.
440
441    procedure Insert_After_Last_Decl (N : Node_Id; F_Node : Node_Id);
442    --  Insert freeze node at the end of the declarative part that includes the
443    --  instance node N. If N is in the visible part of an enclosing package
444    --  declaration, the freeze node has to be inserted at the end of the
445    --  private declarations, if any.
446
447    procedure Freeze_Subprogram_Body
448      (Inst_Node : Node_Id;
449       Gen_Body  : Node_Id;
450       Pack_Id   : Entity_Id);
451    --  The generic body may appear textually after the instance, including
452    --  in the proper body of a stub, or within a different package instance.
453    --  Given that the instance can only be elaborated after the generic, we
454    --  place freeze_nodes for the instance and/or for packages that may enclose
455    --  the instance and the generic, so that the back-end can establish the
456    --  proper order of elaboration.
457
458    procedure Init_Env;
459    --  Establish environment for subsequent instantiation. Separated from
460    --  Save_Env because data-structures for visibility handling must be
461    --  initialized before call to Check_Generic_Child_Unit.
462
463    procedure Install_Parent (P : Entity_Id; In_Body : Boolean := False);
464    --  When compiling an instance of a child unit the parent (which is
465    --  itself an instance) is an enclosing scope that must be made
466    --  immediately visible. This procedure is also used to install the non-
467    --  generic parent of a generic child unit when compiling its body, so that
468    --  full views of types in the parent are made visible.
469
470    procedure Remove_Parent (In_Body : Boolean := False);
471    --  Reverse effect after instantiation of child is complete.
472
473    procedure Inline_Instance_Body
474      (N        : Node_Id;
475       Gen_Unit : Entity_Id;
476       Act_Decl : Node_Id);
477    --  If front-end inlining is requested, instantiate the package body,
478    --  and preserve the visibility of its compilation unit, to insure
479    --  that successive instantiations succeed.
480
481    --  The functions Instantiate_XXX perform various legality checks and build
482    --  the declarations for instantiated generic parameters.
483    --  Need to describe what the parameters are ???
484
485    function Instantiate_Object
486      (Formal          : Node_Id;
487       Actual          : Node_Id;
488       Analyzed_Formal : Node_Id)
489       return            List_Id;
490
491    function Instantiate_Type
492      (Formal          : Node_Id;
493       Actual          : Node_Id;
494       Analyzed_Formal : Node_Id;
495       Actual_Decls    : List_Id)
496       return            Node_Id;
497
498    function Instantiate_Formal_Subprogram
499      (Formal          : Node_Id;
500       Actual          : Node_Id;
501       Analyzed_Formal : Node_Id)
502       return            Node_Id;
503
504    function Instantiate_Formal_Package
505      (Formal          : Node_Id;
506       Actual          : Node_Id;
507       Analyzed_Formal : Node_Id)
508       return            List_Id;
509    --  If the formal package is declared with a box, special visibility rules
510    --  apply to its formals: they are in the visible part of the package. This
511    --  is true in the declarative region of the formal package, that is to say
512    --  in the enclosing generic or instantiation. For an instantiation, the
513    --  parameters of the formal package are made visible in an explicit step.
514    --  Furthermore, if the actual is a visible use_clause, these formals must
515    --  be made potentially use_visible as well. On exit from the enclosing
516    --  instantiation, the reverse must be done.
517
518    --  For a formal package declared without a box, there are conformance rules
519    --  that apply to the actuals in the generic declaration and the actuals of
520    --  the actual package in the enclosing instantiation. The simplest way to
521    --  apply these rules is to repeat the instantiation of the formal package
522    --  in the context of the enclosing instance, and compare the generic
523    --  associations of this instantiation with those of the actual package.
524
525    function Is_In_Main_Unit (N : Node_Id) return Boolean;
526    --  Test if given node is in the main unit
527
528    procedure Load_Parent_Of_Generic (N : Node_Id; Spec : Node_Id);
529    --  If the generic appears in a separate non-generic library unit,
530    --  load the corresponding body to retrieve the body of the generic.
531    --  N is the node for the generic instantiation, Spec is the generic
532    --  package declaration.
533
534    procedure Inherit_Context (Gen_Decl : Node_Id; Inst : Node_Id);
535    --  Add the context clause of the unit containing a generic unit to
536    --  an instantiation that is a compilation unit.
537
538    function Get_Associated_Node (N : Node_Id) return Node_Id;
539    --  In order to propagate semantic information back from the analyzed
540    --  copy to the original generic, we maintain links between selected nodes
541    --  in the generic and their corresponding copies. At the end of generic
542    --  analysis, the routine Save_Global_References traverses the generic
543    --  tree, examines the semantic information, and preserves the links to
544    --  those nodes that contain global information. At instantiation, the
545    --  information from the associated node is placed on the new copy, so
546    --  that name resolution is not repeated.
547    --
548    --  Three kinds of source nodes have associated nodes:
549    --
550    --    a) those that can reference (denote) entities, that is identifiers,
551    --       character literals, expanded_names, operator symbols, operators,
552    --       and attribute reference nodes. These nodes have an Entity field
553    --       and are the set of nodes that are in N_Has_Entity.
554    --
555    --    b) aggregates (N_Aggregate and N_Extension_Aggregate)
556    --
557    --    c) selected components (N_Selected_Component)
558    --
559    --  For the first class, the associated node preserves the entity if it is
560    --  global. If the generic contains nested instantiations, the associated
561    --  node itself has been recopied, and a chain of them must be followed.
562    --
563    --  For aggregates, the associated node allows retrieval of the type, which
564    --  may otherwise not appear in the generic. The view of this type may be
565    --  different between generic and instantiation, and the full view can be
566    --  installed before the instantiation is analyzed. For aggregates of
567    --  type extensions, the same view exchange may have to be performed for
568    --  some of the ancestor types, if their view is private at the point of
569    --  instantiation.
570    --
571    --  Nodes that are selected components in the parse tree may be rewritten
572    --  as expanded names after resolution, and must be treated as potential
573    --  entity holders. which is why they also have an Associated_Node.
574    --
575    --  Nodes that do not come from source, such as freeze nodes, do not appear
576    --  in the generic tree, and need not have an associated node.
577    --
578    --  The associated node is stored in the Associated_Node field. Note that
579    --  this field overlaps Entity, which is fine, because the whole point is
580    --  that we don't need or want the normal Entity field in this situation.
581
582    procedure Move_Freeze_Nodes
583      (Out_Of : Entity_Id;
584       After  : Node_Id;
585       L      : List_Id);
586    --  Freeze nodes can be generated in the analysis of a generic unit, but
587    --  will not be seen by the back-end. It is necessary to move those nodes
588    --  to the enclosing scope if they freeze an outer entity. We place them
589    --  at the end of the enclosing generic package, which is semantically
590    --  neutral.
591
592    procedure Pre_Analyze_Actuals (N : Node_Id);
593    --  Analyze actuals to perform name resolution. Full resolution is done
594    --  later, when the expected types are known, but names have to be captured
595    --  before installing parents of generics, that are not visible for the
596    --  actuals themselves.
597
598    procedure Valid_Default_Attribute (Nam : Entity_Id; Def : Node_Id);
599    --  Verify that an attribute that appears as the default for a formal
600    --  subprogram is a function or procedure with the correct profile.
601
602    -------------------------------------------
603    -- Data Structures for Generic Renamings --
604    -------------------------------------------
605
606    --  The map Generic_Renamings associates generic entities with their
607    --  corresponding actuals. Currently used to validate type instances.
608    --  It will eventually be used for all generic parameters to eliminate
609    --  the need for overload resolution in the instance.
610
611    type Assoc_Ptr is new Int;
612
613    Assoc_Null : constant Assoc_Ptr := -1;
614
615    type Assoc is record
616       Gen_Id         : Entity_Id;
617       Act_Id         : Entity_Id;
618       Next_In_HTable : Assoc_Ptr;
619    end record;
620
621    package Generic_Renamings is new Table.Table
622      (Table_Component_Type => Assoc,
623       Table_Index_Type     => Assoc_Ptr,
624       Table_Low_Bound      => 0,
625       Table_Initial        => 10,
626       Table_Increment      => 100,
627       Table_Name           => "Generic_Renamings");
628
629    --  Variable to hold enclosing instantiation. When the environment is
630    --  saved for a subprogram inlining, the corresponding Act_Id is empty.
631
632    Current_Instantiated_Parent : Assoc := (Empty, Empty, Assoc_Null);
633
634    --  Hash table for associations
635
636    HTable_Size : constant := 37;
637    type HTable_Range is range 0 .. HTable_Size - 1;
638
639    procedure Set_Next_Assoc (E : Assoc_Ptr; Next : Assoc_Ptr);
640    function  Next_Assoc     (E : Assoc_Ptr) return Assoc_Ptr;
641    function Get_Gen_Id      (E : Assoc_Ptr) return Entity_Id;
642    function Hash            (F : Entity_Id)   return HTable_Range;
643
644    package Generic_Renamings_HTable is new GNAT.HTable.Static_HTable (
645       Header_Num => HTable_Range,
646       Element    => Assoc,
647       Elmt_Ptr   => Assoc_Ptr,
648       Null_Ptr   => Assoc_Null,
649       Set_Next   => Set_Next_Assoc,
650       Next       => Next_Assoc,
651       Key        => Entity_Id,
652       Get_Key    => Get_Gen_Id,
653       Hash       => Hash,
654       Equal      => "=");
655
656    Exchanged_Views : Elist_Id;
657    --  This list holds the private views that have been exchanged during
658    --  instantiation to restore the visibility of the generic declaration.
659    --  (see comments above). After instantiation, the current visibility is
660    --  reestablished by means of a traversal of this list.
661
662    Hidden_Entities : Elist_Id;
663    --  This list holds the entities of the current scope that are removed
664    --  from immediate visibility when instantiating a child unit. Their
665    --  visibility is restored in Remove_Parent.
666
667    --  Because instantiations can be recursive, the following must be saved
668    --  on entry and restored on exit from an instantiation (spec or body).
669    --  This is done by the two procedures Save_Env and Restore_Env. For
670    --  package and subprogram instantiations (but not for the body instances)
671    --  the action of Save_Env is done in two steps: Init_Env is called before
672    --  Check_Generic_Child_Unit, because setting the parent instances requires
673    --  that the visibility data structures be properly initialized. Once the
674    --  generic is unit is validated, Set_Instance_Env completes Save_Env.
675
676    type Instance_Env is record
677       Ada_83              : Boolean;
678       Instantiated_Parent : Assoc;
679       Exchanged_Views     : Elist_Id;
680       Hidden_Entities     : Elist_Id;
681       Current_Sem_Unit    : Unit_Number_Type;
682    end record;
683
684    package Instance_Envs is new Table.Table (
685      Table_Component_Type => Instance_Env,
686      Table_Index_Type     => Int,
687      Table_Low_Bound      => 0,
688      Table_Initial        => 32,
689      Table_Increment      => 100,
690      Table_Name           => "Instance_Envs");
691
692    procedure Restore_Private_Views
693      (Pack_Id    : Entity_Id;
694       Is_Package : Boolean := True);
695    --  Restore the private views of external types, and unmark the generic
696    --  renamings of actuals, so that they become comptible subtypes again.
697    --  For subprograms, Pack_Id is the package constructed to hold the
698    --  renamings.
699
700    procedure Switch_View (T : Entity_Id);
701    --  Switch the partial and full views of a type and its private
702    --  dependents (i.e. its subtypes and derived types).
703
704    ------------------------------------
705    -- Structures for Error Reporting --
706    ------------------------------------
707
708    Instantiation_Node : Node_Id;
709    --  Used by subprograms that validate instantiation of formal parameters
710    --  where there might be no actual on which to place the error message.
711    --  Also used to locate the instantiation node for generic subunits.
712
713    Instantiation_Error : exception;
714    --  When there is a semantic error in the generic parameter matching,
715    --  there is no point in continuing the instantiation, because the
716    --  number of cascaded errors is unpredictable. This exception aborts
717    --  the instantiation process altogether.
718
719    S_Adjustment : Sloc_Adjustment;
720    --  Offset created for each node in an instantiation, in order to keep
721    --  track of the source position of the instantiation in each of its nodes.
722    --  A subsequent semantic error or warning on a construct of the instance
723    --  points to both places: the original generic node, and the point of
724    --  instantiation. See Sinput and Sinput.L for additional details.
725
726    ------------------------------------------------------------
727    -- Data structure for keeping track when inside a Generic --
728    ------------------------------------------------------------
729
730    --  The following table is used to save values of the Inside_A_Generic
731    --  flag (see spec of Sem) when they are saved by Start_Generic.
732
733    package Generic_Flags is new Table.Table (
734      Table_Component_Type => Boolean,
735      Table_Index_Type     => Int,
736      Table_Low_Bound      => 0,
737      Table_Initial        => 32,
738      Table_Increment      => 200,
739      Table_Name           => "Generic_Flags");
740
741    ---------------------------
742    -- Abandon_Instantiation --
743    ---------------------------
744
745    procedure Abandon_Instantiation (N : Node_Id) is
746    begin
747       Error_Msg_N ("instantiation abandoned!", N);
748       raise Instantiation_Error;
749    end Abandon_Instantiation;
750
751    --------------------------
752    -- Analyze_Associations --
753    --------------------------
754
755    function Analyze_Associations
756      (I_Node  : Node_Id;
757       Formals : List_Id;
758       F_Copy  : List_Id)
759       return    List_Id
760    is
761       Actual_Types    : constant Elist_Id  := New_Elmt_List;
762       Assoc           : constant List_Id   := New_List;
763       Defaults        : constant Elist_Id  := New_Elmt_List;
764       Gen_Unit        : constant Entity_Id := Defining_Entity
765                                                 (Parent (F_Copy));
766       Actuals         : List_Id;
767       Actual          : Node_Id;
768       Formal          : Node_Id;
769       Next_Formal     : Node_Id;
770       Temp_Formal     : Node_Id;
771       Analyzed_Formal : Node_Id;
772       Match           : Node_Id;
773       Named           : Node_Id;
774       First_Named     : Node_Id := Empty;
775       Found_Assoc     : Node_Id;
776       Is_Named_Assoc  : Boolean;
777       Num_Matched     : Int := 0;
778       Num_Actuals     : Int := 0;
779
780       function Matching_Actual
781         (F    : Entity_Id;
782          A_F  : Entity_Id)
783          return Node_Id;
784       --  Find actual that corresponds to a given a formal parameter. If the
785       --  actuals are positional, return the next one, if any. If the actuals
786       --  are named, scan the parameter associations to find the right one.
787       --  A_F is the corresponding entity in the analyzed generic,which is
788       --  placed on the selector name for ASIS use.
789
790       procedure Set_Analyzed_Formal;
791       --  Find the node in the generic copy that corresponds to a given formal.
792       --  The semantic information on this node is used to perform legality
793       --  checks on the actuals. Because semantic analysis can introduce some
794       --  anonymous entities or modify the declaration node itself, the
795       --  correspondence between the two lists is not one-one. In addition to
796       --  anonymous types, the presence a formal equality will introduce an
797       --  implicit declaration for the corresponding inequality.
798
799       ---------------------
800       -- Matching_Actual --
801       ---------------------
802
803       function Matching_Actual
804         (F    : Entity_Id;
805          A_F  : Entity_Id)
806          return Node_Id
807       is
808          Found : Node_Id;
809          Prev  : Node_Id;
810
811       begin
812          Is_Named_Assoc := False;
813
814          --  End of list of purely positional parameters
815
816          if No (Actual) then
817             Found := Empty;
818
819          --  Case of positional parameter corresponding to current formal
820
821          elsif No (Selector_Name (Actual)) then
822             Found := Explicit_Generic_Actual_Parameter (Actual);
823             Found_Assoc := Actual;
824             Num_Matched := Num_Matched + 1;
825             Next (Actual);
826
827          --  Otherwise scan list of named actuals to find the one with the
828          --  desired name. All remaining actuals have explicit names.
829
830          else
831             Is_Named_Assoc := True;
832             Found := Empty;
833             Prev  := Empty;
834
835             while Present (Actual) loop
836                if Chars (Selector_Name (Actual)) = Chars (F) then
837                   Found := Explicit_Generic_Actual_Parameter (Actual);
838                   Set_Entity (Selector_Name (Actual), A_F);
839                   Set_Etype  (Selector_Name (Actual), Etype (A_F));
840                   Generate_Reference (A_F, Selector_Name (Actual));
841                   Found_Assoc := Actual;
842                   Num_Matched := Num_Matched + 1;
843                   exit;
844                end if;
845
846                Prev := Actual;
847                Next (Actual);
848             end loop;
849
850             --  Reset for subsequent searches. In most cases the named
851             --  associations are in order. If they are not, we reorder them
852             --  to avoid scanning twice the same actual. This is not just a
853             --  question of efficiency: there may be multiple defaults with
854             --  boxes that have the same name. In a nested instantiation we
855             --  insert actuals for those defaults, and cannot rely on their
856             --  names to disambiguate them.
857
858             if Actual = First_Named  then
859                Next (First_Named);
860
861             elsif Present (Actual) then
862                Insert_Before (First_Named, Remove_Next (Prev));
863             end if;
864
865             Actual := First_Named;
866          end if;
867
868          return Found;
869       end Matching_Actual;
870
871       -------------------------
872       -- Set_Analyzed_Formal --
873       -------------------------
874
875       procedure Set_Analyzed_Formal is
876          Kind : Node_Kind;
877       begin
878          while Present (Analyzed_Formal) loop
879             Kind := Nkind (Analyzed_Formal);
880
881             case Nkind (Formal) is
882
883                when N_Formal_Subprogram_Declaration =>
884                   exit when Kind = N_Formal_Subprogram_Declaration
885                     and then
886                       Chars
887                         (Defining_Unit_Name (Specification (Formal))) =
888                       Chars
889                         (Defining_Unit_Name (Specification (Analyzed_Formal)));
890
891                when N_Formal_Package_Declaration =>
892                   exit when
893                     Kind = N_Formal_Package_Declaration
894                       or else
895                     Kind = N_Generic_Package_Declaration;
896
897                when N_Use_Package_Clause | N_Use_Type_Clause => exit;
898
899                when others =>
900
901                   --  Skip freeze nodes, and nodes inserted to replace
902                   --  unrecognized pragmas.
903
904                   exit when
905                     Kind /= N_Formal_Subprogram_Declaration
906                       and then Kind /= N_Subprogram_Declaration
907                       and then Kind /= N_Freeze_Entity
908                       and then Kind /= N_Null_Statement
909                       and then Kind /= N_Itype_Reference
910                       and then Chars (Defining_Identifier (Formal)) =
911                                Chars (Defining_Identifier (Analyzed_Formal));
912             end case;
913
914             Next (Analyzed_Formal);
915          end loop;
916
917       end Set_Analyzed_Formal;
918
919    --  Start of processing for Analyze_Associations
920
921    begin
922       --  If named associations are present, save the first named association
923       --  (it may of course be Empty) to facilitate subsequent name search.
924
925       Actuals := Generic_Associations (I_Node);
926
927       if Present (Actuals) then
928          First_Named := First (Actuals);
929
930          while Present (First_Named)
931            and then No (Selector_Name (First_Named))
932          loop
933             Num_Actuals := Num_Actuals + 1;
934             Next (First_Named);
935          end loop;
936       end if;
937
938       Named := First_Named;
939       while Present (Named) loop
940          if No (Selector_Name (Named)) then
941             Error_Msg_N ("invalid positional actual after named one", Named);
942             Abandon_Instantiation (Named);
943          end if;
944
945          --  A named association may lack an actual parameter, if it was
946          --  introduced for a default subprogram that turns out to be local
947          --  to the outer instantiation.
948
949          if Present (Explicit_Generic_Actual_Parameter (Named)) then
950             Num_Actuals := Num_Actuals + 1;
951          end if;
952
953          Next (Named);
954       end loop;
955
956       if Present (Formals) then
957          Formal := First_Non_Pragma (Formals);
958          Analyzed_Formal := First_Non_Pragma (F_Copy);
959
960          if Present (Actuals) then
961             Actual := First (Actuals);
962
963          --  All formals should have default values
964
965          else
966             Actual := Empty;
967          end if;
968
969          while Present (Formal) loop
970             Set_Analyzed_Formal;
971             Next_Formal := Next_Non_Pragma (Formal);
972
973             case Nkind (Formal) is
974                when N_Formal_Object_Declaration =>
975                   Match :=
976                     Matching_Actual (
977                       Defining_Identifier (Formal),
978                       Defining_Identifier (Analyzed_Formal));
979
980                   Append_List
981                     (Instantiate_Object (Formal, Match, Analyzed_Formal),
982                      Assoc);
983
984                when N_Formal_Type_Declaration =>
985                   Match :=
986                     Matching_Actual (
987                       Defining_Identifier (Formal),
988                       Defining_Identifier (Analyzed_Formal));
989
990                   if No (Match) then
991                      Error_Msg_Sloc := Sloc (Gen_Unit);
992                      Error_Msg_NE
993                        ("missing actual&",
994                          Instantiation_Node, Defining_Identifier (Formal));
995                      Error_Msg_NE ("\in instantiation of & declared#",
996                          Instantiation_Node, Gen_Unit);
997                      Abandon_Instantiation (Instantiation_Node);
998
999                   else
1000                      Analyze (Match);
1001                      Append_To (Assoc,
1002                        Instantiate_Type
1003                          (Formal, Match, Analyzed_Formal, Assoc));
1004
1005                      --  an instantiation is a freeze point for the actuals,
1006                      --  unless this is a rewritten formal package.
1007
1008                      if Nkind (I_Node) /= N_Formal_Package_Declaration then
1009                         Append_Elmt (Entity (Match), Actual_Types);
1010                      end if;
1011                   end if;
1012
1013                   --  A remote access-to-class-wide type must not be an
1014                   --  actual parameter for a generic formal of an access
1015                   --  type (E.2.2 (17)).
1016
1017                   if Nkind (Analyzed_Formal) = N_Formal_Type_Declaration
1018                     and then
1019                       Nkind (Formal_Type_Definition (Analyzed_Formal)) =
1020                                             N_Access_To_Object_Definition
1021                   then
1022                      Validate_Remote_Access_To_Class_Wide_Type (Match);
1023                   end if;
1024
1025                when N_Formal_Subprogram_Declaration =>
1026                   Match :=
1027                     Matching_Actual (
1028                       Defining_Unit_Name (Specification (Formal)),
1029                       Defining_Unit_Name (Specification (Analyzed_Formal)));
1030
1031                   --  If the formal subprogram has the same name as
1032                   --  another formal subprogram of the generic, then
1033                   --  a named association is illegal (12.3(9)). Exclude
1034                   --  named associations that are generated for a nested
1035                   --  instance.
1036
1037                   if Present (Match)
1038                     and then Is_Named_Assoc
1039                     and then Comes_From_Source (Found_Assoc)
1040                   then
1041                      Temp_Formal := First (Formals);
1042                      while Present (Temp_Formal) loop
1043                         if Nkind (Temp_Formal) =
1044                              N_Formal_Subprogram_Declaration
1045                           and then Temp_Formal /= Formal
1046                           and then
1047                             Chars (Selector_Name (Found_Assoc)) =
1048                               Chars (Defining_Unit_Name
1049                                        (Specification (Temp_Formal)))
1050                         then
1051                            Error_Msg_N
1052                              ("name not allowed for overloaded formal",
1053                               Found_Assoc);
1054                            Abandon_Instantiation (Instantiation_Node);
1055                         end if;
1056
1057                         Next (Temp_Formal);
1058                      end loop;
1059                   end if;
1060
1061                   Append_To (Assoc,
1062                     Instantiate_Formal_Subprogram
1063                       (Formal, Match, Analyzed_Formal));
1064
1065                   if No (Match)
1066                     and then Box_Present (Formal)
1067                   then
1068                      Append_Elmt
1069                        (Defining_Unit_Name (Specification (Last (Assoc))),
1070                          Defaults);
1071                   end if;
1072
1073                when N_Formal_Package_Declaration =>
1074                   Match :=
1075                     Matching_Actual (
1076                       Defining_Identifier (Formal),
1077                       Defining_Identifier (Original_Node (Analyzed_Formal)));
1078
1079                   if No (Match) then
1080                      Error_Msg_Sloc := Sloc (Gen_Unit);
1081                      Error_Msg_NE
1082                        ("missing actual&",
1083                          Instantiation_Node, Defining_Identifier (Formal));
1084                      Error_Msg_NE ("\in instantiation of & declared#",
1085                          Instantiation_Node, Gen_Unit);
1086
1087                      Abandon_Instantiation (Instantiation_Node);
1088
1089                   else
1090                      Analyze (Match);
1091                      Append_List
1092                        (Instantiate_Formal_Package
1093                          (Formal, Match, Analyzed_Formal),
1094                         Assoc);
1095                   end if;
1096
1097                --  For use type and use package appearing in the context
1098                --  clause, we have already copied them, so we can just
1099                --  move them where they belong (we mustn't recopy them
1100                --  since this would mess up the Sloc values).
1101
1102                when N_Use_Package_Clause |
1103                     N_Use_Type_Clause    =>
1104                   Remove (Formal);
1105                   Append (Formal, Assoc);
1106
1107                when others =>
1108                   raise Program_Error;
1109
1110             end case;
1111
1112             Formal := Next_Formal;
1113             Next_Non_Pragma (Analyzed_Formal);
1114          end loop;
1115
1116          if Num_Actuals > Num_Matched then
1117             Error_Msg_Sloc := Sloc (Gen_Unit);
1118
1119             if Present (Selector_Name (Actual)) then
1120                Error_Msg_NE
1121                  ("unmatched actual&",
1122                     Actual, Selector_Name (Actual));
1123                Error_Msg_NE ("\in instantiation of& declared#",
1124                     Actual, Gen_Unit);
1125             else
1126                Error_Msg_NE
1127                  ("unmatched actual in instantiation of& declared#",
1128                    Actual, Gen_Unit);
1129             end if;
1130          end if;
1131
1132       elsif Present (Actuals) then
1133          Error_Msg_N
1134            ("too many actuals in generic instantiation", Instantiation_Node);
1135       end if;
1136
1137       declare
1138          Elmt : Elmt_Id := First_Elmt (Actual_Types);
1139
1140       begin
1141          while Present (Elmt) loop
1142             Freeze_Before (I_Node, Node (Elmt));
1143             Next_Elmt (Elmt);
1144          end loop;
1145       end;
1146
1147       --  If there are default subprograms, normalize the tree by adding
1148       --  explicit associations for them. This is required if the instance
1149       --  appears within a generic.
1150
1151       declare
1152          Elmt  : Elmt_Id;
1153          Subp  : Entity_Id;
1154          New_D : Node_Id;
1155
1156       begin
1157          Elmt := First_Elmt (Defaults);
1158          while Present (Elmt) loop
1159             if No (Actuals) then
1160                Actuals := New_List;
1161                Set_Generic_Associations (I_Node, Actuals);
1162             end if;
1163
1164             Subp := Node (Elmt);
1165             New_D :=
1166               Make_Generic_Association (Sloc (Subp),
1167                 Selector_Name => New_Occurrence_Of (Subp, Sloc (Subp)),
1168                   Explicit_Generic_Actual_Parameter =>
1169                     New_Occurrence_Of (Subp, Sloc (Subp)));
1170             Mark_Rewrite_Insertion (New_D);
1171             Append_To (Actuals, New_D);
1172             Next_Elmt (Elmt);
1173          end loop;
1174       end;
1175
1176       return Assoc;
1177    end Analyze_Associations;
1178
1179    -------------------------------
1180    -- Analyze_Formal_Array_Type --
1181    -------------------------------
1182
1183    procedure Analyze_Formal_Array_Type
1184      (T   : in out Entity_Id;
1185       Def : Node_Id)
1186    is
1187       DSS : Node_Id;
1188
1189    begin
1190       --  Treated like a non-generic array declaration, with
1191       --  additional semantic checks.
1192
1193       Enter_Name (T);
1194
1195       if Nkind (Def) = N_Constrained_Array_Definition then
1196          DSS := First (Discrete_Subtype_Definitions (Def));
1197          while Present (DSS) loop
1198             if Nkind (DSS) = N_Subtype_Indication
1199               or else Nkind (DSS) = N_Range
1200               or else Nkind (DSS) = N_Attribute_Reference
1201             then
1202                Error_Msg_N ("only a subtype mark is allowed in a formal", DSS);
1203             end if;
1204
1205             Next (DSS);
1206          end loop;
1207       end if;
1208
1209       Array_Type_Declaration (T, Def);
1210       Set_Is_Generic_Type (Base_Type (T));
1211
1212       if Ekind (Component_Type (T)) = E_Incomplete_Type
1213         and then No (Full_View (Component_Type (T)))
1214       then
1215          Error_Msg_N ("premature usage of incomplete type", Def);
1216
1217       elsif Is_Internal (Component_Type (T))
1218         and then Nkind (Original_Node
1219                         (Subtype_Indication (Component_Definition (Def))))
1220           /= N_Attribute_Reference
1221       then
1222          Error_Msg_N
1223            ("only a subtype mark is allowed in a formal",
1224               Subtype_Indication (Component_Definition (Def)));
1225       end if;
1226
1227    end Analyze_Formal_Array_Type;
1228
1229    ---------------------------------------------
1230    -- Analyze_Formal_Decimal_Fixed_Point_Type --
1231    ---------------------------------------------
1232
1233    --  As for other generic types, we create a valid type representation
1234    --  with legal but arbitrary attributes, whose values are never considered
1235    --  static. For all scalar types we introduce an anonymous base type, with
1236    --  the same attributes. We choose the corresponding integer type to be
1237    --  Standard_Integer.
1238
1239    procedure Analyze_Formal_Decimal_Fixed_Point_Type
1240      (T   : Entity_Id;
1241       Def : Node_Id)
1242    is
1243       Loc       : constant Source_Ptr := Sloc (Def);
1244       Base      : constant Entity_Id :=
1245                     New_Internal_Entity
1246                       (E_Decimal_Fixed_Point_Type,
1247                        Current_Scope, Sloc (Def), 'G');
1248       Int_Base  : constant Entity_Id := Standard_Integer;
1249       Delta_Val : constant Ureal := Ureal_1;
1250       Digs_Val  : constant Uint  := Uint_6;
1251
1252    begin
1253       Enter_Name (T);
1254
1255       Set_Etype          (Base, Base);
1256       Set_Size_Info      (Base, Int_Base);
1257       Set_RM_Size        (Base, RM_Size (Int_Base));
1258       Set_First_Rep_Item (Base, First_Rep_Item (Int_Base));
1259       Set_Digits_Value   (Base, Digs_Val);
1260       Set_Delta_Value    (Base, Delta_Val);
1261       Set_Small_Value    (Base, Delta_Val);
1262       Set_Scalar_Range   (Base,
1263         Make_Range (Loc,
1264           Low_Bound  => Make_Real_Literal (Loc, Ureal_1),
1265           High_Bound => Make_Real_Literal (Loc, Ureal_1)));
1266
1267       Set_Is_Generic_Type (Base);
1268       Set_Parent          (Base, Parent (Def));
1269
1270       Set_Ekind          (T, E_Decimal_Fixed_Point_Subtype);
1271       Set_Etype          (T, Base);
1272       Set_Size_Info      (T, Int_Base);
1273       Set_RM_Size        (T, RM_Size (Int_Base));
1274       Set_First_Rep_Item (T, First_Rep_Item (Int_Base));
1275       Set_Digits_Value   (T, Digs_Val);
1276       Set_Delta_Value    (T, Delta_Val);
1277       Set_Small_Value    (T, Delta_Val);
1278       Set_Scalar_Range   (T, Scalar_Range (Base));
1279
1280       Check_Restriction (No_Fixed_Point, Def);
1281    end Analyze_Formal_Decimal_Fixed_Point_Type;
1282
1283    ---------------------------------
1284    -- Analyze_Formal_Derived_Type --
1285    ---------------------------------
1286
1287    procedure Analyze_Formal_Derived_Type
1288      (N   : Node_Id;
1289       T   : Entity_Id;
1290       Def : Node_Id)
1291    is
1292       Loc      : constant Source_Ptr := Sloc (Def);
1293       Unk_Disc : constant Boolean    := Unknown_Discriminants_Present (N);
1294       New_N    : Node_Id;
1295
1296    begin
1297       Set_Is_Generic_Type (T);
1298
1299       if Private_Present (Def) then
1300          New_N :=
1301            Make_Private_Extension_Declaration (Loc,
1302              Defining_Identifier           => T,
1303              Discriminant_Specifications   => Discriminant_Specifications (N),
1304              Unknown_Discriminants_Present => Unk_Disc,
1305              Subtype_Indication            => Subtype_Mark (Def));
1306
1307          Set_Abstract_Present (New_N, Abstract_Present (Def));
1308
1309       else
1310          New_N :=
1311            Make_Full_Type_Declaration (Loc,
1312              Defining_Identifier => T,
1313              Discriminant_Specifications =>
1314                Discriminant_Specifications (Parent (T)),
1315               Type_Definition =>
1316                 Make_Derived_Type_Definition (Loc,
1317                   Subtype_Indication => Subtype_Mark (Def)));
1318
1319          Set_Abstract_Present
1320            (Type_Definition (New_N), Abstract_Present (Def));
1321       end if;
1322
1323       Rewrite (N, New_N);
1324       Analyze (N);
1325
1326       if Unk_Disc then
1327          if not Is_Composite_Type (T) then
1328             Error_Msg_N
1329               ("unknown discriminants not allowed for elementary types", N);
1330          else
1331             Set_Has_Unknown_Discriminants (T);
1332             Set_Is_Constrained (T, False);
1333          end if;
1334       end if;
1335
1336       --  If the parent type has a known size, so does the formal, which
1337       --  makes legal representation clauses that involve the formal.
1338
1339       Set_Size_Known_At_Compile_Time
1340         (T, Size_Known_At_Compile_Time (Entity (Subtype_Mark (Def))));
1341
1342    end Analyze_Formal_Derived_Type;
1343
1344    ----------------------------------
1345    -- Analyze_Formal_Discrete_Type --
1346    ----------------------------------
1347
1348    --  The operations defined for a discrete types are those of an
1349    --  enumeration type. The size is set to an arbitrary value, for use
1350    --  in analyzing the generic unit.
1351
1352    procedure Analyze_Formal_Discrete_Type (T : Entity_Id; Def : Node_Id) is
1353       Loc : constant Source_Ptr := Sloc (Def);
1354       Lo  : Node_Id;
1355       Hi  : Node_Id;
1356
1357    begin
1358       Enter_Name     (T);
1359       Set_Ekind      (T, E_Enumeration_Type);
1360       Set_Etype      (T, T);
1361       Init_Size      (T, 8);
1362       Init_Alignment (T);
1363
1364       --  For semantic analysis, the bounds of the type must be set to some
1365       --  non-static value. The simplest is to create attribute nodes for
1366       --  those bounds, that refer to the type itself. These bounds are never
1367       --  analyzed but serve as place-holders.
1368
1369       Lo :=
1370         Make_Attribute_Reference (Loc,
1371           Attribute_Name => Name_First,
1372           Prefix => New_Reference_To (T, Loc));
1373       Set_Etype (Lo, T);
1374
1375       Hi :=
1376         Make_Attribute_Reference (Loc,
1377           Attribute_Name => Name_Last,
1378           Prefix => New_Reference_To (T, Loc));
1379       Set_Etype (Hi, T);
1380
1381       Set_Scalar_Range (T,
1382         Make_Range (Loc,
1383           Low_Bound => Lo,
1384           High_Bound => Hi));
1385
1386    end Analyze_Formal_Discrete_Type;
1387
1388    ----------------------------------
1389    -- Analyze_Formal_Floating_Type --
1390    ---------------------------------
1391
1392    procedure Analyze_Formal_Floating_Type (T : Entity_Id; Def : Node_Id) is
1393       Base : constant Entity_Id :=
1394                New_Internal_Entity
1395                  (E_Floating_Point_Type, Current_Scope, Sloc (Def), 'G');
1396
1397    begin
1398       --  The various semantic attributes are taken from the predefined type
1399       --  Float, just so that all of them are initialized. Their values are
1400       --  never used because no constant folding or expansion takes place in
1401       --  the generic itself.
1402
1403       Enter_Name (T);
1404       Set_Ekind        (T, E_Floating_Point_Subtype);
1405       Set_Etype        (T, Base);
1406       Set_Size_Info    (T,              (Standard_Float));
1407       Set_RM_Size      (T, RM_Size      (Standard_Float));
1408       Set_Digits_Value (T, Digits_Value (Standard_Float));
1409       Set_Scalar_Range (T, Scalar_Range (Standard_Float));
1410
1411       Set_Is_Generic_Type (Base);
1412       Set_Etype           (Base, Base);
1413       Set_Size_Info       (Base,              (Standard_Float));
1414       Set_RM_Size         (Base, RM_Size      (Standard_Float));
1415       Set_Digits_Value    (Base, Digits_Value (Standard_Float));
1416       Set_Scalar_Range    (Base, Scalar_Range (Standard_Float));
1417       Set_Parent          (Base, Parent (Def));
1418
1419       Check_Restriction (No_Floating_Point, Def);
1420    end Analyze_Formal_Floating_Type;
1421
1422    ---------------------------------
1423    -- Analyze_Formal_Modular_Type --
1424    ---------------------------------
1425
1426    procedure Analyze_Formal_Modular_Type (T : Entity_Id; Def : Node_Id) is
1427    begin
1428       --  Apart from their entity kind, generic modular types are treated
1429       --  like signed integer types, and have the same attributes.
1430
1431       Analyze_Formal_Signed_Integer_Type (T, Def);
1432       Set_Ekind (T, E_Modular_Integer_Subtype);
1433       Set_Ekind (Etype (T), E_Modular_Integer_Type);
1434
1435    end Analyze_Formal_Modular_Type;
1436
1437    ---------------------------------------
1438    -- Analyze_Formal_Object_Declaration --
1439    ---------------------------------------
1440
1441    procedure Analyze_Formal_Object_Declaration (N : Node_Id) is
1442       E  : constant Node_Id := Expression (N);
1443       Id : constant Node_Id := Defining_Identifier (N);
1444       K  : Entity_Kind;
1445       T  : Node_Id;
1446
1447    begin
1448       Enter_Name (Id);
1449
1450       --  Determine the mode of the formal object
1451
1452       if Out_Present (N) then
1453          K := E_Generic_In_Out_Parameter;
1454
1455          if not In_Present (N) then
1456             Error_Msg_N ("formal generic objects cannot have mode OUT", N);
1457          end if;
1458
1459       else
1460          K := E_Generic_In_Parameter;
1461       end if;
1462
1463       Find_Type (Subtype_Mark (N));
1464       T  := Entity (Subtype_Mark (N));
1465
1466       if Ekind (T) = E_Incomplete_Type then
1467          Error_Msg_N ("premature usage of incomplete type", Subtype_Mark (N));
1468       end if;
1469
1470       if K = E_Generic_In_Parameter then
1471
1472          --  Ada 0Y (AI-287): Limited aggregates allowed in generic formals
1473
1474          if not Extensions_Allowed and then Is_Limited_Type (T) then
1475             Error_Msg_N
1476               ("generic formal of mode IN must not be of limited type", N);
1477             Explain_Limited_Type (T, N);
1478          end if;
1479
1480          if Is_Abstract (T) then
1481             Error_Msg_N
1482               ("generic formal of mode IN must not be of abstract type", N);
1483          end if;
1484
1485          if Present (E) then
1486             Analyze_Per_Use_Expression (E, T);
1487          end if;
1488
1489          Set_Ekind (Id, K);
1490          Set_Etype (Id, T);
1491
1492       --  Case of generic IN OUT parameter.
1493
1494       else
1495          --  If the formal has an unconstrained type, construct its
1496          --  actual subtype, as is done for subprogram formals. In this
1497          --  fashion, all its uses can refer to specific bounds.
1498
1499          Set_Ekind (Id, K);
1500          Set_Etype (Id, T);
1501
1502          if (Is_Array_Type (T)
1503               and then not Is_Constrained (T))
1504            or else
1505             (Ekind (T) = E_Record_Type
1506               and then Has_Discriminants (T))
1507          then
1508             declare
1509                Non_Freezing_Ref : constant Node_Id :=
1510                                     New_Reference_To (Id, Sloc (Id));
1511                Decl : Node_Id;
1512
1513             begin
1514                --  Make sure that the actual subtype doesn't generate
1515                --  bogus freezing.
1516
1517                Set_Must_Not_Freeze (Non_Freezing_Ref);
1518                Decl := Build_Actual_Subtype (T, Non_Freezing_Ref);
1519                Insert_Before_And_Analyze (N, Decl);
1520                Set_Actual_Subtype (Id, Defining_Identifier (Decl));
1521             end;
1522          else
1523             Set_Actual_Subtype (Id, T);
1524          end if;
1525
1526          if Present (E) then
1527             Error_Msg_N
1528               ("initialization not allowed for `IN OUT` formals", N);
1529          end if;
1530       end if;
1531
1532    end Analyze_Formal_Object_Declaration;
1533
1534    ----------------------------------------------
1535    -- Analyze_Formal_Ordinary_Fixed_Point_Type --
1536    ----------------------------------------------
1537
1538    procedure Analyze_Formal_Ordinary_Fixed_Point_Type
1539      (T   : Entity_Id;
1540       Def : Node_Id)
1541    is
1542       Loc  : constant Source_Ptr := Sloc (Def);
1543       Base : constant Entity_Id :=
1544                New_Internal_Entity
1545                  (E_Ordinary_Fixed_Point_Type, Current_Scope, Sloc (Def), 'G');
1546    begin
1547       --  The semantic attributes are set for completeness only, their
1548       --  values will never be used, because all properties of the type
1549       --  are non-static.
1550
1551       Enter_Name (T);
1552       Set_Ekind            (T, E_Ordinary_Fixed_Point_Subtype);
1553       Set_Etype            (T, Base);
1554       Set_Size_Info        (T, Standard_Integer);
1555       Set_RM_Size          (T, RM_Size (Standard_Integer));
1556       Set_Small_Value      (T, Ureal_1);
1557       Set_Delta_Value      (T, Ureal_1);
1558       Set_Scalar_Range     (T,
1559         Make_Range (Loc,
1560           Low_Bound  => Make_Real_Literal (Loc, Ureal_1),
1561           High_Bound => Make_Real_Literal (Loc, Ureal_1)));
1562
1563       Set_Is_Generic_Type (Base);
1564       Set_Etype           (Base, Base);
1565       Set_Size_Info       (Base, Standard_Integer);
1566       Set_RM_Size         (Base, RM_Size (Standard_Integer));
1567       Set_Small_Value     (Base, Ureal_1);
1568       Set_Delta_Value     (Base, Ureal_1);
1569       Set_Scalar_Range    (Base, Scalar_Range (T));
1570       Set_Parent          (Base, Parent (Def));
1571
1572       Check_Restriction (No_Fixed_Point, Def);
1573    end Analyze_Formal_Ordinary_Fixed_Point_Type;
1574
1575    ----------------------------
1576    -- Analyze_Formal_Package --
1577    ----------------------------
1578
1579    procedure Analyze_Formal_Package (N : Node_Id) is
1580       Loc              : constant Source_Ptr := Sloc (N);
1581       Pack_Id          : constant Entity_Id := Defining_Identifier (N);
1582       Formal           : Entity_Id;
1583       Gen_Id           : constant Node_Id    := Name (N);
1584       Gen_Decl         : Node_Id;
1585       Gen_Unit         : Entity_Id;
1586       New_N            : Node_Id;
1587       Parent_Installed : Boolean := False;
1588       Renaming         : Node_Id;
1589       Parent_Instance  : Entity_Id;
1590       Renaming_In_Par  : Entity_Id;
1591
1592    begin
1593       Text_IO_Kludge (Gen_Id);
1594
1595       Init_Env;
1596       Check_Generic_Child_Unit (Gen_Id, Parent_Installed);
1597       Gen_Unit := Entity (Gen_Id);
1598
1599       if Ekind (Gen_Unit) /= E_Generic_Package then
1600          Error_Msg_N ("expect generic package name", Gen_Id);
1601          Restore_Env;
1602          return;
1603
1604       elsif  Gen_Unit = Current_Scope then
1605          Error_Msg_N
1606            ("generic package cannot be used as a formal package of itself",
1607              Gen_Id);
1608          Restore_Env;
1609          return;
1610
1611       elsif In_Open_Scopes (Gen_Unit) then
1612          if Is_Compilation_Unit (Gen_Unit)
1613            and then Is_Child_Unit (Current_Scope)
1614          then
1615             --  Special-case the error when the formal is a parent, and
1616             --  continue analysis to minimize cascaded errors.
1617
1618             Error_Msg_N
1619               ("generic parent cannot be used as formal package "
1620                 & "of a child unit",
1621                 Gen_Id);
1622
1623          else
1624             Error_Msg_N
1625               ("generic package cannot be used as a formal package "
1626                 & "within itself",
1627                 Gen_Id);
1628             Restore_Env;
1629             return;
1630          end if;
1631       end if;
1632
1633       --  Check for a formal package that is a package renaming.
1634
1635       if Present (Renamed_Object (Gen_Unit)) then
1636          Gen_Unit := Renamed_Object (Gen_Unit);
1637       end if;
1638
1639       --  The formal package is treated like a regular instance, but only
1640       --  the specification needs to be instantiated, to make entities visible.
1641
1642       if not Box_Present (N) then
1643          Hidden_Entities := New_Elmt_List;
1644          Analyze_Package_Instantiation (N);
1645
1646          if Parent_Installed then
1647             Remove_Parent;
1648          end if;
1649
1650       else
1651          --  If there are no generic associations, the generic parameters
1652          --  appear as local entities and are instantiated like them. We copy
1653          --  the generic package declaration as if it were an instantiation,
1654          --  and analyze it like a regular package, except that we treat the
1655          --  formals as additional visible components.
1656
1657          Gen_Decl := Unit_Declaration_Node (Gen_Unit);
1658
1659          if In_Extended_Main_Source_Unit (N) then
1660             Set_Is_Instantiated (Gen_Unit);
1661             Generate_Reference  (Gen_Unit, N);
1662          end if;
1663
1664          Formal := New_Copy (Pack_Id);
1665          New_N :=
1666            Copy_Generic_Node
1667              (Original_Node (Gen_Decl), Empty, Instantiating => True);
1668          Rewrite (N, New_N);
1669          Set_Defining_Unit_Name (Specification (New_N), Formal);
1670          Set_Instance_Env (Gen_Unit, Formal);
1671
1672          Enter_Name (Formal);
1673          Set_Ekind  (Formal, E_Generic_Package);
1674          Set_Etype  (Formal, Standard_Void_Type);
1675          Set_Inner_Instances (Formal, New_Elmt_List);
1676          New_Scope  (Formal);
1677
1678          --  Within the formal, the name of the generic package is a renaming
1679          --  of the formal (as for a regular instantiation).
1680
1681          Renaming := Make_Package_Renaming_Declaration (Loc,
1682              Defining_Unit_Name =>
1683                Make_Defining_Identifier (Loc, Chars (Gen_Unit)),
1684              Name => New_Reference_To (Formal, Loc));
1685
1686          if Present (Visible_Declarations (Specification (N))) then
1687             Prepend (Renaming, To => Visible_Declarations (Specification (N)));
1688          elsif Present (Private_Declarations (Specification (N))) then
1689             Prepend (Renaming, To => Private_Declarations (Specification (N)));
1690          end if;
1691
1692          if Is_Child_Unit (Gen_Unit)
1693            and then Parent_Installed
1694          then
1695             --  Similarly, we have to make the name of the formal visible in
1696             --  the parent instance, to resolve properly fully qualified names
1697             --  that may appear in the generic unit. The parent instance has
1698             --  been placed on the scope stack ahead of the current scope.
1699
1700             Parent_Instance := Scope_Stack.Table (Scope_Stack.Last - 1).Entity;
1701
1702             Renaming_In_Par :=
1703               Make_Defining_Identifier (Loc, Chars (Gen_Unit));
1704             Set_Ekind (Renaming_In_Par, E_Package);
1705             Set_Etype (Renaming_In_Par, Standard_Void_Type);
1706             Set_Scope (Renaming_In_Par, Parent_Instance);
1707             Set_Parent (Renaming_In_Par, Parent (Formal));
1708             Set_Renamed_Object (Renaming_In_Par, Formal);
1709             Append_Entity (Renaming_In_Par, Parent_Instance);
1710          end if;
1711
1712          Analyze_Generic_Formal_Part (N);
1713          Analyze (Specification (N));
1714          End_Package_Scope (Formal);
1715
1716          if Parent_Installed then
1717             Remove_Parent;
1718          end if;
1719
1720          Restore_Env;
1721
1722          --  Inside the generic unit, the formal package is a regular
1723          --  package, but no body is needed for it. Note that after
1724          --  instantiation, the defining_unit_name we need is in the
1725          --  new tree and not in the original. (see Package_Instantiation).
1726          --  A generic formal package is an instance, and can be used as
1727          --  an actual for an inner instance. Mark its generic parent.
1728
1729          Set_Ekind (Formal, E_Package);
1730          Set_Generic_Parent (Specification (N), Gen_Unit);
1731          Set_Has_Completion (Formal, True);
1732
1733          Set_Ekind (Pack_Id, E_Package);
1734          Set_Etype (Pack_Id, Standard_Void_Type);
1735          Set_Scope (Pack_Id, Scope (Formal));
1736          Set_Has_Completion (Pack_Id, True);
1737       end if;
1738    end Analyze_Formal_Package;
1739
1740    ---------------------------------
1741    -- Analyze_Formal_Private_Type --
1742    ---------------------------------
1743
1744    procedure Analyze_Formal_Private_Type
1745      (N   : Node_Id;
1746       T   : Entity_Id;
1747       Def : Node_Id)
1748    is
1749    begin
1750       New_Private_Type (N, T, Def);
1751
1752       --  Set the size to an arbitrary but legal value.
1753
1754       Set_Size_Info (T, Standard_Integer);
1755       Set_RM_Size   (T, RM_Size (Standard_Integer));
1756    end Analyze_Formal_Private_Type;
1757
1758    ----------------------------------------
1759    -- Analyze_Formal_Signed_Integer_Type --
1760    ----------------------------------------
1761
1762    procedure Analyze_Formal_Signed_Integer_Type
1763      (T   : Entity_Id;
1764       Def : Node_Id)
1765    is
1766       Base : constant Entity_Id :=
1767                New_Internal_Entity
1768                  (E_Signed_Integer_Type, Current_Scope, Sloc (Def), 'G');
1769
1770    begin
1771       Enter_Name (T);
1772
1773       Set_Ekind        (T, E_Signed_Integer_Subtype);
1774       Set_Etype        (T, Base);
1775       Set_Size_Info    (T, Standard_Integer);
1776       Set_RM_Size      (T, RM_Size (Standard_Integer));
1777       Set_Scalar_Range (T, Scalar_Range (Standard_Integer));
1778
1779       Set_Is_Generic_Type (Base);
1780       Set_Size_Info       (Base, Standard_Integer);
1781       Set_RM_Size         (Base, RM_Size (Standard_Integer));
1782       Set_Etype           (Base, Base);
1783       Set_Scalar_Range    (Base, Scalar_Range (Standard_Integer));
1784       Set_Parent          (Base, Parent (Def));
1785    end Analyze_Formal_Signed_Integer_Type;
1786
1787    -------------------------------
1788    -- Analyze_Formal_Subprogram --
1789    -------------------------------
1790
1791    procedure Analyze_Formal_Subprogram (N : Node_Id) is
1792       Spec : constant Node_Id   := Specification (N);
1793       Def  : constant Node_Id   := Default_Name (N);
1794       Nam  : constant Entity_Id := Defining_Unit_Name (Spec);
1795       Subp : Entity_Id;
1796
1797    begin
1798       if Nam = Error then
1799          return;
1800       end if;
1801
1802       if Nkind (Nam) = N_Defining_Program_Unit_Name then
1803          Error_Msg_N ("name of formal subprogram must be a direct name", Nam);
1804          return;
1805       end if;
1806
1807       Analyze_Subprogram_Declaration (N);
1808       Set_Is_Formal_Subprogram (Nam);
1809       Set_Has_Completion (Nam);
1810
1811       --  Default name is resolved at the point of instantiation
1812
1813       if Box_Present (N) then
1814          null;
1815
1816       --  Else default is bound at the point of generic declaration
1817
1818       elsif Present (Def) then
1819          if Nkind (Def) = N_Operator_Symbol then
1820             Find_Direct_Name (Def);
1821
1822          elsif Nkind (Def) /= N_Attribute_Reference then
1823             Analyze (Def);
1824
1825          else
1826             --  For an attribute reference, analyze the prefix and verify
1827             --  that it has the proper profile for the subprogram.
1828
1829             Analyze (Prefix (Def));
1830             Valid_Default_Attribute (Nam, Def);
1831             return;
1832          end if;
1833
1834          --  Default name may be overloaded, in which case the interpretation
1835          --  with the correct profile must be  selected, as for a renaming.
1836
1837          if Etype (Def) = Any_Type then
1838             return;
1839
1840          elsif Nkind (Def) = N_Selected_Component then
1841             Subp := Entity (Selector_Name (Def));
1842
1843             if Ekind (Subp) /= E_Entry then
1844                Error_Msg_N ("expect valid subprogram name as default", Def);
1845                return;
1846             end if;
1847
1848          elsif Nkind (Def) = N_Indexed_Component then
1849
1850             if  Nkind (Prefix (Def)) /= N_Selected_Component then
1851                Error_Msg_N ("expect valid subprogram name as default", Def);
1852                return;
1853
1854             else
1855                Subp := Entity (Selector_Name (Prefix (Def)));
1856
1857                if Ekind (Subp) /= E_Entry_Family then
1858                   Error_Msg_N ("expect valid subprogram name as default", Def);
1859                   return;
1860                end if;
1861             end if;
1862
1863          elsif Nkind (Def) = N_Character_Literal then
1864
1865             --  Needs some type checks: subprogram should be parameterless???
1866
1867             Resolve (Def, (Etype (Nam)));
1868
1869          elsif not Is_Entity_Name (Def)
1870            or else not Is_Overloadable (Entity (Def))
1871          then
1872             Error_Msg_N ("expect valid subprogram name as default", Def);
1873             return;
1874
1875          elsif not Is_Overloaded (Def) then
1876             Subp := Entity (Def);
1877
1878             if Subp = Nam then
1879                Error_Msg_N ("premature usage of formal subprogram", Def);
1880
1881             elsif not Entity_Matches_Spec (Subp, Nam) then
1882                Error_Msg_N ("no visible entity matches specification", Def);
1883             end if;
1884
1885          else
1886             declare
1887                I   : Interp_Index;
1888                I1  : Interp_Index := 0;
1889                It  : Interp;
1890                It1 : Interp;
1891
1892             begin
1893                Subp := Any_Id;
1894                Get_First_Interp (Def, I, It);
1895                while Present (It.Nam) loop
1896
1897                   if Entity_Matches_Spec (It.Nam, Nam) then
1898                      if Subp /= Any_Id then
1899                         It1 := Disambiguate (Def, I1, I, Etype (Subp));
1900
1901                         if It1 = No_Interp then
1902                            Error_Msg_N ("ambiguous default subprogram", Def);
1903                         else
1904                            Subp := It1.Nam;
1905                         end if;
1906
1907                         exit;
1908
1909                      else
1910                         I1  := I;
1911                         Subp := It.Nam;
1912                      end if;
1913                   end if;
1914
1915                   Get_Next_Interp (I, It);
1916                end loop;
1917             end;
1918
1919             if Subp /= Any_Id then
1920                Set_Entity (Def, Subp);
1921
1922                if Subp = Nam then
1923                   Error_Msg_N ("premature usage of formal subprogram", Def);
1924
1925                elsif Ekind (Subp) /= E_Operator then
1926                   Check_Mode_Conformant (Subp, Nam);
1927                end if;
1928
1929             else
1930                Error_Msg_N ("no visible subprogram matches specification", N);
1931             end if;
1932          end if;
1933       end if;
1934    end Analyze_Formal_Subprogram;
1935
1936    -------------------------------------
1937    -- Analyze_Formal_Type_Declaration --
1938    -------------------------------------
1939
1940    procedure Analyze_Formal_Type_Declaration (N : Node_Id) is
1941       Def : constant Node_Id := Formal_Type_Definition (N);
1942       T   : Entity_Id;
1943
1944    begin
1945       T := Defining_Identifier (N);
1946
1947       if Present (Discriminant_Specifications (N))
1948         and then Nkind (Def) /= N_Formal_Private_Type_Definition
1949       then
1950          Error_Msg_N
1951            ("discriminants not allowed for this formal type",
1952             Defining_Identifier (First (Discriminant_Specifications (N))));
1953       end if;
1954
1955       --  Enter the new name, and branch to specific routine.
1956
1957       case Nkind (Def) is
1958          when N_Formal_Private_Type_Definition         =>
1959             Analyze_Formal_Private_Type (N, T, Def);
1960
1961          when N_Formal_Derived_Type_Definition         =>
1962             Analyze_Formal_Derived_Type (N, T, Def);
1963
1964          when N_Formal_Discrete_Type_Definition        =>
1965             Analyze_Formal_Discrete_Type (T, Def);
1966
1967          when N_Formal_Signed_Integer_Type_Definition  =>
1968             Analyze_Formal_Signed_Integer_Type (T, Def);
1969
1970          when N_Formal_Modular_Type_Definition         =>
1971             Analyze_Formal_Modular_Type (T, Def);
1972
1973          when N_Formal_Floating_Point_Definition       =>
1974             Analyze_Formal_Floating_Type (T, Def);
1975
1976          when N_Formal_Ordinary_Fixed_Point_Definition =>
1977             Analyze_Formal_Ordinary_Fixed_Point_Type (T, Def);
1978
1979          when N_Formal_Decimal_Fixed_Point_Definition  =>
1980             Analyze_Formal_Decimal_Fixed_Point_Type (T, Def);
1981
1982          when N_Array_Type_Definition =>
1983             Analyze_Formal_Array_Type (T, Def);
1984
1985          when N_Access_To_Object_Definition            |
1986               N_Access_Function_Definition             |
1987               N_Access_Procedure_Definition            =>
1988             Analyze_Generic_Access_Type (T, Def);
1989
1990          when N_Error                                  =>
1991             null;
1992
1993          when others                                   =>
1994             raise Program_Error;
1995
1996       end case;
1997
1998       Set_Is_Generic_Type (T);
1999    end Analyze_Formal_Type_Declaration;
2000
2001    ------------------------------------
2002    -- Analyze_Function_Instantiation --
2003    ------------------------------------
2004
2005    procedure Analyze_Function_Instantiation (N : Node_Id) is
2006    begin
2007       Analyze_Subprogram_Instantiation (N, E_Function);
2008    end Analyze_Function_Instantiation;
2009
2010    ---------------------------------
2011    -- Analyze_Generic_Access_Type --
2012    ---------------------------------
2013
2014    procedure Analyze_Generic_Access_Type (T : Entity_Id; Def : Node_Id) is
2015    begin
2016       Enter_Name (T);
2017
2018       if Nkind (Def) = N_Access_To_Object_Definition then
2019          Access_Type_Declaration (T, Def);
2020
2021          if Is_Incomplete_Or_Private_Type (Designated_Type (T))
2022            and then No (Full_View (Designated_Type (T)))
2023            and then not Is_Generic_Type (Designated_Type (T))
2024          then
2025             Error_Msg_N ("premature usage of incomplete type", Def);
2026
2027          elsif Is_Internal (Designated_Type (T)) then
2028             Error_Msg_N
2029               ("only a subtype mark is allowed in a formal", Def);
2030          end if;
2031
2032       else
2033          Access_Subprogram_Declaration (T, Def);
2034       end if;
2035    end Analyze_Generic_Access_Type;
2036
2037    ---------------------------------
2038    -- Analyze_Generic_Formal_Part --
2039    ---------------------------------
2040
2041    procedure Analyze_Generic_Formal_Part (N : Node_Id) is
2042       Gen_Parm_Decl : Node_Id;
2043
2044    begin
2045       --  The generic formals are processed in the scope of the generic
2046       --  unit, where they are immediately visible. The scope is installed
2047       --  by the caller.
2048
2049       Gen_Parm_Decl := First (Generic_Formal_Declarations (N));
2050
2051       while Present (Gen_Parm_Decl) loop
2052          Analyze (Gen_Parm_Decl);
2053          Next (Gen_Parm_Decl);
2054       end loop;
2055
2056       Generate_Reference_To_Generic_Formals (Current_Scope);
2057    end Analyze_Generic_Formal_Part;
2058
2059    ------------------------------------------
2060    -- Analyze_Generic_Package_Declaration  --
2061    ------------------------------------------
2062
2063    procedure Analyze_Generic_Package_Declaration (N : Node_Id) is
2064       Loc         : constant Source_Ptr := Sloc (N);
2065       Id          : Entity_Id;
2066       New_N       : Node_Id;
2067       Save_Parent : Node_Id;
2068       Renaming    : Node_Id;
2069       Decls       : constant List_Id :=
2070                       Visible_Declarations (Specification (N));
2071       Decl        : Node_Id;
2072
2073    begin
2074       --  We introduce a renaming of the enclosing package, to have a usable
2075       --  entity as the prefix of an expanded name for a local entity of the
2076       --  form Par.P.Q, where P is the generic package. This is because a local
2077       --  entity named P may hide it, so that the usual visibility rules in
2078       --  the instance will not resolve properly.
2079
2080       Renaming :=
2081         Make_Package_Renaming_Declaration (Loc,
2082           Defining_Unit_Name =>
2083             Make_Defining_Identifier (Loc,
2084              Chars => New_External_Name (Chars (Defining_Entity (N)), "GH")),
2085           Name => Make_Identifier (Loc, Chars (Defining_Entity (N))));
2086
2087       if Present (Decls) then
2088          Decl := First (Decls);
2089          while Present (Decl)
2090            and then Nkind (Decl) = N_Pragma
2091          loop
2092             Next (Decl);
2093          end loop;
2094
2095          if Present (Decl) then
2096             Insert_Before (Decl, Renaming);
2097          else
2098             Append (Renaming, Visible_Declarations (Specification (N)));
2099          end if;
2100
2101       else
2102          Set_Visible_Declarations (Specification (N), New_List (Renaming));
2103       end if;
2104
2105       --  Create copy of generic unit, and save for instantiation.
2106       --  If the unit is a child unit, do not copy the specifications
2107       --  for the parent, which are not part of the generic tree.
2108
2109       Save_Parent := Parent_Spec (N);
2110       Set_Parent_Spec (N, Empty);
2111
2112       New_N := Copy_Generic_Node (N, Empty, Instantiating => False);
2113       Set_Parent_Spec (New_N, Save_Parent);
2114       Rewrite (N, New_N);
2115       Id := Defining_Entity (N);
2116       Generate_Definition (Id);
2117
2118       --  Expansion is not applied to generic units.
2119
2120       Start_Generic;
2121
2122       Enter_Name (Id);
2123       Set_Ekind (Id, E_Generic_Package);
2124       Set_Etype (Id, Standard_Void_Type);
2125       New_Scope (Id);
2126       Enter_Generic_Scope (Id);
2127       Set_Inner_Instances (Id, New_Elmt_List);
2128
2129       Set_Categorization_From_Pragmas (N);
2130       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2131
2132       --  Link the declaration of the generic homonym in the generic copy
2133       --  to the package it renames, so that it is always resolved properly.
2134
2135       Set_Generic_Homonym (Id, Defining_Unit_Name (Renaming));
2136       Set_Entity (Associated_Node (Name (Renaming)), Id);
2137
2138       --  For a library unit, we have reconstructed the entity for the
2139       --  unit, and must reset it in the library tables.
2140
2141       if Nkind (Parent (N)) = N_Compilation_Unit then
2142          Set_Cunit_Entity (Current_Sem_Unit, Id);
2143       end if;
2144
2145       Analyze_Generic_Formal_Part (N);
2146
2147       --  After processing the generic formals, analysis proceeds
2148       --  as for a non-generic package.
2149
2150       Analyze (Specification (N));
2151
2152       Validate_Categorization_Dependency (N, Id);
2153
2154       End_Generic;
2155
2156       End_Package_Scope (Id);
2157       Exit_Generic_Scope (Id);
2158
2159       if Nkind (Parent (N)) /= N_Compilation_Unit then
2160          Move_Freeze_Nodes (Id, N, Visible_Declarations (Specification (N)));
2161          Move_Freeze_Nodes (Id, N, Private_Declarations (Specification (N)));
2162          Move_Freeze_Nodes (Id, N, Generic_Formal_Declarations (N));
2163
2164       else
2165          Set_Body_Required (Parent (N), Unit_Requires_Body (Id));
2166          Validate_RT_RAT_Component (N);
2167
2168          --  If this is a spec without a body, check that generic parameters
2169          --  are referenced.
2170
2171          if not Body_Required (Parent (N)) then
2172             Check_References (Id);
2173          end if;
2174       end if;
2175    end Analyze_Generic_Package_Declaration;
2176
2177    --------------------------------------------
2178    -- Analyze_Generic_Subprogram_Declaration --
2179    --------------------------------------------
2180
2181    procedure Analyze_Generic_Subprogram_Declaration (N : Node_Id) is
2182       Spec        : Node_Id;
2183       Id          : Entity_Id;
2184       Formals     : List_Id;
2185       New_N       : Node_Id;
2186       Save_Parent : Node_Id;
2187
2188    begin
2189       --  Create copy of generic unit,and save for instantiation.
2190       --  If the unit is a child unit, do not copy the specifications
2191       --  for the parent, which are not part of the generic tree.
2192
2193       Save_Parent := Parent_Spec (N);
2194       Set_Parent_Spec (N, Empty);
2195
2196       New_N := Copy_Generic_Node (N, Empty, Instantiating => False);
2197       Set_Parent_Spec (New_N, Save_Parent);
2198       Rewrite (N, New_N);
2199
2200       Spec := Specification (N);
2201       Id := Defining_Entity (Spec);
2202       Generate_Definition (Id);
2203
2204       if Nkind (Id) = N_Defining_Operator_Symbol then
2205          Error_Msg_N
2206            ("operator symbol not allowed for generic subprogram", Id);
2207       end if;
2208
2209       Start_Generic;
2210
2211       Enter_Name (Id);
2212
2213       Set_Scope_Depth_Value (Id, Scope_Depth (Current_Scope) + 1);
2214       New_Scope (Id);
2215       Enter_Generic_Scope (Id);
2216       Set_Inner_Instances (Id, New_Elmt_List);
2217       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2218
2219       Analyze_Generic_Formal_Part (N);
2220
2221       Formals := Parameter_Specifications (Spec);
2222
2223       if Present (Formals) then
2224          Process_Formals (Formals, Spec);
2225       end if;
2226
2227       if Nkind (Spec) = N_Function_Specification then
2228          Set_Ekind (Id, E_Generic_Function);
2229          Find_Type (Subtype_Mark (Spec));
2230          Set_Etype (Id, Entity (Subtype_Mark (Spec)));
2231       else
2232          Set_Ekind (Id, E_Generic_Procedure);
2233          Set_Etype (Id, Standard_Void_Type);
2234       end if;
2235
2236       --  For a library unit, we have reconstructed the entity for the
2237       --  unit, and must reset it in the library tables. We also need
2238       --  to make sure that Body_Required is set properly in the original
2239       --  compilation unit node.
2240
2241       if Nkind (Parent (N)) = N_Compilation_Unit then
2242          Set_Cunit_Entity (Current_Sem_Unit, Id);
2243          Set_Body_Required (Parent (N), Unit_Requires_Body (Id));
2244       end if;
2245
2246       Set_Categorization_From_Pragmas (N);
2247       Validate_Categorization_Dependency (N, Id);
2248
2249       Save_Global_References (Original_Node (N));
2250
2251       End_Generic;
2252       End_Scope;
2253       Exit_Generic_Scope (Id);
2254       Generate_Reference_To_Formals (Id);
2255    end Analyze_Generic_Subprogram_Declaration;
2256
2257    -----------------------------------
2258    -- Analyze_Package_Instantiation --
2259    -----------------------------------
2260
2261    --  Note: this procedure is also used for formal package declarations,
2262    --  in which case the argument N is an N_Formal_Package_Declaration
2263    --  node. This should really be noted in the spec! ???
2264
2265    procedure Analyze_Package_Instantiation (N : Node_Id) is
2266       Loc    : constant Source_Ptr := Sloc (N);
2267       Gen_Id : constant Node_Id    := Name (N);
2268
2269       Act_Decl      : Node_Id;
2270       Act_Decl_Name : Node_Id;
2271       Act_Decl_Id   : Entity_Id;
2272       Act_Spec      : Node_Id;
2273       Act_Tree      : Node_Id;
2274
2275       Gen_Decl : Node_Id;
2276       Gen_Unit : Entity_Id;
2277
2278       Is_Actual_Pack : constant Boolean :=
2279                          Is_Internal (Defining_Entity (N));
2280
2281       Parent_Installed : Boolean := False;
2282       Renaming_List    : List_Id;
2283       Unit_Renaming    : Node_Id;
2284       Needs_Body       : Boolean;
2285       Inline_Now       : Boolean := False;
2286
2287       procedure Delay_Descriptors (E : Entity_Id);
2288       --  Delay generation of subprogram descriptors for given entity
2289
2290       function Might_Inline_Subp return Boolean;
2291       --  If inlining is active and the generic contains inlined subprograms,
2292       --  we instantiate the body. This may cause superfluous instantiations,
2293       --  but it is simpler than detecting the need for the body at the point
2294       --  of inlining, when the context of the instance is not available.
2295
2296       -----------------------
2297       -- Delay_Descriptors --
2298       -----------------------
2299
2300       procedure Delay_Descriptors (E : Entity_Id) is
2301       begin
2302          if not Delay_Subprogram_Descriptors (E) then
2303             Set_Delay_Subprogram_Descriptors (E);
2304             Pending_Descriptor.Increment_Last;
2305             Pending_Descriptor.Table (Pending_Descriptor.Last) := E;
2306          end if;
2307       end Delay_Descriptors;
2308
2309       -----------------------
2310       -- Might_Inline_Subp --
2311       -----------------------
2312
2313       function Might_Inline_Subp return Boolean is
2314          E : Entity_Id;
2315
2316       begin
2317          if not Inline_Processing_Required then
2318             return False;
2319
2320          else
2321             E := First_Entity (Gen_Unit);
2322
2323             while Present (E) loop
2324
2325                if Is_Subprogram (E)
2326                  and then Is_Inlined (E)
2327                then
2328                   return True;
2329                end if;
2330
2331                Next_Entity (E);
2332             end loop;
2333          end if;
2334
2335          return False;
2336       end Might_Inline_Subp;
2337
2338    --  Start of processing for Analyze_Package_Instantiation
2339
2340    begin
2341       --  Very first thing: apply the special kludge for Text_IO processing
2342       --  in case we are instantiating one of the children of [Wide_]Text_IO.
2343
2344       Text_IO_Kludge (Name (N));
2345
2346       --  Make node global for error reporting.
2347
2348       Instantiation_Node := N;
2349
2350       --  Case of instantiation of a generic package
2351
2352       if Nkind (N) = N_Package_Instantiation then
2353          Act_Decl_Id := New_Copy (Defining_Entity (N));
2354          Set_Comes_From_Source (Act_Decl_Id, True);
2355
2356          if Nkind (Defining_Unit_Name (N)) = N_Defining_Program_Unit_Name then
2357             Act_Decl_Name :=
2358               Make_Defining_Program_Unit_Name (Loc,
2359                 Name => New_Copy_Tree (Name (Defining_Unit_Name (N))),
2360                 Defining_Identifier => Act_Decl_Id);
2361          else
2362             Act_Decl_Name :=  Act_Decl_Id;
2363          end if;
2364
2365       --  Case of instantiation of a formal package
2366
2367       else
2368          Act_Decl_Id   := Defining_Identifier (N);
2369          Act_Decl_Name := Act_Decl_Id;
2370       end if;
2371
2372       Generate_Definition (Act_Decl_Id);
2373       Pre_Analyze_Actuals (N);
2374
2375       Init_Env;
2376       Check_Generic_Child_Unit (Gen_Id, Parent_Installed);
2377       Gen_Unit := Entity (Gen_Id);
2378
2379       --  Verify that it is the name of a generic package
2380
2381       if Etype (Gen_Unit) = Any_Type then
2382          Restore_Env;
2383          return;
2384
2385       elsif Ekind (Gen_Unit) /= E_Generic_Package then
2386
2387          --  Ada 0Y (AI-50217): Instance can not be used in limited with_clause
2388
2389          if From_With_Type (Gen_Unit) then
2390             Error_Msg_N
2391               ("cannot instantiate a limited withed package", Gen_Id);
2392          else
2393             Error_Msg_N
2394               ("expect name of generic package in instantiation", Gen_Id);
2395          end if;
2396
2397          Restore_Env;
2398          return;
2399       end if;
2400
2401       if In_Extended_Main_Source_Unit (N) then
2402          Set_Is_Instantiated (Gen_Unit);
2403          Generate_Reference  (Gen_Unit, N);
2404
2405          if Present (Renamed_Object (Gen_Unit)) then
2406             Set_Is_Instantiated (Renamed_Object (Gen_Unit));
2407             Generate_Reference  (Renamed_Object (Gen_Unit), N);
2408          end if;
2409       end if;
2410
2411       if Nkind (Gen_Id) = N_Identifier
2412         and then Chars (Gen_Unit) = Chars (Defining_Entity (N))
2413       then
2414          Error_Msg_NE
2415            ("& is hidden within declaration of instance", Gen_Id, Gen_Unit);
2416
2417       elsif Nkind (Gen_Id) = N_Expanded_Name
2418         and then Is_Child_Unit (Gen_Unit)
2419         and then Nkind (Prefix (Gen_Id)) = N_Identifier
2420         and then Chars (Act_Decl_Id) = Chars (Prefix (Gen_Id))
2421       then
2422          Error_Msg_N
2423            ("& is hidden within declaration of instance ", Prefix (Gen_Id));
2424       end if;
2425
2426       Set_Entity (Gen_Id, Gen_Unit);
2427
2428       --  If generic is a renaming, get original generic unit.
2429
2430       if Present (Renamed_Object (Gen_Unit))
2431         and then Ekind (Renamed_Object (Gen_Unit)) = E_Generic_Package
2432       then
2433          Gen_Unit := Renamed_Object (Gen_Unit);
2434       end if;
2435
2436       --  Verify that there are no circular instantiations.
2437
2438       if In_Open_Scopes (Gen_Unit) then
2439          Error_Msg_NE ("instantiation of & within itself", N, Gen_Unit);
2440          Restore_Env;
2441          return;
2442
2443       elsif Contains_Instance_Of (Gen_Unit, Current_Scope, Gen_Id) then
2444          Error_Msg_Node_2 := Current_Scope;
2445          Error_Msg_NE
2446            ("circular Instantiation: & instantiated in &!", N, Gen_Unit);
2447          Circularity_Detected := True;
2448          Restore_Env;
2449          return;
2450
2451       else
2452          Set_Instance_Env (Gen_Unit, Act_Decl_Id);
2453          Gen_Decl := Unit_Declaration_Node (Gen_Unit);
2454
2455          --  Initialize renamings map, for error checking, and the list
2456          --  that holds private entities whose views have changed between
2457          --  generic definition and instantiation. If this is the instance
2458          --  created to validate an actual package, the instantiation
2459          --  environment is that of the enclosing instance.
2460
2461          Generic_Renamings.Set_Last (0);
2462          Generic_Renamings_HTable.Reset;
2463
2464          Create_Instantiation_Source (N, Gen_Unit, False, S_Adjustment);
2465
2466          --  Copy original generic tree, to produce text for instantiation.
2467
2468          Act_Tree :=
2469            Copy_Generic_Node
2470              (Original_Node (Gen_Decl), Empty, Instantiating => True);
2471
2472          Act_Spec := Specification (Act_Tree);
2473
2474          --  If this is the instance created to validate an actual package,
2475          --  only the formals matter, do not examine the package spec itself.
2476
2477          if Is_Actual_Pack then
2478             Set_Visible_Declarations (Act_Spec, New_List);
2479             Set_Private_Declarations (Act_Spec, New_List);
2480          end if;
2481
2482          Renaming_List :=
2483            Analyze_Associations
2484              (N,
2485               Generic_Formal_Declarations (Act_Tree),
2486               Generic_Formal_Declarations (Gen_Decl));
2487
2488          Set_Defining_Unit_Name (Act_Spec, Act_Decl_Name);
2489          Set_Is_Generic_Instance (Act_Decl_Id);
2490
2491          Set_Generic_Parent (Act_Spec, Gen_Unit);
2492
2493          --  References to the generic in its own declaration or its body
2494          --  are references to the instance. Add a renaming declaration for
2495          --  the generic unit itself. This declaration, as well as the renaming
2496          --  declarations for the generic formals, must remain private to the
2497          --  unit: the formals, because this is the language semantics, and
2498          --  the unit because its use is an artifact of the implementation.
2499
2500          Unit_Renaming :=
2501            Make_Package_Renaming_Declaration (Loc,
2502              Defining_Unit_Name =>
2503                Make_Defining_Identifier (Loc, Chars (Gen_Unit)),
2504              Name => New_Reference_To (Act_Decl_Id, Loc));
2505
2506          Append (Unit_Renaming, Renaming_List);
2507
2508          --  The renaming declarations are the first local declarations of
2509          --  the new unit.
2510
2511          if Is_Non_Empty_List (Visible_Declarations (Act_Spec)) then
2512             Insert_List_Before
2513               (First (Visible_Declarations (Act_Spec)), Renaming_List);
2514          else
2515             Set_Visible_Declarations (Act_Spec, Renaming_List);
2516          end if;
2517
2518          Act_Decl :=
2519            Make_Package_Declaration (Loc,
2520              Specification => Act_Spec);
2521
2522          --  Save the instantiation node, for subsequent instantiation
2523          --  of the body, if there is one and we are generating code for
2524          --  the current unit. Mark the unit as having a body, to avoid
2525          --  a premature error message.
2526
2527          --  We instantiate the body if we are generating code, if we are
2528          --  generating cross-reference information, or if we are building
2529          --  trees for ASIS use.
2530
2531          declare
2532             Enclosing_Body_Present : Boolean := False;
2533             --  If the generic unit is not a compilation unit, then a body
2534             --  may be present in its parent even if none is required. We
2535             --  create a tentative pending instantiation for the body, which
2536             --  will be discarded if none is actually present.
2537
2538             Scop : Entity_Id;
2539
2540          begin
2541             if Scope (Gen_Unit) /= Standard_Standard
2542               and then not Is_Child_Unit (Gen_Unit)
2543             then
2544                Scop := Scope (Gen_Unit);
2545
2546                while Present (Scop)
2547                  and then Scop /= Standard_Standard
2548                loop
2549                   if Unit_Requires_Body (Scop) then
2550                      Enclosing_Body_Present := True;
2551                      exit;
2552                   end if;
2553
2554                   exit when Is_Compilation_Unit (Scop);
2555                   Scop := Scope (Scop);
2556                end loop;
2557             end if;
2558
2559             --  If front-end inlining is enabled, and this is a unit for which
2560             --  code will be generated, we instantiate the body at once.
2561             --  This is done if the instance is not the main unit, and if the
2562             --  generic is not a child unit of another generic, to avoid scope
2563             --  problems and the reinstallation of parent instances.
2564
2565             if Front_End_Inlining
2566               and then Expander_Active
2567               and then (not Is_Child_Unit (Gen_Unit)
2568                          or else not Is_Generic_Unit (Scope (Gen_Unit)))
2569               and then Is_In_Main_Unit (N)
2570               and then Nkind (Parent (N)) /= N_Compilation_Unit
2571               and then Might_Inline_Subp
2572               and then not Is_Actual_Pack
2573             then
2574                Inline_Now := True;
2575             end if;
2576
2577             Needs_Body :=
2578               (Unit_Requires_Body (Gen_Unit)
2579                   or else Enclosing_Body_Present
2580                   or else Present (Corresponding_Body (Gen_Decl)))
2581                 and then (Is_In_Main_Unit (N)
2582                            or else Might_Inline_Subp)
2583                 and then not Is_Actual_Pack
2584                 and then not Inline_Now
2585
2586                 and then (Operating_Mode = Generate_Code
2587                             or else (Operating_Mode = Check_Semantics
2588                                       and then ASIS_Mode));
2589
2590             --  If front_end_inlining is enabled, do not instantiate a
2591             --  body if within a generic context.
2592
2593             if Front_End_Inlining
2594               and then not Expander_Active
2595             then
2596                Needs_Body := False;
2597             end if;
2598
2599             --  If the current context is generic, and the package being
2600             --  instantiated is declared within a formal package, there
2601             --  is no body to instantiate until the enclosing generic is
2602             --  instantiated, and there is an actual for the formal
2603             --  package. If the formal package has parameters, we build a
2604             --  regular package instance for it, that preceeds the original
2605             --  formal package declaration.
2606
2607             if In_Open_Scopes (Scope (Scope (Gen_Unit))) then
2608                declare
2609                   Decl : constant Node_Id :=
2610                            Original_Node
2611                              (Unit_Declaration_Node (Scope (Gen_Unit)));
2612                begin
2613                   if Nkind (Decl) = N_Formal_Package_Declaration
2614                     or else (Nkind (Decl) = N_Package_Declaration
2615                       and then Is_List_Member (Decl)
2616                       and then Present (Next (Decl))
2617                       and then
2618                         Nkind (Next (Decl)) = N_Formal_Package_Declaration)
2619                   then
2620                      Needs_Body := False;
2621                   end if;
2622                end;
2623             end if;
2624          end;
2625
2626          --  If we are generating the calling stubs from the instantiation
2627          --  of a generic RCI package, we will not use the body of the
2628          --  generic package.
2629
2630          if Distribution_Stub_Mode = Generate_Caller_Stub_Body
2631            and then Is_Compilation_Unit (Defining_Entity (N))
2632          then
2633             Needs_Body := False;
2634          end if;
2635
2636          if Needs_Body then
2637
2638             --  Here is a defence against a ludicrous number of instantiations
2639             --  caused by a circular set of instantiation attempts.
2640
2641             if Pending_Instantiations.Last >
2642                  Hostparm.Max_Instantiations
2643             then
2644                Error_Msg_N ("too many instantiations", N);
2645                raise Unrecoverable_Error;
2646             end if;
2647
2648             --  Indicate that the enclosing scopes contain an instantiation,
2649             --  and that cleanup actions should be delayed until after the
2650             --  instance body is expanded.
2651
2652             Check_Forward_Instantiation (Gen_Decl);
2653             if Nkind (N) = N_Package_Instantiation then
2654                declare
2655                   Enclosing_Master : Entity_Id := Current_Scope;
2656
2657                begin
2658                   while Enclosing_Master /= Standard_Standard loop
2659
2660                      if Ekind (Enclosing_Master) = E_Package then
2661                         if Is_Compilation_Unit (Enclosing_Master) then
2662                            if In_Package_Body (Enclosing_Master) then
2663                               Delay_Descriptors
2664                                 (Body_Entity (Enclosing_Master));
2665                            else
2666                               Delay_Descriptors
2667                                 (Enclosing_Master);
2668                            end if;
2669
2670                            exit;
2671
2672                         else
2673                            Enclosing_Master := Scope (Enclosing_Master);
2674                         end if;
2675
2676                      elsif Ekind (Enclosing_Master) = E_Generic_Package then
2677                         Enclosing_Master := Scope (Enclosing_Master);
2678
2679                      elsif Is_Generic_Subprogram (Enclosing_Master)
2680                        or else Ekind (Enclosing_Master) = E_Void
2681                      then
2682                         --  Cleanup actions will eventually be performed on
2683                         --  the enclosing instance, if any. enclosing scope
2684                         --  is void in the formal part of a generic subp.
2685
2686                         exit;
2687
2688                      else
2689                         if Ekind (Enclosing_Master) = E_Entry
2690                           and then
2691                             Ekind (Scope (Enclosing_Master)) = E_Protected_Type
2692                         then
2693                            Enclosing_Master :=
2694                              Protected_Body_Subprogram (Enclosing_Master);
2695                         end if;
2696
2697                         Set_Delay_Cleanups (Enclosing_Master);
2698
2699                         while Ekind (Enclosing_Master) = E_Block loop
2700                            Enclosing_Master := Scope (Enclosing_Master);
2701                         end loop;
2702
2703                         if Is_Subprogram (Enclosing_Master) then
2704                            Delay_Descriptors (Enclosing_Master);
2705
2706                         elsif Is_Task_Type (Enclosing_Master) then
2707                            declare
2708                               TBP : constant Node_Id :=
2709                                       Get_Task_Body_Procedure
2710                                         (Enclosing_Master);
2711
2712                            begin
2713                               if Present (TBP) then
2714                                  Delay_Descriptors  (TBP);
2715                                  Set_Delay_Cleanups (TBP);
2716                               end if;
2717                            end;
2718                         end if;
2719
2720                         exit;
2721                      end if;
2722                   end loop;
2723                end;
2724
2725                --  Make entry in table
2726
2727                Pending_Instantiations.Increment_Last;
2728                Pending_Instantiations.Table (Pending_Instantiations.Last) :=
2729                  (N, Act_Decl, Expander_Active, Current_Sem_Unit);
2730             end if;
2731          end if;
2732
2733          Set_Categorization_From_Pragmas (Act_Decl);
2734
2735          if Parent_Installed then
2736             Hide_Current_Scope;
2737          end if;
2738
2739          Set_Instance_Spec (N, Act_Decl);
2740
2741          --  If not a compilation unit, insert the package declaration
2742          --  before the original instantiation node.
2743
2744          if Nkind (Parent (N)) /= N_Compilation_Unit then
2745             Mark_Rewrite_Insertion (Act_Decl);
2746             Insert_Before (N, Act_Decl);
2747             Analyze (Act_Decl);
2748
2749          --  For an instantiation that is a compilation unit, place
2750          --  declaration on current node so context is complete
2751          --  for analysis (including nested instantiations). It this
2752          --  is the main unit, the declaration eventually replaces the
2753          --  instantiation node. If the instance body is later created, it
2754          --  replaces the instance node, and the declation is attached to
2755          --  it (see Build_Instance_Compilation_Unit_Nodes).
2756
2757          else
2758             if Cunit_Entity (Current_Sem_Unit) = Defining_Entity (N) then
2759
2760                --  The entity for the current unit is the newly created one,
2761                --  and all semantic information is attached to it.
2762
2763                Set_Cunit_Entity (Current_Sem_Unit, Act_Decl_Id);
2764
2765                --  If this is the main unit, replace the main entity as well.
2766
2767                if Current_Sem_Unit = Main_Unit then
2768                   Main_Unit_Entity := Act_Decl_Id;
2769                end if;
2770             end if;
2771
2772             Set_Unit (Parent (N), Act_Decl);
2773             Set_Parent_Spec (Act_Decl, Parent_Spec (N));
2774             Analyze (Act_Decl);
2775             Set_Unit (Parent (N), N);
2776             Set_Body_Required (Parent (N), False);
2777
2778             --  We never need elaboration checks on instantiations, since
2779             --  by definition, the body instantiation is elaborated at the
2780             --  same time as the spec instantiation.
2781
2782             Set_Suppress_Elaboration_Warnings (Act_Decl_Id);
2783             Set_Kill_Elaboration_Checks       (Act_Decl_Id);
2784          end if;
2785
2786          Check_Elab_Instantiation (N);
2787
2788          if ABE_Is_Certain (N) and then Needs_Body then
2789             Pending_Instantiations.Decrement_Last;
2790          end if;
2791          Check_Hidden_Child_Unit (N, Gen_Unit, Act_Decl_Id);
2792
2793          Set_First_Private_Entity (Defining_Unit_Name (Unit_Renaming),
2794            First_Private_Entity (Act_Decl_Id));
2795
2796          --  If the instantiation will receive a body, the unit will
2797          --  be transformed into a package body, and receive its own
2798          --  elaboration entity. Otherwise, the nature of the unit is
2799          --  now a package declaration.
2800
2801          if Nkind (Parent (N)) = N_Compilation_Unit
2802            and then not Needs_Body
2803          then
2804             Rewrite (N, Act_Decl);
2805          end if;
2806
2807          if Present (Corresponding_Body (Gen_Decl))
2808            or else Unit_Requires_Body (Gen_Unit)
2809          then
2810             Set_Has_Completion (Act_Decl_Id);
2811          end if;
2812
2813          Check_Formal_Packages (Act_Decl_Id);
2814
2815          Restore_Private_Views (Act_Decl_Id);
2816
2817          if not Generic_Separately_Compiled (Gen_Unit) then
2818             Inherit_Context (Gen_Decl, N);
2819          end if;
2820
2821          if Parent_Installed then
2822             Remove_Parent;
2823          end if;
2824
2825          Restore_Env;
2826       end if;
2827
2828       Validate_Categorization_Dependency (N, Act_Decl_Id);
2829
2830       --  Check restriction, but skip this if something went wrong in
2831       --  the above analysis, indicated by Act_Decl_Id being void.
2832
2833       if Ekind (Act_Decl_Id) /= E_Void
2834         and then not Is_Library_Level_Entity (Act_Decl_Id)
2835       then
2836          Check_Restriction (No_Local_Allocators, N);
2837       end if;
2838
2839       if Inline_Now then
2840          Inline_Instance_Body (N, Gen_Unit, Act_Decl);
2841       end if;
2842
2843    exception
2844       when Instantiation_Error =>
2845          if Parent_Installed then
2846             Remove_Parent;
2847          end if;
2848    end Analyze_Package_Instantiation;
2849
2850    ---------------------------
2851    --  Inline_Instance_Body --
2852    ---------------------------
2853
2854    procedure Inline_Instance_Body
2855      (N        : Node_Id;
2856       Gen_Unit : Entity_Id;
2857       Act_Decl : Node_Id)
2858    is
2859       Vis          : Boolean;
2860       Gen_Comp     : constant Entity_Id :=
2861                       Cunit_Entity (Get_Source_Unit (Gen_Unit));
2862       Curr_Comp    : constant Node_Id := Cunit (Current_Sem_Unit);
2863       Curr_Scope   : Entity_Id := Empty;
2864       Curr_Unit    : constant Entity_Id :=
2865                        Cunit_Entity (Current_Sem_Unit);
2866       Removed      : Boolean := False;
2867       Num_Scopes   : Int := 0;
2868       Use_Clauses  : array (1 .. Scope_Stack.Last) of Node_Id;
2869       Instances    : array (1 .. Scope_Stack.Last) of Entity_Id;
2870       Inner_Scopes : array (1 .. Scope_Stack.Last) of Entity_Id;
2871       Num_Inner    : Int := 0;
2872       N_Instances  : Int := 0;
2873       S            : Entity_Id;
2874
2875    begin
2876       --  Case of generic unit defined in another unit. We must remove
2877       --  the complete context of the current unit to install that of
2878       --  the generic.
2879
2880       if Gen_Comp /= Cunit_Entity (Current_Sem_Unit) then
2881          S := Current_Scope;
2882
2883          while Present (S)
2884            and then S /= Standard_Standard
2885          loop
2886             Num_Scopes := Num_Scopes + 1;
2887
2888             Use_Clauses (Num_Scopes) :=
2889               (Scope_Stack.Table
2890                  (Scope_Stack.Last - Num_Scopes + 1).
2891                     First_Use_Clause);
2892             End_Use_Clauses (Use_Clauses (Num_Scopes));
2893
2894             exit when Is_Generic_Instance (S)
2895               and then (In_Package_Body (S)
2896                           or else Ekind (S) = E_Procedure
2897                           or else Ekind (S) = E_Function);
2898             S := Scope (S);
2899          end loop;
2900
2901          Vis := Is_Immediately_Visible (Gen_Comp);
2902
2903          --  Find and save all enclosing instances
2904
2905          S := Current_Scope;
2906
2907          while Present (S)
2908            and then S /= Standard_Standard
2909          loop
2910             if Is_Generic_Instance (S) then
2911                N_Instances := N_Instances + 1;
2912                Instances (N_Instances) := S;
2913
2914                exit when In_Package_Body (S);
2915             end if;
2916
2917             S := Scope (S);
2918          end loop;
2919
2920          --  Remove context of current compilation unit, unless we
2921          --  are within a nested package instantiation, in which case
2922          --  the context has been removed previously.
2923
2924          --  If current scope is the body of a child unit, remove context
2925          --  of spec as well.
2926
2927          S := Current_Scope;
2928
2929          while Present (S)
2930            and then S /= Standard_Standard
2931          loop
2932             exit when Is_Generic_Instance (S)
2933                  and then (In_Package_Body (S)
2934                             or else Ekind (S) = E_Procedure
2935                             or else Ekind (S) = E_Function);
2936
2937             if S = Curr_Unit
2938               or else (Ekind (Curr_Unit) = E_Package_Body
2939                         and then S = Spec_Entity (Curr_Unit))
2940               or else (Ekind (Curr_Unit) = E_Subprogram_Body
2941                         and then S =
2942                           Corresponding_Spec
2943                             (Unit_Declaration_Node (Curr_Unit)))
2944             then
2945                Removed := True;
2946
2947                --  Remove entities in current scopes from visibility, so
2948                --  than instance body is compiled in a clean environment.
2949
2950                Save_Scope_Stack (Handle_Use => False);
2951
2952                if Is_Child_Unit (S) then
2953
2954                   --  Remove child unit from stack, as well as inner scopes.
2955                   --  Removing the context of a child unit removes parent
2956                   --  units as well.
2957
2958                   while Current_Scope /= S loop
2959                      Num_Inner := Num_Inner + 1;
2960                      Inner_Scopes (Num_Inner) := Current_Scope;
2961                      Pop_Scope;
2962                   end loop;
2963
2964                   Pop_Scope;
2965                   Remove_Context (Curr_Comp);
2966                   Curr_Scope := S;
2967
2968                else
2969                   Remove_Context (Curr_Comp);
2970                end if;
2971
2972                if Ekind (Curr_Unit) = E_Package_Body then
2973                   Remove_Context (Library_Unit (Curr_Comp));
2974                end if;
2975             end if;
2976
2977             S := Scope (S);
2978          end loop;
2979
2980          New_Scope (Standard_Standard);
2981          Scope_Stack.Table (Scope_Stack.Last).Is_Active_Stack_Base := True;
2982          Instantiate_Package_Body
2983            ((N, Act_Decl, Expander_Active, Current_Sem_Unit), True);
2984          Pop_Scope;
2985
2986          --  Restore context
2987
2988          Set_Is_Immediately_Visible (Gen_Comp, Vis);
2989
2990          --  Reset Generic_Instance flag so that use clauses can be installed
2991          --  in the proper order. (See Use_One_Package for effect of enclosing
2992          --  instances on processing of use clauses).
2993
2994          for J in 1 .. N_Instances loop
2995             Set_Is_Generic_Instance (Instances (J), False);
2996          end loop;
2997
2998          if Removed then
2999             Install_Context (Curr_Comp);
3000
3001             if Present (Curr_Scope)
3002               and then Is_Child_Unit (Curr_Scope)
3003             then
3004                New_Scope (Curr_Scope);
3005                Set_Is_Immediately_Visible (Curr_Scope);
3006
3007                --  Finally, restore inner scopes as well.
3008
3009                for J in reverse 1 .. Num_Inner loop
3010                   New_Scope (Inner_Scopes (J));
3011                end loop;
3012             end if;
3013
3014             Restore_Scope_Stack (Handle_Use => False);
3015          end if;
3016
3017          --  Restore use clauses. For a child unit, use clauses in the
3018          --  parents are restored when installing the context, so only
3019          --  those in inner scopes (and those local to the child unit itself)
3020          --  need to be installed explicitly.
3021
3022          if Is_Child_Unit (Curr_Unit)
3023            and then Removed
3024          then
3025             for J in reverse 1 .. Num_Inner + 1 loop
3026                Scope_Stack.Table (Scope_Stack.Last - J + 1).First_Use_Clause :=
3027                  Use_Clauses (J);
3028                Install_Use_Clauses (Use_Clauses (J));
3029             end  loop;
3030
3031          else
3032             for J in reverse 1 .. Num_Scopes loop
3033                Scope_Stack.Table (Scope_Stack.Last - J + 1).First_Use_Clause :=
3034                  Use_Clauses (J);
3035                Install_Use_Clauses (Use_Clauses (J));
3036             end  loop;
3037          end if;
3038
3039          for J in 1 .. N_Instances loop
3040             Set_Is_Generic_Instance (Instances (J), True);
3041          end loop;
3042
3043       --  If generic unit is in current unit, current context is correct.
3044
3045       else
3046          Instantiate_Package_Body
3047            ((N, Act_Decl, Expander_Active, Current_Sem_Unit), True);
3048       end if;
3049    end Inline_Instance_Body;
3050
3051    -------------------------------------
3052    -- Analyze_Procedure_Instantiation --
3053    -------------------------------------
3054
3055    procedure Analyze_Procedure_Instantiation (N : Node_Id) is
3056    begin
3057       Analyze_Subprogram_Instantiation (N, E_Procedure);
3058    end Analyze_Procedure_Instantiation;
3059
3060    --------------------------------------
3061    -- Analyze_Subprogram_Instantiation --
3062    --------------------------------------
3063
3064    procedure Analyze_Subprogram_Instantiation
3065      (N : Node_Id;
3066       K : Entity_Kind)
3067    is
3068       Loc    : constant Source_Ptr := Sloc (N);
3069       Gen_Id : constant Node_Id    := Name (N);
3070
3071       Anon_Id : constant Entity_Id :=
3072                   Make_Defining_Identifier (Sloc (Defining_Entity (N)),
3073                     Chars => New_External_Name
3074                                (Chars (Defining_Entity (N)), 'R'));
3075
3076       Act_Decl_Id : Entity_Id;
3077       Act_Decl    : Node_Id;
3078       Act_Spec    : Node_Id;
3079       Act_Tree    : Node_Id;
3080
3081       Gen_Unit         : Entity_Id;
3082       Gen_Decl         : Node_Id;
3083       Pack_Id          : Entity_Id;
3084       Parent_Installed : Boolean := False;
3085       Renaming_List    : List_Id;
3086
3087       procedure Analyze_Instance_And_Renamings;
3088       --  The instance must be analyzed in a context that includes the
3089       --  mappings of generic parameters into actuals. We create a package
3090       --  declaration for this purpose, and a subprogram with an internal
3091       --  name within the package. The subprogram instance is simply an
3092       --  alias for the internal subprogram, declared in the current scope.
3093
3094       ------------------------------------
3095       -- Analyze_Instance_And_Renamings --
3096       ------------------------------------
3097
3098       procedure Analyze_Instance_And_Renamings is
3099          Def_Ent   : constant Entity_Id := Defining_Entity (N);
3100          Pack_Decl : Node_Id;
3101
3102       begin
3103          if Nkind (Parent (N)) = N_Compilation_Unit then
3104
3105             --  For the case of a compilation unit, the container package
3106             --  has the same name as the instantiation, to insure that the
3107             --  binder calls the elaboration procedure with the right name.
3108             --  Copy the entity of the instance, which may have compilation
3109             --  level flags (e.g. Is_Child_Unit) set.
3110
3111             Pack_Id := New_Copy (Def_Ent);
3112
3113          else
3114             --  Otherwise we use the name of the instantiation concatenated
3115             --  with its source position to ensure uniqueness if there are
3116             --  several instantiations with the same name.
3117
3118             Pack_Id :=
3119               Make_Defining_Identifier (Loc,
3120                 Chars => New_External_Name
3121                            (Related_Id   => Chars (Def_Ent),
3122                             Suffix       => "GP",
3123                             Suffix_Index => Source_Offset (Sloc (Def_Ent))));
3124          end if;
3125
3126          Pack_Decl := Make_Package_Declaration (Loc,
3127            Specification => Make_Package_Specification (Loc,
3128              Defining_Unit_Name   => Pack_Id,
3129              Visible_Declarations => Renaming_List,
3130              End_Label            => Empty));
3131
3132          Set_Instance_Spec (N, Pack_Decl);
3133          Set_Is_Generic_Instance (Pack_Id);
3134          Set_Needs_Debug_Info (Pack_Id);
3135
3136          --  Case of not a compilation unit
3137
3138          if Nkind (Parent (N)) /= N_Compilation_Unit then
3139             Mark_Rewrite_Insertion (Pack_Decl);
3140             Insert_Before (N, Pack_Decl);
3141             Set_Has_Completion (Pack_Id);
3142
3143          --  Case of an instantiation that is a compilation unit
3144
3145          --  Place declaration on current node so context is complete
3146          --  for analysis (including nested instantiations), and for
3147          --  use in a context_clause (see Analyze_With_Clause).
3148
3149          else
3150             Set_Unit (Parent (N), Pack_Decl);
3151             Set_Parent_Spec (Pack_Decl, Parent_Spec (N));
3152          end if;
3153
3154          Analyze (Pack_Decl);
3155          Check_Formal_Packages (Pack_Id);
3156          Set_Is_Generic_Instance (Pack_Id, False);
3157
3158          --  Body of the enclosing package is supplied when instantiating
3159          --  the subprogram body, after semantic  analysis is completed.
3160
3161          if Nkind (Parent (N)) = N_Compilation_Unit then
3162
3163             --  Remove package itself from visibility, so it does not
3164             --  conflict with subprogram.
3165
3166             Set_Name_Entity_Id (Chars (Pack_Id), Homonym (Pack_Id));
3167
3168             --  Set name and scope of internal subprogram so that the
3169             --  proper external name will be generated. The proper scope
3170             --  is the scope of the wrapper package. We need to generate
3171             --  debugging information for the internal subprogram, so set
3172             --  flag accordingly.
3173
3174             Set_Chars (Anon_Id, Chars (Defining_Entity (N)));
3175             Set_Scope (Anon_Id, Scope (Pack_Id));
3176
3177             --  Mark wrapper package as referenced, to avoid spurious
3178             --  warnings if the instantiation appears in various with_
3179             --  clauses of subunits of the main unit.
3180
3181             Set_Referenced (Pack_Id);
3182          end if;
3183
3184          Set_Is_Generic_Instance (Anon_Id);
3185          Set_Needs_Debug_Info    (Anon_Id);
3186          Act_Decl_Id := New_Copy (Anon_Id);
3187
3188          Set_Parent            (Act_Decl_Id, Parent (Anon_Id));
3189          Set_Chars             (Act_Decl_Id, Chars (Defining_Entity (N)));
3190          Set_Sloc              (Act_Decl_Id, Sloc (Defining_Entity (N)));
3191          Set_Comes_From_Source (Act_Decl_Id, True);
3192
3193          --  The signature may involve types that are not frozen yet, but
3194          --  the subprogram will be frozen at the point the wrapper package
3195          --  is frozen, so it does not need its own freeze node. In fact, if
3196          --  one is created, it might conflict with the freezing actions from
3197          --  the wrapper package (see 7206-013).
3198
3199          Set_Has_Delayed_Freeze (Anon_Id, False);
3200
3201          --  If the instance is a child unit, mark the Id accordingly. Mark
3202          --  the anonymous entity as well, which is the real subprogram and
3203          --  which is used when the instance appears in a context clause.
3204
3205          Set_Is_Child_Unit (Act_Decl_Id, Is_Child_Unit (Defining_Entity (N)));
3206          Set_Is_Child_Unit (Anon_Id, Is_Child_Unit (Defining_Entity (N)));
3207          New_Overloaded_Entity (Act_Decl_Id);
3208          Check_Eliminated  (Act_Decl_Id);
3209
3210          --  In compilation unit case, kill elaboration checks on the
3211          --  instantiation, since they are never needed -- the body is
3212          --  instantiated at the same point as the spec.
3213
3214          if Nkind (Parent (N)) = N_Compilation_Unit then
3215             Set_Suppress_Elaboration_Warnings (Act_Decl_Id);
3216             Set_Kill_Elaboration_Checks       (Act_Decl_Id);
3217             Set_Is_Compilation_Unit (Anon_Id);
3218
3219             Set_Cunit_Entity (Current_Sem_Unit, Pack_Id);
3220          end if;
3221
3222          --  The instance is not a freezing point for the new subprogram.
3223
3224          Set_Is_Frozen (Act_Decl_Id, False);
3225
3226          if Nkind (Defining_Entity (N)) = N_Defining_Operator_Symbol then
3227             Valid_Operator_Definition (Act_Decl_Id);
3228          end if;
3229
3230          Set_Alias  (Act_Decl_Id, Anon_Id);
3231          Set_Parent (Act_Decl_Id, Parent (Anon_Id));
3232          Set_Has_Completion (Act_Decl_Id);
3233          Set_Related_Instance (Pack_Id, Act_Decl_Id);
3234
3235          if Nkind (Parent (N)) = N_Compilation_Unit then
3236             Set_Body_Required (Parent (N), False);
3237          end if;
3238
3239       end Analyze_Instance_And_Renamings;
3240
3241    --  Start of processing for Analyze_Subprogram_Instantiation
3242
3243    begin
3244       --  Very first thing: apply the special kludge for Text_IO processing
3245       --  in case we are instantiating one of the children of [Wide_]Text_IO.
3246       --  Of course such an instantiation is bogus (these are packages, not
3247       --  subprograms), but we get a better error message if we do this.
3248
3249       Text_IO_Kludge (Gen_Id);
3250
3251       --  Make node global for error reporting.
3252
3253       Instantiation_Node := N;
3254       Pre_Analyze_Actuals (N);
3255
3256       Init_Env;
3257       Check_Generic_Child_Unit (Gen_Id, Parent_Installed);
3258       Gen_Unit := Entity (Gen_Id);
3259
3260       Generate_Reference (Gen_Unit, Gen_Id);
3261
3262       if Nkind (Gen_Id) = N_Identifier
3263         and then Chars (Gen_Unit) = Chars (Defining_Entity (N))
3264       then
3265          Error_Msg_NE
3266            ("& is hidden within declaration of instance", Gen_Id, Gen_Unit);
3267       end if;
3268
3269       if Etype (Gen_Unit) = Any_Type then
3270          Restore_Env;
3271          return;
3272       end if;
3273
3274       --  Verify that it is a generic subprogram of the right kind, and that
3275       --  it does not lead to a circular instantiation.
3276
3277       if Ekind (Gen_Unit) /= E_Generic_Procedure
3278         and then Ekind (Gen_Unit) /= E_Generic_Function
3279       then
3280          Error_Msg_N ("expect generic subprogram in instantiation", Gen_Id);
3281
3282       elsif In_Open_Scopes (Gen_Unit) then
3283          Error_Msg_NE ("instantiation of & within itself", N, Gen_Unit);
3284
3285       elsif K = E_Procedure
3286         and then Ekind (Gen_Unit) /= E_Generic_Procedure
3287       then
3288          if Ekind (Gen_Unit) = E_Generic_Function then
3289             Error_Msg_N
3290               ("cannot instantiate generic function as procedure", Gen_Id);
3291          else
3292             Error_Msg_N
3293               ("expect name of generic procedure in instantiation", Gen_Id);
3294          end if;
3295
3296       elsif K = E_Function
3297         and then Ekind (Gen_Unit) /= E_Generic_Function
3298       then
3299          if Ekind (Gen_Unit) = E_Generic_Procedure then
3300             Error_Msg_N
3301               ("cannot instantiate generic procedure as function", Gen_Id);
3302          else
3303             Error_Msg_N
3304               ("expect name of generic function in instantiation", Gen_Id);
3305          end if;
3306
3307       else
3308          Set_Entity (Gen_Id, Gen_Unit);
3309          Set_Is_Instantiated (Gen_Unit);
3310
3311          if In_Extended_Main_Source_Unit (N) then
3312             Generate_Reference (Gen_Unit, N);
3313          end if;
3314
3315          --  If renaming, get original unit
3316
3317          if Present (Renamed_Object (Gen_Unit))
3318            and then (Ekind (Renamed_Object (Gen_Unit)) = E_Generic_Procedure
3319                        or else
3320                      Ekind (Renamed_Object (Gen_Unit)) = E_Generic_Function)
3321          then
3322             Gen_Unit := Renamed_Object (Gen_Unit);
3323             Set_Is_Instantiated (Gen_Unit);
3324             Generate_Reference  (Gen_Unit, N);
3325          end if;
3326
3327          if Contains_Instance_Of (Gen_Unit, Current_Scope, Gen_Id) then
3328             Error_Msg_Node_2 := Current_Scope;
3329             Error_Msg_NE
3330               ("circular Instantiation: & instantiated in &!", N, Gen_Unit);
3331             Circularity_Detected := True;
3332             return;
3333          end if;
3334
3335          Gen_Decl := Unit_Declaration_Node (Gen_Unit);
3336
3337          --  The subprogram itself cannot contain a nested instance, so
3338          --  the current parent is left empty.
3339
3340          Set_Instance_Env (Gen_Unit, Empty);
3341
3342          --  Initialize renamings map, for error checking.
3343
3344          Generic_Renamings.Set_Last (0);
3345          Generic_Renamings_HTable.Reset;
3346
3347          Create_Instantiation_Source (N, Gen_Unit, False, S_Adjustment);
3348
3349          --  Copy original generic tree, to produce text for instantiation.
3350
3351          Act_Tree :=
3352            Copy_Generic_Node
3353              (Original_Node (Gen_Decl), Empty, Instantiating => True);
3354
3355          Act_Spec := Specification (Act_Tree);
3356          Renaming_List :=
3357            Analyze_Associations
3358              (N,
3359               Generic_Formal_Declarations (Act_Tree),
3360               Generic_Formal_Declarations (Gen_Decl));
3361
3362          --  Build the subprogram declaration, which does not appear
3363          --  in the generic template, and give it a sloc consistent
3364          --  with that of the template.
3365
3366          Set_Defining_Unit_Name (Act_Spec, Anon_Id);
3367          Set_Generic_Parent (Act_Spec, Gen_Unit);
3368          Act_Decl :=
3369            Make_Subprogram_Declaration (Sloc (Act_Spec),
3370              Specification => Act_Spec);
3371
3372          Set_Categorization_From_Pragmas (Act_Decl);
3373
3374          if Parent_Installed then
3375             Hide_Current_Scope;
3376          end if;
3377
3378          Append (Act_Decl, Renaming_List);
3379          Analyze_Instance_And_Renamings;
3380
3381          --  If the generic is marked Import (Intrinsic), then so is the
3382          --  instance. This indicates that there is no body to instantiate.
3383          --  If generic is marked inline, so it the instance, and the
3384          --  anonymous subprogram it renames. If inlined, or else if inlining
3385          --  is enabled for the compilation, we generate the instance body
3386          --  even if it is not within the main unit.
3387
3388          --  Any other  pragmas might also be inherited ???
3389
3390          if Is_Intrinsic_Subprogram (Gen_Unit) then
3391             Set_Is_Intrinsic_Subprogram (Anon_Id);
3392             Set_Is_Intrinsic_Subprogram (Act_Decl_Id);
3393
3394             if Chars (Gen_Unit) = Name_Unchecked_Conversion then
3395                Validate_Unchecked_Conversion (N, Act_Decl_Id);
3396             end if;
3397          end if;
3398
3399          Generate_Definition (Act_Decl_Id);
3400
3401          Set_Is_Inlined (Act_Decl_Id, Is_Inlined (Gen_Unit));
3402          Set_Is_Inlined (Anon_Id,     Is_Inlined (Gen_Unit));
3403
3404          if not Is_Intrinsic_Subprogram (Gen_Unit) then
3405             Check_Elab_Instantiation (N);
3406          end if;
3407
3408          Check_Hidden_Child_Unit (N, Gen_Unit, Act_Decl_Id);
3409
3410          --  Subject to change, pending on if other pragmas are inherited ???
3411
3412          Validate_Categorization_Dependency (N, Act_Decl_Id);
3413
3414          if not Is_Intrinsic_Subprogram (Act_Decl_Id) then
3415
3416             if not Generic_Separately_Compiled (Gen_Unit) then
3417                Inherit_Context (Gen_Decl, N);
3418             end if;
3419
3420             Restore_Private_Views (Pack_Id, False);
3421
3422             --  If the context requires a full instantiation, mark node for
3423             --  subsequent construction of the body.
3424
3425             if (Is_In_Main_Unit (N)
3426                   or else Is_Inlined (Act_Decl_Id))
3427               and then (Operating_Mode = Generate_Code
3428                           or else (Operating_Mode = Check_Semantics
3429                                     and then ASIS_Mode))
3430               and then (Expander_Active or else ASIS_Mode)
3431               and then not ABE_Is_Certain (N)
3432               and then not Is_Eliminated (Act_Decl_Id)
3433             then
3434                Pending_Instantiations.Increment_Last;
3435                Pending_Instantiations.Table (Pending_Instantiations.Last) :=
3436                  (N, Act_Decl, Expander_Active, Current_Sem_Unit);
3437                Check_Forward_Instantiation (Gen_Decl);
3438
3439                --  The wrapper package is always delayed, because it does
3440                --  not constitute a freeze point, but to insure that the
3441                --  freeze node is placed properly, it is created directly
3442                --  when instantiating the body (otherwise the freeze node
3443                --  might appear to early for nested instantiations).
3444
3445             elsif Nkind (Parent (N)) = N_Compilation_Unit then
3446
3447                --  For ASIS purposes, indicate that the wrapper package has
3448                --  replaced the instantiation node.
3449
3450                Rewrite (N, Unit (Parent (N)));
3451                Set_Unit (Parent (N), N);
3452             end if;
3453
3454          elsif Nkind (Parent (N)) = N_Compilation_Unit then
3455
3456                --  Replace instance node for library-level instantiations
3457                --  of intrinsic subprograms, for ASIS use.
3458
3459                Rewrite (N, Unit (Parent (N)));
3460                Set_Unit (Parent (N), N);
3461          end if;
3462
3463          if Parent_Installed then
3464             Remove_Parent;
3465          end if;
3466
3467          Restore_Env;
3468          Generic_Renamings.Set_Last (0);
3469          Generic_Renamings_HTable.Reset;
3470       end if;
3471
3472    exception
3473       when Instantiation_Error =>
3474          if Parent_Installed then
3475             Remove_Parent;
3476          end if;
3477    end Analyze_Subprogram_Instantiation;
3478
3479    -------------------------
3480    -- Get_Associated_Node --
3481    -------------------------
3482
3483    function Get_Associated_Node (N : Node_Id) return Node_Id is
3484       Assoc : Node_Id := Associated_Node (N);
3485
3486    begin
3487       if Nkind (Assoc) /= Nkind (N) then
3488          return Assoc;
3489
3490       elsif Nkind (Assoc) = N_Aggregate
3491         or else Nkind (Assoc) = N_Extension_Aggregate
3492       then
3493          return Assoc;
3494       else
3495          --  If the node is part of an inner generic, it may itself have been
3496          --  remapped into a further generic copy. Associated_Node is otherwise
3497          --  used for the entity of the node, and will be of a different node
3498          --  kind, or else N has been rewritten as a literal or function call.
3499
3500          while Present (Associated_Node (Assoc))
3501            and then Nkind (Associated_Node (Assoc)) = Nkind (Assoc)
3502          loop
3503             Assoc := Associated_Node (Assoc);
3504          end loop;
3505
3506          --  Follow and additional link in case the final node was rewritten.
3507          --  This can only happen with nested generic units.
3508
3509          if (Nkind (Assoc) = N_Identifier or else Nkind (Assoc) in N_Op)
3510            and then Present (Associated_Node (Assoc))
3511            and then (Nkind (Associated_Node (Assoc)) = N_Function_Call
3512                        or else
3513                      Nkind (Associated_Node (Assoc)) = N_Explicit_Dereference
3514                        or else
3515                      Nkind (Associated_Node (Assoc)) = N_Integer_Literal
3516                        or else
3517                      Nkind (Associated_Node (Assoc)) = N_Real_Literal
3518                        or else
3519                      Nkind (Associated_Node (Assoc)) = N_String_Literal)
3520          then
3521             Assoc := Associated_Node (Assoc);
3522          end if;
3523
3524          return Assoc;
3525       end if;
3526    end Get_Associated_Node;
3527
3528    -------------------------------------------
3529    -- Build_Instance_Compilation_Unit_Nodes --
3530    -------------------------------------------
3531
3532    procedure Build_Instance_Compilation_Unit_Nodes
3533      (N        : Node_Id;
3534       Act_Body : Node_Id;
3535       Act_Decl : Node_Id)
3536    is
3537       Decl_Cunit : Node_Id;
3538       Body_Cunit : Node_Id;
3539       Citem      : Node_Id;
3540       New_Main   : constant Entity_Id := Defining_Entity (Act_Decl);
3541       Old_Main   : constant Entity_Id := Cunit_Entity (Main_Unit);
3542
3543    begin
3544       --  A new compilation unit node is built for the instance declaration
3545
3546       Decl_Cunit :=
3547         Make_Compilation_Unit (Sloc (N),
3548           Context_Items  => Empty_List,
3549           Unit           => Act_Decl,
3550           Aux_Decls_Node =>
3551             Make_Compilation_Unit_Aux (Sloc (N)));
3552
3553       Set_Parent_Spec   (Act_Decl, Parent_Spec (N));
3554       Set_Body_Required (Decl_Cunit, True);
3555
3556       --  We use the original instantiation compilation unit as the resulting
3557       --  compilation unit of the instance, since this is the main unit.
3558
3559       Rewrite (N, Act_Body);
3560       Body_Cunit := Parent (N);
3561
3562       --  The two compilation unit nodes are linked by the Library_Unit field
3563
3564       Set_Library_Unit  (Decl_Cunit, Body_Cunit);
3565       Set_Library_Unit  (Body_Cunit, Decl_Cunit);
3566
3567       --  Preserve the private nature of the package if needed.
3568
3569       Set_Private_Present (Decl_Cunit, Private_Present (Body_Cunit));
3570
3571       --  If the instance is not the main unit, its context, categorization,
3572       --  and elaboration entity are not relevant to the compilation.
3573
3574       if Parent (N) /= Cunit (Main_Unit) then
3575          return;
3576       end if;
3577
3578       --  The context clause items on the instantiation, which are now
3579       --  attached to the body compilation unit (since the body overwrote
3580       --  the original instantiation node), semantically belong on the spec,
3581       --  so copy them there. It's harmless to leave them on the body as well.
3582       --  In fact one could argue that they belong in both places.
3583
3584       Citem := First (Context_Items (Body_Cunit));
3585       while Present (Citem) loop
3586          Append (New_Copy (Citem), Context_Items (Decl_Cunit));
3587          Next (Citem);
3588       end loop;
3589
3590       --  Propagate categorization flags on packages, so that they appear
3591       --  in ali file for the spec of the unit.
3592
3593       if Ekind (New_Main) = E_Package then
3594          Set_Is_Pure           (Old_Main, Is_Pure (New_Main));
3595          Set_Is_Preelaborated  (Old_Main, Is_Preelaborated (New_Main));
3596          Set_Is_Remote_Types   (Old_Main, Is_Remote_Types (New_Main));
3597          Set_Is_Shared_Passive (Old_Main, Is_Shared_Passive (New_Main));
3598          Set_Is_Remote_Call_Interface
3599            (Old_Main, Is_Remote_Call_Interface (New_Main));
3600       end if;
3601
3602       --  Make entry in Units table, so that binder can generate call to
3603       --  elaboration procedure for body, if any.
3604
3605       Make_Instance_Unit (Body_Cunit);
3606       Main_Unit_Entity := New_Main;
3607       Set_Cunit_Entity (Main_Unit, Main_Unit_Entity);
3608
3609       --  Build elaboration entity, since the instance may certainly
3610       --  generate elaboration code requiring a flag for protection.
3611
3612       Build_Elaboration_Entity (Decl_Cunit, New_Main);
3613    end Build_Instance_Compilation_Unit_Nodes;
3614
3615    -----------------------------------
3616    -- Check_Formal_Package_Instance --
3617    -----------------------------------
3618
3619    --  If the formal has specific parameters, they must match those of the
3620    --  actual. Both of them are instances, and the renaming declarations
3621    --  for their formal parameters appear in the same order in both. The
3622    --  analyzed formal has been analyzed in the context of the current
3623    --  instance.
3624
3625    procedure Check_Formal_Package_Instance
3626      (Formal_Pack : Entity_Id;
3627       Actual_Pack : Entity_Id)
3628    is
3629       E1 : Entity_Id := First_Entity (Actual_Pack);
3630       E2 : Entity_Id := First_Entity (Formal_Pack);
3631
3632       Expr1 : Node_Id;
3633       Expr2 : Node_Id;
3634
3635       procedure Check_Mismatch (B : Boolean);
3636       --  Common error routine for mismatch between the parameters of
3637       --  the actual instance and those of the formal package.
3638
3639       function Same_Instantiated_Entity (E1, E2 : Entity_Id) return Boolean;
3640       --  The formal may come from a nested formal package, and the actual
3641       --  may have been constant-folded. To determine whether the two denote
3642       --  the same entity we may have to traverse several definitions to
3643       --  recover the ultimate entity that they refer to.
3644
3645       --------------------
3646       -- Check_Mismatch --
3647       --------------------
3648
3649       procedure Check_Mismatch (B : Boolean) is
3650       begin
3651          if B then
3652             Error_Msg_NE
3653               ("actual for & in actual instance does not match formal",
3654                Parent (Actual_Pack), E1);
3655          end if;
3656       end Check_Mismatch;
3657
3658       ------------------------------
3659       -- Same_Instantiated_Entity --
3660       ------------------------------
3661
3662       function Same_Instantiated_Entity (E1, E2 : Entity_Id) return Boolean is
3663          Ent : Entity_Id;
3664
3665       begin
3666          Ent := E2;
3667          while Present (Ent) loop
3668             if E1 = Ent then
3669                return True;
3670
3671             elsif Ekind (Ent) /= E_Constant then
3672                return False;
3673
3674             elsif Is_Entity_Name (Constant_Value (Ent)) then
3675                if  Entity (Constant_Value (Ent)) = E1 then
3676                   return True;
3677                else
3678                   Ent := Entity (Constant_Value (Ent));
3679                end if;
3680
3681             --  The actual may be a constant that has been folded. Recover
3682             --  original name.
3683
3684             elsif Is_Entity_Name (Original_Node (Constant_Value (Ent))) then
3685                   Ent := Entity (Original_Node (Constant_Value (Ent)));
3686             else
3687                return False;
3688             end if;
3689          end loop;
3690
3691          return False;
3692       end Same_Instantiated_Entity;
3693
3694    --  Start of processing for Check_Formal_Package_Instance
3695
3696    begin
3697       while Present (E1)
3698         and then Present (E2)
3699       loop
3700          exit when Ekind (E1) = E_Package
3701            and then Renamed_Entity (E1) = Renamed_Entity (Actual_Pack);
3702
3703          if Is_Type (E1) then
3704
3705             --  Subtypes must statically match. E1 and E2 are the
3706             --  local entities that are subtypes of the actuals.
3707             --  Itypes generated for other parameters need not be checked,
3708             --  the check will be performed on the parameters themselves.
3709
3710             if not Is_Itype (E1)
3711               and then not Is_Itype (E2)
3712             then
3713                Check_Mismatch
3714                  (not Is_Type (E2)
3715                    or else Etype (E1) /= Etype (E2)
3716                    or else not Subtypes_Statically_Match (E1, E2));
3717             end if;
3718
3719          elsif Ekind (E1) = E_Constant then
3720
3721             --  IN parameters must denote the same static value, or
3722             --  the same constant, or the literal null.
3723
3724             Expr1 := Expression (Parent (E1));
3725
3726             if Ekind (E2) /= E_Constant then
3727                Check_Mismatch (True);
3728                goto Next_E;
3729             else
3730                Expr2 := Expression (Parent (E2));
3731             end if;
3732
3733             if Is_Static_Expression (Expr1) then
3734
3735                if not Is_Static_Expression (Expr2) then
3736                   Check_Mismatch (True);
3737
3738                elsif Is_Integer_Type (Etype (E1)) then
3739
3740                   declare
3741                      V1 : constant Uint := Expr_Value (Expr1);
3742                      V2 : constant Uint := Expr_Value (Expr2);
3743                   begin
3744                      Check_Mismatch (V1 /= V2);
3745                   end;
3746
3747                elsif Is_Real_Type (Etype (E1)) then
3748                   declare
3749                      V1 : constant Ureal := Expr_Value_R (Expr1);
3750                      V2 : constant Ureal := Expr_Value_R (Expr2);
3751                   begin
3752                      Check_Mismatch (V1 /= V2);
3753                   end;
3754
3755                elsif Is_String_Type (Etype (E1))
3756                  and then Nkind (Expr1) = N_String_Literal
3757                then
3758
3759                   if Nkind (Expr2) /= N_String_Literal then
3760                      Check_Mismatch (True);
3761                   else
3762                      Check_Mismatch
3763                        (not String_Equal (Strval (Expr1), Strval (Expr2)));
3764                   end if;
3765                end if;
3766
3767             elsif Is_Entity_Name (Expr1) then
3768                if Is_Entity_Name (Expr2) then
3769                   if Entity (Expr1) = Entity (Expr2) then
3770                      null;
3771
3772                   elsif
3773                     Same_Instantiated_Entity (Entity (Expr1), Entity (Expr2))
3774                   then
3775                      null;
3776                   else
3777                      Check_Mismatch (True);
3778                   end if;
3779                else
3780                   Check_Mismatch (True);
3781                end if;
3782
3783             elsif Is_Entity_Name (Original_Node (Expr1))
3784               and then Is_Entity_Name (Expr2)
3785             and then
3786               Same_Instantiated_Entity
3787                 (Entity (Original_Node (Expr1)), Entity (Expr2))
3788             then
3789                null;
3790
3791             elsif Nkind (Expr1) = N_Null then
3792                Check_Mismatch (Nkind (Expr1) /= N_Null);
3793
3794             else
3795                Check_Mismatch (True);
3796             end if;
3797
3798          elsif Ekind (E1) = E_Variable
3799            or else Ekind (E1) = E_Package
3800          then
3801             Check_Mismatch
3802               (Ekind (E1) /= Ekind (E2)
3803                 or else Renamed_Object (E1) /= Renamed_Object (E2));
3804
3805          elsif Is_Overloadable (E1) then
3806
3807             --  Verify that the names of the  entities match.
3808             --  What if actual is an attribute ???
3809
3810             Check_Mismatch
3811               (Ekind (E2) /= Ekind (E1) or else (Alias (E1)) /= Alias (E2));
3812
3813          else
3814             raise Program_Error;
3815          end if;
3816
3817          <<Next_E>>
3818             Next_Entity (E1);
3819             Next_Entity (E2);
3820       end loop;
3821    end Check_Formal_Package_Instance;
3822
3823    ---------------------------
3824    -- Check_Formal_Packages --
3825    ---------------------------
3826
3827    procedure Check_Formal_Packages (P_Id : Entity_Id) is
3828       E        : Entity_Id;
3829       Formal_P : Entity_Id;
3830
3831    begin
3832       --  Iterate through the declarations in the instance, looking for
3833       --  package renaming declarations that denote instances of formal
3834       --  packages. Stop when we find the renaming of the current package
3835       --  itself. The declaration for a formal package without a box is
3836       --  followed by an internal entity that repeats the instantiation.
3837
3838       E := First_Entity (P_Id);
3839       while Present (E) loop
3840          if Ekind (E) = E_Package then
3841             if Renamed_Object (E) = P_Id then
3842                exit;
3843
3844             elsif Nkind (Parent (E)) /= N_Package_Renaming_Declaration then
3845                null;
3846
3847             elsif not Box_Present (Parent (Associated_Formal_Package (E))) then
3848                Formal_P := Next_Entity (E);
3849                Check_Formal_Package_Instance (Formal_P, E);
3850             end if;
3851          end if;
3852
3853          Next_Entity (E);
3854       end loop;
3855    end Check_Formal_Packages;
3856
3857    ---------------------------------
3858    -- Check_Forward_Instantiation --
3859    ---------------------------------
3860
3861    procedure Check_Forward_Instantiation (Decl : Node_Id) is
3862       S        : Entity_Id;
3863       Gen_Comp : Entity_Id := Cunit_Entity (Get_Source_Unit (Decl));
3864
3865    begin
3866       --  The instantiation appears before the generic body if we are in the
3867       --  scope of the unit containing the generic, either in its spec or in
3868       --  the package body. and before the generic body.
3869
3870       if Ekind (Gen_Comp) = E_Package_Body then
3871          Gen_Comp := Spec_Entity (Gen_Comp);
3872       end if;
3873
3874       if In_Open_Scopes (Gen_Comp)
3875         and then No (Corresponding_Body (Decl))
3876       then
3877          S := Current_Scope;
3878
3879          while Present (S)
3880            and then not Is_Compilation_Unit (S)
3881            and then not Is_Child_Unit (S)
3882          loop
3883             if Ekind (S) = E_Package then
3884                Set_Has_Forward_Instantiation (S);
3885             end if;
3886
3887             S := Scope (S);
3888          end loop;
3889       end if;
3890    end Check_Forward_Instantiation;
3891
3892    ---------------------------
3893    -- Check_Generic_Actuals --
3894    ---------------------------
3895
3896    --  The visibility of the actuals may be different between the
3897    --  point of generic instantiation and the instantiation of the body.
3898
3899    procedure Check_Generic_Actuals
3900      (Instance      : Entity_Id;
3901       Is_Formal_Box : Boolean)
3902    is
3903       E      : Entity_Id;
3904       Astype : Entity_Id;
3905
3906    begin
3907       E := First_Entity (Instance);
3908       while Present (E) loop
3909          if Is_Type (E)
3910            and then Nkind (Parent (E)) = N_Subtype_Declaration
3911            and then Scope (Etype (E)) /= Instance
3912            and then Is_Entity_Name (Subtype_Indication (Parent (E)))
3913          then
3914             Check_Private_View (Subtype_Indication (Parent (E)));
3915             Set_Is_Generic_Actual_Type (E, True);
3916             Set_Is_Hidden (E, False);
3917
3918             --  We constructed the generic actual type as a subtype of
3919             --  the supplied type. This means that it normally would not
3920             --  inherit subtype specific attributes of the actual, which
3921             --  is wrong for the generic case.
3922
3923             Astype := Ancestor_Subtype (E);
3924
3925             if No (Astype) then
3926
3927                --  can happen when E is an itype that is the full view of
3928                --  a private type completed, e.g. with a constrained array.
3929
3930                Astype := Base_Type (E);
3931             end if;
3932
3933             Set_Size_Info      (E,                (Astype));
3934             Set_RM_Size        (E, RM_Size        (Astype));
3935             Set_First_Rep_Item (E, First_Rep_Item (Astype));
3936
3937             if Is_Discrete_Or_Fixed_Point_Type (E) then
3938                Set_RM_Size (E, RM_Size (Astype));
3939
3940             --  In  nested instances, the base type of an access actual
3941             --  may itself be private, and need to be exchanged.
3942
3943             elsif Is_Access_Type (E)
3944               and then Is_Private_Type (Etype (E))
3945             then
3946                Check_Private_View
3947                  (New_Occurrence_Of (Etype (E), Sloc (Instance)));
3948             end if;
3949
3950          elsif Ekind (E) = E_Package then
3951
3952             --  If this is the renaming for the current instance, we're done.
3953             --  Otherwise it is a formal package. If the corresponding formal
3954             --  was declared with a box, the (instantiations of the) generic
3955             --  formal part are also visible. Otherwise, ignore the entity
3956             --  created to validate the actuals.
3957
3958             if Renamed_Object (E) = Instance then
3959                exit;
3960
3961             elsif Nkind (Parent (E)) /= N_Package_Renaming_Declaration then
3962                null;
3963
3964             --  The visibility of a formal of an enclosing generic is already
3965             --  correct.
3966
3967             elsif Denotes_Formal_Package (E) then
3968                null;
3969
3970             elsif Present (Associated_Formal_Package (E))
3971               and then Box_Present (Parent (Associated_Formal_Package (E)))
3972             then
3973                Check_Generic_Actuals (Renamed_Object (E), True);
3974                Set_Is_Hidden (E, False);
3975             end if;
3976
3977          --  If this is a subprogram instance (in a wrapper package) the
3978          --  actual is fully visible.
3979
3980          elsif Is_Wrapper_Package (Instance) then
3981             Set_Is_Hidden (E, False);
3982
3983          else
3984             Set_Is_Hidden (E, not Is_Formal_Box);
3985          end if;
3986
3987          Next_Entity (E);
3988       end loop;
3989    end Check_Generic_Actuals;
3990
3991    ------------------------------
3992    -- Check_Generic_Child_Unit --
3993    ------------------------------
3994
3995    procedure Check_Generic_Child_Unit
3996      (Gen_Id           : Node_Id;
3997       Parent_Installed : in out Boolean)
3998    is
3999       Loc      : constant Source_Ptr := Sloc (Gen_Id);
4000       Gen_Par  : Entity_Id := Empty;
4001       Inst_Par : Entity_Id;
4002       E        : Entity_Id;
4003       S        : Node_Id;
4004
4005       function Find_Generic_Child
4006         (Scop : Entity_Id;
4007          Id   : Node_Id)
4008          return Entity_Id;
4009       --  Search generic parent for possible child unit with the given name.
4010
4011       function In_Enclosing_Instance return Boolean;
4012       --  Within an instance of the parent, the child unit may be denoted
4013       --  by a simple name, or an abbreviated expanded name. Examine enclosing
4014       --  scopes to locate a possible parent instantiation.
4015
4016       ------------------------
4017       -- Find_Generic_Child --
4018       ------------------------
4019
4020       function Find_Generic_Child
4021         (Scop : Entity_Id;
4022          Id   : Node_Id)
4023          return Entity_Id
4024       is
4025          E : Entity_Id;
4026
4027       begin
4028          --  If entity of name is already set, instance has already been
4029          --  resolved, e.g. in an enclosing instantiation.
4030
4031          if Present (Entity (Id)) then
4032             if Scope (Entity (Id)) = Scop then
4033                return Entity (Id);
4034             else
4035                return Empty;
4036             end if;
4037
4038          else
4039             E := First_Entity (Scop);
4040             while Present (E) loop
4041                if Chars (E) = Chars (Id)
4042                  and then Is_Child_Unit (E)
4043                then
4044                   if Is_Child_Unit (E)
4045                     and then not Is_Visible_Child_Unit (E)
4046                   then
4047                      Error_Msg_NE
4048                        ("generic child unit& is not visible", Gen_Id, E);
4049                   end if;
4050
4051                   Set_Entity (Id, E);
4052                   return E;
4053                end if;
4054
4055                Next_Entity (E);
4056             end loop;
4057
4058             return Empty;
4059          end if;
4060       end Find_Generic_Child;
4061
4062       ---------------------------
4063       -- In_Enclosing_Instance --
4064       ---------------------------
4065
4066       function In_Enclosing_Instance return Boolean is
4067          Enclosing_Instance : Node_Id;
4068          Instance_Decl      : Node_Id;
4069
4070       begin
4071          Enclosing_Instance := Current_Scope;
4072
4073          while Present (Enclosing_Instance) loop
4074             Instance_Decl := Unit_Declaration_Node (Enclosing_Instance);
4075
4076             if Ekind (Enclosing_Instance) = E_Package
4077               and then Is_Generic_Instance (Enclosing_Instance)
4078               and then Present
4079                 (Generic_Parent (Specification (Instance_Decl)))
4080             then
4081                --  Check whether the generic we are looking for is a child
4082                --  of this instance.
4083
4084                E := Find_Generic_Child
4085                       (Generic_Parent (Specification (Instance_Decl)), Gen_Id);
4086                exit when Present (E);
4087
4088             else
4089                E := Empty;
4090             end if;
4091
4092             Enclosing_Instance := Scope (Enclosing_Instance);
4093          end loop;
4094
4095          if No (E) then
4096
4097             --  Not a child unit
4098
4099             Analyze (Gen_Id);
4100             return False;
4101
4102          else
4103             Rewrite (Gen_Id,
4104               Make_Expanded_Name (Loc,
4105                 Chars         => Chars (E),
4106                 Prefix        => New_Occurrence_Of (Enclosing_Instance, Loc),
4107                 Selector_Name => New_Occurrence_Of (E, Loc)));
4108
4109             Set_Entity (Gen_Id, E);
4110             Set_Etype  (Gen_Id, Etype (E));
4111             Parent_Installed := False;      -- Already in scope.
4112             return True;
4113          end if;
4114       end In_Enclosing_Instance;
4115
4116    --  Start of processing for Check_Generic_Child_Unit
4117
4118    begin
4119       --  If the name of the generic is given by a selected component, it
4120       --  may be the name of a generic child unit, and the prefix is the name
4121       --  of an instance of the parent, in which case the child unit must be
4122       --  visible. If this instance is not in scope, it must be placed there
4123       --  and removed after instantiation, because what is being instantiated
4124       --  is not the original child, but the corresponding child present in
4125       --  the instance of the parent.
4126
4127       --  If the child is instantiated within the parent, it can be given by
4128       --  a simple name. In this case the instance is already in scope, but
4129       --  the child generic must be recovered from the generic parent as well.
4130
4131       if Nkind (Gen_Id) = N_Selected_Component then
4132          S := Selector_Name (Gen_Id);
4133          Analyze (Prefix (Gen_Id));
4134          Inst_Par := Entity (Prefix (Gen_Id));
4135
4136          if Ekind (Inst_Par) = E_Package
4137            and then Present (Renamed_Object (Inst_Par))
4138          then
4139             Inst_Par := Renamed_Object (Inst_Par);
4140          end if;
4141
4142          if Ekind (Inst_Par) = E_Package then
4143             if Nkind (Parent (Inst_Par)) = N_Package_Specification then
4144                Gen_Par := Generic_Parent (Parent (Inst_Par));
4145
4146             elsif Nkind (Parent (Inst_Par)) = N_Defining_Program_Unit_Name
4147               and then
4148                 Nkind (Parent (Parent (Inst_Par))) = N_Package_Specification
4149             then
4150                Gen_Par := Generic_Parent (Parent (Parent (Inst_Par)));
4151             end if;
4152
4153          elsif Ekind (Inst_Par) = E_Generic_Package
4154            and then Nkind (Parent (Gen_Id)) = N_Formal_Package_Declaration
4155          then
4156             --  A formal package may be a real child package, and not the
4157             --  implicit instance within a parent. In this case the child is
4158             --  not visible and has to be retrieved explicitly as well.
4159
4160             Gen_Par := Inst_Par;
4161          end if;
4162
4163          if Present (Gen_Par) then
4164
4165             --  The prefix denotes an instantiation. The entity itself
4166             --  may be a nested generic, or a child unit.
4167
4168             E := Find_Generic_Child (Gen_Par, S);
4169
4170             if Present (E) then
4171                Change_Selected_Component_To_Expanded_Name (Gen_Id);
4172                Set_Entity (Gen_Id, E);
4173                Set_Etype (Gen_Id, Etype (E));
4174                Set_Entity (S, E);
4175                Set_Etype (S, Etype (E));
4176
4177                --  Indicate that this is a reference to the parent.
4178
4179                if In_Extended_Main_Source_Unit (Gen_Id) then
4180                   Set_Is_Instantiated (Inst_Par);
4181                end if;
4182
4183                --  A common mistake is to replicate the naming scheme of
4184                --  a hierarchy by instantiating a generic child directly,
4185                --  rather than the implicit child in a parent instance:
4186
4187                --  generic .. package Gpar is ..
4188                --  generic .. package Gpar.Child is ..
4189                --  package Par is new Gpar ();
4190
4191                --  with Gpar.Child;
4192                --  package Par.Child is new Gpar.Child ();
4193                --                           rather than Par.Child
4194
4195                --  In this case the instantiation is within Par, which is
4196                --  an instance, but Gpar does not denote Par because we are
4197                --  not IN the instance of Gpar, so this is illegal. The test
4198                --  below recognizes this particular case.
4199
4200                if Is_Child_Unit (E)
4201                  and then not Comes_From_Source (Entity (Prefix (Gen_Id)))
4202                  and then (not In_Instance
4203                              or else Nkind (Parent (Parent (Gen_Id))) =
4204                                                          N_Compilation_Unit)
4205                then
4206                   Error_Msg_N
4207                     ("prefix of generic child unit must be instance of parent",
4208                       Gen_Id);
4209                end if;
4210
4211                if not In_Open_Scopes (Inst_Par)
4212                  and then Nkind (Parent (Gen_Id)) not in
4213                                            N_Generic_Renaming_Declaration
4214                then
4215                   Install_Parent (Inst_Par);
4216                   Parent_Installed := True;
4217                end if;
4218
4219             else
4220                --  If the generic parent does not contain an entity that
4221                --  corresponds to the selector, the instance doesn't either.
4222                --  Analyzing the node will yield the appropriate error message.
4223                --  If the entity is not a child unit, then it is an inner
4224                --  generic in the parent.
4225
4226                Analyze (Gen_Id);
4227             end if;
4228
4229          else
4230             Analyze (Gen_Id);
4231
4232             if Is_Child_Unit (Entity (Gen_Id))
4233               and then
4234                 Nkind (Parent (Gen_Id)) not in N_Generic_Renaming_Declaration
4235               and then not In_Open_Scopes (Inst_Par)
4236             then
4237                Install_Parent (Inst_Par);
4238                Parent_Installed := True;
4239             end if;
4240          end if;
4241
4242       elsif Nkind (Gen_Id) = N_Expanded_Name then
4243
4244          --  Entity already present, analyze prefix, whose meaning may be
4245          --  an instance in the current context. If it is an instance of
4246          --  a relative within another, the proper parent may still have
4247          --  to be installed, if they are not of the same generation.
4248
4249          Analyze (Prefix (Gen_Id));
4250          Inst_Par := Entity (Prefix (Gen_Id));
4251
4252          if In_Enclosing_Instance then
4253             null;
4254
4255          elsif Present (Entity (Gen_Id))
4256            and then Is_Child_Unit (Entity (Gen_Id))
4257            and then not In_Open_Scopes (Inst_Par)
4258          then
4259             Install_Parent (Inst_Par);
4260             Parent_Installed := True;
4261          end if;
4262
4263       elsif In_Enclosing_Instance then
4264
4265          --  The child unit is found in some enclosing scope
4266
4267          null;
4268
4269       else
4270          Analyze (Gen_Id);
4271
4272          --  If this is the renaming of the implicit child in a parent
4273          --  instance, recover the parent name and install it.
4274
4275          if Is_Entity_Name (Gen_Id) then
4276             E := Entity (Gen_Id);
4277
4278             if Is_Generic_Unit (E)
4279               and then Nkind (Parent (E)) in N_Generic_Renaming_Declaration
4280               and then Is_Child_Unit (Renamed_Object (E))
4281               and then Is_Generic_Unit (Scope (Renamed_Object (E)))
4282               and then Nkind (Name (Parent (E))) = N_Expanded_Name
4283             then
4284                Rewrite (Gen_Id,
4285                  New_Copy_Tree (Name (Parent (E))));
4286                Inst_Par := Entity (Prefix (Gen_Id));
4287
4288                if not In_Open_Scopes (Inst_Par) then
4289                   Install_Parent (Inst_Par);
4290                   Parent_Installed := True;
4291                end if;
4292
4293             --  If it is a child unit of a non-generic parent, it may be
4294             --  use-visible and given by a direct name. Install parent as
4295             --  for other cases.
4296
4297             elsif Is_Generic_Unit (E)
4298               and then Is_Child_Unit (E)
4299               and then
4300                 Nkind (Parent (Gen_Id)) not in N_Generic_Renaming_Declaration
4301               and then not Is_Generic_Unit (Scope (E))
4302             then
4303                if not In_Open_Scopes (Scope (E)) then
4304                   Install_Parent (Scope (E));
4305                   Parent_Installed := True;
4306                end if;
4307             end if;
4308          end if;
4309       end if;
4310    end Check_Generic_Child_Unit;
4311
4312    -----------------------------
4313    -- Check_Hidden_Child_Unit --
4314    -----------------------------
4315
4316    procedure Check_Hidden_Child_Unit
4317      (N           : Node_Id;
4318       Gen_Unit    : Entity_Id;
4319       Act_Decl_Id : Entity_Id)
4320    is
4321       Gen_Id : constant Node_Id := Name (N);
4322
4323    begin
4324       if Is_Child_Unit (Gen_Unit)
4325         and then Is_Child_Unit (Act_Decl_Id)
4326         and then Nkind (Gen_Id) = N_Expanded_Name
4327         and then Entity (Prefix (Gen_Id)) = Scope (Act_Decl_Id)
4328         and then Chars (Gen_Unit) = Chars (Act_Decl_Id)
4329       then
4330          Error_Msg_Node_2 := Scope (Act_Decl_Id);
4331          Error_Msg_NE
4332            ("generic unit & is implicitly declared in &",
4333              Defining_Unit_Name (N), Gen_Unit);
4334          Error_Msg_N ("\instance must have different name",
4335            Defining_Unit_Name (N));
4336       end if;
4337    end Check_Hidden_Child_Unit;
4338
4339    ------------------------
4340    -- Check_Private_View --
4341    ------------------------
4342
4343    procedure Check_Private_View (N : Node_Id) is
4344       T : constant Entity_Id := Etype (N);
4345       BT : Entity_Id;
4346
4347    begin
4348       --  Exchange views if the type was not private in the generic but is
4349       --  private at the point of instantiation. Do not exchange views if
4350       --  the scope of the type is in scope. This can happen if both generic
4351       --  and instance are sibling units, or if type is defined in a parent.
4352       --  In this case the visibility of the type will be correct for all
4353       --  semantic checks.
4354
4355       if Present (T) then
4356          BT := Base_Type (T);
4357
4358          if Is_Private_Type (T)
4359            and then not Has_Private_View (N)
4360            and then Present (Full_View (T))
4361            and then not In_Open_Scopes (Scope (T))
4362          then
4363             --  In the generic, the full type was visible. Save the
4364             --  private entity, for subsequent exchange.
4365
4366             Switch_View (T);
4367
4368          elsif Has_Private_View (N)
4369            and then not Is_Private_Type (T)
4370            and then not Has_Been_Exchanged (T)
4371            and then Etype (Get_Associated_Node (N)) /= T
4372          then
4373             --  Only the private declaration was visible in the generic. If
4374             --  the type appears in a subtype declaration, the subtype in the
4375             --  instance must have a view compatible with that of its parent,
4376             --  which must be exchanged (see corresponding code in Restore_
4377             --  Private_Views). Otherwise, if the type is defined in a parent
4378             --  unit, leave full visibility within instance, which is safe.
4379
4380             if In_Open_Scopes (Scope (Base_Type (T)))
4381               and then not Is_Private_Type (Base_Type (T))
4382               and then Comes_From_Source (Base_Type (T))
4383             then
4384                null;
4385
4386             elsif Nkind (Parent (N)) = N_Subtype_Declaration
4387               or else not In_Private_Part (Scope (Base_Type (T)))
4388             then
4389                Append_Elmt (T, Exchanged_Views);
4390                Exchange_Declarations (Etype (Get_Associated_Node (N)));
4391             end if;
4392
4393          --  For composite types with inconsistent representation
4394          --  exchange component types accordingly.
4395
4396          elsif Is_Access_Type (T)
4397            and then Is_Private_Type (Designated_Type (T))
4398            and then not Has_Private_View (N)
4399            and then Present (Full_View (Designated_Type (T)))
4400          then
4401             Switch_View (Designated_Type (T));
4402
4403          elsif Is_Array_Type (T)
4404            and then Is_Private_Type (Component_Type (T))
4405            and then not Has_Private_View (N)
4406            and then Present (Full_View (Component_Type (T)))
4407          then
4408             Switch_View (Component_Type (T));
4409
4410          elsif Is_Private_Type (T)
4411            and then Present (Full_View (T))
4412            and then Is_Array_Type (Full_View (T))
4413            and then Is_Private_Type (Component_Type (Full_View (T)))
4414          then
4415             Switch_View (T);
4416
4417          --  Finally, a non-private subtype may have a private base type,
4418          --  which must be exchanged for consistency. This can happen when
4419          --  instantiating a package body, when the scope stack is empty
4420          --  but in fact the subtype and the base type are declared in an
4421          --  enclosing scope.
4422
4423          elsif not Is_Private_Type (T)
4424            and then not Has_Private_View (N)
4425            and then Is_Private_Type (Base_Type (T))
4426            and then Present (Full_View (BT))
4427            and then not Is_Generic_Type (BT)
4428            and then not In_Open_Scopes (BT)
4429          then
4430             Append_Elmt (Full_View (BT), Exchanged_Views);
4431             Exchange_Declarations (BT);
4432          end if;
4433       end if;
4434    end Check_Private_View;
4435
4436    --------------------------
4437    -- Contains_Instance_Of --
4438    --------------------------
4439
4440    function Contains_Instance_Of
4441      (Inner : Entity_Id;
4442       Outer : Entity_Id;
4443       N     : Node_Id)
4444       return  Boolean
4445    is
4446       Elmt : Elmt_Id;
4447       Scop : Entity_Id;
4448
4449    begin
4450       Scop := Outer;
4451
4452       --  Verify that there are no circular instantiations. We check whether
4453       --  the unit contains an instance of the current scope or some enclosing
4454       --  scope (in case one of the instances appears in a subunit). Longer
4455       --  circularities involving subunits might seem too pathological to
4456       --  consider, but they were not too pathological for the authors of
4457       --  DEC bc30vsq, so we loop over all enclosing scopes, and mark all
4458       --  enclosing generic scopes as containing an instance.
4459
4460       loop
4461          --  Within a generic subprogram body, the scope is not generic, to
4462          --  allow for recursive subprograms. Use the declaration to determine
4463          --  whether this is a generic unit.
4464
4465          if Ekind (Scop) = E_Generic_Package
4466            or else (Is_Subprogram (Scop)
4467                       and then Nkind (Unit_Declaration_Node (Scop)) =
4468                                         N_Generic_Subprogram_Declaration)
4469          then
4470             Elmt := First_Elmt (Inner_Instances (Inner));
4471
4472             while Present (Elmt) loop
4473                if Node (Elmt) = Scop then
4474                   Error_Msg_Node_2 := Inner;
4475                   Error_Msg_NE
4476                     ("circular Instantiation: & instantiated within &!",
4477                        N, Scop);
4478                   return True;
4479
4480                elsif Node (Elmt) = Inner then
4481                   return True;
4482
4483                elsif Contains_Instance_Of (Node (Elmt), Scop, N) then
4484                   Error_Msg_Node_2 := Inner;
4485                   Error_Msg_NE
4486                     ("circular Instantiation: & instantiated within &!",
4487                       N, Node (Elmt));
4488                   return True;
4489                end if;
4490
4491                Next_Elmt (Elmt);
4492             end loop;
4493
4494             --  Indicate that Inner is being instantiated within  Scop.
4495
4496             Append_Elmt (Inner, Inner_Instances (Scop));
4497          end if;
4498
4499          if Scop = Standard_Standard then
4500             exit;
4501          else
4502             Scop := Scope (Scop);
4503          end if;
4504       end loop;
4505
4506       return False;
4507    end Contains_Instance_Of;
4508
4509    -----------------------
4510    -- Copy_Generic_Node --
4511    -----------------------
4512
4513    function Copy_Generic_Node
4514      (N             : Node_Id;
4515       Parent_Id     : Node_Id;
4516       Instantiating : Boolean)
4517       return          Node_Id
4518    is
4519       Ent   : Entity_Id;
4520       New_N : Node_Id;
4521
4522       function Copy_Generic_Descendant (D : Union_Id) return Union_Id;
4523       --  Check the given value of one of the Fields referenced by the
4524       --  current node to determine whether to copy it recursively. The
4525       --  field may hold a Node_Id, a List_Id, or an Elist_Id, or a plain
4526       --  value (Sloc, Uint, Char) in which case it need not be copied.
4527
4528       procedure Copy_Descendants;
4529       --  Common utility for various nodes.
4530
4531       function Copy_Generic_Elist (E : Elist_Id) return Elist_Id;
4532       --  Make copy of element list.
4533
4534       function Copy_Generic_List
4535         (L         : List_Id;
4536          Parent_Id : Node_Id)
4537          return      List_Id;
4538       --  Apply Copy_Node recursively to the members of a node list.
4539
4540       function In_Defining_Unit_Name (Nam : Node_Id) return Boolean;
4541       --  True if an identifier is part of the defining program unit name
4542       --  of a child unit. The entity of such an identifier must be kept
4543       --  (for ASIS use) even though as the name of an enclosing generic
4544       --   it would otherwise not be preserved in the generic tree.
4545
4546       -----------------------
4547       --  Copy_Descendants --
4548       -----------------------
4549
4550       procedure Copy_Descendants is
4551
4552          use Atree.Unchecked_Access;
4553          --  This code section is part of the implementation of an untyped
4554          --  tree traversal, so it needs direct access to node fields.
4555
4556       begin
4557          Set_Field1 (New_N, Copy_Generic_Descendant (Field1 (N)));
4558          Set_Field2 (New_N, Copy_Generic_Descendant (Field2 (N)));
4559          Set_Field3 (New_N, Copy_Generic_Descendant (Field3 (N)));
4560          Set_Field4 (New_N, Copy_Generic_Descendant (Field4 (N)));
4561          Set_Field5 (New_N, Copy_Generic_Descendant (Field5 (N)));
4562       end Copy_Descendants;
4563
4564       -----------------------------
4565       -- Copy_Generic_Descendant --
4566       -----------------------------
4567
4568       function Copy_Generic_Descendant (D : Union_Id) return Union_Id is
4569       begin
4570          if D = Union_Id (Empty) then
4571             return D;
4572
4573          elsif D in Node_Range then
4574             return Union_Id
4575               (Copy_Generic_Node (Node_Id (D), New_N, Instantiating));
4576
4577          elsif D in List_Range then
4578             return Union_Id (Copy_Generic_List (List_Id (D), New_N));
4579
4580          elsif D in Elist_Range then
4581             return Union_Id (Copy_Generic_Elist (Elist_Id (D)));
4582
4583          --  Nothing else is copyable (e.g. Uint values), return as is
4584
4585          else
4586             return D;
4587          end if;
4588       end Copy_Generic_Descendant;
4589
4590       ------------------------
4591       -- Copy_Generic_Elist --
4592       ------------------------
4593
4594       function Copy_Generic_Elist (E : Elist_Id) return Elist_Id is
4595          M : Elmt_Id;
4596          L : Elist_Id;
4597
4598       begin
4599          if Present (E) then
4600             L := New_Elmt_List;
4601             M := First_Elmt (E);
4602             while Present (M) loop
4603                Append_Elmt
4604                  (Copy_Generic_Node (Node (M), Empty, Instantiating), L);
4605                Next_Elmt (M);
4606             end loop;
4607
4608             return L;
4609
4610          else
4611             return No_Elist;
4612          end if;
4613       end Copy_Generic_Elist;
4614
4615       -----------------------
4616       -- Copy_Generic_List --
4617       -----------------------
4618
4619       function Copy_Generic_List
4620         (L         : List_Id;
4621          Parent_Id : Node_Id)
4622          return      List_Id
4623       is
4624          N     : Node_Id;
4625          New_L : List_Id;
4626
4627       begin
4628          if Present (L) then
4629             New_L := New_List;
4630             Set_Parent (New_L, Parent_Id);
4631
4632             N := First (L);
4633             while Present (N) loop
4634                Append (Copy_Generic_Node (N, Empty, Instantiating), New_L);
4635                Next (N);
4636             end loop;
4637
4638             return New_L;
4639
4640          else
4641             return No_List;
4642          end if;
4643       end Copy_Generic_List;
4644
4645       ---------------------------
4646       -- In_Defining_Unit_Name --
4647       ---------------------------
4648
4649       function In_Defining_Unit_Name (Nam : Node_Id) return Boolean is
4650       begin
4651          return Present (Parent (Nam))
4652            and then (Nkind (Parent (Nam)) = N_Defining_Program_Unit_Name
4653                       or else
4654                         (Nkind (Parent (Nam)) = N_Expanded_Name
4655                           and then In_Defining_Unit_Name (Parent (Nam))));
4656       end In_Defining_Unit_Name;
4657
4658    --  Start of processing for Copy_Generic_Node
4659
4660    begin
4661       if N = Empty then
4662          return N;
4663       end if;
4664
4665       New_N := New_Copy (N);
4666
4667       if Instantiating then
4668          Adjust_Instantiation_Sloc (New_N, S_Adjustment);
4669       end if;
4670
4671       if not Is_List_Member (N) then
4672          Set_Parent (New_N, Parent_Id);
4673       end if;
4674
4675       --  If defining identifier, then all fields have been copied already
4676
4677       if Nkind (New_N) in N_Entity then
4678          null;
4679
4680       --  Special casing for identifiers and other entity names and operators
4681
4682       elsif     Nkind (New_N) = N_Identifier
4683         or else Nkind (New_N) = N_Character_Literal
4684         or else Nkind (New_N) = N_Expanded_Name
4685         or else Nkind (New_N) = N_Operator_Symbol
4686         or else Nkind (New_N) in N_Op
4687       then
4688          if not Instantiating then
4689
4690             --  Link both nodes in order to assign subsequently the
4691             --  entity of the copy to the original node, in case this
4692             --  is a global reference.
4693
4694             Set_Associated_Node (N, New_N);
4695
4696             --  If we are within an instantiation, this is a nested generic
4697             --  that has already been analyzed at the point of definition. We
4698             --  must preserve references that were global to the enclosing
4699             --  parent at that point. Other occurrences, whether global or
4700             --  local to the current generic, must be resolved anew, so we
4701             --  reset the entity in the generic copy. A global reference has
4702             --  a smaller depth than the parent, or else the same depth in
4703             --  case both are distinct compilation units.
4704
4705             --  It is also possible for Current_Instantiated_Parent to be
4706             --  defined, and for this not to be a nested generic, namely
4707             --  if the unit is loaded through Rtsfind. In that case, the
4708             --  entity of New_N is only a link to the associated node, and
4709             --  not a defining occurrence.
4710
4711             --  The entities for parent units in the defining_program_unit
4712             --  of a generic child unit are established when the context of
4713             --  the unit is first analyzed, before the generic copy is made.
4714             --  They are preserved in the copy for use in ASIS queries.
4715
4716             Ent := Entity (New_N);
4717
4718             if No (Current_Instantiated_Parent.Gen_Id) then
4719                if No (Ent)
4720                  or else Nkind (Ent) /= N_Defining_Identifier
4721                  or else not In_Defining_Unit_Name (N)
4722                then
4723                   Set_Associated_Node (New_N, Empty);
4724                end if;
4725
4726             elsif No (Ent)
4727               or else
4728                 not (Nkind (Ent) = N_Defining_Identifier
4729                        or else
4730                      Nkind (Ent) = N_Defining_Character_Literal
4731                        or else
4732                      Nkind (Ent) = N_Defining_Operator_Symbol)
4733               or else No (Scope (Ent))
4734               or else Scope (Ent) = Current_Instantiated_Parent.Gen_Id
4735               or else (Scope_Depth (Scope (Ent)) >
4736                              Scope_Depth (Current_Instantiated_Parent.Gen_Id)
4737                          and then
4738                        Get_Source_Unit (Ent) =
4739                        Get_Source_Unit (Current_Instantiated_Parent.Gen_Id))
4740             then
4741                Set_Associated_Node (New_N, Empty);
4742             end if;
4743
4744          --  Case of instantiating identifier or some other name or operator
4745
4746          else
4747             --  If the associated node is still defined, the entity in
4748             --  it is global, and must be copied to the instance.
4749             --  If this copy is being made for a body to inline, it is
4750             --  applied to an instantiated tree, and the entity is already
4751             --  present and must be also preserved.
4752
4753             declare
4754                Assoc : constant Node_Id := Get_Associated_Node (N);
4755             begin
4756                if Present (Assoc) then
4757                   if Nkind (Assoc) = Nkind (N) then
4758                      Set_Entity (New_N, Entity (Assoc));
4759                      Check_Private_View (N);
4760
4761                   elsif Nkind (Assoc) = N_Function_Call then
4762                      Set_Entity (New_N, Entity (Name (Assoc)));
4763
4764                   elsif (Nkind (Assoc) = N_Defining_Identifier
4765                           or else Nkind (Assoc) = N_Defining_Character_Literal
4766                           or else Nkind (Assoc) = N_Defining_Operator_Symbol)
4767                     and then Expander_Active
4768                   then
4769                      --  Inlining case: we are copying a tree that contains
4770                      --  global entities, which are preserved in the copy
4771                      --  to be used for subsequent inlining.
4772
4773                      null;
4774
4775                   else
4776                      Set_Entity (New_N, Empty);
4777                   end if;
4778                end if;
4779             end;
4780          end if;
4781
4782          --  For expanded name, we must copy the Prefix and Selector_Name
4783
4784          if Nkind (N) = N_Expanded_Name then
4785             Set_Prefix
4786               (New_N, Copy_Generic_Node (Prefix (N), New_N, Instantiating));
4787
4788             Set_Selector_Name (New_N,
4789               Copy_Generic_Node (Selector_Name (N), New_N, Instantiating));
4790
4791          --  For operators, we must copy the right operand
4792
4793          elsif Nkind (N) in N_Op then
4794             Set_Right_Opnd (New_N,
4795               Copy_Generic_Node (Right_Opnd (N), New_N, Instantiating));
4796
4797             --  And for binary operators, the left operand as well
4798
4799             if Nkind (N) in N_Binary_Op then
4800                Set_Left_Opnd (New_N,
4801                  Copy_Generic_Node (Left_Opnd (N), New_N, Instantiating));
4802             end if;
4803          end if;
4804
4805       --  Special casing for stubs
4806
4807       elsif Nkind (N) in N_Body_Stub then
4808
4809          --  In any case, we must copy the specification or defining
4810          --  identifier as appropriate.
4811
4812          if Nkind (N) = N_Subprogram_Body_Stub then
4813             Set_Specification (New_N,
4814               Copy_Generic_Node (Specification (N), New_N, Instantiating));
4815
4816          else
4817             Set_Defining_Identifier (New_N,
4818               Copy_Generic_Node
4819                 (Defining_Identifier (N), New_N, Instantiating));
4820          end if;
4821
4822          --  If we are not instantiating, then this is where we load and
4823          --  analyze subunits, i.e. at the point where the stub occurs. A
4824          --  more permissivle system might defer this analysis to the point
4825          --  of instantiation, but this seems to complicated for now.
4826
4827          if not Instantiating then
4828             declare
4829                Subunit_Name : constant Unit_Name_Type := Get_Unit_Name (N);
4830                Subunit      : Node_Id;
4831                Unum         : Unit_Number_Type;
4832                New_Body     : Node_Id;
4833
4834             begin
4835                Unum :=
4836                  Load_Unit
4837                    (Load_Name  => Subunit_Name,
4838                     Required   => False,
4839                     Subunit    => True,
4840                     Error_Node => N);
4841
4842                --  If the proper body is not found, a warning message will
4843                --  be emitted when analyzing the stub, or later at the the
4844                --  point of instantiation. Here we just leave the stub as is.
4845
4846                if Unum = No_Unit then
4847                   Subunits_Missing := True;
4848                   goto Subunit_Not_Found;
4849                end if;
4850
4851                Subunit := Cunit (Unum);
4852
4853                if Nkind (Unit (Subunit)) /= N_Subunit then
4854                   Error_Msg_Sloc := Sloc (N);
4855                   Error_Msg_N
4856                     ("expected SEPARATE subunit to complete stub at#,"
4857                        & " found child unit", Subunit);
4858                   goto Subunit_Not_Found;
4859                end if;
4860
4861                --  We must create a generic copy of the subunit, in order
4862                --  to perform semantic analysis on it, and we must replace
4863                --  the stub in the original generic unit with the subunit,
4864                --  in order to preserve non-local references within.
4865
4866                --  Only the proper body needs to be copied. Library_Unit and
4867                --  context clause are simply inherited by the generic copy.
4868                --  Note that the copy (which may be recursive if there are
4869                --  nested subunits) must be done first, before attaching it
4870                --  to the enclosing generic.
4871
4872                New_Body :=
4873                  Copy_Generic_Node
4874                    (Proper_Body (Unit (Subunit)),
4875                     Empty, Instantiating => False);
4876
4877                --  Now place the original proper body in the original
4878                --  generic unit. This is a body, not a compilation unit.
4879
4880                Rewrite (N, Proper_Body (Unit (Subunit)));
4881                Set_Is_Compilation_Unit (Defining_Entity (N), False);
4882                Set_Was_Originally_Stub (N);
4883
4884                --  Finally replace the body of the subunit with its copy,
4885                --  and make this new subunit into the library unit of the
4886                --  generic copy, which does not have stubs any longer.
4887
4888                Set_Proper_Body (Unit (Subunit), New_Body);
4889                Set_Library_Unit (New_N, Subunit);
4890                Inherit_Context (Unit (Subunit), N);
4891             end;
4892
4893          --  If we are instantiating, this must be an error case, since
4894          --  otherwise we would have replaced the stub node by the proper
4895          --  body that corresponds. So just ignore it in the copy (i.e.
4896          --  we have copied it, and that is good enough).
4897
4898          else
4899             null;
4900          end if;
4901
4902          <<Subunit_Not_Found>> null;
4903
4904       --  If the node is a compilation unit, it is the subunit of a stub,
4905       --  which has been loaded already (see code below). In this case,
4906       --  the library unit field of N points to the parent unit (which
4907       --  is a compilation unit) and need not (and cannot!) be copied.
4908
4909       --  When the proper body of the stub is analyzed, thie library_unit
4910       --  link is used to establish the proper context (see sem_ch10).
4911
4912       --  The other fields of a compilation unit are copied as usual
4913
4914       elsif Nkind (N) = N_Compilation_Unit then
4915
4916          --  This code can only be executed when not instantiating, because
4917          --  in the copy made for an instantiation, the compilation unit
4918          --  node has disappeared at the point that a stub is replaced by
4919          --  its proper body.
4920
4921          pragma Assert (not Instantiating);
4922
4923          Set_Context_Items (New_N,
4924            Copy_Generic_List (Context_Items (N), New_N));
4925
4926          Set_Unit (New_N,
4927            Copy_Generic_Node (Unit (N), New_N, False));
4928
4929          Set_First_Inlined_Subprogram (New_N,
4930            Copy_Generic_Node
4931              (First_Inlined_Subprogram (N), New_N, False));
4932
4933          Set_Aux_Decls_Node (New_N,
4934            Copy_Generic_Node (Aux_Decls_Node (N), New_N, False));
4935
4936       --  For an assignment node, the assignment is known to be semantically
4937       --  legal if we are instantiating the template. This avoids incorrect
4938       --  diagnostics in generated code.
4939
4940       elsif Nkind (N) = N_Assignment_Statement then
4941
4942          --  Copy name and expression fields in usual manner
4943
4944          Set_Name (New_N,
4945            Copy_Generic_Node (Name (N), New_N, Instantiating));
4946
4947          Set_Expression (New_N,
4948            Copy_Generic_Node (Expression (N), New_N, Instantiating));
4949
4950          if Instantiating then
4951             Set_Assignment_OK (Name (New_N), True);
4952          end if;
4953
4954       elsif Nkind (N) = N_Aggregate
4955               or else Nkind (N) = N_Extension_Aggregate
4956       then
4957
4958          if not Instantiating then
4959             Set_Associated_Node (N, New_N);
4960
4961          else
4962             if Present (Get_Associated_Node (N))
4963               and then Nkind (Get_Associated_Node (N)) = Nkind (N)
4964             then
4965                --  In the generic the aggregate has some composite type. If at
4966                --  the point of instantiation the type has a private view,
4967                --  install the full view (and that of its ancestors, if any).
4968
4969                declare
4970                   T   : Entity_Id := (Etype (Get_Associated_Node (New_N)));
4971                   Rt  : Entity_Id;
4972
4973                begin
4974                   if Present (T)
4975                     and then Is_Private_Type (T)
4976                   then
4977                      Switch_View (T);
4978                   end if;
4979
4980                   if Present (T)
4981                     and then Is_Tagged_Type (T)
4982                     and then Is_Derived_Type (T)
4983                   then
4984                      Rt := Root_Type (T);
4985
4986                      loop
4987                         T := Etype (T);
4988
4989                         if Is_Private_Type (T) then
4990                            Switch_View (T);
4991                         end if;
4992
4993                         exit when T = Rt;
4994                      end loop;
4995                   end if;
4996                end;
4997             end if;
4998          end if;
4999
5000          --  Do not copy the associated node, which points to
5001          --  the generic copy of the aggregate.
5002
5003          declare
5004             use Atree.Unchecked_Access;
5005             --  This code section is part of the implementation of an untyped
5006             --  tree traversal, so it needs direct access to node fields.
5007
5008          begin
5009             Set_Field1 (New_N, Copy_Generic_Descendant (Field1 (N)));
5010             Set_Field2 (New_N, Copy_Generic_Descendant (Field2 (N)));
5011             Set_Field3 (New_N, Copy_Generic_Descendant (Field3 (N)));
5012             Set_Field5 (New_N, Copy_Generic_Descendant (Field5 (N)));
5013          end;
5014
5015       --  Allocators do not have an identifier denoting the access type,
5016       --  so we must locate it through the expression to check whether
5017       --  the views are consistent.
5018
5019       elsif Nkind (N) = N_Allocator
5020         and then Nkind (Expression (N)) = N_Qualified_Expression
5021         and then Is_Entity_Name (Subtype_Mark (Expression (N)))
5022         and then Instantiating
5023       then
5024          declare
5025             T     : constant Node_Id :=
5026                       Get_Associated_Node (Subtype_Mark (Expression (N)));
5027             Acc_T : Entity_Id;
5028
5029          begin
5030             if Present (T) then
5031                --  Retrieve the allocator node in the generic copy.
5032
5033                Acc_T := Etype (Parent (Parent (T)));
5034                if Present (Acc_T)
5035                  and then Is_Private_Type (Acc_T)
5036                then
5037                   Switch_View (Acc_T);
5038                end if;
5039             end if;
5040
5041             Copy_Descendants;
5042          end;
5043
5044       --  For a proper body, we must catch the case of a proper body that
5045       --  replaces a stub. This represents the point at which a separate
5046       --  compilation unit, and hence template file, may be referenced, so
5047       --  we must make a new source instantiation entry for the template
5048       --  of the subunit, and ensure that all nodes in the subunit are
5049       --  adjusted using this new source instantiation entry.
5050
5051       elsif Nkind (N) in N_Proper_Body then
5052          declare
5053             Save_Adjustment : constant Sloc_Adjustment := S_Adjustment;
5054
5055          begin
5056             if Instantiating and then Was_Originally_Stub (N) then
5057                Create_Instantiation_Source
5058                  (Instantiation_Node,
5059                   Defining_Entity (N),
5060                   False,
5061                   S_Adjustment);
5062             end if;
5063
5064             --  Now copy the fields of the proper body, using the new
5065             --  adjustment factor if one was needed as per test above.
5066
5067             Copy_Descendants;
5068
5069             --  Restore the original adjustment factor in case changed
5070
5071             S_Adjustment := Save_Adjustment;
5072          end;
5073
5074       --  Don't copy Ident or Comment pragmas, since the comment belongs
5075       --  to the generic unit, not to the instantiating unit.
5076
5077       elsif Nkind (N) = N_Pragma
5078         and then Instantiating
5079       then
5080          declare
5081             Prag_Id : constant Pragma_Id := Get_Pragma_Id (Chars (N));
5082
5083          begin
5084             if Prag_Id = Pragma_Ident
5085               or else Prag_Id = Pragma_Comment
5086             then
5087                New_N := Make_Null_Statement (Sloc (N));
5088
5089             else
5090                Copy_Descendants;
5091             end if;
5092          end;
5093
5094       elsif Nkind (N) = N_Integer_Literal
5095         or else Nkind (N) = N_Real_Literal
5096       then
5097          --  No descendant fields need traversing
5098
5099          null;
5100
5101       --  For the remaining nodes, copy recursively their descendants
5102
5103       else
5104          Copy_Descendants;
5105
5106          if Instantiating
5107            and then Nkind (N) = N_Subprogram_Body
5108          then
5109             Set_Generic_Parent (Specification (New_N), N);
5110          end if;
5111       end if;
5112
5113       return New_N;
5114    end Copy_Generic_Node;
5115
5116    ----------------------------
5117    -- Denotes_Formal_Package --
5118    ----------------------------
5119
5120    function Denotes_Formal_Package (Pack : Entity_Id) return Boolean is
5121       Par  : constant Entity_Id := Current_Instantiated_Parent.Act_Id;
5122       Scop : constant Entity_Id := Scope (Pack);
5123       E    : Entity_Id;
5124
5125    begin
5126       if Ekind (Scop) = E_Generic_Package
5127         or else Nkind (Unit_Declaration_Node (Scop)) =
5128                                          N_Generic_Subprogram_Declaration
5129       then
5130          return True;
5131
5132       elsif Nkind (Parent (Pack)) = N_Formal_Package_Declaration then
5133          return True;
5134
5135       elsif No (Par) then
5136          return False;
5137
5138       else
5139          --  Check whether this package is associated with a formal
5140          --  package of the enclosing instantiation. Iterate over the
5141          --  list of renamings.
5142
5143          E := First_Entity (Par);
5144          while Present (E) loop
5145             if Ekind (E) /= E_Package
5146               or else Nkind (Parent (E)) /= N_Package_Renaming_Declaration
5147             then
5148                null;
5149             elsif Renamed_Object (E) = Par then
5150                return False;
5151
5152             elsif Renamed_Object (E) = Pack then
5153                return True;
5154             end if;
5155
5156             Next_Entity (E);
5157          end loop;
5158
5159          return False;
5160       end if;
5161    end Denotes_Formal_Package;
5162
5163    -----------------
5164    -- End_Generic --
5165    -----------------
5166
5167    procedure End_Generic is
5168    begin
5169       --  ??? More things could be factored out in this
5170       --  routine. Should probably be done at a later stage.
5171
5172       Inside_A_Generic := Generic_Flags.Table (Generic_Flags.Last);
5173       Generic_Flags.Decrement_Last;
5174
5175       Expander_Mode_Restore;
5176    end End_Generic;
5177
5178    ----------------------
5179    -- Find_Actual_Type --
5180    ----------------------
5181
5182    function Find_Actual_Type
5183      (Typ       : Entity_Id;
5184       Gen_Scope : Entity_Id)
5185       return      Entity_Id
5186    is
5187       T : Entity_Id;
5188
5189    begin
5190       if not Is_Child_Unit (Gen_Scope) then
5191          return Get_Instance_Of (Typ);
5192
5193       elsif not Is_Generic_Type (Typ)
5194         or else Scope (Typ) = Gen_Scope
5195       then
5196          return Get_Instance_Of (Typ);
5197
5198       else
5199          T := Current_Entity (Typ);
5200          while Present (T) loop
5201             if In_Open_Scopes (Scope (T)) then
5202                return T;
5203             end if;
5204
5205             T := Homonym (T);
5206          end loop;
5207
5208          return Typ;
5209       end if;
5210    end Find_Actual_Type;
5211
5212    ----------------------------
5213    -- Freeze_Subprogram_Body --
5214    ----------------------------
5215
5216    procedure Freeze_Subprogram_Body
5217      (Inst_Node : Node_Id;
5218       Gen_Body  : Node_Id;
5219       Pack_Id   : Entity_Id)
5220   is
5221       F_Node   : Node_Id;
5222       Gen_Unit : constant Entity_Id := Get_Generic_Entity (Inst_Node);
5223       Par      : constant Entity_Id := Scope (Gen_Unit);
5224       Enc_G    : Entity_Id;
5225       Enc_I    : Node_Id;
5226       E_G_Id   : Entity_Id;
5227
5228       function Earlier (N1, N2 : Node_Id) return Boolean;
5229       --  Yields True if N1 and N2 appear in the same compilation unit,
5230       --  ignoring subunits, and if N1 is to the left of N2 in a left-to-right
5231       --  traversal of the tree for the unit.
5232
5233       function Enclosing_Body (N : Node_Id) return Node_Id;
5234       --  Find innermost package body that encloses the given node, and which
5235       --  is not a compilation unit. Freeze nodes for the instance, or for its
5236       --  enclosing body, may be inserted after the enclosing_body of the
5237       --  generic unit.
5238
5239       function Package_Freeze_Node (B : Node_Id) return Node_Id;
5240       --  Find entity for given package body, and locate or create a freeze
5241       --  node for it.
5242
5243       function True_Parent (N : Node_Id) return Node_Id;
5244       --  For a subunit, return parent of corresponding stub.
5245
5246       -------------
5247       -- Earlier --
5248       -------------
5249
5250       function Earlier (N1, N2 : Node_Id) return Boolean is
5251          D1 : Integer := 0;
5252          D2 : Integer := 0;
5253          P1 : Node_Id := N1;
5254          P2 : Node_Id := N2;
5255
5256          procedure Find_Depth (P : in out Node_Id; D : in out Integer);
5257          --  Find distance from given node to enclosing compilation unit.
5258
5259          ----------------
5260          -- Find_Depth --
5261          ----------------
5262
5263          procedure Find_Depth (P : in out Node_Id; D : in out Integer) is
5264          begin
5265             while Present (P)
5266               and then Nkind (P) /= N_Compilation_Unit
5267             loop
5268                P := True_Parent (P);
5269                D := D + 1;
5270             end loop;
5271          end Find_Depth;
5272
5273       --  Start of procesing for Earlier
5274
5275       begin
5276          Find_Depth (P1, D1);
5277          Find_Depth (P2, D2);
5278
5279          if P1 /= P2 then
5280             return False;
5281          else
5282             P1 := N1;
5283             P2 := N2;
5284          end if;
5285
5286          while D1 > D2 loop
5287             P1 := True_Parent (P1);
5288             D1 := D1 - 1;
5289          end loop;
5290
5291          while D2 > D1 loop
5292             P2 := True_Parent (P2);
5293             D2 := D2 - 1;
5294          end loop;
5295
5296          --  At this point P1 and P2 are at the same distance from the root.
5297          --  We examine their parents until we find a common declarative
5298          --  list, at which point we can establish their relative placement
5299          --  by comparing their ultimate slocs. If we reach the root,
5300          --  N1 and N2 do not descend from the same declarative list (e.g.
5301          --  one is nested in the declarative part and the other is in a block
5302          --  in the statement part) and the earlier one is already frozen.
5303
5304          while not Is_List_Member (P1)
5305            or else not Is_List_Member (P2)
5306            or else List_Containing (P1) /= List_Containing (P2)
5307          loop
5308             P1 := True_Parent (P1);
5309             P2 := True_Parent (P2);
5310
5311             if Nkind (Parent (P1)) = N_Subunit then
5312                P1 := Corresponding_Stub (Parent (P1));
5313             end if;
5314
5315             if Nkind (Parent (P2)) = N_Subunit then
5316                P2 := Corresponding_Stub (Parent (P2));
5317             end if;
5318
5319             if P1 = P2 then
5320                return False;
5321             end if;
5322          end loop;
5323
5324          return
5325            Top_Level_Location (Sloc (P1)) < Top_Level_Location (Sloc (P2));
5326       end Earlier;
5327
5328       --------------------
5329       -- Enclosing_Body --
5330       --------------------
5331
5332       function Enclosing_Body (N : Node_Id) return Node_Id is
5333          P : Node_Id := Parent (N);
5334
5335       begin
5336          while Present (P)
5337            and then Nkind (Parent (P)) /= N_Compilation_Unit
5338          loop
5339             if Nkind (P) = N_Package_Body then
5340
5341                if Nkind (Parent (P)) = N_Subunit then
5342                   return Corresponding_Stub (Parent (P));
5343                else
5344                   return P;
5345                end if;
5346             end if;
5347
5348             P := True_Parent (P);
5349          end loop;
5350
5351          return Empty;
5352       end Enclosing_Body;
5353
5354       -------------------------
5355       -- Package_Freeze_Node --
5356       -------------------------
5357
5358       function Package_Freeze_Node (B : Node_Id) return Node_Id is
5359          Id : Entity_Id;
5360
5361       begin
5362          if Nkind (B) = N_Package_Body then
5363             Id := Corresponding_Spec (B);
5364
5365          else pragma Assert (Nkind (B) = N_Package_Body_Stub);
5366             Id := Corresponding_Spec (Proper_Body (Unit (Library_Unit (B))));
5367          end if;
5368
5369          Ensure_Freeze_Node (Id);
5370          return Freeze_Node (Id);
5371       end Package_Freeze_Node;
5372
5373       -----------------
5374       -- True_Parent --
5375       -----------------
5376
5377       function True_Parent (N : Node_Id) return Node_Id is
5378       begin
5379          if Nkind (Parent (N)) = N_Subunit then
5380             return Parent (Corresponding_Stub (Parent (N)));
5381          else
5382             return Parent (N);
5383          end if;
5384       end True_Parent;
5385
5386    --  Start of processing of Freeze_Subprogram_Body
5387
5388    begin
5389       --  If the instance and the generic body appear within the same
5390       --  unit, and the instance preceeds the generic, the freeze node for
5391       --  the instance must appear after that of the generic. If the generic
5392       --  is nested within another instance I2, then current instance must
5393       --  be frozen after I2. In both cases, the freeze nodes are those of
5394       --  enclosing packages. Otherwise, the freeze node is placed at the end
5395       --  of the current declarative part.
5396
5397       Enc_G  := Enclosing_Body (Gen_Body);
5398       Enc_I  := Enclosing_Body (Inst_Node);
5399       Ensure_Freeze_Node (Pack_Id);
5400       F_Node := Freeze_Node (Pack_Id);
5401
5402       if Is_Generic_Instance (Par)
5403         and then Present (Freeze_Node (Par))
5404         and then
5405           In_Same_Declarative_Part (Freeze_Node (Par), Inst_Node)
5406       then
5407          if ABE_Is_Certain (Get_Package_Instantiation_Node (Par)) then
5408
5409             --  The parent was a premature instantiation. Insert freeze
5410             --  node at the end the current declarative part.
5411
5412             Insert_After_Last_Decl (Inst_Node, F_Node);
5413
5414          else
5415             Insert_After (Freeze_Node (Par), F_Node);
5416          end if;
5417
5418       --  The body enclosing the instance should be frozen after the body
5419       --  that includes the generic, because the body of the instance may
5420       --  make references to entities therein. If the two are not in the
5421       --  same declarative part, or if the one enclosing the instance is
5422       --  frozen already, freeze the instance at the end of the current
5423       --  declarative part.
5424
5425       elsif Is_Generic_Instance (Par)
5426         and then Present (Freeze_Node (Par))
5427         and then Present (Enc_I)
5428       then
5429          if In_Same_Declarative_Part (Freeze_Node (Par), Enc_I)
5430            or else
5431              (Nkind (Enc_I) = N_Package_Body
5432                and then
5433              In_Same_Declarative_Part (Freeze_Node (Par), Parent (Enc_I)))
5434          then
5435             --  The enclosing package may contain several instances. Rather
5436             --  than computing the earliest point at which to insert its
5437             --  freeze node, we place it at the end of the declarative part
5438             --  of the parent of the generic.
5439
5440             Insert_After_Last_Decl
5441               (Freeze_Node (Par), Package_Freeze_Node (Enc_I));
5442          end if;
5443
5444          Insert_After_Last_Decl (Inst_Node, F_Node);
5445
5446       elsif Present (Enc_G)
5447         and then Present (Enc_I)
5448         and then Enc_G /= Enc_I
5449         and then Earlier (Inst_Node, Gen_Body)
5450       then
5451          if Nkind (Enc_G) = N_Package_Body then
5452             E_G_Id := Corresponding_Spec (Enc_G);
5453          else pragma Assert (Nkind (Enc_G) = N_Package_Body_Stub);
5454             E_G_Id :=
5455               Corresponding_Spec (Proper_Body (Unit (Library_Unit (Enc_G))));
5456          end if;
5457
5458          --  Freeze package that encloses instance, and place node after
5459          --  package that encloses generic. If enclosing package is already
5460          --  frozen we have to assume it is at the proper place. This may
5461          --  be a potential ABE that requires dynamic checking.
5462
5463          Insert_After_Last_Decl (Enc_G, Package_Freeze_Node (Enc_I));
5464
5465          --  Freeze enclosing subunit before instance
5466
5467          Ensure_Freeze_Node (E_G_Id);
5468
5469          if not Is_List_Member (Freeze_Node (E_G_Id)) then
5470             Insert_After (Enc_G, Freeze_Node (E_G_Id));
5471          end if;
5472
5473          Insert_After_Last_Decl (Inst_Node, F_Node);
5474
5475       else
5476          --  If none of the above, insert freeze node at the end of the
5477          --  current declarative part.
5478
5479          Insert_After_Last_Decl (Inst_Node, F_Node);
5480       end if;
5481    end Freeze_Subprogram_Body;
5482
5483    ----------------
5484    -- Get_Gen_Id --
5485    ----------------
5486
5487    function Get_Gen_Id (E : Assoc_Ptr) return Entity_Id is
5488    begin
5489       return Generic_Renamings.Table (E).Gen_Id;
5490    end Get_Gen_Id;
5491
5492    ---------------------
5493    -- Get_Instance_Of --
5494    ---------------------
5495
5496    function Get_Instance_Of (A : Entity_Id) return Entity_Id is
5497       Res : constant Assoc_Ptr := Generic_Renamings_HTable.Get (A);
5498
5499    begin
5500       if Res /= Assoc_Null then
5501          return Generic_Renamings.Table (Res).Act_Id;
5502       else
5503          --  On exit, entity is not instantiated: not a generic parameter,
5504          --  or else parameter of an inner generic unit.
5505
5506          return A;
5507       end if;
5508    end Get_Instance_Of;
5509
5510    ------------------------------------
5511    -- Get_Package_Instantiation_Node --
5512    ------------------------------------
5513
5514    function Get_Package_Instantiation_Node (A : Entity_Id) return Node_Id is
5515       Decl : Node_Id := Unit_Declaration_Node (A);
5516       Inst : Node_Id;
5517
5518    begin
5519       --  If the instantiation is a compilation unit that does not need a
5520       --  body then the instantiation node has been rewritten as a package
5521       --  declaration for the instance, and we return the original node.
5522
5523       --  If it is a compilation unit and the instance node has not been
5524       --  rewritten, then it is still the unit of the compilation. Finally,
5525       --  if a body is present, this is a parent of the main unit whose body
5526       --  has been compiled for inlining purposes, and the instantiation node
5527       --  has been rewritten with the instance body.
5528
5529       --  Otherwise the instantiation node appears after the declaration.
5530       --  If the entity is a formal package, the declaration may have been
5531       --  rewritten as a generic declaration (in the case of a formal with a
5532       --  box) or left as a formal package declaration if it has actuals, and
5533       --  is found with a forward search.
5534
5535       if Nkind (Parent (Decl)) = N_Compilation_Unit then
5536          if Nkind (Decl) = N_Package_Declaration
5537            and then Present (Corresponding_Body (Decl))
5538          then
5539             Decl := Unit_Declaration_Node (Corresponding_Body (Decl));
5540          end if;
5541
5542          if Nkind (Original_Node (Decl)) = N_Package_Instantiation then
5543             return Original_Node (Decl);
5544          else
5545             return Unit (Parent (Decl));
5546          end if;
5547
5548       elsif Nkind (Decl) = N_Generic_Package_Declaration
5549         and then Nkind (Original_Node (Decl)) = N_Formal_Package_Declaration
5550       then
5551          return Original_Node (Decl);
5552
5553       else
5554          Inst := Next (Decl);
5555          while Nkind (Inst) /= N_Package_Instantiation
5556            and then Nkind (Inst) /= N_Formal_Package_Declaration
5557          loop
5558             Next (Inst);
5559          end loop;
5560
5561          return Inst;
5562       end if;
5563    end Get_Package_Instantiation_Node;
5564
5565    ------------------------
5566    -- Has_Been_Exchanged --
5567    ------------------------
5568
5569    function Has_Been_Exchanged (E : Entity_Id) return Boolean is
5570       Next : Elmt_Id := First_Elmt (Exchanged_Views);
5571
5572    begin
5573       while Present (Next) loop
5574          if Full_View (Node (Next)) = E then
5575             return True;
5576          end if;
5577
5578          Next_Elmt (Next);
5579       end loop;
5580
5581       return False;
5582    end Has_Been_Exchanged;
5583
5584    ----------
5585    -- Hash --
5586    ----------
5587
5588    function Hash (F : Entity_Id) return HTable_Range is
5589    begin
5590       return HTable_Range (F mod HTable_Size);
5591    end Hash;
5592
5593    ------------------------
5594    -- Hide_Current_Scope --
5595    ------------------------
5596
5597    procedure Hide_Current_Scope is
5598       C : constant Entity_Id := Current_Scope;
5599       E : Entity_Id;
5600
5601    begin
5602       Set_Is_Hidden_Open_Scope (C);
5603       E := First_Entity (C);
5604
5605       while Present (E) loop
5606          if Is_Immediately_Visible (E) then
5607             Set_Is_Immediately_Visible (E, False);
5608             Append_Elmt (E, Hidden_Entities);
5609          end if;
5610
5611          Next_Entity (E);
5612       end loop;
5613
5614       --  Make the scope name invisible as well. This is necessary, but
5615       --  might conflict with calls to Rtsfind later on, in case the scope
5616       --  is a predefined one. There is no clean solution to this problem, so
5617       --  for now we depend on the user not redefining Standard itself in one
5618       --  of the parent units.
5619
5620       if Is_Immediately_Visible (C)
5621         and then C /= Standard_Standard
5622       then
5623          Set_Is_Immediately_Visible (C, False);
5624          Append_Elmt (C, Hidden_Entities);
5625       end if;
5626
5627    end Hide_Current_Scope;
5628
5629    --------------
5630    -- Init_Env --
5631    --------------
5632
5633    procedure Init_Env is
5634       Saved : Instance_Env;
5635
5636    begin
5637       Saved.Ada_83              := Ada_83;
5638       Saved.Instantiated_Parent := Current_Instantiated_Parent;
5639       Saved.Exchanged_Views     := Exchanged_Views;
5640       Saved.Hidden_Entities     := Hidden_Entities;
5641       Saved.Current_Sem_Unit    := Current_Sem_Unit;
5642       Instance_Envs.Increment_Last;
5643       Instance_Envs.Table (Instance_Envs.Last) := Saved;
5644
5645       Exchanged_Views := New_Elmt_List;
5646       Hidden_Entities := New_Elmt_List;
5647
5648       --  Make dummy entry for Instantiated parent. If generic unit is
5649       --  legal, this is set properly in Set_Instance_Env.
5650
5651       Current_Instantiated_Parent :=
5652         (Current_Scope, Current_Scope, Assoc_Null);
5653    end Init_Env;
5654
5655    ------------------------------
5656    -- In_Same_Declarative_Part --
5657    ------------------------------
5658
5659    function In_Same_Declarative_Part
5660      (F_Node : Node_Id;
5661       Inst   : Node_Id)
5662       return   Boolean
5663    is
5664       Decls : constant Node_Id := Parent (F_Node);
5665       Nod   : Node_Id := Parent (Inst);
5666
5667    begin
5668       while Present (Nod) loop
5669          if Nod = Decls then
5670             return True;
5671
5672          elsif Nkind (Nod) = N_Subprogram_Body
5673            or else Nkind (Nod) = N_Package_Body
5674            or else Nkind (Nod) = N_Task_Body
5675            or else Nkind (Nod) = N_Protected_Body
5676            or else Nkind (Nod) = N_Block_Statement
5677          then
5678             return False;
5679
5680          elsif Nkind (Nod) = N_Subunit then
5681             Nod :=  Corresponding_Stub (Nod);
5682
5683          elsif Nkind (Nod) = N_Compilation_Unit then
5684             return False;
5685          else
5686             Nod := Parent (Nod);
5687          end if;
5688       end loop;
5689
5690       return False;
5691    end In_Same_Declarative_Part;
5692
5693    ---------------------
5694    -- Inherit_Context --
5695    ---------------------
5696
5697    procedure Inherit_Context (Gen_Decl : Node_Id; Inst : Node_Id) is
5698       Current_Context : List_Id;
5699       Current_Unit    : Node_Id;
5700       Item            : Node_Id;
5701       New_I           : Node_Id;
5702
5703    begin
5704       if Nkind (Parent (Gen_Decl)) = N_Compilation_Unit then
5705
5706          --  The inherited context is attached to the enclosing compilation
5707          --  unit. This is either the main unit, or the declaration for the
5708          --  main unit (in case the instantation appears within the package
5709          --  declaration and the main unit is its body).
5710
5711          Current_Unit := Parent (Inst);
5712          while Present (Current_Unit)
5713            and then Nkind (Current_Unit) /= N_Compilation_Unit
5714          loop
5715             Current_Unit := Parent (Current_Unit);
5716          end loop;
5717
5718          Current_Context := Context_Items (Current_Unit);
5719
5720          Item := First (Context_Items (Parent (Gen_Decl)));
5721          while Present (Item) loop
5722             if Nkind (Item) = N_With_Clause then
5723                New_I := New_Copy (Item);
5724                Set_Implicit_With (New_I, True);
5725                Append (New_I, Current_Context);
5726             end if;
5727
5728             Next (Item);
5729          end loop;
5730       end if;
5731    end Inherit_Context;
5732
5733    ----------------
5734    -- Initialize --
5735    ----------------
5736
5737    procedure Initialize is
5738    begin
5739       Generic_Renamings.Init;
5740       Instance_Envs.Init;
5741       Generic_Flags.Init;
5742       Generic_Renamings_HTable.Reset;
5743       Circularity_Detected := False;
5744       Exchanged_Views      := No_Elist;
5745       Hidden_Entities      := No_Elist;
5746    end Initialize;
5747
5748    ----------------------------
5749    -- Insert_After_Last_Decl --
5750    ----------------------------
5751
5752    procedure Insert_After_Last_Decl (N : Node_Id; F_Node : Node_Id) is
5753       L : List_Id          := List_Containing (N);
5754       P : constant Node_Id := Parent (L);
5755
5756    begin
5757       if not Is_List_Member (F_Node) then
5758          if Nkind (P) = N_Package_Specification
5759            and then L = Visible_Declarations (P)
5760            and then Present (Private_Declarations (P))
5761            and then not Is_Empty_List (Private_Declarations (P))
5762          then
5763             L := Private_Declarations (P);
5764          end if;
5765
5766          Insert_After (Last (L), F_Node);
5767       end if;
5768    end Insert_After_Last_Decl;
5769
5770    ------------------
5771    -- Install_Body --
5772    ------------------
5773
5774    procedure Install_Body
5775      (Act_Body : Node_Id;
5776       N        : Node_Id;
5777       Gen_Body : Node_Id;
5778       Gen_Decl : Node_Id)
5779    is
5780       Act_Id    : constant Entity_Id := Corresponding_Spec (Act_Body);
5781       Act_Unit  : constant Node_Id   := Unit (Cunit (Get_Source_Unit (N)));
5782       Gen_Id    : constant Entity_Id := Corresponding_Spec (Gen_Body);
5783       Par       : constant Entity_Id := Scope (Gen_Id);
5784       Gen_Unit  : constant Node_Id :=
5785                     Unit (Cunit (Get_Source_Unit (Gen_Decl)));
5786       Orig_Body : Node_Id := Gen_Body;
5787       F_Node    : Node_Id;
5788       Body_Unit : Node_Id;
5789
5790       Must_Delay : Boolean;
5791
5792       function Enclosing_Subp (Id : Entity_Id) return Entity_Id;
5793       --  Find subprogram (if any) that encloses instance and/or generic body.
5794
5795       function True_Sloc (N : Node_Id) return Source_Ptr;
5796       --  If the instance is nested inside a generic unit, the Sloc of the
5797       --  instance indicates the place of the original definition, not the
5798       --  point of the current enclosing instance. Pending a better usage of
5799       --  Slocs to indicate instantiation places, we determine the place of
5800       --  origin of a node by finding the maximum sloc of any ancestor node.
5801       --  Why is this not equivalent fo Top_Level_Location ???
5802
5803       function Enclosing_Subp (Id : Entity_Id) return Entity_Id is
5804          Scop : Entity_Id := Scope (Id);
5805
5806       begin
5807          while Scop /= Standard_Standard
5808            and then not Is_Overloadable (Scop)
5809          loop
5810             Scop := Scope (Scop);
5811          end loop;
5812
5813          return Scop;
5814       end Enclosing_Subp;
5815
5816       function True_Sloc (N : Node_Id) return Source_Ptr is
5817          Res : Source_Ptr;
5818          N1  : Node_Id;
5819
5820       begin
5821          Res := Sloc (N);
5822          N1 := N;
5823          while Present (N1) and then N1 /= Act_Unit loop
5824             if Sloc (N1) > Res then
5825                Res := Sloc (N1);
5826             end if;
5827
5828             N1 := Parent (N1);
5829          end loop;
5830
5831          return Res;
5832       end True_Sloc;
5833
5834    --  Start of processing for Install_Body
5835
5836    begin
5837       --  If the body is a subunit, the freeze point is the corresponding
5838       --  stub in the current compilation, not the subunit itself.
5839
5840       if Nkind (Parent (Gen_Body)) = N_Subunit then
5841          Orig_Body :=  Corresponding_Stub (Parent (Gen_Body));
5842       else
5843          Orig_Body := Gen_Body;
5844       end if;
5845
5846       Body_Unit := Unit (Cunit (Get_Source_Unit (Orig_Body)));
5847
5848       --  If the instantiation and the generic definition appear in the
5849       --  same package declaration, this is an early instantiation.
5850       --  If they appear in the same declarative part, it is an early
5851       --  instantiation only if the generic body appears textually later,
5852       --  and the generic body is also in the main unit.
5853
5854       --  If instance is nested within a subprogram, and the generic body is
5855       --  not, the instance is delayed because the enclosing body is. If
5856       --  instance and body are within the same scope, or the same sub-
5857       --  program body, indicate explicitly that the instance is delayed.
5858
5859       Must_Delay :=
5860         (Gen_Unit = Act_Unit
5861           and then ((Nkind (Gen_Unit) = N_Package_Declaration)
5862                       or else Nkind (Gen_Unit) = N_Generic_Package_Declaration
5863                       or else (Gen_Unit = Body_Unit
5864                                 and then True_Sloc (N) < Sloc (Orig_Body)))
5865           and then Is_In_Main_Unit (Gen_Unit)
5866           and then (Scope (Act_Id) = Scope (Gen_Id)
5867                       or else
5868                     Enclosing_Subp (Act_Id) = Enclosing_Subp (Gen_Id)));
5869
5870       --  If this is an early instantiation, the freeze node is placed after
5871       --  the generic body. Otherwise, if the generic appears in an instance,
5872       --  we cannot freeze the current instance until the outer one is frozen.
5873       --  This is only relevant if the current instance is nested within some
5874       --  inner scope not itself within the outer instance. If this scope is
5875       --  a package body in the same declarative part as the outer instance,
5876       --  then that body needs to be frozen after the outer instance. Finally,
5877       --  if no delay is needed, we place the freeze node at the end of the
5878       --  current declarative part.
5879
5880       if Expander_Active then
5881          Ensure_Freeze_Node (Act_Id);
5882          F_Node := Freeze_Node (Act_Id);
5883
5884          if Must_Delay then
5885             Insert_After (Orig_Body, F_Node);
5886
5887          elsif Is_Generic_Instance (Par)
5888            and then Present (Freeze_Node (Par))
5889            and then Scope (Act_Id) /= Par
5890          then
5891             --  Freeze instance of inner generic after instance of enclosing
5892             --  generic.
5893
5894             if In_Same_Declarative_Part (Freeze_Node (Par), N) then
5895                Insert_After (Freeze_Node (Par), F_Node);
5896
5897             --  Freeze package enclosing instance of inner generic after
5898             --  instance of enclosing generic.
5899
5900             elsif Nkind (Parent (N)) = N_Package_Body
5901               and then In_Same_Declarative_Part (Freeze_Node (Par), Parent (N))
5902             then
5903
5904                declare
5905                   Enclosing : constant Entity_Id :=
5906                                 Corresponding_Spec (Parent (N));
5907
5908                begin
5909                   Insert_After_Last_Decl (N, F_Node);
5910                   Ensure_Freeze_Node (Enclosing);
5911
5912                   if not Is_List_Member (Freeze_Node (Enclosing)) then
5913                      Insert_After (Freeze_Node (Par), Freeze_Node (Enclosing));
5914                   end if;
5915                end;
5916
5917             else
5918                Insert_After_Last_Decl (N, F_Node);
5919             end if;
5920
5921          else
5922             Insert_After_Last_Decl (N, F_Node);
5923          end if;
5924       end if;
5925
5926       Set_Is_Frozen (Act_Id);
5927       Insert_Before (N, Act_Body);
5928       Mark_Rewrite_Insertion (Act_Body);
5929    end Install_Body;
5930
5931    --------------------
5932    -- Install_Parent --
5933    --------------------
5934
5935    procedure Install_Parent (P : Entity_Id; In_Body : Boolean := False) is
5936       Ancestors : constant Elist_Id  := New_Elmt_List;
5937       S         : constant Entity_Id := Current_Scope;
5938       Inst_Par  : Entity_Id;
5939       First_Par : Entity_Id;
5940       Inst_Node : Node_Id;
5941       Gen_Par   : Entity_Id;
5942       First_Gen : Entity_Id;
5943       Elmt      : Elmt_Id;
5944
5945       procedure Install_Formal_Packages (Par : Entity_Id);
5946       --  If any of the formals of the parent are formal packages with box,
5947       --  their formal parts are visible in the parent and thus in the child
5948       --  unit as well. Analogous to what is done in Check_Generic_Actuals
5949       --  for the unit itself.
5950
5951       procedure Install_Noninstance_Specs (Par : Entity_Id);
5952       --  Install the scopes of noninstance parent units ending with Par.
5953
5954       procedure Install_Spec (Par : Entity_Id);
5955       --  The child unit is within the declarative part of the parent, so
5956       --  the declarations within the parent are immediately visible.
5957
5958       -----------------------------
5959       -- Install_Formal_Packages --
5960       -----------------------------
5961
5962       procedure Install_Formal_Packages (Par : Entity_Id) is
5963          E : Entity_Id;
5964
5965       begin
5966          E := First_Entity (Par);
5967
5968          while Present (E) loop
5969
5970             if Ekind (E) = E_Package
5971               and then Nkind (Parent (E)) = N_Package_Renaming_Declaration
5972             then
5973                --  If this is the renaming for the parent instance, done.
5974
5975                if Renamed_Object (E) = Par then
5976                   exit;
5977
5978                --  The visibility of a formal of an enclosing generic is
5979                --  already correct.
5980
5981                elsif Denotes_Formal_Package (E) then
5982                   null;
5983
5984                elsif Present (Associated_Formal_Package (E))
5985                  and then Box_Present (Parent (Associated_Formal_Package (E)))
5986                then
5987                   Check_Generic_Actuals (Renamed_Object (E), True);
5988                   Set_Is_Hidden (E, False);
5989                end if;
5990             end if;
5991
5992             Next_Entity (E);
5993          end loop;
5994       end Install_Formal_Packages;
5995
5996       -------------------------------
5997       -- Install_Noninstance_Specs --
5998       -------------------------------
5999
6000       procedure Install_Noninstance_Specs (Par : Entity_Id) is
6001       begin
6002          if Present (Par)
6003            and then Par /= Standard_Standard
6004            and then not In_Open_Scopes (Par)
6005          then
6006             Install_Noninstance_Specs (Scope (Par));
6007             Install_Spec (Par);
6008          end if;
6009       end Install_Noninstance_Specs;
6010
6011       ------------------
6012       -- Install_Spec --
6013       ------------------
6014
6015       procedure Install_Spec (Par : Entity_Id) is
6016          Spec : constant Node_Id :=
6017                   Specification (Unit_Declaration_Node (Par));
6018
6019       begin
6020          New_Scope (Par);
6021          Set_Is_Immediately_Visible   (Par);
6022          Install_Visible_Declarations (Par);
6023          Install_Private_Declarations (Par);
6024          Set_Use (Visible_Declarations (Spec));
6025          Set_Use (Private_Declarations (Spec));
6026       end Install_Spec;
6027
6028    --  Start of processing for Install_Parent
6029
6030    begin
6031       --  We need to install the parent instance to compile the instantiation
6032       --  of the child, but the child instance must appear in the current
6033       --  scope. Given that we cannot place the parent above the current
6034       --  scope in the scope stack, we duplicate the current scope and unstack
6035       --  both after the instantiation is complete.
6036
6037       --  If the parent is itself the instantiation of a child unit, we must
6038       --  also stack the instantiation of its parent, and so on. Each such
6039       --  ancestor is the prefix of the name in a prior instantiation.
6040
6041       --  If this is a nested instance, the parent unit itself resolves to
6042       --  a renaming of the parent instance, whose declaration we need.
6043
6044       --  Finally, the parent may be a generic (not an instance) when the
6045       --  child unit appears as a formal package.
6046
6047       Inst_Par := P;
6048
6049       if Present (Renamed_Entity (Inst_Par)) then
6050          Inst_Par := Renamed_Entity (Inst_Par);
6051       end if;
6052
6053       First_Par := Inst_Par;
6054
6055       Gen_Par :=
6056         Generic_Parent (Specification (Unit_Declaration_Node (Inst_Par)));
6057
6058       First_Gen := Gen_Par;
6059
6060       while Present (Gen_Par)
6061         and then Is_Child_Unit (Gen_Par)
6062       loop
6063          --  Load grandparent instance as well
6064
6065          Inst_Node := Get_Package_Instantiation_Node (Inst_Par);
6066
6067          if Nkind (Name (Inst_Node)) = N_Expanded_Name then
6068             Inst_Par := Entity (Prefix (Name (Inst_Node)));
6069
6070             if Present (Renamed_Entity (Inst_Par)) then
6071                Inst_Par := Renamed_Entity (Inst_Par);
6072             end if;
6073
6074             Gen_Par :=
6075               Generic_Parent
6076                 (Specification (Unit_Declaration_Node (Inst_Par)));
6077
6078             if Present (Gen_Par) then
6079                Prepend_Elmt (Inst_Par, Ancestors);
6080
6081             else
6082                --  Parent is not the name of an instantiation
6083
6084                Install_Noninstance_Specs (Inst_Par);
6085
6086                exit;
6087             end if;
6088
6089          else
6090             --  Previous error
6091
6092             exit;
6093          end if;
6094       end loop;
6095
6096       if Present (First_Gen) then
6097          Append_Elmt (First_Par, Ancestors);
6098
6099       else
6100          Install_Noninstance_Specs (First_Par);
6101       end if;
6102
6103       if not Is_Empty_Elmt_List (Ancestors) then
6104          Elmt := First_Elmt (Ancestors);
6105
6106          while Present (Elmt) loop
6107             Install_Spec (Node (Elmt));
6108             Install_Formal_Packages (Node (Elmt));
6109
6110             Next_Elmt (Elmt);
6111          end loop;
6112       end if;
6113
6114       if not In_Body then
6115          New_Scope (S);
6116       end if;
6117    end Install_Parent;
6118
6119    --------------------------------
6120    -- Instantiate_Formal_Package --
6121    --------------------------------
6122
6123    function Instantiate_Formal_Package
6124      (Formal          : Node_Id;
6125       Actual          : Node_Id;
6126       Analyzed_Formal : Node_Id)
6127       return            List_Id
6128    is
6129       Loc         : constant Source_Ptr := Sloc (Actual);
6130       Actual_Pack : Entity_Id;
6131       Formal_Pack : Entity_Id;
6132       Gen_Parent  : Entity_Id;
6133       Decls       : List_Id;
6134       Nod         : Node_Id;
6135       Parent_Spec : Node_Id;
6136
6137       procedure Find_Matching_Actual
6138        (F    : Node_Id;
6139         Act  : in out Entity_Id);
6140       --  We need to associate each formal entity in the formal package
6141       --  with the corresponding entity in the actual package. The actual
6142       --  package has been analyzed and possibly expanded, and as a result
6143       --  there is no one-to-one correspondence between the two lists (for
6144       --  example, the actual may include subtypes, itypes, and inherited
6145       --  primitive operations, interspersed among the renaming declarations
6146       --  for the actuals) . We retrieve the corresponding actual by name
6147       --  because each actual has the same name as the formal, and they do
6148       --  appear in the same order.
6149
6150       function Formal_Entity
6151         (F       : Node_Id;
6152          Act_Ent : Entity_Id)
6153          return    Entity_Id;
6154       --  Returns the entity associated with the given formal F. In the
6155       --  case where F is a formal package, this function will iterate
6156       --  through all of F's formals and enter map associations from the
6157       --  actuals occurring in the formal package's corresponding actual
6158       --  package (obtained via Act_Ent) to the formal package's formal
6159       --  parameters. This function is called recursively for arbitrary
6160       --  levels of formal packages.
6161
6162       function Is_Instance_Of
6163         (Act_Spec : Entity_Id;
6164          Gen_Anc  : Entity_Id)
6165          return     Boolean;
6166       --  The actual can be an instantiation of a generic within another
6167       --  instance, in which case there is no direct link from it to the
6168       --  original generic ancestor. In that case, we recognize that the
6169       --  ultimate ancestor is the same by examining names and scopes.
6170
6171       procedure Map_Entities (Form : Entity_Id; Act : Entity_Id);
6172       --  Within the generic part, entities in the formal package are
6173       --  visible. To validate subsequent type declarations, indicate
6174       --  the correspondence betwen the entities in the analyzed formal,
6175       --  and the entities in  the actual package. There are three packages
6176       --  involved in the instantiation of a formal package: the parent
6177       --  generic P1 which appears in the generic declaration, the fake
6178       --  instantiation P2 which appears in the analyzed generic, and whose
6179       --  visible entities may be used in subsequent formals, and the actual
6180       --  P3 in the instance. To validate subsequent formals, me indicate
6181       --  that the entities in P2 are mapped into those of P3. The mapping of
6182       --  entities has to be done recursively for nested packages.
6183
6184       --------------------------
6185       -- Find_Matching_Actual --
6186       --------------------------
6187
6188       procedure Find_Matching_Actual
6189         (F   : Node_Id;
6190          Act : in out Entity_Id)
6191      is
6192          Formal_Ent : Entity_Id;
6193
6194       begin
6195          case Nkind (Original_Node (F)) is
6196             when N_Formal_Object_Declaration |
6197                  N_Formal_Type_Declaration   =>
6198                Formal_Ent := Defining_Identifier (F);
6199
6200                while Chars (Act) /= Chars (Formal_Ent) loop
6201                   Next_Entity (Act);
6202                end loop;
6203
6204             when N_Formal_Subprogram_Declaration |
6205                  N_Formal_Package_Declaration    |
6206                  N_Package_Declaration           |
6207                  N_Generic_Package_Declaration   =>
6208                Formal_Ent := Defining_Entity (F);
6209
6210                while Chars (Act) /= Chars (Formal_Ent) loop
6211                   Next_Entity (Act);
6212                end loop;
6213
6214             when others =>
6215                raise Program_Error;
6216          end case;
6217       end Find_Matching_Actual;
6218
6219       -------------------
6220       -- Formal_Entity --
6221       -------------------
6222
6223       function Formal_Entity
6224         (F       : Node_Id;
6225          Act_Ent : Entity_Id)
6226          return    Entity_Id
6227       is
6228          Orig_Node : Node_Id := F;
6229          Act_Pkg   : Entity_Id;
6230
6231       begin
6232          case Nkind (Original_Node (F)) is
6233             when N_Formal_Object_Declaration     =>
6234                return Defining_Identifier (F);
6235
6236             when N_Formal_Type_Declaration       =>
6237                return Defining_Identifier (F);
6238
6239             when N_Formal_Subprogram_Declaration =>
6240                return Defining_Unit_Name (Specification (F));
6241
6242             when N_Package_Declaration           =>
6243                return Defining_Unit_Name (Specification (F));
6244
6245             when N_Formal_Package_Declaration |
6246                  N_Generic_Package_Declaration   =>
6247
6248                if Nkind (F) = N_Generic_Package_Declaration then
6249                   Orig_Node := Original_Node (F);
6250                end if;
6251
6252                Act_Pkg := Act_Ent;
6253
6254                --  Find matching actual package, skipping over itypes and
6255                --  other entities generated when analyzing the formal. We
6256                --  know that if the instantiation is legal then there is
6257                --  a matching package for the formal.
6258
6259                while Ekind (Act_Pkg) /= E_Package loop
6260                   Act_Pkg := Next_Entity (Act_Pkg);
6261                end loop;
6262
6263                declare
6264                   Actual_Ent  : Entity_Id := First_Entity (Act_Pkg);
6265                   Formal_Node : Node_Id;
6266                   Formal_Ent  : Entity_Id;
6267
6268                   Gen_Decl : constant Node_Id :=
6269                                Unit_Declaration_Node
6270                                  (Entity (Name (Orig_Node)));
6271
6272                   Formals : constant List_Id :=
6273                               Generic_Formal_Declarations (Gen_Decl);
6274
6275                begin
6276                   if Present (Formals) then
6277                      Formal_Node := First_Non_Pragma (Formals);
6278                   else
6279                      Formal_Node := Empty;
6280                   end if;
6281
6282                   while Present (Actual_Ent)
6283                     and then Present (Formal_Node)
6284                     and then Actual_Ent /= First_Private_Entity (Act_Ent)
6285                   loop
6286                      --  ???  Are the following calls also needed here:
6287                      --
6288                      --  Set_Is_Hidden (Actual_Ent, False);
6289                      --  Set_Is_Potentially_Use_Visible
6290                      --    (Actual_Ent, In_Use (Act_Ent));
6291
6292                      Formal_Ent := Formal_Entity (Formal_Node, Actual_Ent);
6293                      if Present (Formal_Ent) then
6294                         Set_Instance_Of (Formal_Ent, Actual_Ent);
6295                      end if;
6296                      Next_Non_Pragma (Formal_Node);
6297
6298                      Next_Entity (Actual_Ent);
6299                   end loop;
6300                end;
6301
6302                return Defining_Identifier (Orig_Node);
6303
6304             when N_Use_Package_Clause =>
6305                return Empty;
6306
6307             when N_Use_Type_Clause =>
6308                return Empty;
6309
6310             --  We return Empty for all other encountered forms of
6311             --  declarations because there are some cases of nonformal
6312             --  sorts of declaration that can show up (e.g., when array
6313             --  formals are present). Since it's not clear what kinds
6314             --  can appear among the formals, we won't raise failure here.
6315
6316             when others =>
6317                return Empty;
6318
6319          end case;
6320       end Formal_Entity;
6321
6322       --------------------
6323       -- Is_Instance_Of --
6324       --------------------
6325
6326       function Is_Instance_Of
6327         (Act_Spec : Entity_Id;
6328          Gen_Anc  : Entity_Id)
6329          return     Boolean
6330       is
6331          Gen_Par : constant Entity_Id := Generic_Parent (Act_Spec);
6332
6333       begin
6334          if No (Gen_Par) then
6335             return False;
6336
6337          --  Simplest case: the generic parent of the actual is the formal.
6338
6339          elsif Gen_Par = Gen_Anc then
6340             return True;
6341
6342          elsif Chars (Gen_Par) /= Chars (Gen_Anc) then
6343             return False;
6344
6345          --  The actual may be obtained through several instantiations. Its
6346          --  scope must itself be an instance of a generic declared in the
6347          --  same scope as the formal. Any other case is detected above.
6348
6349          elsif not Is_Generic_Instance (Scope (Gen_Par)) then
6350             return False;
6351
6352          else
6353             return Generic_Parent (Parent (Scope (Gen_Par))) = Scope (Gen_Anc);
6354          end if;
6355       end Is_Instance_Of;
6356
6357       ------------------
6358       -- Map_Entities --
6359       ------------------
6360
6361       procedure Map_Entities (Form : Entity_Id; Act : Entity_Id) is
6362          E1 : Entity_Id;
6363          E2 : Entity_Id;
6364
6365       begin
6366          Set_Instance_Of (Form, Act);
6367
6368          --  Traverse formal and actual package to map the corresponding
6369          --  entities. We skip over internal entities that may be generated
6370          --  during semantic analysis, and find the matching entities by
6371          --  name, given that they must appear in the same order.
6372
6373          E1 := First_Entity (Form);
6374          E2 := First_Entity (Act);
6375          while Present (E1)
6376            and then E1 /= First_Private_Entity (Form)
6377          loop
6378             if not Is_Internal (E1)
6379               and then not Is_Class_Wide_Type (E1)
6380               and then Present (Parent (E1))
6381             then
6382                while Present (E2)
6383                  and then Chars (E2) /= Chars (E1)
6384                loop
6385                   Next_Entity (E2);
6386                end loop;
6387
6388                if No (E2) then
6389                   exit;
6390                else
6391                   Set_Instance_Of (E1, E2);
6392
6393                   if Is_Type (E1)
6394                     and then Is_Tagged_Type (E2)
6395                   then
6396                      Set_Instance_Of
6397                        (Class_Wide_Type (E1), Class_Wide_Type (E2));
6398                   end if;
6399
6400                   if Ekind (E1) = E_Package
6401                     and then No (Renamed_Object (E1))
6402                   then
6403                      Map_Entities (E1, E2);
6404                   end if;
6405                end if;
6406             end if;
6407
6408             Next_Entity (E1);
6409          end loop;
6410       end Map_Entities;
6411
6412    --  Start of processing for Instantiate_Formal_Package
6413
6414    begin
6415       Analyze (Actual);
6416
6417       if not Is_Entity_Name (Actual)
6418         or else  Ekind (Entity (Actual)) /= E_Package
6419       then
6420          Error_Msg_N
6421            ("expect package instance to instantiate formal", Actual);
6422          Abandon_Instantiation (Actual);
6423          raise Program_Error;
6424
6425       else
6426          Actual_Pack := Entity (Actual);
6427          Set_Is_Instantiated (Actual_Pack);
6428
6429          --  The actual may be a renamed package, or an outer generic
6430          --  formal package whose instantiation is converted into a renaming.
6431
6432          if Present (Renamed_Object (Actual_Pack)) then
6433             Actual_Pack := Renamed_Object (Actual_Pack);
6434          end if;
6435
6436          if Nkind (Analyzed_Formal) = N_Formal_Package_Declaration then
6437             Gen_Parent  := Get_Instance_Of (Entity (Name (Analyzed_Formal)));
6438             Formal_Pack := Defining_Identifier (Analyzed_Formal);
6439          else
6440             Gen_Parent :=
6441               Generic_Parent (Specification (Analyzed_Formal));
6442             Formal_Pack :=
6443               Defining_Unit_Name (Specification (Analyzed_Formal));
6444          end if;
6445
6446          if Nkind (Parent (Actual_Pack)) = N_Defining_Program_Unit_Name then
6447             Parent_Spec := Specification (Unit_Declaration_Node (Actual_Pack));
6448          else
6449             Parent_Spec := Parent (Actual_Pack);
6450          end if;
6451
6452          if Gen_Parent = Any_Id then
6453             Error_Msg_N
6454               ("previous error in declaration of formal package", Actual);
6455             Abandon_Instantiation (Actual);
6456
6457          elsif
6458            Is_Instance_Of (Parent_Spec, Get_Instance_Of (Gen_Parent))
6459          then
6460             null;
6461
6462          else
6463             Error_Msg_NE
6464               ("actual parameter must be instance of&", Actual, Gen_Parent);
6465             Abandon_Instantiation (Actual);
6466          end if;
6467
6468          Set_Instance_Of (Defining_Identifier (Formal), Actual_Pack);
6469          Map_Entities (Formal_Pack, Actual_Pack);
6470
6471          Nod :=
6472            Make_Package_Renaming_Declaration (Loc,
6473              Defining_Unit_Name => New_Copy (Defining_Identifier (Formal)),
6474              Name               => New_Reference_To (Actual_Pack, Loc));
6475
6476          Set_Associated_Formal_Package (Defining_Unit_Name (Nod),
6477            Defining_Identifier (Formal));
6478          Decls := New_List (Nod);
6479
6480          --  If the formal F has a box, then the generic declarations are
6481          --  visible in the generic G. In an instance of G, the corresponding
6482          --  entities in the actual for F (which are the actuals for the
6483          --  instantiation of the generic that F denotes) must also be made
6484          --  visible for analysis of the current instance. On exit from the
6485          --  current instance, those entities are made private again. If the
6486          --  actual is currently in use, these entities are also use-visible.
6487
6488          --  The loop through the actual entities also steps through the
6489          --  formal entities and enters associations from formals to
6490          --  actuals into the renaming map. This is necessary to properly
6491          --  handle checking of actual parameter associations for later
6492          --  formals that depend on actuals declared in the formal package.
6493
6494          if Box_Present (Formal) then
6495             declare
6496                Gen_Decl    : constant Node_Id :=
6497                                Unit_Declaration_Node (Gen_Parent);
6498                Formals     : constant List_Id :=
6499                                Generic_Formal_Declarations (Gen_Decl);
6500                Actual_Ent  : Entity_Id;
6501                Formal_Node : Node_Id;
6502                Formal_Ent  : Entity_Id;
6503
6504             begin
6505                if Present (Formals) then
6506                   Formal_Node := First_Non_Pragma (Formals);
6507                else
6508                   Formal_Node := Empty;
6509                end if;
6510
6511                Actual_Ent := First_Entity (Actual_Pack);
6512
6513                while Present (Actual_Ent)
6514                  and then Actual_Ent /= First_Private_Entity (Actual_Pack)
6515                loop
6516                   Set_Is_Hidden (Actual_Ent, False);
6517                   Set_Is_Potentially_Use_Visible
6518                     (Actual_Ent, In_Use (Actual_Pack));
6519
6520                   if Present (Formal_Node) then
6521                      Formal_Ent := Formal_Entity (Formal_Node, Actual_Ent);
6522
6523                      if Present (Formal_Ent) then
6524                         Find_Matching_Actual (Formal_Node, Actual_Ent);
6525                         Set_Instance_Of (Formal_Ent, Actual_Ent);
6526                      end if;
6527
6528                      Next_Non_Pragma (Formal_Node);
6529
6530                   else
6531                      --  No further formals to match.
6532
6533                      exit;
6534                   end if;
6535
6536                end loop;
6537             end;
6538
6539          --  If the formal is not declared with a box, reanalyze it as
6540          --  an instantiation, to verify the matching rules of 12.7. The
6541          --  actual checks are performed after the generic associations
6542          --  been analyzed.
6543
6544          else
6545             declare
6546                I_Pack : constant Entity_Id :=
6547                           Make_Defining_Identifier (Sloc (Actual),
6548                             Chars => New_Internal_Name  ('P'));
6549
6550             begin
6551                Set_Is_Internal (I_Pack);
6552
6553                Append_To (Decls,
6554                  Make_Package_Instantiation (Sloc (Actual),
6555                    Defining_Unit_Name => I_Pack,
6556                    Name => New_Occurrence_Of (Gen_Parent, Sloc (Actual)),
6557                    Generic_Associations =>
6558                      Generic_Associations (Formal)));
6559             end;
6560          end if;
6561
6562          return Decls;
6563       end if;
6564    end Instantiate_Formal_Package;
6565
6566    -----------------------------------
6567    -- Instantiate_Formal_Subprogram --
6568    -----------------------------------
6569
6570    function Instantiate_Formal_Subprogram
6571      (Formal          : Node_Id;
6572       Actual          : Node_Id;
6573       Analyzed_Formal : Node_Id)
6574       return            Node_Id
6575    is
6576       Loc        : Source_Ptr := Sloc (Instantiation_Node);
6577       Formal_Sub : constant Entity_Id :=
6578                      Defining_Unit_Name (Specification (Formal));
6579       Analyzed_S : constant Entity_Id :=
6580                      Defining_Unit_Name (Specification (Analyzed_Formal));
6581       Decl_Node  : Node_Id;
6582       Nam        : Node_Id;
6583       New_Spec   : Node_Id;
6584
6585       function From_Parent_Scope (Subp : Entity_Id) return Boolean;
6586       --  If the generic is a child unit, the parent has been installed
6587       --  on the scope stack, but a default subprogram cannot resolve to
6588       --  something on the parent because that parent is not really part
6589       --  of the visible context (it is there to resolve explicit local
6590       --  entities). If the default has resolved in this way, we remove
6591       --  the entity from immediate visibility and analyze the node again
6592       --  to emit an error message or find another visible candidate.
6593
6594       procedure Valid_Actual_Subprogram (Act : Node_Id);
6595       --  Perform legality check and raise exception on failure.
6596
6597       -----------------------
6598       -- From_Parent_Scope --
6599       -----------------------
6600
6601       function From_Parent_Scope (Subp : Entity_Id) return Boolean is
6602          Gen_Scope : Node_Id := Scope (Analyzed_S);
6603
6604       begin
6605          while Present (Gen_Scope)
6606            and then  Is_Child_Unit (Gen_Scope)
6607          loop
6608             if Scope (Subp) = Scope (Gen_Scope) then
6609                return True;
6610             end if;
6611
6612             Gen_Scope := Scope (Gen_Scope);
6613          end loop;
6614
6615          return False;
6616       end From_Parent_Scope;
6617
6618       -----------------------------
6619       -- Valid_Actual_Subprogram --
6620       -----------------------------
6621
6622       procedure Valid_Actual_Subprogram (Act : Node_Id) is
6623          Act_E : Entity_Id := Empty;
6624
6625       begin
6626          if Is_Entity_Name (Act) then
6627             Act_E := Entity (Act);
6628          elsif Nkind (Act) = N_Selected_Component
6629            and then Is_Entity_Name (Selector_Name (Act))
6630          then
6631             Act_E := Entity (Selector_Name (Act));
6632          end if;
6633
6634          if (Present (Act_E) and then Is_Overloadable (Act_E))
6635            or else Nkind (Act) = N_Attribute_Reference
6636            or else Nkind (Act) = N_Indexed_Component
6637            or else Nkind (Act) = N_Character_Literal
6638            or else Nkind (Act) = N_Explicit_Dereference
6639          then
6640             return;
6641          end if;
6642
6643          Error_Msg_NE
6644            ("expect subprogram or entry name in instantiation of&",
6645             Instantiation_Node, Formal_Sub);
6646          Abandon_Instantiation (Instantiation_Node);
6647
6648       end Valid_Actual_Subprogram;
6649
6650    --  Start of processing for Instantiate_Formal_Subprogram
6651
6652    begin
6653       New_Spec := New_Copy_Tree (Specification (Formal));
6654
6655       --  Create new entity for the actual (New_Copy_Tree does not).
6656
6657       Set_Defining_Unit_Name
6658         (New_Spec, Make_Defining_Identifier (Loc, Chars (Formal_Sub)));
6659
6660       --  Find entity of actual. If the actual is an attribute reference, it
6661       --  cannot be resolved here (its formal is missing) but is handled
6662       --  instead in Attribute_Renaming. If the actual is overloaded, it is
6663       --  fully resolved subsequently, when the renaming declaration for the
6664       --  formal is analyzed. If it is an explicit dereference, resolve the
6665       --  prefix but not the actual itself, to prevent interpretation as a
6666       --  call.
6667
6668       if Present (Actual) then
6669          Loc := Sloc (Actual);
6670          Set_Sloc (New_Spec, Loc);
6671
6672          if Nkind (Actual) = N_Operator_Symbol then
6673             Find_Direct_Name (Actual);
6674
6675          elsif Nkind (Actual) = N_Explicit_Dereference then
6676             Analyze (Prefix (Actual));
6677
6678          elsif Nkind (Actual) /= N_Attribute_Reference then
6679             Analyze (Actual);
6680          end if;
6681
6682          Valid_Actual_Subprogram (Actual);
6683          Nam := Actual;
6684
6685       elsif Present (Default_Name (Formal)) then
6686          if Nkind (Default_Name (Formal)) /= N_Attribute_Reference
6687            and then Nkind (Default_Name (Formal)) /= N_Selected_Component
6688            and then Nkind (Default_Name (Formal)) /= N_Indexed_Component
6689            and then Nkind (Default_Name (Formal)) /= N_Character_Literal
6690            and then Present (Entity (Default_Name (Formal)))
6691          then
6692             Nam := New_Occurrence_Of (Entity (Default_Name (Formal)), Loc);
6693          else
6694             Nam := New_Copy (Default_Name (Formal));
6695             Set_Sloc (Nam, Loc);
6696          end if;
6697
6698       elsif Box_Present (Formal) then
6699
6700          --  Actual is resolved at the point of instantiation. Create
6701          --  an identifier or operator with the same name as the formal.
6702
6703          if Nkind (Formal_Sub) = N_Defining_Operator_Symbol then
6704             Nam := Make_Operator_Symbol (Loc,
6705               Chars =>  Chars (Formal_Sub),
6706               Strval => No_String);
6707          else
6708             Nam := Make_Identifier (Loc, Chars (Formal_Sub));
6709          end if;
6710
6711       else
6712          Error_Msg_Sloc := Sloc (Scope (Analyzed_S));
6713          Error_Msg_NE
6714            ("missing actual&", Instantiation_Node, Formal_Sub);
6715          Error_Msg_NE
6716            ("\in instantiation of & declared#",
6717               Instantiation_Node, Scope (Analyzed_S));
6718          Abandon_Instantiation (Instantiation_Node);
6719       end if;
6720
6721       Decl_Node :=
6722         Make_Subprogram_Renaming_Declaration (Loc,
6723           Specification => New_Spec,
6724           Name          => Nam);
6725
6726       --  If we do not have an actual and the formal specified <> then
6727       --  set to get proper default.
6728
6729       if No (Actual) and then Box_Present (Formal) then
6730          Set_From_Default (Decl_Node);
6731       end if;
6732
6733       --  Gather possible interpretations for the actual before analyzing the
6734       --  instance. If overloaded, it will be resolved when analyzing the
6735       --  renaming declaration.
6736
6737       if Box_Present (Formal)
6738         and then No (Actual)
6739       then
6740          Analyze (Nam);
6741
6742          if Is_Child_Unit (Scope (Analyzed_S))
6743            and then Present (Entity (Nam))
6744          then
6745             if not Is_Overloaded (Nam) then
6746
6747                if From_Parent_Scope (Entity (Nam)) then
6748                   Set_Is_Immediately_Visible (Entity (Nam), False);
6749                   Set_Entity (Nam, Empty);
6750                   Set_Etype (Nam, Empty);
6751
6752                   Analyze (Nam);
6753
6754                   Set_Is_Immediately_Visible (Entity (Nam));
6755                end if;
6756
6757             else
6758                declare
6759                   I  : Interp_Index;
6760                   It : Interp;
6761
6762                begin
6763                   Get_First_Interp (Nam, I, It);
6764
6765                   while Present (It.Nam) loop
6766                      if From_Parent_Scope (It.Nam) then
6767                         Remove_Interp (I);
6768                      end if;
6769
6770                      Get_Next_Interp (I, It);
6771                   end loop;
6772                end;
6773             end if;
6774          end if;
6775       end if;
6776
6777       --  The generic instantiation freezes the actual. This can only be
6778       --  done once the actual is resolved, in the analysis of the renaming
6779       --  declaration. To indicate that must be done, we set the corresponding
6780       --  spec of the node to point to the formal subprogram entity.
6781
6782       Set_Corresponding_Spec (Decl_Node, Analyzed_S);
6783
6784       --  We cannot analyze the renaming declaration, and thus find the
6785       --  actual, until the all the actuals are assembled in the instance.
6786       --  For subsequent checks of other actuals, indicate the node that
6787       --  will hold the instance of this formal.
6788
6789       Set_Instance_Of (Analyzed_S, Nam);
6790
6791       if Nkind (Actual) = N_Selected_Component
6792         and then Is_Task_Type (Etype (Prefix (Actual)))
6793         and then not Is_Frozen (Etype (Prefix (Actual)))
6794       then
6795          --  The renaming declaration will create a body, which must appear
6796          --  outside of the instantiation, We move the renaming declaration
6797          --  out of the instance, and create an additional renaming inside,
6798          --  to prevent freezing anomalies.
6799
6800          declare
6801             Anon_Id : constant Entity_Id :=
6802                         Make_Defining_Identifier
6803                           (Loc, New_Internal_Name ('E'));
6804          begin
6805             Set_Defining_Unit_Name (New_Spec, Anon_Id);
6806             Insert_Before (Instantiation_Node, Decl_Node);
6807             Analyze (Decl_Node);
6808
6809             --  Now create renaming within the instance
6810
6811             Decl_Node :=
6812               Make_Subprogram_Renaming_Declaration (Loc,
6813                 Specification => New_Copy_Tree (New_Spec),
6814                 Name => New_Occurrence_Of (Anon_Id, Loc));
6815
6816             Set_Defining_Unit_Name (Specification (Decl_Node),
6817               Make_Defining_Identifier (Loc, Chars (Formal_Sub)));
6818          end;
6819       end if;
6820
6821       return Decl_Node;
6822    end Instantiate_Formal_Subprogram;
6823
6824    ------------------------
6825    -- Instantiate_Object --
6826    ------------------------
6827
6828    function Instantiate_Object
6829      (Formal          : Node_Id;
6830       Actual          : Node_Id;
6831       Analyzed_Formal : Node_Id)
6832       return            List_Id
6833    is
6834       Formal_Id : constant Entity_Id  := Defining_Identifier (Formal);
6835       Type_Id   : constant Node_Id    := Subtype_Mark (Formal);
6836       Loc       : constant Source_Ptr := Sloc (Actual);
6837       Act_Assoc : constant Node_Id    := Parent (Actual);
6838       Orig_Ftyp : constant Entity_Id  :=
6839                     Etype (Defining_Identifier (Analyzed_Formal));
6840       List      : constant List_Id    := New_List;
6841       Ftyp      : Entity_Id;
6842       Decl_Node : Node_Id;
6843       Subt_Decl : Node_Id := Empty;
6844
6845    begin
6846       --  Sloc for error message on missing actual.
6847       Error_Msg_Sloc := Sloc (Scope (Defining_Identifier (Analyzed_Formal)));
6848
6849       if Get_Instance_Of (Formal_Id) /= Formal_Id then
6850          Error_Msg_N ("duplicate instantiation of generic parameter", Actual);
6851       end if;
6852
6853       Set_Parent (List, Parent (Actual));
6854
6855       --  OUT present
6856
6857       if Out_Present (Formal) then
6858
6859          --  An IN OUT generic actual must be a name. The instantiation is
6860          --  a renaming declaration. The actual is the name being renamed.
6861          --  We use the actual directly, rather than a copy, because it is not
6862          --  used further in the list of actuals, and because a copy or a use
6863          --  of relocate_node is incorrect if the instance is nested within
6864          --  a generic. In order to simplify ASIS searches, the Generic_Parent
6865          --  field links the declaration to the generic association.
6866
6867          if No (Actual) then
6868             Error_Msg_NE
6869               ("missing actual&",
6870                Instantiation_Node, Formal_Id);
6871             Error_Msg_NE
6872               ("\in instantiation of & declared#",
6873                  Instantiation_Node,
6874                    Scope (Defining_Identifier (Analyzed_Formal)));
6875             Abandon_Instantiation (Instantiation_Node);
6876          end if;
6877
6878          Decl_Node :=
6879            Make_Object_Renaming_Declaration (Loc,
6880              Defining_Identifier => New_Copy (Formal_Id),
6881              Subtype_Mark        => New_Copy_Tree (Type_Id),
6882              Name                => Actual);
6883
6884          Set_Corresponding_Generic_Association (Decl_Node, Act_Assoc);
6885
6886          --  The analysis of the actual may produce insert_action nodes, so
6887          --  the declaration must have a context in which to attach them.
6888
6889          Append (Decl_Node, List);
6890          Analyze (Actual);
6891
6892          --  This check is performed here because Analyze_Object_Renaming
6893          --  will not check it when Comes_From_Source is False. Note
6894          --  though that the check for the actual being the name of an
6895          --  object will be performed in Analyze_Object_Renaming.
6896
6897          if Is_Object_Reference (Actual)
6898            and then Is_Dependent_Component_Of_Mutable_Object (Actual)
6899          then
6900             Error_Msg_N
6901               ("illegal discriminant-dependent component for in out parameter",
6902                Actual);
6903          end if;
6904
6905          --  The actual has to be resolved in order to check that it is
6906          --  a variable (due to cases such as F(1), where F returns
6907          --  access to an array, and for overloaded prefixes).
6908
6909          Ftyp :=
6910            Get_Instance_Of (Etype (Defining_Identifier (Analyzed_Formal)));
6911
6912          if Is_Private_Type (Ftyp)
6913            and then not Is_Private_Type (Etype (Actual))
6914            and then (Base_Type (Full_View (Ftyp)) = Base_Type (Etype (Actual))
6915                       or else Base_Type (Etype (Actual)) = Ftyp)
6916          then
6917             --  If the actual has the type of the full view of the formal,
6918             --  or else a non-private subtype of the formal, then
6919             --  the visibility of the formal type has changed. Add to the
6920             --  actuals a subtype declaration that will force the exchange
6921             --  of views in the body of the instance as well.
6922
6923             Subt_Decl :=
6924               Make_Subtype_Declaration (Loc,
6925                  Defining_Identifier =>
6926                    Make_Defining_Identifier (Loc, New_Internal_Name ('P')),
6927                  Subtype_Indication  => New_Occurrence_Of (Ftyp, Loc));
6928
6929             Prepend (Subt_Decl, List);
6930
6931             Append_Elmt (Full_View (Ftyp), Exchanged_Views);
6932             Exchange_Declarations (Ftyp);
6933          end if;
6934
6935          Resolve (Actual, Ftyp);
6936
6937          if not Is_Variable (Actual) or else Paren_Count (Actual) > 0 then
6938             Error_Msg_NE
6939               ("actual for& must be a variable", Actual, Formal_Id);
6940
6941          elsif Base_Type (Ftyp) /= Base_Type (Etype (Actual)) then
6942             Error_Msg_NE (
6943               "type of actual does not match type of&", Actual, Formal_Id);
6944
6945          end if;
6946
6947          Note_Possible_Modification (Actual);
6948
6949          --  Check for instantiation of atomic/volatile actual for
6950          --  non-atomic/volatile formal (RM C.6 (12)).
6951
6952          if Is_Atomic_Object (Actual)
6953            and then not Is_Atomic (Orig_Ftyp)
6954          then
6955             Error_Msg_N
6956               ("cannot instantiate non-atomic formal object " &
6957                "with atomic actual", Actual);
6958
6959          elsif Is_Volatile_Object (Actual)
6960            and then not Is_Volatile (Orig_Ftyp)
6961          then
6962             Error_Msg_N
6963               ("cannot instantiate non-volatile formal object " &
6964                "with volatile actual", Actual);
6965          end if;
6966
6967       --  OUT not present
6968
6969       else
6970          --  The instantiation of a generic formal in-parameter
6971          --  is a constant declaration. The actual is the expression for
6972          --  that declaration.
6973
6974          if Present (Actual) then
6975
6976             Decl_Node := Make_Object_Declaration (Loc,
6977               Defining_Identifier => New_Copy (Formal_Id),
6978               Constant_Present => True,
6979               Object_Definition => New_Copy_Tree (Type_Id),
6980               Expression => Actual);
6981
6982             Set_Corresponding_Generic_Association (Decl_Node, Act_Assoc);
6983
6984             --  A generic formal object of a tagged type is defined
6985             --  to be aliased so the new constant must also be treated
6986             --  as aliased.
6987
6988             if Is_Tagged_Type
6989                  (Etype (Defining_Identifier (Analyzed_Formal)))
6990             then
6991                Set_Aliased_Present (Decl_Node);
6992             end if;
6993
6994             Append (Decl_Node, List);
6995
6996             --  No need to repeat (pre-)analysis of some expression nodes
6997             --  already handled in Pre_Analyze_Actuals.
6998
6999             if Nkind (Actual) /= N_Allocator then
7000                Analyze (Actual);
7001             end if;
7002
7003             declare
7004                Typ : constant Entity_Id :=
7005                        Get_Instance_Of
7006                          (Etype (Defining_Identifier (Analyzed_Formal)));
7007
7008             begin
7009                Freeze_Before (Instantiation_Node, Typ);
7010
7011                --  If the actual is an aggregate, perform name resolution
7012                --  on its components (the analysis of an aggregate does not
7013                --  do it) to capture local names that may be hidden if the
7014                --  generic is a child unit.
7015
7016                if Nkind (Actual) = N_Aggregate then
7017                      Pre_Analyze_And_Resolve (Actual, Typ);
7018                end if;
7019             end;
7020
7021          elsif Present (Expression (Formal)) then
7022
7023             --  Use default to construct declaration.
7024
7025             Decl_Node :=
7026               Make_Object_Declaration (Sloc (Formal),
7027                 Defining_Identifier => New_Copy (Formal_Id),
7028                 Constant_Present    => True,
7029                 Object_Definition   => New_Copy (Type_Id),
7030                 Expression          => New_Copy_Tree (Expression (Formal)));
7031
7032             Append (Decl_Node, List);
7033             Set_Analyzed (Expression (Decl_Node), False);
7034
7035          else
7036             Error_Msg_NE
7037               ("missing actual&",
7038                 Instantiation_Node, Formal_Id);
7039             Error_Msg_NE ("\in instantiation of & declared#",
7040               Instantiation_Node,
7041                 Scope (Defining_Identifier (Analyzed_Formal)));
7042
7043             if Is_Scalar_Type
7044                  (Etype (Defining_Identifier (Analyzed_Formal)))
7045             then
7046                --  Create dummy constant declaration so that instance can
7047                --  be analyzed, to minimize cascaded visibility errors.
7048
7049                Decl_Node :=
7050                  Make_Object_Declaration (Loc,
7051                    Defining_Identifier => New_Copy (Formal_Id),
7052                    Constant_Present    => True,
7053                    Object_Definition   => New_Copy (Type_Id),
7054                    Expression          =>
7055                       Make_Attribute_Reference (Sloc (Formal_Id),
7056                         Attribute_Name => Name_First,
7057                         Prefix         => New_Copy (Type_Id)));
7058
7059                Append (Decl_Node, List);
7060
7061             else
7062                Abandon_Instantiation (Instantiation_Node);
7063             end if;
7064          end if;
7065
7066       end if;
7067
7068       return List;
7069    end Instantiate_Object;
7070
7071    ------------------------------
7072    -- Instantiate_Package_Body --
7073    ------------------------------
7074
7075    procedure Instantiate_Package_Body
7076      (Body_Info    : Pending_Body_Info;
7077       Inlined_Body : Boolean := False)
7078    is
7079       Act_Decl    : constant Node_Id    := Body_Info.Act_Decl;
7080       Inst_Node   : constant Node_Id    := Body_Info.Inst_Node;
7081       Loc         : constant Source_Ptr := Sloc (Inst_Node);
7082
7083       Gen_Id      : constant Node_Id    := Name (Inst_Node);
7084       Gen_Unit    : constant Entity_Id  := Get_Generic_Entity (Inst_Node);
7085       Gen_Decl    : constant Node_Id    := Unit_Declaration_Node (Gen_Unit);
7086       Act_Spec    : constant Node_Id    := Specification (Act_Decl);
7087       Act_Decl_Id : constant Entity_Id  := Defining_Entity (Act_Spec);
7088
7089       Act_Body_Name : Node_Id;
7090       Gen_Body      : Node_Id;
7091       Gen_Body_Id   : Node_Id;
7092       Act_Body      : Node_Id;
7093       Act_Body_Id   : Entity_Id;
7094
7095       Parent_Installed : Boolean := False;
7096       Save_Style_Check : constant Boolean := Style_Check;
7097
7098    begin
7099       Gen_Body_Id := Corresponding_Body (Gen_Decl);
7100
7101       --  The instance body may already have been processed, as the parent
7102       --  of another instance that is inlined. (Load_Parent_Of_Generic).
7103
7104       if Present (Corresponding_Body (Instance_Spec (Inst_Node))) then
7105          return;
7106       end if;
7107
7108       Expander_Mode_Save_And_Set (Body_Info.Expander_Status);
7109
7110       if No (Gen_Body_Id) then
7111          Load_Parent_Of_Generic (Inst_Node, Specification (Gen_Decl));
7112          Gen_Body_Id := Corresponding_Body (Gen_Decl);
7113       end if;
7114
7115       --  Establish global variable for sloc adjustment and for error
7116       --  recovery.
7117
7118       Instantiation_Node := Inst_Node;
7119
7120       if Present (Gen_Body_Id) then
7121          Save_Env (Gen_Unit, Act_Decl_Id);
7122          Style_Check := False;
7123          Current_Sem_Unit := Body_Info.Current_Sem_Unit;
7124
7125          Gen_Body := Unit_Declaration_Node (Gen_Body_Id);
7126
7127          Create_Instantiation_Source
7128           (Inst_Node, Gen_Body_Id, False, S_Adjustment);
7129
7130          Act_Body :=
7131            Copy_Generic_Node
7132              (Original_Node (Gen_Body), Empty, Instantiating => True);
7133
7134          --  Build new name (possibly qualified) for body declaration
7135
7136          Act_Body_Id := New_Copy (Act_Decl_Id);
7137
7138          --  Some attributes of the spec entity are not inherited by the
7139          --  body entity.
7140
7141          Set_Handler_Records (Act_Body_Id, No_List);
7142
7143          if Nkind (Defining_Unit_Name (Act_Spec)) =
7144                                            N_Defining_Program_Unit_Name
7145          then
7146             Act_Body_Name :=
7147               Make_Defining_Program_Unit_Name (Loc,
7148                 Name => New_Copy_Tree (Name (Defining_Unit_Name (Act_Spec))),
7149                 Defining_Identifier => Act_Body_Id);
7150          else
7151             Act_Body_Name :=  Act_Body_Id;
7152          end if;
7153
7154          Set_Defining_Unit_Name (Act_Body, Act_Body_Name);
7155
7156          Set_Corresponding_Spec (Act_Body, Act_Decl_Id);
7157          Check_Generic_Actuals (Act_Decl_Id, False);
7158
7159          --  If it is a child unit, make the parent instance (which is an
7160          --  instance of the parent of the generic) visible. The parent
7161          --  instance is the prefix of the name of the generic unit.
7162
7163          if Ekind (Scope (Gen_Unit)) = E_Generic_Package
7164            and then Nkind (Gen_Id) = N_Expanded_Name
7165          then
7166             Install_Parent (Entity (Prefix (Gen_Id)), In_Body => True);
7167             Parent_Installed := True;
7168
7169          elsif Is_Child_Unit (Gen_Unit) then
7170             Install_Parent (Scope (Gen_Unit), In_Body => True);
7171             Parent_Installed := True;
7172          end if;
7173
7174          --  If the instantiation is a library unit, and this is the main
7175          --  unit, then build the resulting compilation unit nodes for the
7176          --  instance. If this is a compilation unit but it is not the main
7177          --  unit, then it is the body of a unit in the context, that is being
7178          --  compiled because it is encloses some inlined unit or another
7179          --  generic unit being instantiated. In that case, this body is not
7180          --  part of the current compilation, and is not attached to the tree,
7181          --  but its parent must be set for analysis.
7182
7183          if Nkind (Parent (Inst_Node)) = N_Compilation_Unit then
7184
7185             --  Replace instance node with body of instance, and create
7186             --  new node for corresponding instance declaration.
7187
7188             Build_Instance_Compilation_Unit_Nodes
7189               (Inst_Node, Act_Body, Act_Decl);
7190             Analyze (Inst_Node);
7191
7192             if Parent (Inst_Node) = Cunit (Main_Unit) then
7193
7194                --  If the instance is a child unit itself, then set the
7195                --  scope of the expanded body to be the parent of the
7196                --  instantiation (ensuring that the fully qualified name
7197                --  will be generated for the elaboration subprogram).
7198
7199                if Nkind (Defining_Unit_Name (Act_Spec)) =
7200                                               N_Defining_Program_Unit_Name
7201                then
7202                   Set_Scope
7203                     (Defining_Entity (Inst_Node), Scope (Act_Decl_Id));
7204                end if;
7205             end if;
7206
7207          --  Case where instantiation is not a library unit
7208
7209          else
7210             --  If this is an early instantiation, i.e. appears textually
7211             --  before the corresponding body and must be elaborated first,
7212             --  indicate that the body instance is to be delayed.
7213
7214             Install_Body (Act_Body, Inst_Node, Gen_Body, Gen_Decl);
7215
7216             --  Now analyze the body. We turn off all checks if this is
7217             --  an internal unit, since there is no reason to have checks
7218             --  on for any predefined run-time library code. All such
7219             --  code is designed to be compiled with checks off.
7220
7221             --  Note that we do NOT apply this criterion to children of
7222             --  GNAT (or on VMS, children of DEC). The latter units must
7223             --  suppress checks explicitly if this is needed.
7224
7225             if Is_Predefined_File_Name
7226                  (Unit_File_Name (Get_Source_Unit (Gen_Decl)))
7227             then
7228                Analyze (Act_Body, Suppress => All_Checks);
7229             else
7230                Analyze (Act_Body);
7231             end if;
7232          end if;
7233
7234          if not Generic_Separately_Compiled (Gen_Unit) then
7235             Inherit_Context (Gen_Body, Inst_Node);
7236          end if;
7237
7238          --  Remove the parent instances if they have been placed on the
7239          --  scope stack to compile the body.
7240
7241          if Parent_Installed then
7242             Remove_Parent (In_Body => True);
7243          end if;
7244
7245          Restore_Private_Views (Act_Decl_Id);
7246
7247          --  Remove the current unit from visibility if this is an instance
7248          --  that is not elaborated on the fly for inlining purposes.
7249
7250          if not Inlined_Body then
7251             Set_Is_Immediately_Visible (Act_Decl_Id, False);
7252          end if;
7253
7254          Restore_Env;
7255          Style_Check := Save_Style_Check;
7256
7257       --  If we have no body, and the unit requires a body, then complain.
7258       --  This complaint is suppressed if we have detected other errors
7259       --  (since a common reason for missing the body is that it had errors).
7260
7261       elsif Unit_Requires_Body (Gen_Unit) then
7262          if Serious_Errors_Detected = 0 then
7263             Error_Msg_NE
7264               ("cannot find body of generic package &", Inst_Node, Gen_Unit);
7265
7266          --  Don't attempt to perform any cleanup actions if some other
7267          --  error was aready detected, since this can cause blowups.
7268
7269          else
7270             return;
7271          end if;
7272
7273       --  Case of package that does not need a body
7274
7275       else
7276          --  If the instantiation of the declaration is a library unit,
7277          --  rewrite the original package instantiation as a package
7278          --  declaration in the compilation unit node.
7279
7280          if Nkind (Parent (Inst_Node)) = N_Compilation_Unit then
7281             Set_Parent_Spec (Act_Decl, Parent_Spec (Inst_Node));
7282             Rewrite (Inst_Node, Act_Decl);
7283
7284             --  Generate elaboration entity, in case spec has elaboration
7285             --  code. This cannot be done when the instance is analyzed,
7286             --  because it is not known yet whether the body exists.
7287
7288             Set_Elaboration_Entity_Required (Act_Decl_Id, False);
7289             Build_Elaboration_Entity (Parent (Inst_Node), Act_Decl_Id);
7290
7291          --  If the instantiation is not a library unit, then append the
7292          --  declaration to the list of implicitly generated entities.
7293          --  unless it is already a list member which means that it was
7294          --  already processed
7295
7296          elsif not Is_List_Member (Act_Decl) then
7297             Mark_Rewrite_Insertion (Act_Decl);
7298             Insert_Before (Inst_Node, Act_Decl);
7299          end if;
7300       end if;
7301
7302       Expander_Mode_Restore;
7303    end Instantiate_Package_Body;
7304
7305    ---------------------------------
7306    -- Instantiate_Subprogram_Body --
7307    ---------------------------------
7308
7309    procedure Instantiate_Subprogram_Body
7310      (Body_Info : Pending_Body_Info)
7311    is
7312       Act_Decl      : constant Node_Id    := Body_Info.Act_Decl;
7313       Inst_Node     : constant Node_Id    := Body_Info.Inst_Node;
7314       Loc           : constant Source_Ptr := Sloc (Inst_Node);
7315       Gen_Id        : constant Node_Id   := Name (Inst_Node);
7316       Gen_Unit      : constant Entity_Id := Get_Generic_Entity (Inst_Node);
7317       Gen_Decl      : constant Node_Id   := Unit_Declaration_Node (Gen_Unit);
7318       Anon_Id       : constant Entity_Id :=
7319                         Defining_Unit_Name (Specification (Act_Decl));
7320       Pack_Id       : constant Entity_Id :=
7321                         Defining_Unit_Name (Parent (Act_Decl));
7322       Decls         : List_Id;
7323       Gen_Body      : Node_Id;
7324       Gen_Body_Id   : Node_Id;
7325       Act_Body      : Node_Id;
7326       Act_Body_Id   : Entity_Id;
7327       Pack_Body     : Node_Id;
7328       Prev_Formal   : Entity_Id;
7329       Ret_Expr      : Node_Id;
7330       Unit_Renaming : Node_Id;
7331
7332       Parent_Installed : Boolean := False;
7333       Save_Style_Check : constant Boolean := Style_Check;
7334
7335    begin
7336       Gen_Body_Id := Corresponding_Body (Gen_Decl);
7337
7338       Expander_Mode_Save_And_Set (Body_Info.Expander_Status);
7339
7340       if No (Gen_Body_Id) then
7341          Load_Parent_Of_Generic (Inst_Node, Specification (Gen_Decl));
7342          Gen_Body_Id := Corresponding_Body (Gen_Decl);
7343       end if;
7344
7345       Instantiation_Node := Inst_Node;
7346
7347       if Present (Gen_Body_Id) then
7348          Gen_Body := Unit_Declaration_Node (Gen_Body_Id);
7349
7350          if Nkind (Gen_Body) = N_Subprogram_Body_Stub then
7351
7352             --  Either body is not present, or context is non-expanding, as
7353             --  when compiling a subunit. Mark the instance as completed.
7354
7355             Set_Has_Completion (Anon_Id);
7356             return;
7357          end if;
7358
7359          Save_Env (Gen_Unit, Anon_Id);
7360          Style_Check := False;
7361          Current_Sem_Unit := Body_Info.Current_Sem_Unit;
7362          Create_Instantiation_Source
7363            (Inst_Node,
7364             Gen_Body_Id,
7365             False,
7366             S_Adjustment);
7367
7368          Act_Body :=
7369            Copy_Generic_Node
7370              (Original_Node (Gen_Body), Empty, Instantiating => True);
7371          Act_Body_Id := Defining_Entity (Act_Body);
7372          Set_Chars (Act_Body_Id, Chars (Anon_Id));
7373          Set_Sloc (Act_Body_Id, Sloc (Defining_Entity (Inst_Node)));
7374          Set_Corresponding_Spec (Act_Body, Anon_Id);
7375          Set_Has_Completion (Anon_Id);
7376          Check_Generic_Actuals (Pack_Id, False);
7377
7378          --  If it is a child unit, make the parent instance (which is an
7379          --  instance of the parent of the generic) visible. The parent
7380          --  instance is the prefix of the name of the generic unit.
7381
7382          if Ekind (Scope (Gen_Unit)) = E_Generic_Package
7383            and then Nkind (Gen_Id) = N_Expanded_Name
7384          then
7385             Install_Parent (Entity (Prefix (Gen_Id)), In_Body => True);
7386             Parent_Installed := True;
7387
7388          elsif Is_Child_Unit (Gen_Unit) then
7389             Install_Parent (Scope (Gen_Unit), In_Body => True);
7390             Parent_Installed := True;
7391          end if;
7392
7393          --  Inside its body, a reference to the generic unit is a reference
7394          --  to the instance. The corresponding renaming is the first
7395          --  declaration in the body.
7396
7397          Unit_Renaming :=
7398            Make_Subprogram_Renaming_Declaration (Loc,
7399              Specification =>
7400                Copy_Generic_Node (
7401                  Specification (Original_Node (Gen_Body)),
7402                  Empty,
7403                  Instantiating => True),
7404              Name => New_Occurrence_Of (Anon_Id, Loc));
7405
7406          --  If there is a formal subprogram with the same name as the
7407          --  unit itself, do not add this renaming declaration. This is
7408          --  a temporary fix for one ACVC test. ???
7409
7410          Prev_Formal := First_Entity (Pack_Id);
7411          while Present (Prev_Formal) loop
7412             if Chars (Prev_Formal) = Chars (Gen_Unit)
7413               and then Is_Overloadable (Prev_Formal)
7414             then
7415                exit;
7416             end if;
7417
7418             Next_Entity (Prev_Formal);
7419          end loop;
7420
7421          if Present (Prev_Formal) then
7422             Decls :=  New_List (Act_Body);
7423          else
7424             Decls :=  New_List (Unit_Renaming, Act_Body);
7425          end if;
7426
7427          --  The subprogram body is placed in the body of a dummy package
7428          --  body, whose spec contains the subprogram declaration as well
7429          --  as the renaming declarations for the generic parameters.
7430
7431          Pack_Body := Make_Package_Body (Loc,
7432            Defining_Unit_Name => New_Copy (Pack_Id),
7433            Declarations       => Decls);
7434
7435          Set_Corresponding_Spec (Pack_Body, Pack_Id);
7436
7437          --  If the instantiation is a library unit, then build resulting
7438          --  compilation unit nodes for the instance. The declaration of
7439          --  the enclosing package is the grandparent of the subprogram
7440          --  declaration. First replace the instantiation node as the unit
7441          --  of the corresponding compilation.
7442
7443          if Nkind (Parent (Inst_Node)) = N_Compilation_Unit then
7444             if Parent (Inst_Node) = Cunit (Main_Unit) then
7445                Set_Unit (Parent (Inst_Node), Inst_Node);
7446                Build_Instance_Compilation_Unit_Nodes
7447                  (Inst_Node, Pack_Body, Parent (Parent (Act_Decl)));
7448                Analyze (Inst_Node);
7449             else
7450                Set_Parent (Pack_Body, Parent (Inst_Node));
7451                Analyze (Pack_Body);
7452             end if;
7453
7454          else
7455             Insert_Before (Inst_Node, Pack_Body);
7456             Mark_Rewrite_Insertion (Pack_Body);
7457             Analyze (Pack_Body);
7458
7459             if Expander_Active then
7460                Freeze_Subprogram_Body (Inst_Node, Gen_Body, Pack_Id);
7461             end if;
7462          end if;
7463
7464          if not Generic_Separately_Compiled (Gen_Unit) then
7465             Inherit_Context (Gen_Body, Inst_Node);
7466          end if;
7467
7468          Restore_Private_Views (Pack_Id, False);
7469
7470          if Parent_Installed then
7471             Remove_Parent (In_Body => True);
7472          end if;
7473
7474          Restore_Env;
7475          Style_Check := Save_Style_Check;
7476
7477       --  Body not found. Error was emitted already. If there were no
7478       --  previous errors, this may be an instance whose scope is a premature
7479       --  instance. In that case we must insure that the (legal) program does
7480       --  raise program error if executed. We generate a subprogram body for
7481       --  this purpose. See DEC ac30vso.
7482
7483       elsif Serious_Errors_Detected = 0
7484         and then Nkind (Parent (Inst_Node)) /= N_Compilation_Unit
7485       then
7486          if Ekind (Anon_Id) = E_Procedure then
7487             Act_Body :=
7488               Make_Subprogram_Body (Loc,
7489                  Specification              =>
7490                    Make_Procedure_Specification (Loc,
7491                      Defining_Unit_Name         => New_Copy (Anon_Id),
7492                        Parameter_Specifications =>
7493                        New_Copy_List
7494                          (Parameter_Specifications (Parent (Anon_Id)))),
7495
7496                  Declarations               => Empty_List,
7497                  Handled_Statement_Sequence =>
7498                    Make_Handled_Sequence_Of_Statements (Loc,
7499                      Statements =>
7500                        New_List (
7501                          Make_Raise_Program_Error (Loc,
7502                            Reason =>
7503                              PE_Access_Before_Elaboration))));
7504
7505          else
7506             Ret_Expr :=
7507               Make_Raise_Program_Error (Loc,
7508                 Reason => PE_Access_Before_Elaboration);
7509
7510             Set_Etype (Ret_Expr, (Etype (Anon_Id)));
7511             Set_Analyzed (Ret_Expr);
7512
7513             Act_Body :=
7514               Make_Subprogram_Body (Loc,
7515                 Specification =>
7516                   Make_Function_Specification (Loc,
7517                      Defining_Unit_Name         => New_Copy (Anon_Id),
7518                        Parameter_Specifications =>
7519                        New_Copy_List
7520                          (Parameter_Specifications (Parent (Anon_Id))),
7521                      Subtype_Mark =>
7522                        New_Occurrence_Of (Etype (Anon_Id), Loc)),
7523
7524                   Declarations               => Empty_List,
7525                   Handled_Statement_Sequence =>
7526                     Make_Handled_Sequence_Of_Statements (Loc,
7527                       Statements =>
7528                         New_List (Make_Return_Statement (Loc, Ret_Expr))));
7529          end if;
7530
7531          Pack_Body := Make_Package_Body (Loc,
7532            Defining_Unit_Name => New_Copy (Pack_Id),
7533            Declarations       => New_List (Act_Body));
7534
7535          Insert_After (Inst_Node, Pack_Body);
7536          Set_Corresponding_Spec (Pack_Body, Pack_Id);
7537          Analyze (Pack_Body);
7538       end if;
7539
7540       Expander_Mode_Restore;
7541    end Instantiate_Subprogram_Body;
7542
7543    ----------------------
7544    -- Instantiate_Type --
7545    ----------------------
7546
7547    function Instantiate_Type
7548      (Formal          : Node_Id;
7549       Actual          : Node_Id;
7550       Analyzed_Formal : Node_Id;
7551       Actual_Decls    : List_Id)
7552       return            Node_Id
7553    is
7554       Loc       : constant Source_Ptr := Sloc (Actual);
7555       Gen_T     : constant Entity_Id  := Defining_Identifier (Formal);
7556       A_Gen_T   : constant Entity_Id  := Defining_Identifier (Analyzed_Formal);
7557       Ancestor  : Entity_Id := Empty;
7558       Def       : constant Node_Id    := Formal_Type_Definition (Formal);
7559       Act_T     : Entity_Id;
7560       Decl_Node : Node_Id;
7561
7562       procedure Validate_Array_Type_Instance;
7563       procedure Validate_Access_Subprogram_Instance;
7564       procedure Validate_Access_Type_Instance;
7565       procedure Validate_Derived_Type_Instance;
7566       procedure Validate_Private_Type_Instance;
7567       --  These procedures perform validation tests for the named case
7568
7569       function Subtypes_Match (Gen_T, Act_T : Entity_Id) return Boolean;
7570       --  Check that base types are the same and that the subtypes match
7571       --  statically. Used in several of the above.
7572
7573       --------------------
7574       -- Subtypes_Match --
7575       --------------------
7576
7577       function Subtypes_Match (Gen_T, Act_T : Entity_Id) return Boolean is
7578          T : constant Entity_Id := Get_Instance_Of (Gen_T);
7579
7580       begin
7581          return (Base_Type (T) = Base_Type (Act_T)
7582 --  why is the and then commented out here???
7583 --                  and then Is_Constrained (T) = Is_Constrained (Act_T)
7584                   and then Subtypes_Statically_Match (T, Act_T))
7585
7586            or else (Is_Class_Wide_Type (Gen_T)
7587                      and then Is_Class_Wide_Type (Act_T)
7588                      and then
7589                        Subtypes_Match (
7590                          Get_Instance_Of (Root_Type (Gen_T)),
7591                          Root_Type (Act_T)));
7592       end Subtypes_Match;
7593
7594       -----------------------------------------
7595       -- Validate_Access_Subprogram_Instance --
7596       -----------------------------------------
7597
7598       procedure Validate_Access_Subprogram_Instance is
7599       begin
7600          if not Is_Access_Type (Act_T)
7601            or else Ekind (Designated_Type (Act_T)) /= E_Subprogram_Type
7602          then
7603             Error_Msg_NE
7604               ("expect access type in instantiation of &", Actual, Gen_T);
7605             Abandon_Instantiation (Actual);
7606          end if;
7607
7608          Check_Mode_Conformant
7609            (Designated_Type (Act_T),
7610             Designated_Type (A_Gen_T),
7611             Actual,
7612             Get_Inst => True);
7613
7614          if Ekind (Base_Type (Act_T)) = E_Access_Protected_Subprogram_Type then
7615             if Ekind (A_Gen_T) = E_Access_Subprogram_Type then
7616                Error_Msg_NE
7617                  ("protected access type not allowed for formal &",
7618                   Actual, Gen_T);
7619             end if;
7620
7621          elsif Ekind (A_Gen_T) = E_Access_Protected_Subprogram_Type then
7622             Error_Msg_NE
7623               ("expect protected access type for formal &",
7624                Actual, Gen_T);
7625          end if;
7626       end Validate_Access_Subprogram_Instance;
7627
7628       -----------------------------------
7629       -- Validate_Access_Type_Instance --
7630       -----------------------------------
7631
7632       procedure Validate_Access_Type_Instance is
7633          Desig_Type : constant Entity_Id :=
7634                         Find_Actual_Type
7635                           (Designated_Type (A_Gen_T), Scope (A_Gen_T));
7636
7637       begin
7638          if not Is_Access_Type (Act_T) then
7639             Error_Msg_NE
7640               ("expect access type in instantiation of &", Actual, Gen_T);
7641             Abandon_Instantiation (Actual);
7642          end if;
7643
7644          if Is_Access_Constant (A_Gen_T) then
7645             if not Is_Access_Constant (Act_T) then
7646                Error_Msg_N
7647                  ("actual type must be access-to-constant type", Actual);
7648                Abandon_Instantiation (Actual);
7649             end if;
7650          else
7651             if Is_Access_Constant (Act_T) then
7652                Error_Msg_N
7653                  ("actual type must be access-to-variable type", Actual);
7654                Abandon_Instantiation (Actual);
7655
7656             elsif Ekind (A_Gen_T) = E_General_Access_Type
7657               and then Ekind (Base_Type (Act_T)) /= E_General_Access_Type
7658             then
7659                Error_Msg_N ("actual must be general access type!", Actual);
7660                Error_Msg_NE ("add ALL to }!", Actual, Act_T);
7661                Abandon_Instantiation (Actual);
7662             end if;
7663          end if;
7664
7665          --  The designated subtypes, that is to say the subtypes introduced
7666          --  by an access type declaration (and not by a subtype declaration)
7667          --  must match.
7668
7669          if not Subtypes_Match
7670            (Desig_Type, Designated_Type (Base_Type (Act_T)))
7671          then
7672             Error_Msg_NE
7673               ("designated type of actual does not match that of formal &",
7674                  Actual, Gen_T);
7675             Abandon_Instantiation (Actual);
7676
7677          elsif Is_Access_Type (Designated_Type (Act_T))
7678            and then Is_Constrained (Designated_Type (Designated_Type (Act_T)))
7679                       /=
7680                   Is_Constrained (Designated_Type (Desig_Type))
7681          then
7682             Error_Msg_NE
7683               ("designated type of actual does not match that of formal &",
7684                  Actual, Gen_T);
7685             Abandon_Instantiation (Actual);
7686          end if;
7687       end Validate_Access_Type_Instance;
7688
7689       ----------------------------------
7690       -- Validate_Array_Type_Instance --
7691       ----------------------------------
7692
7693       procedure Validate_Array_Type_Instance is
7694          I1 : Node_Id;
7695          I2 : Node_Id;
7696          T2 : Entity_Id;
7697
7698          function Formal_Dimensions return Int;
7699          --  Count number of dimensions in array type formal
7700
7701          function Formal_Dimensions return Int is
7702             Num   : Int := 0;
7703             Index : Node_Id;
7704
7705          begin
7706             if Nkind (Def) = N_Constrained_Array_Definition then
7707                Index := First (Discrete_Subtype_Definitions (Def));
7708             else
7709                Index := First (Subtype_Marks (Def));
7710             end if;
7711
7712             while Present (Index) loop
7713                Num := Num + 1;
7714                Next_Index (Index);
7715             end loop;
7716
7717             return Num;
7718          end Formal_Dimensions;
7719
7720       --  Start of processing for Validate_Array_Type_Instance
7721
7722       begin
7723          if not Is_Array_Type (Act_T) then
7724             Error_Msg_NE
7725               ("expect array type in instantiation of &", Actual, Gen_T);
7726             Abandon_Instantiation (Actual);
7727
7728          elsif Nkind (Def) = N_Constrained_Array_Definition then
7729             if not (Is_Constrained (Act_T)) then
7730                Error_Msg_NE
7731                  ("expect constrained array in instantiation of &",
7732                   Actual, Gen_T);
7733                Abandon_Instantiation (Actual);
7734             end if;
7735
7736          else
7737             if Is_Constrained (Act_T) then
7738                Error_Msg_NE
7739                  ("expect unconstrained array in instantiation of &",
7740                   Actual, Gen_T);
7741                Abandon_Instantiation (Actual);
7742             end if;
7743          end if;
7744
7745          if Formal_Dimensions /= Number_Dimensions (Act_T) then
7746             Error_Msg_NE
7747               ("dimensions of actual do not match formal &", Actual, Gen_T);
7748             Abandon_Instantiation (Actual);
7749          end if;
7750
7751          I1 := First_Index (A_Gen_T);
7752          I2 := First_Index (Act_T);
7753          for J in 1 .. Formal_Dimensions loop
7754
7755             --  If the indices of the actual were given by a subtype_mark,
7756             --  the index was transformed into a range attribute. Retrieve
7757             --  the original type mark for checking.
7758
7759             if Is_Entity_Name (Original_Node (I2)) then
7760                T2 := Entity (Original_Node (I2));
7761             else
7762                T2 := Etype (I2);
7763             end if;
7764
7765             if not Subtypes_Match
7766               (Find_Actual_Type (Etype (I1), Scope (A_Gen_T)), T2)
7767             then
7768                Error_Msg_NE
7769                  ("index types of actual do not match those of formal &",
7770                   Actual, Gen_T);
7771                Abandon_Instantiation (Actual);
7772             end if;
7773
7774             Next_Index (I1);
7775             Next_Index (I2);
7776          end loop;
7777
7778          if not Subtypes_Match (
7779             Find_Actual_Type (Component_Type (A_Gen_T), Scope (A_Gen_T)),
7780             Component_Type (Act_T))
7781          then
7782             Error_Msg_NE
7783               ("component subtype of actual does not match that of formal &",
7784                Actual, Gen_T);
7785             Abandon_Instantiation (Actual);
7786          end if;
7787
7788          if Has_Aliased_Components (A_Gen_T)
7789            and then not Has_Aliased_Components (Act_T)
7790          then
7791             Error_Msg_NE
7792               ("actual must have aliased components to match formal type &",
7793                Actual, Gen_T);
7794          end if;
7795
7796       end Validate_Array_Type_Instance;
7797
7798       ------------------------------------
7799       -- Validate_Derived_Type_Instance --
7800       ------------------------------------
7801
7802       procedure Validate_Derived_Type_Instance is
7803          Actual_Discr   : Entity_Id;
7804          Ancestor_Discr : Entity_Id;
7805
7806       begin
7807          --  If the parent type in the generic declaration is itself
7808          --  a previous formal type, then it is local to the generic
7809          --  and absent from the analyzed generic definition. In  that
7810          --  case the ancestor is the instance of the formal (which must
7811          --  have been instantiated previously), unless the ancestor is
7812          --  itself a formal derived type. In this latter case (which is the
7813          --  subject of Corrigendum 8652/0038 (AI-202) the ancestor of the
7814          --  formals is the ancestor of its parent. Otherwise, the analyzed
7815          --  generic carries the parent type. If the parent type is defined
7816          --  in a previous formal package, then the scope of that formal
7817          --  package is that of the generic type itself, and it has already
7818          --  been mapped into the corresponding type in the actual package.
7819
7820          --  Common case: parent type defined outside of the generic
7821
7822          if Is_Entity_Name (Subtype_Mark (Def))
7823            and then Present (Entity (Subtype_Mark (Def)))
7824          then
7825             Ancestor := Get_Instance_Of (Entity (Subtype_Mark (Def)));
7826
7827          --  Check whether parent is defined in a previous formal package
7828
7829          elsif
7830            Scope (Scope (Base_Type (Etype (A_Gen_T)))) = Scope (A_Gen_T)
7831          then
7832             Ancestor :=
7833               Get_Instance_Of (Base_Type (Etype (A_Gen_T)));
7834
7835          --  The type may be a local derivation, or a type extension of
7836          --  a previous formal, or of a formal of a parent package.
7837
7838          elsif Is_Derived_Type (Get_Instance_Of (A_Gen_T))
7839           or else
7840             Ekind (Get_Instance_Of (A_Gen_T)) = E_Record_Type_With_Private
7841          then
7842             --  Check whether the parent is another derived formal type
7843             --  in the same generic unit.
7844
7845             if Etype (A_Gen_T) /= A_Gen_T
7846               and then Is_Generic_Type (Etype (A_Gen_T))
7847               and then Scope (Etype (A_Gen_T)) = Scope (A_Gen_T)
7848               and then Etype (Etype (A_Gen_T)) /= Etype (A_Gen_T)
7849             then
7850                --  Locate ancestor of parent from the subtype declaration
7851                --  created for the actual.
7852
7853                declare
7854                   Decl : Node_Id;
7855
7856                begin
7857                   Decl := First (Actual_Decls);
7858                   while Present (Decl) loop
7859                      if Nkind (Decl) = N_Subtype_Declaration
7860                        and then Chars (Defining_Identifier (Decl)) =
7861                                                     Chars (Etype (A_Gen_T))
7862                      then
7863                         Ancestor := Generic_Parent_Type (Decl);
7864                         exit;
7865                      else
7866                         Next (Decl);
7867                      end if;
7868                   end loop;
7869                end;
7870
7871                pragma Assert (Present (Ancestor));
7872
7873             else
7874                Ancestor :=
7875                  Get_Instance_Of (Base_Type (Get_Instance_Of (A_Gen_T)));
7876             end if;
7877
7878          else
7879             Ancestor := Get_Instance_Of (Etype (Base_Type (A_Gen_T)));
7880          end if;
7881
7882          if not Is_Ancestor (Base_Type (Ancestor), Act_T) then
7883             Error_Msg_NE
7884               ("expect type derived from & in instantiation",
7885                Actual, First_Subtype (Ancestor));
7886             Abandon_Instantiation (Actual);
7887          end if;
7888
7889          --  Perform atomic/volatile checks (RM C.6(12))
7890
7891          if Is_Atomic (Act_T) and then not Is_Atomic (Ancestor) then
7892             Error_Msg_N
7893               ("cannot have atomic actual type for non-atomic formal type",
7894                Actual);
7895
7896          elsif Is_Volatile (Act_T)
7897            and then not Is_Volatile (Ancestor)
7898            and then Is_By_Reference_Type (Ancestor)
7899          then
7900             Error_Msg_N
7901               ("cannot have volatile actual type for non-volatile formal type",
7902                Actual);
7903          end if;
7904
7905          --  It should not be necessary to check for unknown discriminants
7906          --  on Formal, but for some reason Has_Unknown_Discriminants is
7907          --  false for A_Gen_T, so Is_Indefinite_Subtype incorrectly
7908          --  returns False. This needs fixing. ???
7909
7910          if not Is_Indefinite_Subtype (A_Gen_T)
7911            and then not Unknown_Discriminants_Present (Formal)
7912            and then Is_Indefinite_Subtype (Act_T)
7913          then
7914             Error_Msg_N
7915               ("actual subtype must be constrained", Actual);
7916             Abandon_Instantiation (Actual);
7917          end if;
7918
7919          if not Unknown_Discriminants_Present (Formal) then
7920             if Is_Constrained (Ancestor) then
7921                if not Is_Constrained (Act_T) then
7922                   Error_Msg_N
7923                     ("actual subtype must be constrained", Actual);
7924                   Abandon_Instantiation (Actual);
7925                end if;
7926
7927             --  Ancestor is unconstrained
7928
7929             elsif Is_Constrained (Act_T) then
7930                if Ekind (Ancestor) = E_Access_Type
7931                  or else Is_Composite_Type (Ancestor)
7932                then
7933                   Error_Msg_N
7934                     ("actual subtype must be unconstrained", Actual);
7935                   Abandon_Instantiation (Actual);
7936                end if;
7937
7938             --  A class-wide type is only allowed if the formal has
7939             --  unknown discriminants.
7940
7941             elsif Is_Class_Wide_Type (Act_T)
7942               and then not Has_Unknown_Discriminants (Ancestor)
7943             then
7944                Error_Msg_NE
7945                  ("actual for & cannot be a class-wide type", Actual, Gen_T);
7946                Abandon_Instantiation (Actual);
7947
7948             --  Otherwise, the formal and actual shall have the same
7949             --  number of discriminants and each discriminant of the
7950             --  actual must correspond to a discriminant of the formal.
7951
7952             elsif Has_Discriminants (Act_T)
7953               and then not Has_Unknown_Discriminants (Act_T)
7954               and then Has_Discriminants (Ancestor)
7955             then
7956                Actual_Discr   := First_Discriminant (Act_T);
7957                Ancestor_Discr := First_Discriminant (Ancestor);
7958                while Present (Actual_Discr)
7959                  and then Present (Ancestor_Discr)
7960                loop
7961                   if Base_Type (Act_T) /= Base_Type (Ancestor) and then
7962                     not Present (Corresponding_Discriminant (Actual_Discr))
7963                   then
7964                      Error_Msg_NE
7965                        ("discriminant & does not correspond " &
7966                         "to ancestor discriminant", Actual, Actual_Discr);
7967                      Abandon_Instantiation (Actual);
7968                   end if;
7969
7970                   Next_Discriminant (Actual_Discr);
7971                   Next_Discriminant (Ancestor_Discr);
7972                end loop;
7973
7974                if Present (Actual_Discr) or else Present (Ancestor_Discr) then
7975                   Error_Msg_NE
7976                     ("actual for & must have same number of discriminants",
7977                      Actual, Gen_T);
7978                   Abandon_Instantiation (Actual);
7979                end if;
7980
7981             --  This case should be caught by the earlier check for
7982             --  for constrainedness, but the check here is added for
7983             --  completeness.
7984
7985             elsif Has_Discriminants (Act_T)
7986               and then not Has_Unknown_Discriminants (Act_T)
7987             then
7988                Error_Msg_NE
7989                  ("actual for & must not have discriminants", Actual, Gen_T);
7990                Abandon_Instantiation (Actual);
7991
7992             elsif Has_Discriminants (Ancestor) then
7993                Error_Msg_NE
7994                  ("actual for & must have known discriminants", Actual, Gen_T);
7995                Abandon_Instantiation (Actual);
7996             end if;
7997
7998             if not Subtypes_Statically_Compatible (Act_T, Ancestor) then
7999                Error_Msg_N
8000                  ("constraint on actual is incompatible with formal", Actual);
8001                Abandon_Instantiation (Actual);
8002             end if;
8003          end if;
8004       end Validate_Derived_Type_Instance;
8005
8006       ------------------------------------
8007       -- Validate_Private_Type_Instance --
8008       ------------------------------------
8009
8010       procedure Validate_Private_Type_Instance is
8011          Formal_Discr : Entity_Id;
8012          Actual_Discr : Entity_Id;
8013          Formal_Subt  : Entity_Id;
8014
8015       begin
8016          if Is_Limited_Type (Act_T)
8017            and then not Is_Limited_Type (A_Gen_T)
8018          then
8019             Error_Msg_NE
8020               ("actual for non-limited  & cannot be a limited type", Actual,
8021                Gen_T);
8022             Explain_Limited_Type (Act_T, Actual);
8023             Abandon_Instantiation (Actual);
8024
8025          elsif Is_Indefinite_Subtype (Act_T)
8026             and then not Is_Indefinite_Subtype (A_Gen_T)
8027             and then Ada_95
8028          then
8029             Error_Msg_NE
8030               ("actual for & must be a definite subtype", Actual, Gen_T);
8031
8032          elsif not Is_Tagged_Type (Act_T)
8033            and then Is_Tagged_Type (A_Gen_T)
8034          then
8035             Error_Msg_NE
8036               ("actual for & must be a tagged type", Actual, Gen_T);
8037
8038          elsif Has_Discriminants (A_Gen_T) then
8039             if not Has_Discriminants (Act_T) then
8040                Error_Msg_NE
8041                  ("actual for & must have discriminants", Actual, Gen_T);
8042                Abandon_Instantiation (Actual);
8043
8044             elsif Is_Constrained (Act_T) then
8045                Error_Msg_NE
8046                  ("actual for & must be unconstrained", Actual, Gen_T);
8047                Abandon_Instantiation (Actual);
8048
8049             else
8050                Formal_Discr := First_Discriminant (A_Gen_T);
8051                Actual_Discr := First_Discriminant (Act_T);
8052                while Formal_Discr /= Empty loop
8053                   if Actual_Discr = Empty then
8054                      Error_Msg_NE
8055                        ("discriminants on actual do not match formal",
8056                         Actual, Gen_T);
8057                      Abandon_Instantiation (Actual);
8058                   end if;
8059
8060                   Formal_Subt := Get_Instance_Of (Etype (Formal_Discr));
8061
8062                   --  access discriminants match if designated types do.
8063
8064                   if Ekind (Base_Type (Formal_Subt)) = E_Anonymous_Access_Type
8065                     and then (Ekind (Base_Type (Etype (Actual_Discr))))
8066                       = E_Anonymous_Access_Type
8067                     and then Get_Instance_Of (
8068                       Designated_Type (Base_Type (Formal_Subt)))
8069                       = Designated_Type (Base_Type (Etype (Actual_Discr)))
8070                   then
8071                      null;
8072
8073                   elsif Base_Type (Formal_Subt) /=
8074                                        Base_Type (Etype (Actual_Discr))
8075                   then
8076                      Error_Msg_NE
8077                        ("types of actual discriminants must match formal",
8078                         Actual, Gen_T);
8079                      Abandon_Instantiation (Actual);
8080
8081                   elsif not Subtypes_Statically_Match
8082                               (Formal_Subt, Etype (Actual_Discr))
8083                     and then Ada_95
8084                   then
8085                      Error_Msg_NE
8086                        ("subtypes of actual discriminants must match formal",
8087                         Actual, Gen_T);
8088                      Abandon_Instantiation (Actual);
8089                   end if;
8090
8091                   Next_Discriminant (Formal_Discr);
8092                   Next_Discriminant (Actual_Discr);
8093                end loop;
8094
8095                if Actual_Discr /= Empty then
8096                   Error_Msg_NE
8097                     ("discriminants on actual do not match formal",
8098                      Actual, Gen_T);
8099                   Abandon_Instantiation (Actual);
8100                end if;
8101             end if;
8102
8103          end if;
8104
8105          Ancestor := Gen_T;
8106       end Validate_Private_Type_Instance;
8107
8108    --  Start of processing for Instantiate_Type
8109
8110    begin
8111       if Get_Instance_Of (A_Gen_T) /= A_Gen_T then
8112          Error_Msg_N ("duplicate instantiation of generic type", Actual);
8113          return Error;
8114
8115       elsif not Is_Entity_Name (Actual)
8116         or else not Is_Type (Entity (Actual))
8117       then
8118          Error_Msg_NE
8119            ("expect valid subtype mark to instantiate &", Actual, Gen_T);
8120          Abandon_Instantiation (Actual);
8121
8122       else
8123          Act_T := Entity (Actual);
8124
8125          --  Deal with fixed/floating restrictions
8126
8127          if Is_Floating_Point_Type (Act_T) then
8128             Check_Restriction (No_Floating_Point, Actual);
8129          elsif Is_Fixed_Point_Type (Act_T) then
8130             Check_Restriction (No_Fixed_Point, Actual);
8131          end if;
8132
8133          --  Deal with error of using incomplete type as generic actual
8134
8135          if Ekind (Act_T) = E_Incomplete_Type then
8136             if No (Underlying_Type (Act_T)) then
8137                Error_Msg_N ("premature use of incomplete type", Actual);
8138                Abandon_Instantiation (Actual);
8139             else
8140                Act_T := Full_View (Act_T);
8141                Set_Entity (Actual, Act_T);
8142
8143                if Has_Private_Component (Act_T) then
8144                   Error_Msg_N
8145                     ("premature use of type with private component", Actual);
8146                end if;
8147             end if;
8148
8149          --  Deal with error of premature use of private type as generic actual
8150
8151          elsif Is_Private_Type (Act_T)
8152            and then Is_Private_Type (Base_Type (Act_T))
8153            and then not Is_Generic_Type (Act_T)
8154            and then not Is_Derived_Type (Act_T)
8155            and then No (Full_View (Root_Type (Act_T)))
8156          then
8157             Error_Msg_N ("premature use of private type", Actual);
8158
8159          elsif Has_Private_Component (Act_T) then
8160             Error_Msg_N
8161               ("premature use of type with private component", Actual);
8162          end if;
8163
8164          Set_Instance_Of (A_Gen_T, Act_T);
8165
8166          --  If the type is generic, the class-wide type may also be used
8167
8168          if Is_Tagged_Type (A_Gen_T)
8169            and then Is_Tagged_Type (Act_T)
8170            and then not Is_Class_Wide_Type (A_Gen_T)
8171          then
8172             Set_Instance_Of (Class_Wide_Type (A_Gen_T),
8173               Class_Wide_Type (Act_T));
8174          end if;
8175
8176          if not Is_Abstract (A_Gen_T)
8177            and then Is_Abstract (Act_T)
8178          then
8179             Error_Msg_N
8180               ("actual of non-abstract formal cannot be abstract", Actual);
8181          end if;
8182
8183          if Is_Scalar_Type (Gen_T) then
8184             Set_Instance_Of (Etype (A_Gen_T), Etype (Act_T));
8185          end if;
8186       end if;
8187
8188       case Nkind (Def) is
8189          when N_Formal_Private_Type_Definition =>
8190             Validate_Private_Type_Instance;
8191
8192          when N_Formal_Derived_Type_Definition =>
8193             Validate_Derived_Type_Instance;
8194
8195          when N_Formal_Discrete_Type_Definition =>
8196             if not Is_Discrete_Type (Act_T) then
8197                Error_Msg_NE
8198                  ("expect discrete type in instantiation of&", Actual, Gen_T);
8199                Abandon_Instantiation (Actual);
8200             end if;
8201
8202          when N_Formal_Signed_Integer_Type_Definition =>
8203             if not Is_Signed_Integer_Type (Act_T) then
8204                Error_Msg_NE
8205                  ("expect signed integer type in instantiation of&",
8206                   Actual, Gen_T);
8207                Abandon_Instantiation (Actual);
8208             end if;
8209
8210          when N_Formal_Modular_Type_Definition =>
8211             if not Is_Modular_Integer_Type (Act_T) then
8212                Error_Msg_NE
8213                  ("expect modular type in instantiation of &", Actual, Gen_T);
8214                Abandon_Instantiation (Actual);
8215             end if;
8216
8217          when N_Formal_Floating_Point_Definition =>
8218             if not Is_Floating_Point_Type (Act_T) then
8219                Error_Msg_NE
8220                  ("expect float type in instantiation of &", Actual, Gen_T);
8221                Abandon_Instantiation (Actual);
8222             end if;
8223
8224          when N_Formal_Ordinary_Fixed_Point_Definition =>
8225             if not Is_Ordinary_Fixed_Point_Type (Act_T) then
8226                Error_Msg_NE
8227                  ("expect ordinary fixed point type in instantiation of &",
8228                   Actual, Gen_T);
8229                Abandon_Instantiation (Actual);
8230             end if;
8231
8232          when N_Formal_Decimal_Fixed_Point_Definition =>
8233             if not Is_Decimal_Fixed_Point_Type (Act_T) then
8234                Error_Msg_NE
8235                  ("expect decimal type in instantiation of &",
8236                   Actual, Gen_T);
8237                Abandon_Instantiation (Actual);
8238             end if;
8239
8240          when N_Array_Type_Definition =>
8241             Validate_Array_Type_Instance;
8242
8243          when N_Access_To_Object_Definition =>
8244             Validate_Access_Type_Instance;
8245
8246          when N_Access_Function_Definition |
8247               N_Access_Procedure_Definition =>
8248             Validate_Access_Subprogram_Instance;
8249
8250          when others =>
8251             raise Program_Error;
8252
8253       end case;
8254
8255       Decl_Node :=
8256         Make_Subtype_Declaration (Loc,
8257           Defining_Identifier => New_Copy (Gen_T),
8258           Subtype_Indication  => New_Reference_To (Act_T, Loc));
8259
8260       if Is_Private_Type (Act_T) then
8261          Set_Has_Private_View (Subtype_Indication (Decl_Node));
8262
8263       elsif Is_Access_Type (Act_T)
8264         and then Is_Private_Type (Designated_Type (Act_T))
8265       then
8266          Set_Has_Private_View (Subtype_Indication (Decl_Node));
8267       end if;
8268
8269       --  Flag actual derived types so their elaboration produces the
8270       --  appropriate renamings for the primitive operations of the ancestor.
8271       --  Flag actual for formal private types as well, to determine whether
8272       --  operations in the private part may override inherited operations.
8273
8274       if Nkind (Def) = N_Formal_Derived_Type_Definition
8275         or else Nkind (Def) = N_Formal_Private_Type_Definition
8276       then
8277          Set_Generic_Parent_Type (Decl_Node, Ancestor);
8278       end if;
8279
8280       return Decl_Node;
8281    end Instantiate_Type;
8282
8283    ---------------------
8284    -- Is_In_Main_Unit --
8285    ---------------------
8286
8287    function Is_In_Main_Unit (N : Node_Id) return Boolean is
8288       Unum : constant Unit_Number_Type := Get_Source_Unit (N);
8289
8290       Current_Unit : Node_Id;
8291
8292    begin
8293       if Unum = Main_Unit then
8294          return True;
8295
8296       --  If the current unit is a subunit then it is either the main unit
8297       --  or is being compiled as part of the main unit.
8298
8299       elsif Nkind (N) = N_Compilation_Unit then
8300          return Nkind (Unit (N)) = N_Subunit;
8301       end if;
8302
8303       Current_Unit := Parent (N);
8304       while Present (Current_Unit)
8305         and then Nkind (Current_Unit) /= N_Compilation_Unit
8306       loop
8307          Current_Unit := Parent (Current_Unit);
8308       end loop;
8309
8310       --  The instantiation node is in the main unit, or else the current
8311       --  node (perhaps as the result of nested instantiations) is in the
8312       --  main unit, or in the declaration of the main unit, which in this
8313       --  last case must be a body.
8314
8315       return Unum = Main_Unit
8316         or else Current_Unit = Cunit (Main_Unit)
8317         or else Current_Unit = Library_Unit (Cunit (Main_Unit))
8318         or else (Present (Library_Unit (Current_Unit))
8319                   and then Is_In_Main_Unit (Library_Unit (Current_Unit)));
8320    end Is_In_Main_Unit;
8321
8322    ----------------------------
8323    -- Load_Parent_Of_Generic --
8324    ----------------------------
8325
8326    procedure Load_Parent_Of_Generic (N : Node_Id; Spec : Node_Id) is
8327       Comp_Unit        : constant Node_Id := Cunit (Get_Source_Unit (Spec));
8328       Save_Style_Check : constant Boolean := Style_Check;
8329       True_Parent      : Node_Id;
8330       Inst_Node        : Node_Id;
8331       OK               : Boolean;
8332
8333    begin
8334       if not In_Same_Source_Unit (N, Spec)
8335         or else Nkind (Unit (Comp_Unit)) = N_Package_Declaration
8336         or else (Nkind (Unit (Comp_Unit)) = N_Package_Body
8337                    and then not Is_In_Main_Unit (Spec))
8338       then
8339          --  Find body of parent of spec, and analyze it. A special case
8340          --  arises when the parent is an instantiation, that is to say when
8341          --  we are currently instantiating a nested generic. In that case,
8342          --  there is no separate file for the body of the enclosing instance.
8343          --  Instead, the enclosing body must be instantiated as if it were
8344          --  a pending instantiation, in order to produce the body for the
8345          --  nested generic we require now. Note that in that case the
8346          --  generic may be defined in a package body, the instance defined
8347          --  in the same package body, and the original enclosing body may not
8348          --  be in the main unit.
8349
8350          True_Parent := Parent (Spec);
8351          Inst_Node   := Empty;
8352
8353          while Present (True_Parent)
8354            and then Nkind (True_Parent) /= N_Compilation_Unit
8355          loop
8356             if Nkind (True_Parent) = N_Package_Declaration
8357               and then
8358                 Nkind (Original_Node (True_Parent)) = N_Package_Instantiation
8359             then
8360                --  Parent is a compilation unit that is an instantiation.
8361                --  Instantiation node has been replaced with package decl.
8362
8363                Inst_Node := Original_Node (True_Parent);
8364                exit;
8365
8366             elsif Nkind (True_Parent) = N_Package_Declaration
8367               and then Present (Generic_Parent (Specification (True_Parent)))
8368               and then Nkind (Parent (True_Parent)) /= N_Compilation_Unit
8369             then
8370                --  Parent is an instantiation within another specification.
8371                --  Declaration for instance has been inserted before original
8372                --  instantiation node. A direct link would be preferable?
8373
8374                Inst_Node := Next (True_Parent);
8375
8376                while Present (Inst_Node)
8377                  and then Nkind (Inst_Node) /= N_Package_Instantiation
8378                loop
8379                   Next (Inst_Node);
8380                end loop;
8381
8382                --  If the instance appears within a generic, and the generic
8383                --  unit is defined within a formal package of the enclosing
8384                --  generic, there is no generic body available, and none
8385                --  needed. A more precise test should be used ???
8386
8387                if No (Inst_Node) then
8388                   return;
8389                end if;
8390
8391                exit;
8392             else
8393                True_Parent := Parent (True_Parent);
8394             end if;
8395          end loop;
8396
8397          --  Case where we are currently instantiating a nested generic
8398
8399          if Present (Inst_Node) then
8400             if Nkind (Parent (True_Parent)) = N_Compilation_Unit then
8401
8402                --  Instantiation node and declaration of instantiated package
8403                --  were exchanged when only the declaration was needed.
8404                --  Restore instantiation node before proceeding with body.
8405
8406                Set_Unit (Parent (True_Parent), Inst_Node);
8407             end if;
8408
8409             --  Now complete instantiation of enclosing body, if it appears
8410             --  in some other unit. If it appears in the current unit, the
8411             --  body will have been instantiated already.
8412
8413             if No (Corresponding_Body (Instance_Spec (Inst_Node))) then
8414
8415                --  We need to determine the expander mode to instantiate
8416                --  the enclosing body. Because the generic body we need
8417                --  may use global entities declared in the enclosing package
8418                --  (including aggregates) it is in general necessary to
8419                --  compile this body with expansion enabled. The exception
8420                --  is if we are within a generic package, in which case
8421                --  the usual generic rule applies.
8422
8423                declare
8424                   Exp_Status : Boolean := True;
8425                   Scop       : Entity_Id;
8426
8427                begin
8428                   --  Loop through scopes looking for generic package
8429
8430                   Scop := Scope (Defining_Entity (Instance_Spec (Inst_Node)));
8431                   while Present (Scop)
8432                     and then Scop /= Standard_Standard
8433                   loop
8434                      if Ekind (Scop) = E_Generic_Package then
8435                         Exp_Status := False;
8436                         exit;
8437                      end if;
8438
8439                      Scop := Scope (Scop);
8440                   end loop;
8441
8442                   Instantiate_Package_Body
8443                     (Pending_Body_Info'(
8444                        Inst_Node, True_Parent, Exp_Status,
8445                          Get_Code_Unit (Sloc (Inst_Node))));
8446                end;
8447             end if;
8448
8449          --  Case where we are not instantiating a nested generic
8450
8451          else
8452             Opt.Style_Check := False;
8453             Expander_Mode_Save_And_Set (True);
8454             Load_Needed_Body (Comp_Unit, OK);
8455             Opt.Style_Check := Save_Style_Check;
8456             Expander_Mode_Restore;
8457
8458             if not OK
8459               and then Unit_Requires_Body (Defining_Entity (Spec))
8460             then
8461                declare
8462                   Bname : constant Unit_Name_Type :=
8463                             Get_Body_Name (Get_Unit_Name (Unit (Comp_Unit)));
8464
8465                begin
8466                   Error_Msg_Unit_1 := Bname;
8467                   Error_Msg_N ("this instantiation requires$!", N);
8468                   Error_Msg_Name_1 :=
8469                     Get_File_Name (Bname, Subunit => False);
8470                   Error_Msg_N ("\but file{ was not found!", N);
8471                   raise Unrecoverable_Error;
8472                end;
8473             end if;
8474          end if;
8475       end if;
8476
8477       --  If loading the parent of the generic caused an instantiation
8478       --  circularity, we abandon compilation at this point, because
8479       --  otherwise in some cases we get into trouble with infinite
8480       --  recursions after this point.
8481
8482       if Circularity_Detected then
8483          raise Unrecoverable_Error;
8484       end if;
8485    end Load_Parent_Of_Generic;
8486
8487    -----------------------
8488    -- Move_Freeze_Nodes --
8489    -----------------------
8490
8491    procedure Move_Freeze_Nodes
8492      (Out_Of : Entity_Id;
8493       After  : Node_Id;
8494       L      : List_Id)
8495    is
8496       Decl      : Node_Id;
8497       Next_Decl : Node_Id;
8498       Next_Node : Node_Id := After;
8499       Spec      : Node_Id;
8500
8501       function Is_Outer_Type (T : Entity_Id) return Boolean;
8502       --  Check whether entity is declared in a scope external to that
8503       --  of the generic unit.
8504
8505       -------------------
8506       -- Is_Outer_Type --
8507       -------------------
8508
8509       function Is_Outer_Type (T : Entity_Id) return Boolean is
8510          Scop : Entity_Id := Scope (T);
8511
8512       begin
8513          if Scope_Depth (Scop) < Scope_Depth (Out_Of) then
8514             return True;
8515
8516          else
8517             while Scop /= Standard_Standard loop
8518
8519                if Scop = Out_Of then
8520                   return False;
8521                else
8522                   Scop := Scope (Scop);
8523                end if;
8524             end loop;
8525
8526             return True;
8527          end if;
8528       end Is_Outer_Type;
8529
8530    --  Start of processing for Move_Freeze_Nodes
8531
8532    begin
8533       if No (L) then
8534          return;
8535       end if;
8536
8537       --  First remove the freeze nodes that may appear before all other
8538       --  declarations.
8539
8540       Decl := First (L);
8541       while Present (Decl)
8542         and then Nkind (Decl) = N_Freeze_Entity
8543         and then Is_Outer_Type (Entity (Decl))
8544       loop
8545          Decl := Remove_Head (L);
8546          Insert_After (Next_Node, Decl);
8547          Set_Analyzed (Decl, False);
8548          Next_Node := Decl;
8549          Decl := First (L);
8550       end loop;
8551
8552       --  Next scan the list of declarations and remove each freeze node that
8553       --  appears ahead of the current node.
8554
8555       while Present (Decl) loop
8556          while Present (Next (Decl))
8557            and then Nkind (Next (Decl)) = N_Freeze_Entity
8558            and then Is_Outer_Type (Entity (Next (Decl)))
8559          loop
8560             Next_Decl := Remove_Next (Decl);
8561             Insert_After (Next_Node, Next_Decl);
8562             Set_Analyzed (Next_Decl, False);
8563             Next_Node := Next_Decl;
8564          end loop;
8565
8566          --  If the declaration is a nested package or concurrent type, then
8567          --  recurse. Nested generic packages will have been processed from the
8568          --  inside out.
8569
8570          if Nkind (Decl) = N_Package_Declaration then
8571             Spec := Specification (Decl);
8572
8573          elsif Nkind (Decl) = N_Task_Type_Declaration then
8574             Spec := Task_Definition (Decl);
8575
8576          elsif Nkind (Decl) = N_Protected_Type_Declaration then
8577             Spec := Protected_Definition (Decl);
8578
8579          else
8580             Spec := Empty;
8581          end if;
8582
8583          if Present (Spec) then
8584             Move_Freeze_Nodes (Out_Of, Next_Node,
8585               Visible_Declarations (Spec));
8586             Move_Freeze_Nodes (Out_Of, Next_Node,
8587               Private_Declarations (Spec));
8588          end if;
8589
8590          Next (Decl);
8591       end loop;
8592    end Move_Freeze_Nodes;
8593
8594    ----------------
8595    -- Next_Assoc --
8596    ----------------
8597
8598    function Next_Assoc (E : Assoc_Ptr) return Assoc_Ptr is
8599    begin
8600       return Generic_Renamings.Table (E).Next_In_HTable;
8601    end Next_Assoc;
8602
8603    ------------------------
8604    -- Preanalyze_Actuals --
8605    ------------------------
8606
8607    procedure Pre_Analyze_Actuals (N : Node_Id) is
8608       Assoc : Node_Id;
8609       Act   : Node_Id;
8610       Errs  : constant Int := Serious_Errors_Detected;
8611
8612    begin
8613       Assoc := First (Generic_Associations (N));
8614
8615       while Present (Assoc) loop
8616          Act := Explicit_Generic_Actual_Parameter (Assoc);
8617
8618          --  Within a nested instantiation, a defaulted actual is an
8619          --  empty association, so nothing to analyze. If the actual for
8620          --  a subprogram is an attribute, analyze prefix only, because
8621          --  actual is not a complete attribute reference.
8622
8623          --  If actual is an allocator, analyze expression only. The full
8624          --  analysis can generate code, and if the instance is a compilation
8625          --  unit we have to wait until the package instance is installed to
8626          --  have a proper place to insert this code.
8627
8628          --  String literals may be operators, but at this point we do not
8629          --  know whether the actual is a formal subprogram or a string.
8630
8631          if No (Act) then
8632             null;
8633
8634          elsif Nkind (Act) = N_Attribute_Reference then
8635             Analyze (Prefix (Act));
8636
8637          elsif Nkind (Act) = N_Explicit_Dereference then
8638             Analyze (Prefix (Act));
8639
8640          elsif Nkind (Act) = N_Allocator then
8641             declare
8642                Expr : constant Node_Id := Expression (Act);
8643
8644             begin
8645                if Nkind (Expr) = N_Subtype_Indication then
8646                   Analyze (Subtype_Mark (Expr));
8647                   Analyze_List (Constraints (Constraint (Expr)));
8648                else
8649                   Analyze (Expr);
8650                end if;
8651             end;
8652
8653          elsif Nkind (Act) /= N_Operator_Symbol then
8654             Analyze (Act);
8655          end if;
8656
8657          if Errs /= Serious_Errors_Detected then
8658             Abandon_Instantiation (Act);
8659          end if;
8660
8661          Next (Assoc);
8662       end loop;
8663    end Pre_Analyze_Actuals;
8664
8665    -------------------
8666    -- Remove_Parent --
8667    -------------------
8668
8669    procedure Remove_Parent (In_Body : Boolean := False) is
8670       S      : Entity_Id := Current_Scope;
8671       E      : Entity_Id;
8672       P      : Entity_Id;
8673       Hidden : Elmt_Id;
8674
8675    begin
8676       --  After child instantiation is complete, remove from scope stack
8677       --  the extra copy of the current scope, and then remove parent
8678       --  instances.
8679
8680       if not In_Body then
8681          Pop_Scope;
8682
8683          while Current_Scope /= S loop
8684             P := Current_Scope;
8685             End_Package_Scope (Current_Scope);
8686
8687             if In_Open_Scopes (P) then
8688                E := First_Entity (P);
8689
8690                while Present (E) loop
8691                   Set_Is_Immediately_Visible (E, True);
8692                   Next_Entity (E);
8693                end loop;
8694
8695                if Is_Generic_Instance (Current_Scope)
8696                  and then P /= Current_Scope
8697                then
8698                   --  We are within an instance of some sibling. Retain
8699                   --  visibility of parent, for proper subsequent cleanup.
8700
8701                   Set_In_Private_Part (P);
8702                end if;
8703
8704             --  This looks incomplete: what about compilation units that
8705             --  were made visible by Install_Parent but should not remain
8706             --  visible??? Standard is on the scope stack.
8707
8708             elsif not In_Open_Scopes (Scope (P)) then
8709                Set_Is_Immediately_Visible (P, False);
8710             end if;
8711          end loop;
8712
8713          --  Reset visibility of entities in the enclosing scope.
8714
8715          Set_Is_Hidden_Open_Scope (Current_Scope, False);
8716          Hidden := First_Elmt (Hidden_Entities);
8717
8718          while Present (Hidden) loop
8719             Set_Is_Immediately_Visible (Node (Hidden), True);
8720             Next_Elmt (Hidden);
8721          end loop;
8722
8723       else
8724          --  Each body is analyzed separately, and there is no context
8725          --  that needs preserving from one body instance to the next,
8726          --  so remove all parent scopes that have been installed.
8727
8728          while Present (S) loop
8729             End_Package_Scope (S);
8730             Set_Is_Immediately_Visible (S, False);
8731             S := Current_Scope;
8732             exit when S = Standard_Standard;
8733          end loop;
8734       end if;
8735
8736    end Remove_Parent;
8737
8738    -----------------
8739    -- Restore_Env --
8740    -----------------
8741
8742    procedure Restore_Env is
8743       Saved : Instance_Env renames Instance_Envs.Table (Instance_Envs.Last);
8744
8745    begin
8746       Ada_83                       := Saved.Ada_83;
8747
8748       if No (Current_Instantiated_Parent.Act_Id) then
8749
8750          --  Restore environment after subprogram inlining
8751
8752          Restore_Private_Views (Empty);
8753       end if;
8754
8755       Current_Instantiated_Parent  := Saved.Instantiated_Parent;
8756       Exchanged_Views              := Saved.Exchanged_Views;
8757       Hidden_Entities              := Saved.Hidden_Entities;
8758       Current_Sem_Unit             := Saved.Current_Sem_Unit;
8759
8760       Instance_Envs.Decrement_Last;
8761    end Restore_Env;
8762
8763    ---------------------------
8764    -- Restore_Private_Views --
8765    ---------------------------
8766
8767    procedure Restore_Private_Views
8768      (Pack_Id    : Entity_Id;
8769       Is_Package : Boolean := True)
8770    is
8771       M        : Elmt_Id;
8772       E        : Entity_Id;
8773       Typ      : Entity_Id;
8774       Dep_Elmt : Elmt_Id;
8775       Dep_Typ  : Node_Id;
8776
8777    begin
8778       M := First_Elmt (Exchanged_Views);
8779       while Present (M) loop
8780          Typ := Node (M);
8781
8782          --  Subtypes of types whose views have been exchanged, and that
8783          --  are defined within the instance, were not on the list of
8784          --  Private_Dependents on entry to the instance, so they have to
8785          --  be exchanged explicitly now, in order to remain consistent with
8786          --  the view of the parent type.
8787
8788          if Ekind (Typ) = E_Private_Type
8789            or else Ekind (Typ) = E_Limited_Private_Type
8790            or else Ekind (Typ) = E_Record_Type_With_Private
8791          then
8792             Dep_Elmt := First_Elmt (Private_Dependents (Typ));
8793
8794             while Present (Dep_Elmt) loop
8795                Dep_Typ := Node (Dep_Elmt);
8796
8797                if Scope (Dep_Typ) = Pack_Id
8798                  and then Present (Full_View (Dep_Typ))
8799                then
8800                   Replace_Elmt (Dep_Elmt, Full_View (Dep_Typ));
8801                   Exchange_Declarations (Dep_Typ);
8802                end if;
8803
8804                Next_Elmt (Dep_Elmt);
8805             end loop;
8806          end if;
8807
8808          Exchange_Declarations (Node (M));
8809          Next_Elmt (M);
8810       end loop;
8811
8812       if No (Pack_Id) then
8813          return;
8814       end if;
8815
8816       --  Make the generic formal parameters private, and make the formal
8817       --  types into subtypes of the actuals again.
8818
8819       E := First_Entity (Pack_Id);
8820
8821       while Present (E) loop
8822          Set_Is_Hidden (E, True);
8823
8824          if Is_Type (E)
8825            and then Nkind (Parent (E)) = N_Subtype_Declaration
8826          then
8827             Set_Is_Generic_Actual_Type (E, False);
8828
8829             --  An unusual case of aliasing: the actual may also be directly
8830             --  visible in the generic, and be private there, while it is
8831             --  fully visible in the context of the instance. The internal
8832             --  subtype is private in the instance, but has full visibility
8833             --  like its parent in the enclosing scope. This enforces the
8834             --  invariant that the privacy status of all private dependents of
8835             --  a type coincide with that of the parent type. This can only
8836             --  happen when a generic child unit is instantiated within a
8837             --  sibling.
8838
8839             if Is_Private_Type (E)
8840               and then not Is_Private_Type (Etype (E))
8841             then
8842                Exchange_Declarations (E);
8843             end if;
8844
8845          elsif Ekind (E) = E_Package then
8846
8847             --  The end of the renaming list is the renaming of the generic
8848             --  package itself. If the instance is a subprogram, all entities
8849             --  in the corresponding package are renamings. If this entity is
8850             --  a formal package, make its own formals private as well. The
8851             --  actual in this case is itself the renaming of an instantation.
8852             --  If the entity is not a package renaming, it is the entity
8853             --  created to validate formal package actuals: ignore.
8854
8855             --  If the actual is itself a formal package for the enclosing
8856             --  generic, or the actual for such a formal package, it remains
8857             --  visible after the current instance, and therefore nothing
8858             --  needs to be done either, except to keep it accessible.
8859
8860             if Is_Package
8861               and then Renamed_Object (E) = Pack_Id
8862             then
8863                exit;
8864
8865             elsif Nkind (Parent (E)) /= N_Package_Renaming_Declaration then
8866                null;
8867
8868             elsif Denotes_Formal_Package (Renamed_Object (E)) then
8869                Set_Is_Hidden (E, False);
8870
8871             else
8872                declare
8873                   Act_P : constant Entity_Id := Renamed_Object (E);
8874                   Id    : Entity_Id;
8875
8876                begin
8877                   Id := First_Entity (Act_P);
8878                   while Present (Id)
8879                     and then Id /= First_Private_Entity (Act_P)
8880                   loop
8881                      Set_Is_Hidden (Id, True);
8882                      Set_Is_Potentially_Use_Visible (Id, In_Use (Act_P));
8883                      exit when Ekind (Id) = E_Package
8884                                  and then Renamed_Object (Id) = Act_P;
8885
8886                      Next_Entity (Id);
8887                   end loop;
8888                end;
8889                null;
8890             end if;
8891          end if;
8892
8893          Next_Entity (E);
8894       end loop;
8895    end Restore_Private_Views;
8896
8897    --------------
8898    -- Save_Env --
8899    --------------
8900
8901    procedure Save_Env
8902      (Gen_Unit : Entity_Id;
8903       Act_Unit : Entity_Id)
8904    is
8905    begin
8906       Init_Env;
8907       Set_Instance_Env (Gen_Unit, Act_Unit);
8908    end Save_Env;
8909
8910    ----------------------------
8911    -- Save_Global_References --
8912    ----------------------------
8913
8914    procedure Save_Global_References (N : Node_Id) is
8915       Gen_Scope : Entity_Id;
8916       E         : Entity_Id;
8917       N2        : Node_Id;
8918
8919       function Is_Global (E : Entity_Id) return Boolean;
8920       --  Check whether entity is defined outside of generic unit.
8921       --  Examine the scope of an entity, and the scope of the scope,
8922       --  etc, until we find either Standard, in which case the entity
8923       --  is global, or the generic unit itself, which indicates that
8924       --  the entity is local. If the entity is the generic unit itself,
8925       --  as in the case of a recursive call, or the enclosing generic unit,
8926       --  if different from the current scope, then it is local as well,
8927       --  because it will be replaced at the point of instantiation. On
8928       --  the other hand, if it is a reference to a child unit of a common
8929       --  ancestor, which appears in an instantiation, it is global because
8930       --  it is used to denote a specific compilation unit at the time the
8931       --  instantiations will be analyzed.
8932
8933       procedure Reset_Entity (N : Node_Id);
8934       --  Save semantic information on global entity, so that it is not
8935       --  resolved again at instantiation time.
8936
8937       procedure Save_Entity_Descendants (N : Node_Id);
8938       --  Apply Save_Global_References to the two syntactic descendants of
8939       --  non-terminal nodes that carry an Associated_Node and are processed
8940       --  through Reset_Entity. Once the global entity (if any) has been
8941       --  captured together with its type, only two syntactic descendants
8942       --  need to be traversed to complete the processing of the tree rooted
8943       --  at N. This applies to Selected_Components, Expanded_Names, and to
8944       --  Operator nodes. N can also be a character literal, identifier, or
8945       --  operator symbol node, but the call has no effect in these cases.
8946
8947       procedure Save_Global_Defaults (N1, N2 : Node_Id);
8948       --  Default actuals in nested instances must be handled specially
8949       --  because there is no link to them from the original tree. When an
8950       --  actual subprogram is given by a default, we add an explicit generic
8951       --  association for it in the instantiation node. When we save the
8952       --  global references on the name of the instance, we recover the list
8953       --  of generic associations, and add an explicit one to the original
8954       --  generic tree, through which a global actual can be preserved.
8955       --  Similarly, if a child unit is instantiated within a sibling, in the
8956       --  context of the parent, we must preserve the identifier of the parent
8957       --  so that it can be properly resolved in a subsequent instantiation.
8958
8959       procedure Save_Global_Descendant (D : Union_Id);
8960       --  Apply Save_Global_References recursively to the descendents of
8961       --  current node.
8962
8963       procedure Save_References (N : Node_Id);
8964       --  This is the recursive procedure that does the work, once the
8965       --  enclosing generic scope has been established.
8966
8967       ---------------
8968       -- Is_Global --
8969       ---------------
8970
8971       function Is_Global (E : Entity_Id) return Boolean is
8972          Se  : Entity_Id := Scope (E);
8973
8974          function Is_Instance_Node (Decl : Node_Id) return Boolean;
8975          --  Determine whether the parent node of a reference to a child unit
8976          --  denotes an instantiation or a formal package, in which case the
8977          --  reference to the child unit is global, even if it appears within
8978          --  the current scope (e.g. when the instance appears within the body
8979          --  of an ancestor).
8980
8981          function Is_Instance_Node (Decl : Node_Id) return Boolean is
8982          begin
8983             return (Nkind (Decl) in N_Generic_Instantiation
8984               or else
8985                 Nkind (Original_Node (Decl)) = N_Formal_Package_Declaration);
8986          end Is_Instance_Node;
8987
8988       --  Start of processing for Is_Global
8989
8990       begin
8991          if E = Gen_Scope then
8992             return False;
8993
8994          elsif E = Standard_Standard then
8995             return True;
8996
8997          elsif Is_Child_Unit (E)
8998            and then (Is_Instance_Node (Parent (N2))
8999              or else (Nkind (Parent (N2)) = N_Expanded_Name
9000                        and then N2 = Selector_Name (Parent (N2))
9001                        and then Is_Instance_Node (Parent (Parent (N2)))))
9002          then
9003             return True;
9004
9005          else
9006             while Se /= Gen_Scope loop
9007                if Se = Standard_Standard then
9008                   return True;
9009                else
9010                   Se := Scope (Se);
9011                end if;
9012             end loop;
9013
9014             return False;
9015          end if;
9016       end Is_Global;
9017
9018       ------------------
9019       -- Reset_Entity --
9020       ------------------
9021
9022       procedure Reset_Entity (N : Node_Id) is
9023
9024          procedure Set_Global_Type (N : Node_Id; N2 : Node_Id);
9025          --  The type of N2 is global to the generic unit. Save the
9026          --  type in the generic node.
9027
9028          function Top_Ancestor (E : Entity_Id) return Entity_Id;
9029          --  Find the ultimate ancestor of the current unit. If it is
9030          --  not a generic unit, then the name of the current unit
9031          --  in the prefix of an expanded name must be replaced with
9032          --  its generic homonym to ensure that it will be properly
9033          --  resolved in an instance.
9034
9035          ---------------------
9036          -- Set_Global_Type --
9037          ---------------------
9038
9039          procedure Set_Global_Type (N : Node_Id; N2 : Node_Id) is
9040             Typ : constant Entity_Id := Etype (N2);
9041
9042          begin
9043             Set_Etype (N, Typ);
9044
9045             if Entity (N) /= N2
9046               and then Has_Private_View (Entity (N))
9047             then
9048                --  If the entity of N is not the associated node, this is
9049                --  a nested generic and it has an associated node as well,
9050                --  whose type is already the full view (see below). Indicate
9051                --  that the original node has a private view.
9052
9053                Set_Has_Private_View (N);
9054             end if;
9055
9056             --  If not a private type, nothing else to do
9057
9058             if not Is_Private_Type (Typ) then
9059                if Is_Array_Type (Typ)
9060                  and then Is_Private_Type (Component_Type (Typ))
9061                then
9062                   Set_Has_Private_View (N);
9063                end if;
9064
9065             --  If it is a derivation of a private type in a context where
9066             --  no full view is needed, nothing to do either.
9067
9068             elsif No (Full_View (Typ)) and then Typ /= Etype (Typ) then
9069                null;
9070
9071             --  Otherwise mark the type for flipping and use the full_view
9072             --  when available.
9073
9074             else
9075                Set_Has_Private_View (N);
9076
9077                if Present (Full_View (Typ)) then
9078                   Set_Etype (N2, Full_View (Typ));
9079                end if;
9080             end if;
9081          end Set_Global_Type;
9082
9083          ------------------
9084          -- Top_Ancestor --
9085          ------------------
9086
9087          function Top_Ancestor (E : Entity_Id) return Entity_Id is
9088             Par : Entity_Id := E;
9089
9090          begin
9091             while Is_Child_Unit (Par) loop
9092                Par := Scope (Par);
9093             end loop;
9094
9095             return Par;
9096          end Top_Ancestor;
9097
9098       --  Start of processing for Reset_Entity
9099
9100       begin
9101          N2 := Get_Associated_Node (N);
9102          E := Entity (N2);
9103
9104          if Present (E) then
9105             if Is_Global (E) then
9106                Set_Global_Type (N, N2);
9107
9108             elsif Nkind (N) = N_Op_Concat
9109               and then Is_Generic_Type (Etype (N2))
9110               and then
9111                (Base_Type (Etype (Right_Opnd (N2))) = Etype (N2)
9112                   or else Base_Type (Etype (Left_Opnd (N2))) = Etype (N2))
9113               and then Is_Intrinsic_Subprogram (E)
9114             then
9115                null;
9116
9117             else
9118                --  Entity is local. Mark generic node as unresolved.
9119                --  Note that now it does not have an entity.
9120
9121                Set_Associated_Node (N, Empty);
9122                Set_Etype  (N, Empty);
9123             end if;
9124
9125             if (Nkind (Parent (N)) = N_Package_Instantiation
9126                  or else Nkind (Parent (N)) = N_Function_Instantiation
9127                  or else Nkind (Parent (N)) = N_Procedure_Instantiation)
9128               and then N = Name (Parent (N))
9129             then
9130                Save_Global_Defaults (Parent (N), Parent (N2));
9131             end if;
9132
9133          elsif Nkind (Parent (N)) = N_Selected_Component
9134            and then Nkind (Parent (N2)) = N_Expanded_Name
9135          then
9136
9137             if Is_Global (Entity (Parent (N2))) then
9138                Change_Selected_Component_To_Expanded_Name (Parent (N));
9139                Set_Associated_Node (Parent (N), Parent (N2));
9140                Set_Global_Type (Parent (N), Parent (N2));
9141                Save_Entity_Descendants (N);
9142
9143             --  If this is a reference to the current generic entity,
9144             --  replace by the name of the generic homonym of the current
9145             --  package. This is because in an instantiation  Par.P.Q will
9146             --  not resolve to the name of the instance, whose enclosing
9147             --  scope is not necessarily Par. We use the generic homonym
9148             --  rather that the name of the generic itself, because it may
9149             --  be hidden by a local declaration.
9150
9151             elsif In_Open_Scopes (Entity (Parent (N2)))
9152               and then not
9153                 Is_Generic_Unit (Top_Ancestor (Entity (Prefix (Parent (N2)))))
9154             then
9155                if Ekind (Entity (Parent (N2))) = E_Generic_Package then
9156                   Rewrite (Parent (N),
9157                     Make_Identifier (Sloc (N),
9158                       Chars =>
9159                         Chars (Generic_Homonym (Entity (Parent (N2))))));
9160                else
9161                   Rewrite (Parent (N),
9162                     Make_Identifier (Sloc (N),
9163                       Chars => Chars (Selector_Name (Parent (N2)))));
9164                end if;
9165             end if;
9166
9167             if (Nkind (Parent (Parent (N))) = N_Package_Instantiation
9168                  or else Nkind (Parent (Parent (N)))
9169                    = N_Function_Instantiation
9170                  or else Nkind (Parent (Parent (N)))
9171                    = N_Procedure_Instantiation)
9172               and then Parent (N) = Name (Parent (Parent (N)))
9173             then
9174                Save_Global_Defaults
9175                  (Parent (Parent (N)), Parent (Parent ((N2))));
9176             end if;
9177
9178          --  A selected component may denote a static constant that has
9179          --  been folded. Make the same replacement in original tree.
9180
9181          elsif Nkind (Parent (N)) = N_Selected_Component
9182            and then (Nkind (Parent (N2)) = N_Integer_Literal
9183                       or else Nkind (Parent (N2)) = N_Real_Literal)
9184          then
9185             Rewrite (Parent (N),
9186               New_Copy (Parent (N2)));
9187             Set_Analyzed (Parent (N), False);
9188
9189          --  A selected component may be transformed into a parameterless
9190          --  function call. If the called entity is global, rewrite the
9191          --  node appropriately, i.e. as an extended name for the global
9192          --  entity.
9193
9194          elsif Nkind (Parent (N)) = N_Selected_Component
9195            and then Nkind (Parent (N2)) = N_Function_Call
9196            and then Is_Global (Entity (Name (Parent (N2))))
9197          then
9198             Change_Selected_Component_To_Expanded_Name (Parent (N));
9199             Set_Associated_Node (Parent (N), Name (Parent (N2)));
9200             Set_Global_Type (Parent (N), Name (Parent (N2)));
9201             Save_Entity_Descendants (N);
9202
9203          else
9204             --  Entity is local. Reset in generic unit, so that node
9205             --  is resolved anew at the point of instantiation.
9206
9207             Set_Associated_Node (N, Empty);
9208             Set_Etype (N, Empty);
9209          end if;
9210       end Reset_Entity;
9211
9212       -----------------------------
9213       -- Save_Entity_Descendants --
9214       -----------------------------
9215
9216       procedure Save_Entity_Descendants (N : Node_Id) is
9217       begin
9218          case Nkind (N) is
9219             when N_Binary_Op =>
9220                Save_Global_Descendant (Union_Id (Left_Opnd (N)));
9221                Save_Global_Descendant (Union_Id (Right_Opnd (N)));
9222
9223             when N_Unary_Op =>
9224                Save_Global_Descendant (Union_Id (Right_Opnd (N)));
9225
9226             when N_Expanded_Name | N_Selected_Component =>
9227                Save_Global_Descendant (Union_Id (Prefix (N)));
9228                Save_Global_Descendant (Union_Id (Selector_Name (N)));
9229
9230             when N_Identifier | N_Character_Literal | N_Operator_Symbol =>
9231                null;
9232
9233             when others =>
9234                raise Program_Error;
9235          end case;
9236       end Save_Entity_Descendants;
9237
9238       --------------------------
9239       -- Save_Global_Defaults --
9240       --------------------------
9241
9242       procedure Save_Global_Defaults (N1, N2 : Node_Id) is
9243          Loc    : constant Source_Ptr := Sloc (N1);
9244          Assoc2 : constant List_Id    := Generic_Associations (N2);
9245          Gen_Id : constant Entity_Id  := Get_Generic_Entity (N2);
9246          Assoc1 : List_Id;
9247          Act1   : Node_Id;
9248          Act2   : Node_Id;
9249          Def    : Node_Id;
9250          Ndec   : Node_Id;
9251          Subp   : Entity_Id;
9252          Actual : Entity_Id;
9253
9254       begin
9255          Assoc1 := Generic_Associations (N1);
9256
9257          if Present (Assoc1) then
9258             Act1 := First (Assoc1);
9259          else
9260             Act1 := Empty;
9261             Set_Generic_Associations (N1, New_List);
9262             Assoc1 := Generic_Associations (N1);
9263          end if;
9264
9265          if Present (Assoc2) then
9266             Act2 := First (Assoc2);
9267          else
9268             return;
9269          end if;
9270
9271          while Present (Act1) and then Present (Act2) loop
9272             Next (Act1);
9273             Next (Act2);
9274          end loop;
9275
9276          --  Find the associations added for default suprograms.
9277
9278          if Present (Act2) then
9279             while Nkind (Act2) /= N_Generic_Association
9280               or else No (Entity (Selector_Name (Act2)))
9281               or else not Is_Overloadable (Entity (Selector_Name (Act2)))
9282             loop
9283                Next (Act2);
9284             end loop;
9285
9286             --  Add a similar association if the default is global. The
9287             --  renaming declaration for the actual has been analyzed, and
9288             --  its alias is the program it renames. Link the actual in the
9289             --  original generic tree with the node in the analyzed tree.
9290
9291             while Present (Act2) loop
9292                Subp := Entity (Selector_Name (Act2));
9293                Def  := Explicit_Generic_Actual_Parameter (Act2);
9294
9295                --  Following test is defence against rubbish errors
9296
9297                if No (Alias (Subp)) then
9298                   return;
9299                end if;
9300
9301                --  Retrieve the resolved actual from the renaming declaration
9302                --  created for the instantiated formal.
9303
9304                Actual := Entity (Name (Parent (Parent (Subp))));
9305                Set_Entity (Def, Actual);
9306                Set_Etype (Def, Etype (Actual));
9307
9308                if Is_Global (Actual) then
9309                   Ndec :=
9310                     Make_Generic_Association (Loc,
9311                       Selector_Name => New_Occurrence_Of (Subp, Loc),
9312                         Explicit_Generic_Actual_Parameter =>
9313                           New_Occurrence_Of (Actual, Loc));
9314
9315                   Set_Associated_Node
9316                     (Explicit_Generic_Actual_Parameter (Ndec), Def);
9317
9318                   Append (Ndec, Assoc1);
9319
9320                --  If there are other defaults, add a dummy association
9321                --  in case there are other defaulted formals with the same
9322                --  name.
9323
9324                elsif Present (Next (Act2)) then
9325                   Ndec :=
9326                     Make_Generic_Association (Loc,
9327                       Selector_Name => New_Occurrence_Of (Subp, Loc),
9328                         Explicit_Generic_Actual_Parameter => Empty);
9329
9330                   Append (Ndec, Assoc1);
9331                end if;
9332
9333                Next (Act2);
9334             end loop;
9335          end if;
9336
9337          if Nkind (Name (N1)) = N_Identifier
9338            and then Is_Child_Unit (Gen_Id)
9339            and then Is_Global (Gen_Id)
9340            and then Is_Generic_Unit (Scope (Gen_Id))
9341            and then In_Open_Scopes (Scope (Gen_Id))
9342          then
9343             --  This is an instantiation of a child unit within a sibling,
9344             --  so that the generic parent is in scope. An eventual instance
9345             --  must occur within the scope of an instance of the parent.
9346             --  Make name in instance into an expanded name, to preserve the
9347             --  identifier of the parent, so it can be resolved subsequently.
9348
9349             Rewrite (Name (N2),
9350               Make_Expanded_Name (Loc,
9351                 Chars         => Chars (Gen_Id),
9352                 Prefix        => New_Occurrence_Of (Scope (Gen_Id), Loc),
9353                 Selector_Name => New_Occurrence_Of (Gen_Id, Loc)));
9354             Set_Entity (Name (N2), Gen_Id);
9355
9356             Rewrite (Name (N1),
9357                Make_Expanded_Name (Loc,
9358                 Chars         => Chars (Gen_Id),
9359                 Prefix        => New_Occurrence_Of (Scope (Gen_Id), Loc),
9360                 Selector_Name => New_Occurrence_Of (Gen_Id, Loc)));
9361
9362             Set_Associated_Node (Name (N1), Name (N2));
9363             Set_Associated_Node (Prefix (Name (N1)), Empty);
9364             Set_Associated_Node
9365               (Selector_Name (Name (N1)), Selector_Name (Name (N2)));
9366             Set_Etype (Name (N1), Etype (Gen_Id));
9367          end if;
9368
9369       end Save_Global_Defaults;
9370
9371       ----------------------------
9372       -- Save_Global_Descendant --
9373       ----------------------------
9374
9375       procedure Save_Global_Descendant (D : Union_Id) is
9376          N1 : Node_Id;
9377
9378       begin
9379          if D in Node_Range then
9380             if D = Union_Id (Empty) then
9381                null;
9382
9383             elsif Nkind (Node_Id (D)) /= N_Compilation_Unit then
9384                Save_References (Node_Id (D));
9385             end if;
9386
9387          elsif D in List_Range then
9388             if D = Union_Id (No_List)
9389               or else Is_Empty_List (List_Id (D))
9390             then
9391                null;
9392
9393             else
9394                N1 := First (List_Id (D));
9395                while Present (N1) loop
9396                   Save_References (N1);
9397                   Next (N1);
9398                end loop;
9399             end if;
9400
9401          --  Element list or other non-node field, nothing to do
9402
9403          else
9404             null;
9405          end if;
9406       end Save_Global_Descendant;
9407
9408       ---------------------
9409       -- Save_References --
9410       ---------------------
9411
9412       --  This is the recursive procedure that does the work, once the
9413       --  enclosing generic scope has been established. We have to treat
9414       --  specially a number of node rewritings that are required by semantic
9415       --  processing and which change the kind of nodes in the generic copy:
9416       --  typically constant-folding, replacing an operator node by a string
9417       --  literal, or a selected component by an expanded name. In  each of
9418       --  those cases, the transformation is propagated to the generic unit.
9419
9420       procedure Save_References (N : Node_Id) is
9421       begin
9422          if N = Empty then
9423             null;
9424
9425          elsif Nkind (N) = N_Character_Literal
9426            or else Nkind (N) = N_Operator_Symbol
9427          then
9428             if Nkind (N) = Nkind (Get_Associated_Node (N)) then
9429                Reset_Entity (N);
9430
9431             elsif Nkind (N) = N_Operator_Symbol
9432               and then Nkind (Get_Associated_Node (N)) = N_String_Literal
9433             then
9434                Change_Operator_Symbol_To_String_Literal (N);
9435             end if;
9436
9437          elsif Nkind (N) in N_Op then
9438
9439             if Nkind (N) = Nkind (Get_Associated_Node (N)) then
9440
9441                if Nkind (N) = N_Op_Concat then
9442                   Set_Is_Component_Left_Opnd (N,
9443                     Is_Component_Left_Opnd (Get_Associated_Node (N)));
9444
9445                   Set_Is_Component_Right_Opnd (N,
9446                     Is_Component_Right_Opnd (Get_Associated_Node (N)));
9447                end if;
9448
9449                Reset_Entity (N);
9450             else
9451                --  Node may be transformed into call to a user-defined operator
9452
9453                N2 := Get_Associated_Node (N);
9454
9455                if Nkind (N2) = N_Function_Call then
9456                   E := Entity (Name (N2));
9457
9458                   if Present (E)
9459                     and then Is_Global (E)
9460                   then
9461                      Set_Etype (N, Etype (N2));
9462                   else
9463                      Set_Associated_Node (N, Empty);
9464                      Set_Etype (N, Empty);
9465                   end if;
9466
9467                elsif Nkind (N2) = N_Integer_Literal
9468                  or else Nkind (N2) = N_Real_Literal
9469                  or else Nkind (N2) = N_String_Literal
9470                then
9471                   --  Operation was constant-folded, perform the same
9472                   --  replacement in generic.
9473
9474                   Rewrite (N, New_Copy (N2));
9475                   Set_Analyzed (N, False);
9476
9477                elsif Nkind (N2) = N_Identifier
9478                  and then Ekind (Entity (N2)) = E_Enumeration_Literal
9479                then
9480                   --  Same if call was folded into a literal, but in this
9481                   --  case retain the entity to avoid spurious ambiguities
9482                   --  if id is overloaded at the point of instantiation or
9483                   --  inlining.
9484
9485                   Rewrite (N, New_Copy (N2));
9486                   Set_Associated_Node (N, N2);
9487                   Set_Analyzed (N, False);
9488                end if;
9489             end if;
9490
9491             --  Complete the check on operands, if node has not been
9492             --  constant-folded.
9493
9494             if Nkind (N) in N_Op then
9495                Save_Entity_Descendants (N);
9496             end if;
9497
9498          elsif Nkind (N) = N_Identifier then
9499             if Nkind (N) = Nkind (Get_Associated_Node (N)) then
9500
9501                --  If this is a discriminant reference, always save it.
9502                --  It is used in the instance to find the corresponding
9503                --  discriminant positionally rather than  by name.
9504
9505                Set_Original_Discriminant
9506                  (N, Original_Discriminant (Get_Associated_Node (N)));
9507                Reset_Entity (N);
9508
9509             else
9510                N2 := Get_Associated_Node (N);
9511
9512                if Nkind (N2) = N_Function_Call then
9513                   E := Entity (Name (N2));
9514
9515                   --  Name resolves to a call to parameterless function.
9516                   --  If original entity is global, mark node as resolved.
9517
9518                   if Present (E)
9519                     and then Is_Global (E)
9520                   then
9521                      Set_Etype (N, Etype (N2));
9522                   else
9523                      Set_Associated_Node (N, Empty);
9524                      Set_Etype (N, Empty);
9525                   end if;
9526
9527                elsif
9528                  Nkind (N2) = N_Integer_Literal or else
9529                  Nkind (N2) = N_Real_Literal    or else
9530                  Nkind (N2) = N_String_Literal
9531                then
9532                   --  Name resolves to named number that is constant-folded,
9533                   --  or to string literal from concatenation.
9534                   --  Perform the same replacement in generic.
9535
9536                   Rewrite (N, New_Copy (N2));
9537                   Set_Analyzed (N, False);
9538
9539                elsif Nkind (N2) = N_Explicit_Dereference then
9540
9541                   --  An identifier is rewritten as a dereference if it is
9542                   --  the prefix in a selected component, and it denotes an
9543                   --  access to a composite type, or a parameterless function
9544                   --  call that returns an access type.
9545
9546                   --  Check whether corresponding entity in prefix is global.
9547
9548                   if Is_Entity_Name (Prefix (N2))
9549                     and then Present (Entity (Prefix (N2)))
9550                     and then Is_Global (Entity (Prefix (N2)))
9551                   then
9552                      Rewrite (N,
9553                        Make_Explicit_Dereference (Sloc (N),
9554                           Prefix => Make_Identifier (Sloc (N),
9555                             Chars => Chars (N))));
9556                      Set_Associated_Node (Prefix (N), Prefix (N2));
9557
9558                   elsif Nkind (Prefix (N2)) = N_Function_Call
9559                     and then Is_Global (Entity (Name (Prefix (N2))))
9560                   then
9561                      Rewrite (N,
9562                        Make_Explicit_Dereference (Sloc (N),
9563                           Prefix => Make_Function_Call (Sloc (N),
9564                             Name  =>
9565                               Make_Identifier (Sloc (N),
9566                               Chars => Chars (N)))));
9567
9568                      Set_Associated_Node
9569                       (Name (Prefix (N)), Name (Prefix (N2)));
9570
9571                   else
9572                      Set_Associated_Node (N, Empty);
9573                      Set_Etype (N, Empty);
9574                   end if;
9575
9576                --  The subtype mark of a nominally unconstrained object
9577                --  is rewritten as a subtype indication using the bounds
9578                --  of the expression. Recover the original subtype mark.
9579
9580                elsif Nkind (N2) = N_Subtype_Indication
9581                  and then Is_Entity_Name (Original_Node (N2))
9582                then
9583                   Set_Associated_Node (N, Original_Node (N2));
9584                   Reset_Entity (N);
9585
9586                else
9587                   null;
9588                end if;
9589             end if;
9590
9591          elsif Nkind (N) in N_Entity then
9592             null;
9593
9594          else
9595             declare
9596                use Atree.Unchecked_Access;
9597                --  This code section is part of implementing an untyped tree
9598                --  traversal, so it needs direct access to node fields.
9599
9600             begin
9601                if Nkind (N) = N_Aggregate
9602                     or else
9603                   Nkind (N) = N_Extension_Aggregate
9604                then
9605                   N2 := Get_Associated_Node (N);
9606
9607                   if No (N2)
9608                     or else No (Etype (N2))
9609                     or else not Is_Global (Etype (N2))
9610                   then
9611                      Set_Associated_Node (N, Empty);
9612                   end if;
9613
9614                   Save_Global_Descendant (Field1 (N));
9615                   Save_Global_Descendant (Field2 (N));
9616                   Save_Global_Descendant (Field3 (N));
9617                   Save_Global_Descendant (Field5 (N));
9618
9619                --  All other cases than aggregates
9620
9621                else
9622                   Save_Global_Descendant (Field1 (N));
9623                   Save_Global_Descendant (Field2 (N));
9624                   Save_Global_Descendant (Field3 (N));
9625                   Save_Global_Descendant (Field4 (N));
9626                   Save_Global_Descendant (Field5 (N));
9627                end if;
9628             end;
9629          end if;
9630       end Save_References;
9631
9632    --  Start of processing for Save_Global_References
9633
9634    begin
9635       Gen_Scope := Current_Scope;
9636
9637       --  If the generic unit is a child unit, references to entities in
9638       --  the parent are treated as local, because they will be resolved
9639       --  anew in the context of the instance of the parent.
9640
9641       while Is_Child_Unit (Gen_Scope)
9642         and then Ekind (Scope (Gen_Scope)) = E_Generic_Package
9643       loop
9644          Gen_Scope := Scope (Gen_Scope);
9645       end loop;
9646
9647       Save_References (N);
9648    end Save_Global_References;
9649
9650    --------------------------------------
9651    -- Set_Copied_Sloc_For_Inlined_Body --
9652    --------------------------------------
9653
9654    procedure Set_Copied_Sloc_For_Inlined_Body (N : Node_Id; E : Entity_Id) is
9655    begin
9656       Create_Instantiation_Source (N, E, True, S_Adjustment);
9657    end Set_Copied_Sloc_For_Inlined_Body;
9658
9659    ---------------------
9660    -- Set_Instance_Of --
9661    ---------------------
9662
9663    procedure Set_Instance_Of (A : Entity_Id; B : Entity_Id) is
9664    begin
9665       Generic_Renamings.Table (Generic_Renamings.Last) := (A, B, Assoc_Null);
9666       Generic_Renamings_HTable.Set (Generic_Renamings.Last);
9667       Generic_Renamings.Increment_Last;
9668    end Set_Instance_Of;
9669
9670    --------------------
9671    -- Set_Next_Assoc --
9672    --------------------
9673
9674    procedure Set_Next_Assoc (E : Assoc_Ptr; Next : Assoc_Ptr) is
9675    begin
9676       Generic_Renamings.Table (E).Next_In_HTable := Next;
9677    end Set_Next_Assoc;
9678
9679    -------------------
9680    -- Start_Generic --
9681    -------------------
9682
9683    procedure Start_Generic is
9684    begin
9685       --  ??? I am sure more things could be factored out in this
9686       --  routine. Should probably be done at a later stage.
9687
9688       Generic_Flags.Increment_Last;
9689       Generic_Flags.Table (Generic_Flags.Last) := Inside_A_Generic;
9690       Inside_A_Generic := True;
9691
9692       Expander_Mode_Save_And_Set (False);
9693    end Start_Generic;
9694
9695    ----------------------
9696    -- Set_Instance_Env --
9697    ----------------------
9698
9699    procedure Set_Instance_Env
9700      (Gen_Unit : Entity_Id;
9701       Act_Unit : Entity_Id)
9702    is
9703
9704    begin
9705       --  Regardless of the current mode, predefined units are analyzed in
9706       --  Ada95 mode, and Ada83 checks don't apply.
9707
9708       if Is_Internal_File_Name
9709           (Fname => Unit_File_Name (Get_Source_Unit (Gen_Unit)),
9710            Renamings_Included => True) then
9711          Ada_83 := False;
9712       end if;
9713
9714       Current_Instantiated_Parent := (Gen_Unit, Act_Unit, Assoc_Null);
9715    end Set_Instance_Env;
9716
9717    -----------------
9718    -- Switch_View --
9719    -----------------
9720
9721    procedure Switch_View (T : Entity_Id) is
9722       BT        : constant Entity_Id := Base_Type (T);
9723       Priv_Elmt : Elmt_Id := No_Elmt;
9724       Priv_Sub  : Entity_Id;
9725
9726    begin
9727       --  T may be private but its base type may have been exchanged through
9728       --  some other occurrence, in which case there is nothing to switch.
9729
9730       if not Is_Private_Type (BT) then
9731          return;
9732       end if;
9733
9734       Priv_Elmt := First_Elmt (Private_Dependents (BT));
9735
9736       if Present (Full_View (BT)) then
9737          Append_Elmt (Full_View (BT), Exchanged_Views);
9738          Exchange_Declarations (BT);
9739       end if;
9740
9741       while Present (Priv_Elmt) loop
9742          Priv_Sub := (Node (Priv_Elmt));
9743
9744          --  We avoid flipping the subtype if the Etype of its full
9745          --  view is private because this would result in a malformed
9746          --  subtype. This occurs when the Etype of the subtype full
9747          --  view is the full view of the base type (and since the
9748          --  base types were just switched, the subtype is pointing
9749          --  to the wrong view). This is currently the case for
9750          --  tagged record types, access types (maybe more?) and
9751          --  needs to be resolved. ???
9752
9753          if Present (Full_View (Priv_Sub))
9754            and then not Is_Private_Type (Etype (Full_View (Priv_Sub)))
9755          then
9756             Append_Elmt (Full_View (Priv_Sub), Exchanged_Views);
9757             Exchange_Declarations (Priv_Sub);
9758          end if;
9759
9760          Next_Elmt (Priv_Elmt);
9761       end loop;
9762    end Switch_View;
9763
9764    -----------------------------
9765    -- Valid_Default_Attribute --
9766    -----------------------------
9767
9768    procedure Valid_Default_Attribute (Nam : Entity_Id; Def : Node_Id) is
9769       Attr_Id : constant Attribute_Id :=
9770                   Get_Attribute_Id (Attribute_Name (Def));
9771       T       : constant Entity_Id := Entity (Prefix (Def));
9772       Is_Fun  : constant Boolean := (Ekind (Nam) = E_Function);
9773       F       : Entity_Id;
9774       Num_F   : Int;
9775       OK      : Boolean;
9776
9777    begin
9778       if No (T)
9779         or else T = Any_Id
9780       then
9781          return;
9782       end if;
9783
9784       Num_F := 0;
9785       F := First_Formal (Nam);
9786       while Present (F) loop
9787          Num_F := Num_F + 1;
9788          Next_Formal (F);
9789       end loop;
9790
9791       case Attr_Id is
9792          when Attribute_Adjacent |  Attribute_Ceiling   | Attribute_Copy_Sign |
9793               Attribute_Floor    |  Attribute_Fraction  | Attribute_Machine   |
9794               Attribute_Model    |  Attribute_Remainder | Attribute_Rounding  |
9795               Attribute_Unbiased_Rounding  =>
9796             OK := Is_Fun
9797                     and then Num_F = 1
9798                     and then Is_Floating_Point_Type (T);
9799
9800          when Attribute_Image    | Attribute_Pred       | Attribute_Succ |
9801               Attribute_Value    | Attribute_Wide_Image |
9802               Attribute_Wide_Value  =>
9803             OK := (Is_Fun and then Num_F = 1 and then Is_Scalar_Type (T));
9804
9805          when Attribute_Max      |  Attribute_Min  =>
9806             OK := (Is_Fun and then Num_F = 2 and then Is_Scalar_Type (T));
9807
9808          when Attribute_Input =>
9809             OK := (Is_Fun and then Num_F = 1);
9810
9811          when Attribute_Output | Attribute_Read | Attribute_Write =>
9812             OK := (not Is_Fun and then Num_F = 2);
9813
9814          when others =>
9815             OK := False;
9816       end case;
9817
9818       if not OK then
9819          Error_Msg_N ("attribute reference has wrong profile for subprogram",
9820            Def);
9821       end if;
9822    end Valid_Default_Attribute;
9823
9824 end Sem_Ch12;