OSDN Git Service

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