OSDN Git Service

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