OSDN Git Service

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