OSDN Git Service

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