OSDN Git Service

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