OSDN Git Service

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