OSDN Git Service

ca7c00519c45265155709d419579f27706bc39ba
[pf3gnuchains/gcc-fork.git] / gcc / ada / sem_ch6.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              S E M _ C H 6                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2011, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Checks;   use Checks;
28 with Debug;    use Debug;
29 with Einfo;    use Einfo;
30 with Elists;   use Elists;
31 with Errout;   use Errout;
32 with Expander; use Expander;
33 with Exp_Ch6;  use Exp_Ch6;
34 with Exp_Ch7;  use Exp_Ch7;
35 with Exp_Ch9;  use Exp_Ch9;
36 with Exp_Disp; use Exp_Disp;
37 with Exp_Tss;  use Exp_Tss;
38 with Exp_Util; use Exp_Util;
39 with Fname;    use Fname;
40 with Freeze;   use Freeze;
41 with Itypes;   use Itypes;
42 with Lib.Xref; use Lib.Xref;
43 with Layout;   use Layout;
44 with Namet;    use Namet;
45 with Lib;      use Lib;
46 with Nlists;   use Nlists;
47 with Nmake;    use Nmake;
48 with Opt;      use Opt;
49 with Output;   use Output;
50 with Restrict; use Restrict;
51 with Rident;   use Rident;
52 with Rtsfind;  use Rtsfind;
53 with Sem;      use Sem;
54 with Sem_Aux;  use Sem_Aux;
55 with Sem_Cat;  use Sem_Cat;
56 with Sem_Ch3;  use Sem_Ch3;
57 with Sem_Ch4;  use Sem_Ch4;
58 with Sem_Ch5;  use Sem_Ch5;
59 with Sem_Ch8;  use Sem_Ch8;
60 with Sem_Ch10; use Sem_Ch10;
61 with Sem_Ch12; use Sem_Ch12;
62 with Sem_Ch13; use Sem_Ch13;
63 with Sem_Disp; use Sem_Disp;
64 with Sem_Dist; use Sem_Dist;
65 with Sem_Elim; use Sem_Elim;
66 with Sem_Eval; use Sem_Eval;
67 with Sem_Mech; use Sem_Mech;
68 with Sem_Prag; use Sem_Prag;
69 with Sem_Res;  use Sem_Res;
70 with Sem_Util; use Sem_Util;
71 with Sem_Type; use Sem_Type;
72 with Sem_Warn; use Sem_Warn;
73 with Sinput;   use Sinput;
74 with Stand;    use Stand;
75 with Sinfo;    use Sinfo;
76 with Sinfo.CN; use Sinfo.CN;
77 with Snames;   use Snames;
78 with Stringt;  use Stringt;
79 with Style;
80 with Stylesw;  use Stylesw;
81 with Tbuild;   use Tbuild;
82 with Uintp;    use Uintp;
83 with Urealp;   use Urealp;
84 with Validsw;  use Validsw;
85
86 package body Sem_Ch6 is
87
88    May_Hide_Profile : Boolean := False;
89    --  This flag is used to indicate that two formals in two subprograms being
90    --  checked for conformance differ only in that one is an access parameter
91    --  while the other is of a general access type with the same designated
92    --  type. In this case, if the rest of the signatures match, a call to
93    --  either subprogram may be ambiguous, which is worth a warning. The flag
94    --  is set in Compatible_Types, and the warning emitted in
95    --  New_Overloaded_Entity.
96
97    -----------------------
98    -- Local Subprograms --
99    -----------------------
100
101    procedure Analyze_Return_Statement (N : Node_Id);
102    --  Common processing for simple and extended return statements
103
104    procedure Analyze_Function_Return (N : Node_Id);
105    --  Subsidiary to Analyze_Return_Statement. Called when the return statement
106    --  applies to a [generic] function.
107
108    procedure Analyze_Return_Type (N : Node_Id);
109    --  Subsidiary to Process_Formals: analyze subtype mark in function
110    --  specification in a context where the formals are visible and hide
111    --  outer homographs.
112
113    procedure Analyze_Subprogram_Body_Helper (N : Node_Id);
114    --  Does all the real work of Analyze_Subprogram_Body. This is split out so
115    --  that we can use RETURN but not skip the debug output at the end.
116
117    procedure Analyze_Generic_Subprogram_Body (N : Node_Id; Gen_Id : Entity_Id);
118    --  Analyze a generic subprogram body. N is the body to be analyzed, and
119    --  Gen_Id is the defining entity Id for the corresponding spec.
120
121    procedure Build_Body_To_Inline (N : Node_Id; Subp : Entity_Id);
122    --  If a subprogram has pragma Inline and inlining is active, use generic
123    --  machinery to build an unexpanded body for the subprogram. This body is
124    --  subsequently used for inline expansions at call sites. If subprogram can
125    --  be inlined (depending on size and nature of local declarations) this
126    --  function returns true. Otherwise subprogram body is treated normally.
127    --  If proper warnings are enabled and the subprogram contains a construct
128    --  that cannot be inlined, the offending construct is flagged accordingly.
129
130    function Can_Override_Operator (Subp : Entity_Id) return Boolean;
131    --  Returns true if Subp can override a predefined operator.
132
133    procedure Check_Conformance
134      (New_Id                   : Entity_Id;
135       Old_Id                   : Entity_Id;
136       Ctype                    : Conformance_Type;
137       Errmsg                   : Boolean;
138       Conforms                 : out Boolean;
139       Err_Loc                  : Node_Id := Empty;
140       Get_Inst                 : Boolean := False;
141       Skip_Controlling_Formals : Boolean := False);
142    --  Given two entities, this procedure checks that the profiles associated
143    --  with these entities meet the conformance criterion given by the third
144    --  parameter. If they conform, Conforms is set True and control returns
145    --  to the caller. If they do not conform, Conforms is set to False, and
146    --  in addition, if Errmsg is True on the call, proper messages are output
147    --  to complain about the conformance failure. If Err_Loc is non_Empty
148    --  the error messages are placed on Err_Loc, if Err_Loc is empty, then
149    --  error messages are placed on the appropriate part of the construct
150    --  denoted by New_Id. If Get_Inst is true, then this is a mode conformance
151    --  against a formal access-to-subprogram type so Get_Instance_Of must
152    --  be called.
153
154    procedure Check_Subprogram_Order (N : Node_Id);
155    --  N is the N_Subprogram_Body node for a subprogram. This routine applies
156    --  the alpha ordering rule for N if this ordering requirement applicable.
157
158    procedure Check_Returns
159      (HSS  : Node_Id;
160       Mode : Character;
161       Err  : out Boolean;
162       Proc : Entity_Id := Empty);
163    --  Called to check for missing return statements in a function body, or for
164    --  returns present in a procedure body which has No_Return set. HSS is the
165    --  handled statement sequence for the subprogram body. This procedure
166    --  checks all flow paths to make sure they either have return (Mode = 'F',
167    --  used for functions) or do not have a return (Mode = 'P', used for
168    --  No_Return procedures). The flag Err is set if there are any control
169    --  paths not explicitly terminated by a return in the function case, and is
170    --  True otherwise. Proc is the entity for the procedure case and is used
171    --  in posting the warning message.
172
173    procedure Check_Untagged_Equality (Eq_Op : Entity_Id);
174    --  In Ada 2012, a primitive equality operator on an untagged record type
175    --  must appear before the type is frozen, and have the same visibility as
176    --  that of the type. This procedure checks that this rule is met, and
177    --  otherwise emits an error on the subprogram declaration and a warning
178    --  on the earlier freeze point if it is easy to locate.
179
180    procedure Enter_Overloaded_Entity (S : Entity_Id);
181    --  This procedure makes S, a new overloaded entity, into the first visible
182    --  entity with that name.
183
184    procedure Install_Entity (E : Entity_Id);
185    --  Make single entity visible (used for generic formals as well)
186
187    function Is_Non_Overriding_Operation
188      (Prev_E : Entity_Id;
189       New_E  : Entity_Id) return Boolean;
190    --  Enforce the rule given in 12.3(18): a private operation in an instance
191    --  overrides an inherited operation only if the corresponding operation
192    --  was overriding in the generic. This can happen for primitive operations
193    --  of types derived (in the generic unit) from formal private or formal
194    --  derived types.
195
196    procedure Make_Inequality_Operator (S : Entity_Id);
197    --  Create the declaration for an inequality operator that is implicitly
198    --  created by a user-defined equality operator that yields a boolean.
199
200    procedure May_Need_Actuals (Fun : Entity_Id);
201    --  Flag functions that can be called without parameters, i.e. those that
202    --  have no parameters, or those for which defaults exist for all parameters
203
204    procedure Process_PPCs
205      (N       : Node_Id;
206       Spec_Id : Entity_Id;
207       Body_Id : Entity_Id);
208    --  Called from Analyze[_Generic]_Subprogram_Body to deal with scanning post
209    --  conditions for the body and assembling and inserting the _postconditions
210    --  procedure. N is the node for the subprogram body and Body_Id/Spec_Id are
211    --  the entities for the body and separate spec (if there is no separate
212    --  spec, Spec_Id is Empty). Note that invariants and predicates may also
213    --  provide postconditions, and are also handled in this procedure.
214
215    procedure Set_Formal_Validity (Formal_Id : Entity_Id);
216    --  Formal_Id is an formal parameter entity. This procedure deals with
217    --  setting the proper validity status for this entity, which depends on
218    --  the kind of parameter and the validity checking mode.
219
220    ---------------------------------------------
221    -- Analyze_Abstract_Subprogram_Declaration --
222    ---------------------------------------------
223
224    procedure Analyze_Abstract_Subprogram_Declaration (N : Node_Id) is
225       Designator : constant Entity_Id :=
226                      Analyze_Subprogram_Specification (Specification (N));
227       Scop       : constant Entity_Id := Current_Scope;
228
229    begin
230       Check_Formal_Restriction ("abstract subprogram is not allowed", N);
231
232       Generate_Definition (Designator);
233       Set_Is_Abstract_Subprogram (Designator);
234       New_Overloaded_Entity (Designator);
235       Check_Delayed_Subprogram (Designator);
236
237       Set_Categorization_From_Scope (Designator, Scop);
238
239       if Ekind (Scope (Designator)) = E_Protected_Type then
240          Error_Msg_N
241            ("abstract subprogram not allowed in protected type", N);
242
243       --  Issue a warning if the abstract subprogram is neither a dispatching
244       --  operation nor an operation that overrides an inherited subprogram or
245       --  predefined operator, since this most likely indicates a mistake.
246
247       elsif Warn_On_Redundant_Constructs
248         and then not Is_Dispatching_Operation (Designator)
249         and then not Present (Overridden_Operation (Designator))
250         and then (not Is_Operator_Symbol_Name (Chars (Designator))
251                    or else Scop /= Scope (Etype (First_Formal (Designator))))
252       then
253          Error_Msg_N
254            ("?abstract subprogram is not dispatching or overriding", N);
255       end if;
256
257       Generate_Reference_To_Formals (Designator);
258       Check_Eliminated (Designator);
259
260       if Has_Aspects (N) then
261          Analyze_Aspect_Specifications (N, Designator);
262       end if;
263    end Analyze_Abstract_Subprogram_Declaration;
264
265    ---------------------------------
266    -- Analyze_Expression_Function --
267    ---------------------------------
268
269    procedure Analyze_Expression_Function (N : Node_Id) is
270       Loc      : constant Source_Ptr := Sloc (N);
271       LocX     : constant Source_Ptr := Sloc (Expression (N));
272       Def_Id   : constant Entity_Id  := Defining_Entity (Specification (N));
273       New_Body : Node_Id;
274
275       Prev : constant Entity_Id := Current_Entity_In_Scope (Def_Id);
276       --  If the expression is a completion, Prev is the entity whose
277       --  declaration is completed.
278
279    begin
280       --  This is one of the occasions on which we transform the tree during
281       --  semantic analysis. Transform the expression function into an
282       --  equivalent subprogram body, and then analyze that.
283
284       New_Body :=
285         Make_Subprogram_Body (Loc,
286           Specification              => Specification (N),
287           Declarations               => Empty_List,
288           Handled_Statement_Sequence =>
289             Make_Handled_Sequence_Of_Statements (LocX,
290               Statements => New_List (
291                 Make_Simple_Return_Statement (LocX,
292                   Expression => Expression (N)))));
293
294       if Present (Prev)
295         and then Ekind (Prev) = E_Generic_Function
296       then
297          --  If the expression completes a generic subprogram, we must create a
298          --  separate node for the body, because at instantiation the original
299          --  node of the generic copy must be a generic subprogram body, and
300          --  cannot be a expression function. Otherwise we just rewrite the
301          --  expression with the non-generic body.
302
303          Insert_After (N, New_Body);
304          Rewrite (N, Make_Null_Statement (Loc));
305          Analyze (N);
306          Analyze (New_Body);
307
308       else
309          Rewrite (N, New_Body);
310          Analyze (N);
311       end if;
312    end Analyze_Expression_Function;
313
314    ----------------------------------------
315    -- Analyze_Extended_Return_Statement  --
316    ----------------------------------------
317
318    procedure Analyze_Extended_Return_Statement (N : Node_Id) is
319    begin
320       Analyze_Return_Statement (N);
321    end Analyze_Extended_Return_Statement;
322
323    ----------------------------
324    -- Analyze_Function_Call  --
325    ----------------------------
326
327    procedure Analyze_Function_Call (N : Node_Id) is
328       P       : constant Node_Id := Name (N);
329       Actuals : constant List_Id := Parameter_Associations (N);
330       Actual  : Node_Id;
331
332    begin
333       Analyze (P);
334
335       --  A call of the form A.B (X) may be an Ada05 call, which is rewritten
336       --  as B (A, X). If the rewriting is successful, the call has been
337       --  analyzed and we just return.
338
339       if Nkind (P) = N_Selected_Component
340         and then Name (N) /= P
341         and then Is_Rewrite_Substitution (N)
342         and then Present (Etype (N))
343       then
344          return;
345       end if;
346
347       --  If error analyzing name, then set Any_Type as result type and return
348
349       if Etype (P) = Any_Type then
350          Set_Etype (N, Any_Type);
351          return;
352       end if;
353
354       --  Otherwise analyze the parameters
355
356       if Present (Actuals) then
357          Actual := First (Actuals);
358          while Present (Actual) loop
359             Analyze (Actual);
360             Check_Parameterless_Call (Actual);
361             Next (Actual);
362          end loop;
363       end if;
364
365       Analyze_Call (N);
366    end Analyze_Function_Call;
367
368    -----------------------------
369    -- Analyze_Function_Return --
370    -----------------------------
371
372    procedure Analyze_Function_Return (N : Node_Id) is
373       Loc        : constant Source_Ptr  := Sloc (N);
374       Stm_Entity : constant Entity_Id   := Return_Statement_Entity (N);
375       Scope_Id   : constant Entity_Id   := Return_Applies_To (Stm_Entity);
376
377       R_Type : constant Entity_Id := Etype (Scope_Id);
378       --  Function result subtype
379
380       procedure Check_Limited_Return (Expr : Node_Id);
381       --  Check the appropriate (Ada 95 or Ada 2005) rules for returning
382       --  limited types. Used only for simple return statements.
383       --  Expr is the expression returned.
384
385       procedure Check_Return_Subtype_Indication (Obj_Decl : Node_Id);
386       --  Check that the return_subtype_indication properly matches the result
387       --  subtype of the function, as required by RM-6.5(5.1/2-5.3/2).
388
389       --------------------------
390       -- Check_Limited_Return --
391       --------------------------
392
393       procedure Check_Limited_Return (Expr : Node_Id) is
394       begin
395          --  Ada 2005 (AI-318-02): Return-by-reference types have been
396          --  removed and replaced by anonymous access results. This is an
397          --  incompatibility with Ada 95. Not clear whether this should be
398          --  enforced yet or perhaps controllable with special switch. ???
399
400          if Is_Limited_Type (R_Type)
401            and then Comes_From_Source (N)
402            and then not In_Instance_Body
403            and then not OK_For_Limited_Init_In_05 (R_Type, Expr)
404          then
405             --  Error in Ada 2005
406
407             if Ada_Version >= Ada_2005
408               and then not Debug_Flag_Dot_L
409               and then not GNAT_Mode
410             then
411                Error_Msg_N
412                  ("(Ada 2005) cannot copy object of a limited type " &
413                   "(RM-2005 6.5(5.5/2))", Expr);
414
415                if Is_Immutably_Limited_Type (R_Type) then
416                   Error_Msg_N
417                     ("\return by reference not permitted in Ada 2005", Expr);
418                end if;
419
420             --  Warn in Ada 95 mode, to give folks a heads up about this
421             --  incompatibility.
422
423             --  In GNAT mode, this is just a warning, to allow it to be
424             --  evilly turned off. Otherwise it is a real error.
425
426             --  In a generic context, simplify the warning because it makes
427             --  no sense to discuss pass-by-reference or copy.
428
429             elsif Warn_On_Ada_2005_Compatibility or GNAT_Mode then
430                if Inside_A_Generic then
431                   Error_Msg_N
432                     ("return of limited object not permitted in Ada2005 "
433                      & "(RM-2005 6.5(5.5/2))?", Expr);
434
435                elsif Is_Immutably_Limited_Type (R_Type) then
436                   Error_Msg_N
437                     ("return by reference not permitted in Ada 2005 "
438                      & "(RM-2005 6.5(5.5/2))?", Expr);
439                else
440                   Error_Msg_N
441                     ("cannot copy object of a limited type in Ada 2005 "
442                      & "(RM-2005 6.5(5.5/2))?", Expr);
443                end if;
444
445             --  Ada 95 mode, compatibility warnings disabled
446
447             else
448                return; --  skip continuation messages below
449             end if;
450
451             if not Inside_A_Generic then
452                Error_Msg_N
453                  ("\consider switching to return of access type", Expr);
454                Explain_Limited_Type (R_Type, Expr);
455             end if;
456          end if;
457       end Check_Limited_Return;
458
459       -------------------------------------
460       -- Check_Return_Subtype_Indication --
461       -------------------------------------
462
463       procedure Check_Return_Subtype_Indication (Obj_Decl : Node_Id) is
464          Return_Obj : constant Node_Id   := Defining_Identifier (Obj_Decl);
465
466          R_Stm_Type : constant Entity_Id := Etype (Return_Obj);
467          --  Subtype given in the extended return statement (must match R_Type)
468
469          Subtype_Ind : constant Node_Id :=
470                          Object_Definition (Original_Node (Obj_Decl));
471
472          R_Type_Is_Anon_Access :
473            constant Boolean :=
474              Ekind (R_Type) = E_Anonymous_Access_Subprogram_Type
475                or else
476              Ekind (R_Type) = E_Anonymous_Access_Protected_Subprogram_Type
477                or else
478              Ekind (R_Type) = E_Anonymous_Access_Type;
479          --  True if return type of the function is an anonymous access type
480          --  Can't we make Is_Anonymous_Access_Type in einfo ???
481
482          R_Stm_Type_Is_Anon_Access :
483            constant Boolean :=
484              Ekind (R_Stm_Type) = E_Anonymous_Access_Subprogram_Type
485                or else
486              Ekind (R_Stm_Type) = E_Anonymous_Access_Protected_Subprogram_Type
487                or else
488              Ekind (R_Stm_Type) = E_Anonymous_Access_Type;
489          --  True if type of the return object is an anonymous access type
490
491       begin
492          --  First, avoid cascaded errors
493
494          if Error_Posted (Obj_Decl) or else Error_Posted (Subtype_Ind) then
495             return;
496          end if;
497
498          --  "return access T" case; check that the return statement also has
499          --  "access T", and that the subtypes statically match:
500          --   if this is an access to subprogram the signatures must match.
501
502          if R_Type_Is_Anon_Access then
503             if R_Stm_Type_Is_Anon_Access then
504                if
505                  Ekind (Designated_Type (R_Stm_Type)) /= E_Subprogram_Type
506                then
507                   if Base_Type (Designated_Type (R_Stm_Type)) /=
508                      Base_Type (Designated_Type (R_Type))
509                     or else not Subtypes_Statically_Match (R_Stm_Type, R_Type)
510                   then
511                      Error_Msg_N
512                       ("subtype must statically match function result subtype",
513                        Subtype_Mark (Subtype_Ind));
514                   end if;
515
516                else
517                   --  For two anonymous access to subprogram types, the
518                   --  types themselves must be type conformant.
519
520                   if not Conforming_Types
521                     (R_Stm_Type, R_Type, Fully_Conformant)
522                   then
523                      Error_Msg_N
524                       ("subtype must statically match function result subtype",
525                          Subtype_Ind);
526                   end if;
527                end if;
528
529             else
530                Error_Msg_N ("must use anonymous access type", Subtype_Ind);
531             end if;
532
533          --  Subtype indication case: check that the return object's type is
534          --  covered by the result type, and that the subtypes statically match
535          --  when the result subtype is constrained. Also handle record types
536          --  with unknown discriminants for which we have built the underlying
537          --  record view. Coverage is needed to allow specific-type return
538          --  objects when the result type is class-wide (see AI05-32).
539
540          elsif Covers (Base_Type (R_Type), Base_Type (R_Stm_Type))
541            or else (Is_Underlying_Record_View (Base_Type (R_Stm_Type))
542                      and then
543                        Covers
544                          (Base_Type (R_Type),
545                           Underlying_Record_View (Base_Type (R_Stm_Type))))
546          then
547             --  A null exclusion may be present on the return type, on the
548             --  function specification, on the object declaration or on the
549             --  subtype itself.
550
551             if Is_Access_Type (R_Type)
552               and then
553                (Can_Never_Be_Null (R_Type)
554                  or else Null_Exclusion_Present (Parent (Scope_Id))) /=
555                                               Can_Never_Be_Null (R_Stm_Type)
556             then
557                Error_Msg_N
558                  ("subtype must statically match function result subtype",
559                   Subtype_Ind);
560             end if;
561
562             --  AI05-103: for elementary types, subtypes must statically match
563
564             if Is_Constrained (R_Type)
565               or else Is_Access_Type (R_Type)
566             then
567                if not Subtypes_Statically_Match (R_Stm_Type, R_Type) then
568                   Error_Msg_N
569                     ("subtype must statically match function result subtype",
570                      Subtype_Ind);
571                end if;
572             end if;
573
574          elsif Etype (Base_Type (R_Type)) = R_Stm_Type
575            and then Is_Null_Extension (Base_Type (R_Type))
576          then
577             null;
578
579          else
580             Error_Msg_N
581               ("wrong type for return_subtype_indication", Subtype_Ind);
582          end if;
583       end Check_Return_Subtype_Indication;
584
585       ---------------------
586       -- Local Variables --
587       ---------------------
588
589       Expr : Node_Id;
590
591    --  Start of processing for Analyze_Function_Return
592
593    begin
594       Set_Return_Present (Scope_Id);
595
596       if Nkind (N) = N_Simple_Return_Statement then
597          Expr := Expression (N);
598          Analyze_And_Resolve (Expr, R_Type);
599          Check_Limited_Return (Expr);
600
601          --  The only RETURN allowed in SPARK or ALFA is as the last statement
602          --  of the function.
603
604          if Nkind (Parent (N)) /= N_Handled_Sequence_Of_Statements
605            and then
606              (Nkind (Parent (Parent (N))) /= N_Subprogram_Body
607                or else Present (Next (N)))
608          then
609             Check_Formal_Restriction
610               ("RETURN should be the last statement in function", N);
611          end if;
612
613       else
614          Check_Formal_Restriction ("extended RETURN is not allowed", N);
615
616          --  Analyze parts specific to extended_return_statement:
617
618          declare
619             Obj_Decl : constant Node_Id :=
620                          Last (Return_Object_Declarations (N));
621
622             HSS : constant Node_Id := Handled_Statement_Sequence (N);
623
624          begin
625             Expr := Expression (Obj_Decl);
626
627             --  Note: The check for OK_For_Limited_Init will happen in
628             --  Analyze_Object_Declaration; we treat it as a normal
629             --  object declaration.
630
631             Set_Is_Return_Object (Defining_Identifier (Obj_Decl));
632             Analyze (Obj_Decl);
633
634             Check_Return_Subtype_Indication (Obj_Decl);
635
636             if Present (HSS) then
637                Analyze (HSS);
638
639                if Present (Exception_Handlers (HSS)) then
640
641                   --  ???Has_Nested_Block_With_Handler needs to be set.
642                   --  Probably by creating an actual N_Block_Statement.
643                   --  Probably in Expand.
644
645                   null;
646                end if;
647             end if;
648
649             --  Mark the return object as referenced, since the return is an
650             --  implicit reference of the object.
651
652             Set_Referenced (Defining_Identifier (Obj_Decl));
653
654             Check_References (Stm_Entity);
655          end;
656       end if;
657
658       --  Case of Expr present
659
660       if Present (Expr)
661
662          --  Defend against previous errors
663
664         and then Nkind (Expr) /= N_Empty
665         and then Present (Etype (Expr))
666       then
667          --  Apply constraint check. Note that this is done before the implicit
668          --  conversion of the expression done for anonymous access types to
669          --  ensure correct generation of the null-excluding check associated
670          --  with null-excluding expressions found in return statements.
671
672          Apply_Constraint_Check (Expr, R_Type);
673
674          --  Ada 2005 (AI-318-02): When the result type is an anonymous access
675          --  type, apply an implicit conversion of the expression to that type
676          --  to force appropriate static and run-time accessibility checks.
677
678          if Ada_Version >= Ada_2005
679            and then Ekind (R_Type) = E_Anonymous_Access_Type
680          then
681             Rewrite (Expr, Convert_To (R_Type, Relocate_Node (Expr)));
682             Analyze_And_Resolve (Expr, R_Type);
683          end if;
684
685          --  If the result type is class-wide, then check that the return
686          --  expression's type is not declared at a deeper level than the
687          --  function (RM05-6.5(5.6/2)).
688
689          if Ada_Version >= Ada_2005
690            and then Is_Class_Wide_Type (R_Type)
691          then
692             if Type_Access_Level (Etype (Expr)) >
693                  Subprogram_Access_Level (Scope_Id)
694             then
695                Error_Msg_N
696                  ("level of return expression type is deeper than " &
697                   "class-wide function!", Expr);
698             end if;
699          end if;
700
701          --  Check incorrect use of dynamically tagged expression
702
703          if Is_Tagged_Type (R_Type) then
704             Check_Dynamically_Tagged_Expression
705               (Expr => Expr,
706                Typ  => R_Type,
707                Related_Nod => N);
708          end if;
709
710          --  ??? A real run-time accessibility check is needed in cases
711          --  involving dereferences of access parameters. For now we just
712          --  check the static cases.
713
714          if (Ada_Version < Ada_2005 or else Debug_Flag_Dot_L)
715            and then Is_Immutably_Limited_Type (Etype (Scope_Id))
716            and then Object_Access_Level (Expr) >
717                       Subprogram_Access_Level (Scope_Id)
718          then
719
720             --  Suppress the message in a generic, where the rewriting
721             --  is irrelevant.
722
723             if Inside_A_Generic then
724                null;
725
726             else
727                Rewrite (N,
728                  Make_Raise_Program_Error (Loc,
729                    Reason => PE_Accessibility_Check_Failed));
730                Analyze (N);
731
732                Error_Msg_N
733                  ("cannot return a local value by reference?", N);
734                Error_Msg_NE
735                  ("\& will be raised at run time?",
736                    N, Standard_Program_Error);
737             end if;
738          end if;
739
740          if Known_Null (Expr)
741            and then Nkind (Parent (Scope_Id)) = N_Function_Specification
742            and then Null_Exclusion_Present (Parent (Scope_Id))
743          then
744             Apply_Compile_Time_Constraint_Error
745               (N      => Expr,
746                Msg    => "(Ada 2005) null not allowed for "
747                          & "null-excluding return?",
748                Reason => CE_Null_Not_Allowed);
749          end if;
750
751          --  Apply checks suggested by AI05-0144 (dangerous order dependence)
752
753          Check_Order_Dependence;
754       end if;
755    end Analyze_Function_Return;
756
757    -------------------------------------
758    -- Analyze_Generic_Subprogram_Body --
759    -------------------------------------
760
761    procedure Analyze_Generic_Subprogram_Body
762      (N      : Node_Id;
763       Gen_Id : Entity_Id)
764    is
765       Gen_Decl : constant Node_Id     := Unit_Declaration_Node (Gen_Id);
766       Kind     : constant Entity_Kind := Ekind (Gen_Id);
767       Body_Id  : Entity_Id;
768       New_N    : Node_Id;
769       Spec     : Node_Id;
770
771    begin
772       --  Copy body and disable expansion while analyzing the generic For a
773       --  stub, do not copy the stub (which would load the proper body), this
774       --  will be done when the proper body is analyzed.
775
776       if Nkind (N) /= N_Subprogram_Body_Stub then
777          New_N := Copy_Generic_Node (N, Empty, Instantiating => False);
778          Rewrite (N, New_N);
779          Start_Generic;
780       end if;
781
782       Spec := Specification (N);
783
784       --  Within the body of the generic, the subprogram is callable, and
785       --  behaves like the corresponding non-generic unit.
786
787       Body_Id := Defining_Entity (Spec);
788
789       if Kind = E_Generic_Procedure
790         and then Nkind (Spec) /= N_Procedure_Specification
791       then
792          Error_Msg_N ("invalid body for generic procedure ", Body_Id);
793          return;
794
795       elsif Kind = E_Generic_Function
796         and then Nkind (Spec) /= N_Function_Specification
797       then
798          Error_Msg_N ("invalid body for generic function ", Body_Id);
799          return;
800       end if;
801
802       Set_Corresponding_Body (Gen_Decl, Body_Id);
803
804       if Has_Completion (Gen_Id)
805         and then Nkind (Parent (N)) /= N_Subunit
806       then
807          Error_Msg_N ("duplicate generic body", N);
808          return;
809       else
810          Set_Has_Completion (Gen_Id);
811       end if;
812
813       if Nkind (N) = N_Subprogram_Body_Stub then
814          Set_Ekind (Defining_Entity (Specification (N)), Kind);
815       else
816          Set_Corresponding_Spec (N, Gen_Id);
817       end if;
818
819       if Nkind (Parent (N)) = N_Compilation_Unit then
820          Set_Cunit_Entity (Current_Sem_Unit, Defining_Entity (N));
821       end if;
822
823       --  Make generic parameters immediately visible in the body. They are
824       --  needed to process the formals declarations. Then make the formals
825       --  visible in a separate step.
826
827       Push_Scope (Gen_Id);
828
829       declare
830          E         : Entity_Id;
831          First_Ent : Entity_Id;
832
833       begin
834          First_Ent := First_Entity (Gen_Id);
835
836          E := First_Ent;
837          while Present (E) and then not Is_Formal (E) loop
838             Install_Entity (E);
839             Next_Entity (E);
840          end loop;
841
842          Set_Use (Generic_Formal_Declarations (Gen_Decl));
843
844          --  Now generic formals are visible, and the specification can be
845          --  analyzed, for subsequent conformance check.
846
847          Body_Id := Analyze_Subprogram_Specification (Spec);
848
849          --  Make formal parameters visible
850
851          if Present (E) then
852
853             --  E is the first formal parameter, we loop through the formals
854             --  installing them so that they will be visible.
855
856             Set_First_Entity (Gen_Id, E);
857             while Present (E) loop
858                Install_Entity (E);
859                Next_Formal (E);
860             end loop;
861          end if;
862
863          --  Visible generic entity is callable within its own body
864
865          Set_Ekind          (Gen_Id,  Ekind (Body_Id));
866          Set_Ekind          (Body_Id, E_Subprogram_Body);
867          Set_Convention     (Body_Id, Convention (Gen_Id));
868          Set_Is_Obsolescent (Body_Id, Is_Obsolescent (Gen_Id));
869          Set_Scope          (Body_Id, Scope (Gen_Id));
870          Check_Fully_Conformant (Body_Id, Gen_Id, Body_Id);
871
872          if Nkind (N) = N_Subprogram_Body_Stub then
873
874             --  No body to analyze, so restore state of generic unit
875
876             Set_Ekind (Gen_Id, Kind);
877             Set_Ekind (Body_Id, Kind);
878
879             if Present (First_Ent) then
880                Set_First_Entity (Gen_Id, First_Ent);
881             end if;
882
883             End_Scope;
884             return;
885          end if;
886
887          --  If this is a compilation unit, it must be made visible explicitly,
888          --  because the compilation of the declaration, unlike other library
889          --  unit declarations, does not. If it is not a unit, the following
890          --  is redundant but harmless.
891
892          Set_Is_Immediately_Visible (Gen_Id);
893          Reference_Body_Formals (Gen_Id, Body_Id);
894
895          if Is_Child_Unit (Gen_Id) then
896             Generate_Reference (Gen_Id, Scope (Gen_Id), 'k', False);
897          end if;
898
899          Set_Actual_Subtypes (N, Current_Scope);
900          Process_PPCs (N, Gen_Id, Body_Id);
901
902          --  If the generic unit carries pre- or post-conditions, copy them
903          --  to the original generic tree, so that they are properly added
904          --  to any instantiation.
905
906          declare
907             Orig : constant Node_Id := Original_Node (N);
908             Cond : Node_Id;
909
910          begin
911             Cond := First (Declarations (N));
912             while Present (Cond) loop
913                if Nkind (Cond) = N_Pragma
914                  and then Pragma_Name (Cond) = Name_Check
915                then
916                   Prepend (New_Copy_Tree (Cond), Declarations (Orig));
917
918                elsif Nkind (Cond) = N_Pragma
919                  and then Pragma_Name (Cond) = Name_Postcondition
920                then
921                   Set_Ekind (Defining_Entity (Orig), Ekind (Gen_Id));
922                   Prepend (New_Copy_Tree (Cond), Declarations (Orig));
923                else
924                   exit;
925                end if;
926
927                Next (Cond);
928             end loop;
929          end;
930
931          Analyze_Declarations (Declarations (N));
932          Check_Completion;
933          Analyze (Handled_Statement_Sequence (N));
934
935          Save_Global_References (Original_Node (N));
936
937          --  Prior to exiting the scope, include generic formals again (if any
938          --  are present) in the set of local entities.
939
940          if Present (First_Ent) then
941             Set_First_Entity (Gen_Id, First_Ent);
942          end if;
943
944          Check_References (Gen_Id);
945       end;
946
947       Process_End_Label (Handled_Statement_Sequence (N), 't', Current_Scope);
948       End_Scope;
949       Check_Subprogram_Order (N);
950
951       --  Outside of its body, unit is generic again
952
953       Set_Ekind (Gen_Id, Kind);
954       Generate_Reference (Gen_Id, Body_Id, 'b', Set_Ref => False);
955
956       if Style_Check then
957          Style.Check_Identifier (Body_Id, Gen_Id);
958       end if;
959
960       End_Generic;
961    end Analyze_Generic_Subprogram_Body;
962
963    -----------------------------
964    -- Analyze_Operator_Symbol --
965    -----------------------------
966
967    --  An operator symbol such as "+" or "and" may appear in context where the
968    --  literal denotes an entity name, such as "+"(x, y) or in context when it
969    --  is just a string, as in (conjunction = "or"). In these cases the parser
970    --  generates this node, and the semantics does the disambiguation. Other
971    --  such case are actuals in an instantiation, the generic unit in an
972    --  instantiation, and pragma arguments.
973
974    procedure Analyze_Operator_Symbol (N : Node_Id) is
975       Par : constant Node_Id := Parent (N);
976
977    begin
978       if        (Nkind (Par) = N_Function_Call
979                    and then N = Name (Par))
980         or else  Nkind (Par) = N_Function_Instantiation
981         or else (Nkind (Par) = N_Indexed_Component
982                    and then N = Prefix (Par))
983         or else (Nkind (Par) = N_Pragma_Argument_Association
984                    and then not Is_Pragma_String_Literal (Par))
985         or else  Nkind (Par) = N_Subprogram_Renaming_Declaration
986         or else (Nkind (Par) = N_Attribute_Reference
987                   and then Attribute_Name (Par) /= Name_Value)
988       then
989          Find_Direct_Name (N);
990
991       else
992          Change_Operator_Symbol_To_String_Literal (N);
993          Analyze (N);
994       end if;
995    end Analyze_Operator_Symbol;
996
997    -----------------------------------
998    -- Analyze_Parameter_Association --
999    -----------------------------------
1000
1001    procedure Analyze_Parameter_Association (N : Node_Id) is
1002    begin
1003       Analyze (Explicit_Actual_Parameter (N));
1004    end Analyze_Parameter_Association;
1005
1006    ----------------------------
1007    -- Analyze_Procedure_Call --
1008    ----------------------------
1009
1010    procedure Analyze_Procedure_Call (N : Node_Id) is
1011       Loc     : constant Source_Ptr := Sloc (N);
1012       P       : constant Node_Id    := Name (N);
1013       Actuals : constant List_Id    := Parameter_Associations (N);
1014       Actual  : Node_Id;
1015       New_N   : Node_Id;
1016
1017       procedure Analyze_Call_And_Resolve;
1018       --  Do Analyze and Resolve calls for procedure call
1019       --  At end, check illegal order dependence.
1020
1021       ------------------------------
1022       -- Analyze_Call_And_Resolve --
1023       ------------------------------
1024
1025       procedure Analyze_Call_And_Resolve is
1026       begin
1027          if Nkind (N) = N_Procedure_Call_Statement then
1028             Analyze_Call (N);
1029             Resolve (N, Standard_Void_Type);
1030
1031             --  Apply checks suggested by AI05-0144
1032
1033             Check_Order_Dependence;
1034
1035          else
1036             Analyze (N);
1037          end if;
1038       end Analyze_Call_And_Resolve;
1039
1040    --  Start of processing for Analyze_Procedure_Call
1041
1042    begin
1043       --  The syntactic construct: PREFIX ACTUAL_PARAMETER_PART can denote
1044       --  a procedure call or an entry call. The prefix may denote an access
1045       --  to subprogram type, in which case an implicit dereference applies.
1046       --  If the prefix is an indexed component (without implicit dereference)
1047       --  then the construct denotes a call to a member of an entire family.
1048       --  If the prefix is a simple name, it may still denote a call to a
1049       --  parameterless member of an entry family. Resolution of these various
1050       --  interpretations is delicate.
1051
1052       Analyze (P);
1053
1054       --  If this is a call of the form Obj.Op, the call may have been
1055       --  analyzed and possibly rewritten into a block, in which case
1056       --  we are done.
1057
1058       if Analyzed (N) then
1059          return;
1060       end if;
1061
1062       --  If there is an error analyzing the name (which may have been
1063       --  rewritten if the original call was in prefix notation) then error
1064       --  has been emitted already, mark node and return.
1065
1066       if Error_Posted (N)
1067         or else Etype (Name (N)) = Any_Type
1068       then
1069          Set_Etype (N, Any_Type);
1070          return;
1071       end if;
1072
1073       --  Otherwise analyze the parameters
1074
1075       if Present (Actuals) then
1076          Actual := First (Actuals);
1077
1078          while Present (Actual) loop
1079             Analyze (Actual);
1080             Check_Parameterless_Call (Actual);
1081             Next (Actual);
1082          end loop;
1083       end if;
1084
1085       --  Special processing for Elab_Spec and Elab_Body calls
1086
1087       if Nkind (P) = N_Attribute_Reference
1088         and then (Attribute_Name (P) = Name_Elab_Spec
1089                    or else Attribute_Name (P) = Name_Elab_Body)
1090       then
1091          if Present (Actuals) then
1092             Error_Msg_N
1093               ("no parameters allowed for this call", First (Actuals));
1094             return;
1095          end if;
1096
1097          Set_Etype (N, Standard_Void_Type);
1098          Set_Analyzed (N);
1099
1100       elsif Is_Entity_Name (P)
1101         and then Is_Record_Type (Etype (Entity (P)))
1102         and then Remote_AST_I_Dereference (P)
1103       then
1104          return;
1105
1106       elsif Is_Entity_Name (P)
1107         and then Ekind (Entity (P)) /= E_Entry_Family
1108       then
1109          if Is_Access_Type (Etype (P))
1110            and then Ekind (Designated_Type (Etype (P))) = E_Subprogram_Type
1111            and then No (Actuals)
1112            and then Comes_From_Source (N)
1113          then
1114             Error_Msg_N ("missing explicit dereference in call", N);
1115          end if;
1116
1117          Analyze_Call_And_Resolve;
1118
1119       --  If the prefix is the simple name of an entry family, this is
1120       --  a parameterless call from within the task body itself.
1121
1122       elsif Is_Entity_Name (P)
1123         and then Nkind (P) = N_Identifier
1124         and then Ekind (Entity (P)) = E_Entry_Family
1125         and then Present (Actuals)
1126         and then No (Next (First (Actuals)))
1127       then
1128          --  Can be call to parameterless entry family. What appears to be the
1129          --  sole argument is in fact the entry index. Rewrite prefix of node
1130          --  accordingly. Source representation is unchanged by this
1131          --  transformation.
1132
1133          New_N :=
1134            Make_Indexed_Component (Loc,
1135              Prefix =>
1136                Make_Selected_Component (Loc,
1137                  Prefix => New_Occurrence_Of (Scope (Entity (P)), Loc),
1138                  Selector_Name => New_Occurrence_Of (Entity (P), Loc)),
1139              Expressions => Actuals);
1140          Set_Name (N, New_N);
1141          Set_Etype (New_N, Standard_Void_Type);
1142          Set_Parameter_Associations (N, No_List);
1143          Analyze_Call_And_Resolve;
1144
1145       elsif Nkind (P) = N_Explicit_Dereference then
1146          if Ekind (Etype (P)) = E_Subprogram_Type then
1147             Analyze_Call_And_Resolve;
1148          else
1149             Error_Msg_N ("expect access to procedure in call", P);
1150          end if;
1151
1152       --  The name can be a selected component or an indexed component that
1153       --  yields an access to subprogram. Such a prefix is legal if the call
1154       --  has parameter associations.
1155
1156       elsif Is_Access_Type (Etype (P))
1157         and then Ekind (Designated_Type (Etype (P))) = E_Subprogram_Type
1158       then
1159          if Present (Actuals) then
1160             Analyze_Call_And_Resolve;
1161          else
1162             Error_Msg_N ("missing explicit dereference in call ", N);
1163          end if;
1164
1165       --  If not an access to subprogram, then the prefix must resolve to the
1166       --  name of an entry, entry family, or protected operation.
1167
1168       --  For the case of a simple entry call, P is a selected component where
1169       --  the prefix is the task and the selector name is the entry. A call to
1170       --  a protected procedure will have the same syntax. If the protected
1171       --  object contains overloaded operations, the entity may appear as a
1172       --  function, the context will select the operation whose type is Void.
1173
1174       elsif Nkind (P) = N_Selected_Component
1175         and then (Ekind (Entity (Selector_Name (P))) = E_Entry
1176                     or else
1177                   Ekind (Entity (Selector_Name (P))) = E_Procedure
1178                     or else
1179                   Ekind (Entity (Selector_Name (P))) = E_Function)
1180       then
1181          Analyze_Call_And_Resolve;
1182
1183       elsif Nkind (P) = N_Selected_Component
1184         and then Ekind (Entity (Selector_Name (P))) = E_Entry_Family
1185         and then Present (Actuals)
1186         and then No (Next (First (Actuals)))
1187       then
1188          --  Can be call to parameterless entry family. What appears to be the
1189          --  sole argument is in fact the entry index. Rewrite prefix of node
1190          --  accordingly. Source representation is unchanged by this
1191          --  transformation.
1192
1193          New_N :=
1194            Make_Indexed_Component (Loc,
1195              Prefix => New_Copy (P),
1196              Expressions => Actuals);
1197          Set_Name (N, New_N);
1198          Set_Etype (New_N, Standard_Void_Type);
1199          Set_Parameter_Associations (N, No_List);
1200          Analyze_Call_And_Resolve;
1201
1202       --  For the case of a reference to an element of an entry family, P is
1203       --  an indexed component whose prefix is a selected component (task and
1204       --  entry family), and whose index is the entry family index.
1205
1206       elsif Nkind (P) = N_Indexed_Component
1207         and then Nkind (Prefix (P)) = N_Selected_Component
1208         and then Ekind (Entity (Selector_Name (Prefix (P)))) = E_Entry_Family
1209       then
1210          Analyze_Call_And_Resolve;
1211
1212       --  If the prefix is the name of an entry family, it is a call from
1213       --  within the task body itself.
1214
1215       elsif Nkind (P) = N_Indexed_Component
1216         and then Nkind (Prefix (P)) = N_Identifier
1217         and then Ekind (Entity (Prefix (P))) = E_Entry_Family
1218       then
1219          New_N :=
1220            Make_Selected_Component (Loc,
1221              Prefix => New_Occurrence_Of (Scope (Entity (Prefix (P))), Loc),
1222              Selector_Name => New_Occurrence_Of (Entity (Prefix (P)), Loc));
1223          Rewrite (Prefix (P), New_N);
1224          Analyze (P);
1225          Analyze_Call_And_Resolve;
1226
1227       --  Anything else is an error
1228
1229       else
1230          Error_Msg_N ("invalid procedure or entry call", N);
1231       end if;
1232    end Analyze_Procedure_Call;
1233
1234    ------------------------------
1235    -- Analyze_Return_Statement --
1236    ------------------------------
1237
1238    procedure Analyze_Return_Statement (N : Node_Id) is
1239
1240       pragma Assert (Nkind_In (N, N_Simple_Return_Statement,
1241                                   N_Extended_Return_Statement));
1242
1243       Returns_Object : constant Boolean :=
1244                          Nkind (N) = N_Extended_Return_Statement
1245                            or else
1246                             (Nkind (N) = N_Simple_Return_Statement
1247                               and then Present (Expression (N)));
1248       --  True if we're returning something; that is, "return <expression>;"
1249       --  or "return Result : T [:= ...]". False for "return;". Used for error
1250       --  checking: If Returns_Object is True, N should apply to a function
1251       --  body; otherwise N should apply to a procedure body, entry body,
1252       --  accept statement, or extended return statement.
1253
1254       function Find_What_It_Applies_To return Entity_Id;
1255       --  Find the entity representing the innermost enclosing body, accept
1256       --  statement, or extended return statement. If the result is a callable
1257       --  construct or extended return statement, then this will be the value
1258       --  of the Return_Applies_To attribute. Otherwise, the program is
1259       --  illegal. See RM-6.5(4/2).
1260
1261       -----------------------------
1262       -- Find_What_It_Applies_To --
1263       -----------------------------
1264
1265       function Find_What_It_Applies_To return Entity_Id is
1266          Result : Entity_Id := Empty;
1267
1268       begin
1269          --  Loop outward through the Scope_Stack, skipping blocks and loops
1270
1271          for J in reverse 0 .. Scope_Stack.Last loop
1272             Result := Scope_Stack.Table (J).Entity;
1273             exit when Ekind (Result) /= E_Block and then
1274                       Ekind (Result) /= E_Loop;
1275          end loop;
1276
1277          pragma Assert (Present (Result));
1278          return Result;
1279       end Find_What_It_Applies_To;
1280
1281       --  Local declarations
1282
1283       Scope_Id   : constant Entity_Id   := Find_What_It_Applies_To;
1284       Kind       : constant Entity_Kind := Ekind (Scope_Id);
1285       Loc        : constant Source_Ptr  := Sloc (N);
1286       Stm_Entity : constant Entity_Id   :=
1287                      New_Internal_Entity
1288                        (E_Return_Statement, Current_Scope, Loc, 'R');
1289
1290    --  Start of processing for Analyze_Return_Statement
1291
1292    begin
1293       Set_Return_Statement_Entity (N, Stm_Entity);
1294
1295       Set_Etype (Stm_Entity, Standard_Void_Type);
1296       Set_Return_Applies_To (Stm_Entity, Scope_Id);
1297
1298       --  Place Return entity on scope stack, to simplify enforcement of 6.5
1299       --  (4/2): an inner return statement will apply to this extended return.
1300
1301       if Nkind (N) = N_Extended_Return_Statement then
1302          Push_Scope (Stm_Entity);
1303       end if;
1304
1305       --  Check that pragma No_Return is obeyed. Don't complain about the
1306       --  implicitly-generated return that is placed at the end.
1307
1308       if No_Return (Scope_Id) and then Comes_From_Source (N) then
1309          Error_Msg_N ("RETURN statement not allowed (No_Return)", N);
1310       end if;
1311
1312       --  Warn on any unassigned OUT parameters if in procedure
1313
1314       if Ekind (Scope_Id) = E_Procedure then
1315          Warn_On_Unassigned_Out_Parameter (N, Scope_Id);
1316       end if;
1317
1318       --  Check that functions return objects, and other things do not
1319
1320       if Kind = E_Function or else Kind = E_Generic_Function then
1321          if not Returns_Object then
1322             Error_Msg_N ("missing expression in return from function", N);
1323          end if;
1324
1325       elsif Kind = E_Procedure or else Kind = E_Generic_Procedure then
1326          if Returns_Object then
1327             Error_Msg_N ("procedure cannot return value (use function)", N);
1328          end if;
1329
1330       elsif Kind = E_Entry or else Kind = E_Entry_Family then
1331          if Returns_Object then
1332             if Is_Protected_Type (Scope (Scope_Id)) then
1333                Error_Msg_N ("entry body cannot return value", N);
1334             else
1335                Error_Msg_N ("accept statement cannot return value", N);
1336             end if;
1337          end if;
1338
1339       elsif Kind = E_Return_Statement then
1340
1341          --  We are nested within another return statement, which must be an
1342          --  extended_return_statement.
1343
1344          if Returns_Object then
1345             Error_Msg_N
1346               ("extended_return_statement cannot return value; " &
1347                "use `""RETURN;""`", N);
1348          end if;
1349
1350       else
1351          Error_Msg_N ("illegal context for return statement", N);
1352       end if;
1353
1354       if Ekind_In (Kind, E_Function, E_Generic_Function) then
1355          Analyze_Function_Return (N);
1356
1357       elsif Ekind_In (Kind, E_Procedure, E_Generic_Procedure) then
1358          Set_Return_Present (Scope_Id);
1359       end if;
1360
1361       if Nkind (N) = N_Extended_Return_Statement then
1362          End_Scope;
1363       end if;
1364
1365       Kill_Current_Values (Last_Assignment_Only => True);
1366       Check_Unreachable_Code (N);
1367    end Analyze_Return_Statement;
1368
1369    -------------------------------------
1370    -- Analyze_Simple_Return_Statement --
1371    -------------------------------------
1372
1373    procedure Analyze_Simple_Return_Statement (N : Node_Id) is
1374    begin
1375       if Present (Expression (N)) then
1376          Mark_Coextensions (N, Expression (N));
1377       end if;
1378
1379       Analyze_Return_Statement (N);
1380    end Analyze_Simple_Return_Statement;
1381
1382    -------------------------
1383    -- Analyze_Return_Type --
1384    -------------------------
1385
1386    procedure Analyze_Return_Type (N : Node_Id) is
1387       Designator : constant Entity_Id := Defining_Entity (N);
1388       Typ        : Entity_Id := Empty;
1389
1390    begin
1391       --  Normal case where result definition does not indicate an error
1392
1393       if Result_Definition (N) /= Error then
1394          if Nkind (Result_Definition (N)) = N_Access_Definition then
1395             Check_Formal_Restriction
1396               ("access result is not allowed", Result_Definition (N));
1397
1398             --  Ada 2005 (AI-254): Handle anonymous access to subprograms
1399
1400             declare
1401                AD : constant Node_Id :=
1402                       Access_To_Subprogram_Definition (Result_Definition (N));
1403             begin
1404                if Present (AD) and then Protected_Present (AD) then
1405                   Typ := Replace_Anonymous_Access_To_Protected_Subprogram (N);
1406                else
1407                   Typ := Access_Definition (N, Result_Definition (N));
1408                end if;
1409             end;
1410
1411             Set_Parent (Typ, Result_Definition (N));
1412             Set_Is_Local_Anonymous_Access (Typ);
1413             Set_Etype (Designator, Typ);
1414
1415             --  Ada 2005 (AI-231): Ensure proper usage of null exclusion
1416
1417             Null_Exclusion_Static_Checks (N);
1418
1419          --  Subtype_Mark case
1420
1421          else
1422             Find_Type (Result_Definition (N));
1423             Typ := Entity (Result_Definition (N));
1424             Set_Etype (Designator, Typ);
1425
1426             --  Unconstrained array as result is not allowed in SPARK or ALFA
1427
1428             if Is_Array_Type (Typ)
1429               and then not Is_Constrained (Typ)
1430             then
1431                Check_Formal_Restriction
1432                  ("returning an unconstrained array is not allowed",
1433                   Result_Definition (N));
1434             end if;
1435
1436             --  Ada 2005 (AI-231): Ensure proper usage of null exclusion
1437
1438             Null_Exclusion_Static_Checks (N);
1439
1440             --  If a null exclusion is imposed on the result type, then create
1441             --  a null-excluding itype (an access subtype) and use it as the
1442             --  function's Etype. Note that the null exclusion checks are done
1443             --  right before this, because they don't get applied to types that
1444             --  do not come from source.
1445
1446             if Is_Access_Type (Typ)
1447               and then Null_Exclusion_Present (N)
1448             then
1449                Set_Etype  (Designator,
1450                  Create_Null_Excluding_Itype
1451                   (T           => Typ,
1452                    Related_Nod => N,
1453                    Scope_Id    => Scope (Current_Scope)));
1454
1455                --  The new subtype must be elaborated before use because
1456                --  it is visible outside of the function. However its base
1457                --  type may not be frozen yet, so the reference that will
1458                --  force elaboration must be attached to the freezing of
1459                --  the base type.
1460
1461                --  If the return specification appears on a proper body,
1462                --  the subtype will have been created already on the spec.
1463
1464                if Is_Frozen (Typ) then
1465                   if Nkind (Parent (N)) = N_Subprogram_Body
1466                     and then Nkind (Parent (Parent (N))) = N_Subunit
1467                   then
1468                      null;
1469                   else
1470                      Build_Itype_Reference (Etype (Designator), Parent (N));
1471                   end if;
1472
1473                else
1474                   Ensure_Freeze_Node (Typ);
1475
1476                   declare
1477                      IR : constant Node_Id := Make_Itype_Reference (Sloc (N));
1478                   begin
1479                      Set_Itype (IR, Etype (Designator));
1480                      Append_Freeze_Actions (Typ, New_List (IR));
1481                   end;
1482                end if;
1483
1484             else
1485                Set_Etype (Designator, Typ);
1486             end if;
1487
1488             if Ekind (Typ) = E_Incomplete_Type
1489               and then Is_Value_Type (Typ)
1490             then
1491                null;
1492
1493             elsif Ekind (Typ) = E_Incomplete_Type
1494               or else (Is_Class_Wide_Type (Typ)
1495                          and then
1496                            Ekind (Root_Type (Typ)) = E_Incomplete_Type)
1497             then
1498                --  AI05-0151: Tagged incomplete types are allowed in all formal
1499                --  parts. Untagged incomplete types are not allowed in bodies.
1500
1501                if Ada_Version >= Ada_2012 then
1502                   if Is_Tagged_Type (Typ) then
1503                      null;
1504
1505                   elsif Nkind_In (Parent (Parent (N)),
1506                      N_Accept_Statement,
1507                      N_Entry_Body,
1508                      N_Subprogram_Body)
1509                   then
1510                      Error_Msg_NE
1511                        ("invalid use of untagged incomplete type&",
1512                           Designator, Typ);
1513                   end if;
1514
1515                else
1516                   Error_Msg_NE
1517                     ("invalid use of incomplete type&", Designator, Typ);
1518                end if;
1519             end if;
1520          end if;
1521
1522       --  Case where result definition does indicate an error
1523
1524       else
1525          Set_Etype (Designator, Any_Type);
1526       end if;
1527    end Analyze_Return_Type;
1528
1529    -----------------------------
1530    -- Analyze_Subprogram_Body --
1531    -----------------------------
1532
1533    procedure Analyze_Subprogram_Body (N : Node_Id) is
1534       Loc       : constant Source_Ptr := Sloc (N);
1535       Body_Spec : constant Node_Id    := Specification (N);
1536       Body_Id   : constant Entity_Id  := Defining_Entity (Body_Spec);
1537
1538    begin
1539       if Debug_Flag_C then
1540          Write_Str ("==> subprogram body ");
1541          Write_Name (Chars (Body_Id));
1542          Write_Str (" from ");
1543          Write_Location (Loc);
1544          Write_Eol;
1545          Indent;
1546       end if;
1547
1548       Trace_Scope (N, Body_Id, " Analyze subprogram: ");
1549
1550       --  The real work is split out into the helper, so it can do "return;"
1551       --  without skipping the debug output:
1552
1553       Analyze_Subprogram_Body_Helper (N);
1554
1555       if Debug_Flag_C then
1556          Outdent;
1557          Write_Str ("<== subprogram body ");
1558          Write_Name (Chars (Body_Id));
1559          Write_Str (" from ");
1560          Write_Location (Loc);
1561          Write_Eol;
1562       end if;
1563    end Analyze_Subprogram_Body;
1564
1565    ------------------------------------
1566    -- Analyze_Subprogram_Body_Helper --
1567    ------------------------------------
1568
1569    --  This procedure is called for regular subprogram bodies, generic bodies,
1570    --  and for subprogram stubs of both kinds. In the case of stubs, only the
1571    --  specification matters, and is used to create a proper declaration for
1572    --  the subprogram, or to perform conformance checks.
1573
1574    procedure Analyze_Subprogram_Body_Helper (N : Node_Id) is
1575       Loc          : constant Source_Ptr := Sloc (N);
1576       Body_Deleted : constant Boolean    := False;
1577       Body_Spec    : constant Node_Id    := Specification (N);
1578       Body_Id      : Entity_Id           := Defining_Entity (Body_Spec);
1579       Prev_Id      : constant Entity_Id  := Current_Entity_In_Scope (Body_Id);
1580       Conformant   : Boolean;
1581       HSS          : Node_Id;
1582       P_Ent        : Entity_Id;
1583       Prot_Typ     : Entity_Id := Empty;
1584       Spec_Id      : Entity_Id;
1585       Spec_Decl    : Node_Id   := Empty;
1586
1587       Last_Real_Spec_Entity : Entity_Id := Empty;
1588       --  When we analyze a separate spec, the entity chain ends up containing
1589       --  the formals, as well as any itypes generated during analysis of the
1590       --  default expressions for parameters, or the arguments of associated
1591       --  precondition/postcondition pragmas (which are analyzed in the context
1592       --  of the spec since they have visibility on formals).
1593       --
1594       --  These entities belong with the spec and not the body. However we do
1595       --  the analysis of the body in the context of the spec (again to obtain
1596       --  visibility to the formals), and all the entities generated during
1597       --  this analysis end up also chained to the entity chain of the spec.
1598       --  But they really belong to the body, and there is circuitry to move
1599       --  them from the spec to the body.
1600       --
1601       --  However, when we do this move, we don't want to move the real spec
1602       --  entities (first para above) to the body. The Last_Real_Spec_Entity
1603       --  variable points to the last real spec entity, so we only move those
1604       --  chained beyond that point. It is initialized to Empty to deal with
1605       --  the case where there is no separate spec.
1606
1607       procedure Check_Anonymous_Return;
1608       --  Ada 2005: if a function returns an access type that denotes a task,
1609       --  or a type that contains tasks, we must create a master entity for
1610       --  the anonymous type, which typically will be used in an allocator
1611       --  in the body of the function.
1612
1613       procedure Check_Inline_Pragma (Spec : in out Node_Id);
1614       --  Look ahead to recognize a pragma that may appear after the body.
1615       --  If there is a previous spec, check that it appears in the same
1616       --  declarative part. If the pragma is Inline_Always, perform inlining
1617       --  unconditionally, otherwise only if Front_End_Inlining is requested.
1618       --  If the body acts as a spec, and inlining is required, we create a
1619       --  subprogram declaration for it, in order to attach the body to inline.
1620       --  If pragma does not appear after the body, check whether there is
1621       --  an inline pragma before any local declarations.
1622
1623       procedure Check_Missing_Return;
1624       --  Checks for a function with a no return statements, and also performs
1625       --  the warning checks implemented by Check_Returns. In formal mode, also
1626       --  verify that a function ends with a RETURN and that a procedure does
1627       --  not contain any RETURN.
1628
1629       function Disambiguate_Spec return Entity_Id;
1630       --  When a primitive is declared between the private view and the full
1631       --  view of a concurrent type which implements an interface, a special
1632       --  mechanism is used to find the corresponding spec of the primitive
1633       --  body.
1634
1635       function Is_Private_Concurrent_Primitive
1636         (Subp_Id : Entity_Id) return Boolean;
1637       --  Determine whether subprogram Subp_Id is a primitive of a concurrent
1638       --  type that implements an interface and has a private view.
1639
1640       procedure Set_Trivial_Subprogram (N : Node_Id);
1641       --  Sets the Is_Trivial_Subprogram flag in both spec and body of the
1642       --  subprogram whose body is being analyzed. N is the statement node
1643       --  causing the flag to be set, if the following statement is a return
1644       --  of an entity, we mark the entity as set in source to suppress any
1645       --  warning on the stylized use of function stubs with a dummy return.
1646
1647       procedure Verify_Overriding_Indicator;
1648       --  If there was a previous spec, the entity has been entered in the
1649       --  current scope previously. If the body itself carries an overriding
1650       --  indicator, check that it is consistent with the known status of the
1651       --  entity.
1652
1653       ----------------------------
1654       -- Check_Anonymous_Return --
1655       ----------------------------
1656
1657       procedure Check_Anonymous_Return is
1658          Decl : Node_Id;
1659          Par  : Node_Id;
1660          Scop : Entity_Id;
1661
1662       begin
1663          if Present (Spec_Id) then
1664             Scop := Spec_Id;
1665          else
1666             Scop := Body_Id;
1667          end if;
1668
1669          if Ekind (Scop) = E_Function
1670            and then Ekind (Etype (Scop)) = E_Anonymous_Access_Type
1671            and then not Is_Thunk (Scop)
1672            and then (Has_Task (Designated_Type (Etype (Scop)))
1673                       or else
1674                        (Is_Class_Wide_Type (Designated_Type (Etype (Scop)))
1675                           and then
1676                         Is_Limited_Record (Designated_Type (Etype (Scop)))))
1677            and then Expander_Active
1678
1679             --  Avoid cases with no tasking support
1680
1681            and then RTE_Available (RE_Current_Master)
1682            and then not Restriction_Active (No_Task_Hierarchy)
1683          then
1684             Decl :=
1685               Make_Object_Declaration (Loc,
1686                 Defining_Identifier =>
1687                   Make_Defining_Identifier (Loc, Name_uMaster),
1688                 Constant_Present => True,
1689                 Object_Definition =>
1690                   New_Reference_To (RTE (RE_Master_Id), Loc),
1691                 Expression =>
1692                   Make_Explicit_Dereference (Loc,
1693                     New_Reference_To (RTE (RE_Current_Master), Loc)));
1694
1695             if Present (Declarations (N)) then
1696                Prepend (Decl, Declarations (N));
1697             else
1698                Set_Declarations (N, New_List (Decl));
1699             end if;
1700
1701             Set_Master_Id (Etype (Scop), Defining_Identifier (Decl));
1702             Set_Has_Master_Entity (Scop);
1703
1704             --  Now mark the containing scope as a task master
1705
1706             Par := N;
1707             while Nkind (Par) /= N_Compilation_Unit loop
1708                Par := Parent (Par);
1709                pragma Assert (Present (Par));
1710
1711                --  If we fall off the top, we are at the outer level, and
1712                --  the environment task is our effective master, so nothing
1713                --  to mark.
1714
1715                if Nkind_In
1716                    (Par, N_Task_Body, N_Block_Statement, N_Subprogram_Body)
1717                then
1718                   Set_Is_Task_Master (Par, True);
1719                   exit;
1720                end if;
1721             end loop;
1722          end if;
1723       end Check_Anonymous_Return;
1724
1725       -------------------------
1726       -- Check_Inline_Pragma --
1727       -------------------------
1728
1729       procedure Check_Inline_Pragma (Spec : in out Node_Id) is
1730          Prag  : Node_Id;
1731          Plist : List_Id;
1732
1733          function Is_Inline_Pragma (N : Node_Id) return Boolean;
1734          --  True when N is a pragma Inline or Inline_Always that applies
1735          --  to this subprogram.
1736
1737          -----------------------
1738          --  Is_Inline_Pragma --
1739          -----------------------
1740
1741          function Is_Inline_Pragma (N : Node_Id) return Boolean is
1742          begin
1743             return
1744               Nkind (N) = N_Pragma
1745                 and then
1746                    (Pragma_Name (N) = Name_Inline_Always
1747                      or else
1748                       (Front_End_Inlining
1749                         and then Pragma_Name (N) = Name_Inline))
1750                 and then
1751                    Chars
1752                      (Expression (First (Pragma_Argument_Associations (N))))
1753                         = Chars (Body_Id);
1754          end Is_Inline_Pragma;
1755
1756       --  Start of processing for Check_Inline_Pragma
1757
1758       begin
1759          if not Expander_Active then
1760             return;
1761          end if;
1762
1763          if Is_List_Member (N)
1764            and then Present (Next (N))
1765            and then Is_Inline_Pragma (Next (N))
1766          then
1767             Prag := Next (N);
1768
1769          elsif Nkind (N) /= N_Subprogram_Body_Stub
1770            and then Present (Declarations (N))
1771            and then Is_Inline_Pragma (First (Declarations (N)))
1772          then
1773             Prag := First (Declarations (N));
1774
1775          else
1776             Prag := Empty;
1777          end if;
1778
1779          if Present (Prag) then
1780             if Present (Spec_Id) then
1781                if In_Same_List (N, Unit_Declaration_Node (Spec_Id)) then
1782                   Analyze (Prag);
1783                end if;
1784
1785             else
1786                --  Create a subprogram declaration, to make treatment uniform
1787
1788                declare
1789                   Subp : constant Entity_Id :=
1790                            Make_Defining_Identifier (Loc, Chars (Body_Id));
1791                   Decl : constant Node_Id :=
1792                            Make_Subprogram_Declaration (Loc,
1793                              Specification =>
1794                                New_Copy_Tree (Specification (N)));
1795
1796                begin
1797                   Set_Defining_Unit_Name (Specification (Decl), Subp);
1798
1799                   if Present (First_Formal (Body_Id)) then
1800                      Plist := Copy_Parameter_List (Body_Id);
1801                      Set_Parameter_Specifications
1802                        (Specification (Decl), Plist);
1803                   end if;
1804
1805                   Insert_Before (N, Decl);
1806                   Analyze (Decl);
1807                   Analyze (Prag);
1808                   Set_Has_Pragma_Inline (Subp);
1809
1810                   if Pragma_Name (Prag) = Name_Inline_Always then
1811                      Set_Is_Inlined (Subp);
1812                      Set_Has_Pragma_Inline_Always (Subp);
1813                   end if;
1814
1815                   Spec := Subp;
1816                end;
1817             end if;
1818          end if;
1819       end Check_Inline_Pragma;
1820
1821       --------------------------
1822       -- Check_Missing_Return --
1823       --------------------------
1824
1825       procedure Check_Missing_Return is
1826          Id          : Entity_Id;
1827          Missing_Ret : Boolean;
1828
1829       begin
1830          if Nkind (Body_Spec) = N_Function_Specification then
1831             if Present (Spec_Id) then
1832                Id := Spec_Id;
1833             else
1834                Id := Body_Id;
1835             end if;
1836
1837             if Return_Present (Id) then
1838                Check_Returns (HSS, 'F', Missing_Ret);
1839
1840                if Missing_Ret then
1841                   Set_Has_Missing_Return (Id);
1842                end if;
1843
1844             elsif (Is_Generic_Subprogram (Id)
1845                      or else not Is_Machine_Code_Subprogram (Id))
1846               and then not Body_Deleted
1847             then
1848                Error_Msg_N ("missing RETURN statement in function body", N);
1849             end if;
1850
1851          --  If procedure with No_Return, check returns
1852
1853          elsif Nkind (Body_Spec) = N_Procedure_Specification
1854            and then Present (Spec_Id)
1855            and then No_Return (Spec_Id)
1856          then
1857             Check_Returns (HSS, 'P', Missing_Ret, Spec_Id);
1858          end if;
1859
1860          --  Special checks in formal mode
1861
1862          if Nkind (Body_Spec) = N_Function_Specification then
1863
1864             --  In formal mode, last statement of a function should be a return
1865
1866             declare
1867                Stat : constant Node_Id := Last_Source_Statement (HSS);
1868             begin
1869                if Present (Stat)
1870                  and then not Nkind_In (Stat, N_Simple_Return_Statement,
1871                                               N_Extended_Return_Statement)
1872                then
1873                   Check_Formal_Restriction
1874                     ("last statement in function should be RETURN", Stat);
1875                end if;
1876             end;
1877
1878          --  In formal mode, verify that a procedure has no return
1879
1880          elsif Nkind (Body_Spec) = N_Procedure_Specification then
1881             if Present (Spec_Id) then
1882                Id := Spec_Id;
1883             else
1884                Id := Body_Id;
1885             end if;
1886
1887             --  Would be nice to point to return statement here, can we
1888             --  borrow the Check_Returns procedure here ???
1889
1890             if Return_Present (Id) then
1891                Check_Formal_Restriction
1892                  ("procedure should not have RETURN", N);
1893             end if;
1894          end if;
1895       end Check_Missing_Return;
1896
1897       -----------------------
1898       -- Disambiguate_Spec --
1899       -----------------------
1900
1901       function Disambiguate_Spec return Entity_Id is
1902          Priv_Spec : Entity_Id;
1903          Spec_N    : Entity_Id;
1904
1905          procedure Replace_Types (To_Corresponding : Boolean);
1906          --  Depending on the flag, replace the type of formal parameters of
1907          --  Body_Id if it is a concurrent type implementing interfaces with
1908          --  the corresponding record type or the other way around.
1909
1910          procedure Replace_Types (To_Corresponding : Boolean) is
1911             Formal     : Entity_Id;
1912             Formal_Typ : Entity_Id;
1913
1914          begin
1915             Formal := First_Formal (Body_Id);
1916             while Present (Formal) loop
1917                Formal_Typ := Etype (Formal);
1918
1919                --  From concurrent type to corresponding record
1920
1921                if To_Corresponding then
1922                   if Is_Concurrent_Type (Formal_Typ)
1923                     and then Present (Corresponding_Record_Type (Formal_Typ))
1924                     and then Present (Interfaces (
1925                                Corresponding_Record_Type (Formal_Typ)))
1926                   then
1927                      Set_Etype (Formal,
1928                        Corresponding_Record_Type (Formal_Typ));
1929                   end if;
1930
1931                --  From corresponding record to concurrent type
1932
1933                else
1934                   if Is_Concurrent_Record_Type (Formal_Typ)
1935                     and then Present (Interfaces (Formal_Typ))
1936                   then
1937                      Set_Etype (Formal,
1938                        Corresponding_Concurrent_Type (Formal_Typ));
1939                   end if;
1940                end if;
1941
1942                Next_Formal (Formal);
1943             end loop;
1944          end Replace_Types;
1945
1946       --  Start of processing for Disambiguate_Spec
1947
1948       begin
1949          --  Try to retrieve the specification of the body as is. All error
1950          --  messages are suppressed because the body may not have a spec in
1951          --  its current state.
1952
1953          Spec_N := Find_Corresponding_Spec (N, False);
1954
1955          --  It is possible that this is the body of a primitive declared
1956          --  between a private and a full view of a concurrent type. The
1957          --  controlling parameter of the spec carries the concurrent type,
1958          --  not the corresponding record type as transformed by Analyze_
1959          --  Subprogram_Specification. In such cases, we undo the change
1960          --  made by the analysis of the specification and try to find the
1961          --  spec again.
1962
1963          --  Note that wrappers already have their corresponding specs and
1964          --  bodies set during their creation, so if the candidate spec is
1965          --  a wrapper, then we definitely need to swap all types to their
1966          --  original concurrent status.
1967
1968          if No (Spec_N)
1969            or else Is_Primitive_Wrapper (Spec_N)
1970          then
1971             --  Restore all references of corresponding record types to the
1972             --  original concurrent types.
1973
1974             Replace_Types (To_Corresponding => False);
1975             Priv_Spec := Find_Corresponding_Spec (N, False);
1976
1977             --  The current body truly belongs to a primitive declared between
1978             --  a private and a full view. We leave the modified body as is,
1979             --  and return the true spec.
1980
1981             if Present (Priv_Spec)
1982               and then Is_Private_Primitive (Priv_Spec)
1983             then
1984                return Priv_Spec;
1985             end if;
1986
1987             --  In case that this is some sort of error, restore the original
1988             --  state of the body.
1989
1990             Replace_Types (To_Corresponding => True);
1991          end if;
1992
1993          return Spec_N;
1994       end Disambiguate_Spec;
1995
1996       -------------------------------------
1997       -- Is_Private_Concurrent_Primitive --
1998       -------------------------------------
1999
2000       function Is_Private_Concurrent_Primitive
2001         (Subp_Id : Entity_Id) return Boolean
2002       is
2003          Formal_Typ : Entity_Id;
2004
2005       begin
2006          if Present (First_Formal (Subp_Id)) then
2007             Formal_Typ := Etype (First_Formal (Subp_Id));
2008
2009             if Is_Concurrent_Record_Type (Formal_Typ) then
2010                Formal_Typ := Corresponding_Concurrent_Type (Formal_Typ);
2011             end if;
2012
2013             --  The type of the first formal is a concurrent tagged type with
2014             --  a private view.
2015
2016             return
2017               Is_Concurrent_Type (Formal_Typ)
2018                 and then Is_Tagged_Type (Formal_Typ)
2019                 and then Has_Private_Declaration (Formal_Typ);
2020          end if;
2021
2022          return False;
2023       end Is_Private_Concurrent_Primitive;
2024
2025       ----------------------------
2026       -- Set_Trivial_Subprogram --
2027       ----------------------------
2028
2029       procedure Set_Trivial_Subprogram (N : Node_Id) is
2030          Nxt : constant Node_Id := Next (N);
2031
2032       begin
2033          Set_Is_Trivial_Subprogram (Body_Id);
2034
2035          if Present (Spec_Id) then
2036             Set_Is_Trivial_Subprogram (Spec_Id);
2037          end if;
2038
2039          if Present (Nxt)
2040            and then Nkind (Nxt) = N_Simple_Return_Statement
2041            and then No (Next (Nxt))
2042            and then Present (Expression (Nxt))
2043            and then Is_Entity_Name (Expression (Nxt))
2044          then
2045             Set_Never_Set_In_Source (Entity (Expression (Nxt)), False);
2046          end if;
2047       end Set_Trivial_Subprogram;
2048
2049       ---------------------------------
2050       -- Verify_Overriding_Indicator --
2051       ---------------------------------
2052
2053       procedure Verify_Overriding_Indicator is
2054       begin
2055          if Must_Override (Body_Spec) then
2056             if Nkind (Spec_Id) = N_Defining_Operator_Symbol
2057               and then  Operator_Matches_Spec (Spec_Id, Spec_Id)
2058             then
2059                null;
2060
2061             elsif not Present (Overridden_Operation (Spec_Id)) then
2062                Error_Msg_NE
2063                  ("subprogram& is not overriding", Body_Spec, Spec_Id);
2064             end if;
2065
2066          elsif Must_Not_Override (Body_Spec) then
2067             if Present (Overridden_Operation (Spec_Id)) then
2068                Error_Msg_NE
2069                  ("subprogram& overrides inherited operation",
2070                   Body_Spec, Spec_Id);
2071
2072             elsif Nkind (Spec_Id) = N_Defining_Operator_Symbol
2073               and then  Operator_Matches_Spec (Spec_Id, Spec_Id)
2074             then
2075                Error_Msg_NE
2076                  ("subprogram & overrides predefined operator ",
2077                     Body_Spec, Spec_Id);
2078
2079             --  If this is not a primitive operation or protected subprogram,
2080             --  then the overriding indicator is altogether illegal.
2081
2082             elsif not Is_Primitive (Spec_Id)
2083               and then Ekind (Scope (Spec_Id)) /= E_Protected_Type
2084             then
2085                Error_Msg_N
2086                  ("overriding indicator only allowed " &
2087                   "if subprogram is primitive",
2088                   Body_Spec);
2089             end if;
2090
2091          elsif Style_Check
2092            and then Present (Overridden_Operation (Spec_Id))
2093          then
2094             pragma Assert (Unit_Declaration_Node (Body_Id) = N);
2095             Style.Missing_Overriding (N, Body_Id);
2096
2097          elsif Style_Check
2098            and then Can_Override_Operator (Spec_Id)
2099            and then not Is_Predefined_File_Name
2100                           (Unit_File_Name (Get_Source_Unit (Spec_Id)))
2101          then
2102             pragma Assert (Unit_Declaration_Node (Body_Id) = N);
2103             Style.Missing_Overriding (N, Body_Id);
2104          end if;
2105       end Verify_Overriding_Indicator;
2106
2107    --  Start of processing for Analyze_Subprogram_Body_Helper
2108
2109    begin
2110       --  Generic subprograms are handled separately. They always have a
2111       --  generic specification. Determine whether current scope has a
2112       --  previous declaration.
2113
2114       --  If the subprogram body is defined within an instance of the same
2115       --  name, the instance appears as a package renaming, and will be hidden
2116       --  within the subprogram.
2117
2118       if Present (Prev_Id)
2119         and then not Is_Overloadable (Prev_Id)
2120         and then (Nkind (Parent (Prev_Id)) /= N_Package_Renaming_Declaration
2121                    or else Comes_From_Source (Prev_Id))
2122       then
2123          if Is_Generic_Subprogram (Prev_Id) then
2124             Spec_Id := Prev_Id;
2125             Set_Is_Compilation_Unit (Body_Id, Is_Compilation_Unit (Spec_Id));
2126             Set_Is_Child_Unit       (Body_Id, Is_Child_Unit       (Spec_Id));
2127
2128             Analyze_Generic_Subprogram_Body (N, Spec_Id);
2129
2130             if Nkind (N) = N_Subprogram_Body then
2131                HSS := Handled_Statement_Sequence (N);
2132                Check_Missing_Return;
2133             end if;
2134
2135             return;
2136
2137          else
2138             --  Previous entity conflicts with subprogram name. Attempting to
2139             --  enter name will post error.
2140
2141             Enter_Name (Body_Id);
2142             return;
2143          end if;
2144
2145       --  Non-generic case, find the subprogram declaration, if one was seen,
2146       --  or enter new overloaded entity in the current scope. If the
2147       --  Current_Entity is the Body_Id itself, the unit is being analyzed as
2148       --  part of the context of one of its subunits. No need to redo the
2149       --  analysis.
2150
2151       elsif Prev_Id = Body_Id
2152         and then Has_Completion (Body_Id)
2153       then
2154          return;
2155
2156       else
2157          Body_Id := Analyze_Subprogram_Specification (Body_Spec);
2158
2159          if Nkind (N) = N_Subprogram_Body_Stub
2160            or else No (Corresponding_Spec (N))
2161          then
2162             if Is_Private_Concurrent_Primitive (Body_Id) then
2163                Spec_Id := Disambiguate_Spec;
2164             else
2165                Spec_Id := Find_Corresponding_Spec (N);
2166             end if;
2167
2168             --  If this is a duplicate body, no point in analyzing it
2169
2170             if Error_Posted (N) then
2171                return;
2172             end if;
2173
2174             --  A subprogram body should cause freezing of its own declaration,
2175             --  but if there was no previous explicit declaration, then the
2176             --  subprogram will get frozen too late (there may be code within
2177             --  the body that depends on the subprogram having been frozen,
2178             --  such as uses of extra formals), so we force it to be frozen
2179             --  here. Same holds if the body and spec are compilation units.
2180             --  Finally, if the return type is an anonymous access to protected
2181             --  subprogram, it must be frozen before the body because its
2182             --  expansion has generated an equivalent type that is used when
2183             --  elaborating the body.
2184
2185             if No (Spec_Id) then
2186                Freeze_Before (N, Body_Id);
2187
2188             elsif Nkind (Parent (N)) = N_Compilation_Unit then
2189                Freeze_Before (N, Spec_Id);
2190
2191             elsif Is_Access_Subprogram_Type (Etype (Body_Id)) then
2192                Freeze_Before (N, Etype (Body_Id));
2193             end if;
2194
2195          else
2196             Spec_Id := Corresponding_Spec (N);
2197          end if;
2198       end if;
2199
2200       --  Do not inline any subprogram that contains nested subprograms, since
2201       --  the backend inlining circuit seems to generate uninitialized
2202       --  references in this case. We know this happens in the case of front
2203       --  end ZCX support, but it also appears it can happen in other cases as
2204       --  well. The backend often rejects attempts to inline in the case of
2205       --  nested procedures anyway, so little if anything is lost by this.
2206       --  Note that this is test is for the benefit of the back-end. There is
2207       --  a separate test for front-end inlining that also rejects nested
2208       --  subprograms.
2209
2210       --  Do not do this test if errors have been detected, because in some
2211       --  error cases, this code blows up, and we don't need it anyway if
2212       --  there have been errors, since we won't get to the linker anyway.
2213
2214       if Comes_From_Source (Body_Id)
2215         and then Serious_Errors_Detected = 0
2216       then
2217          P_Ent := Body_Id;
2218          loop
2219             P_Ent := Scope (P_Ent);
2220             exit when No (P_Ent) or else P_Ent = Standard_Standard;
2221
2222             if Is_Subprogram (P_Ent) then
2223                Set_Is_Inlined (P_Ent, False);
2224
2225                if Comes_From_Source (P_Ent)
2226                  and then Has_Pragma_Inline (P_Ent)
2227                then
2228                   Cannot_Inline
2229                     ("cannot inline& (nested subprogram)?",
2230                      N, P_Ent);
2231                end if;
2232             end if;
2233          end loop;
2234       end if;
2235
2236       Check_Inline_Pragma (Spec_Id);
2237
2238       --  Deal with special case of a fully private operation in the body of
2239       --  the protected type. We must create a declaration for the subprogram,
2240       --  in order to attach the protected subprogram that will be used in
2241       --  internal calls. We exclude compiler generated bodies from the
2242       --  expander since the issue does not arise for those cases.
2243
2244       if No (Spec_Id)
2245         and then Comes_From_Source (N)
2246         and then Is_Protected_Type (Current_Scope)
2247       then
2248          Spec_Id := Build_Private_Protected_Declaration (N);
2249       end if;
2250
2251       --  If a separate spec is present, then deal with freezing issues
2252
2253       if Present (Spec_Id) then
2254          Spec_Decl := Unit_Declaration_Node (Spec_Id);
2255          Verify_Overriding_Indicator;
2256
2257          --  In general, the spec will be frozen when we start analyzing the
2258          --  body. However, for internally generated operations, such as
2259          --  wrapper functions for inherited operations with controlling
2260          --  results, the spec may not have been frozen by the time we
2261          --  expand the freeze actions that include the bodies. In particular,
2262          --  extra formals for accessibility or for return-in-place may need
2263          --  to be generated. Freeze nodes, if any, are inserted before the
2264          --  current body.
2265
2266          if not Is_Frozen (Spec_Id)
2267            and then Expander_Active
2268          then
2269             --  Force the generation of its freezing node to ensure proper
2270             --  management of access types in the backend.
2271
2272             --  This is definitely needed for some cases, but it is not clear
2273             --  why, to be investigated further???
2274
2275             Set_Has_Delayed_Freeze (Spec_Id);
2276             Freeze_Before (N, Spec_Id);
2277          end if;
2278       end if;
2279
2280       --  Mark presence of postcondition procedure in current scope and mark
2281       --  the procedure itself as needing debug info. The latter is important
2282       --  when analyzing decision coverage (for example, for MC/DC coverage).
2283
2284       if Chars (Body_Id) = Name_uPostconditions then
2285          Set_Has_Postconditions (Current_Scope);
2286          Set_Debug_Info_Needed (Body_Id);
2287       end if;
2288
2289       --  Place subprogram on scope stack, and make formals visible. If there
2290       --  is a spec, the visible entity remains that of the spec.
2291
2292       if Present (Spec_Id) then
2293          Generate_Reference (Spec_Id, Body_Id, 'b', Set_Ref => False);
2294
2295          if Is_Child_Unit (Spec_Id) then
2296             Generate_Reference (Spec_Id, Scope (Spec_Id), 'k', False);
2297          end if;
2298
2299          if Style_Check then
2300             Style.Check_Identifier (Body_Id, Spec_Id);
2301          end if;
2302
2303          Set_Is_Compilation_Unit (Body_Id, Is_Compilation_Unit (Spec_Id));
2304          Set_Is_Child_Unit       (Body_Id, Is_Child_Unit       (Spec_Id));
2305
2306          if Is_Abstract_Subprogram (Spec_Id) then
2307             Error_Msg_N ("an abstract subprogram cannot have a body", N);
2308             return;
2309
2310          else
2311             Set_Convention (Body_Id, Convention (Spec_Id));
2312             Set_Has_Completion (Spec_Id);
2313
2314             if Is_Protected_Type (Scope (Spec_Id)) then
2315                Prot_Typ := Scope (Spec_Id);
2316             end if;
2317
2318             --  If this is a body generated for a renaming, do not check for
2319             --  full conformance. The check is redundant, because the spec of
2320             --  the body is a copy of the spec in the renaming declaration,
2321             --  and the test can lead to spurious errors on nested defaults.
2322
2323             if Present (Spec_Decl)
2324               and then not Comes_From_Source (N)
2325               and then
2326                 (Nkind (Original_Node (Spec_Decl)) =
2327                                         N_Subprogram_Renaming_Declaration
2328                    or else (Present (Corresponding_Body (Spec_Decl))
2329                               and then
2330                                 Nkind (Unit_Declaration_Node
2331                                         (Corresponding_Body (Spec_Decl))) =
2332                                            N_Subprogram_Renaming_Declaration))
2333             then
2334                Conformant := True;
2335
2336             --  Conversely, the spec may have been generated for specless body
2337             --  with an inline pragma.
2338
2339             elsif Comes_From_Source (N)
2340               and then not Comes_From_Source (Spec_Id)
2341               and then Has_Pragma_Inline (Spec_Id)
2342             then
2343                Conformant := True;
2344
2345             else
2346                Check_Conformance
2347                  (Body_Id, Spec_Id,
2348                   Fully_Conformant, True, Conformant, Body_Id);
2349             end if;
2350
2351             --  If the body is not fully conformant, we have to decide if we
2352             --  should analyze it or not. If it has a really messed up profile
2353             --  then we probably should not analyze it, since we will get too
2354             --  many bogus messages.
2355
2356             --  Our decision is to go ahead in the non-fully conformant case
2357             --  only if it is at least mode conformant with the spec. Note
2358             --  that the call to Check_Fully_Conformant has issued the proper
2359             --  error messages to complain about the lack of conformance.
2360
2361             if not Conformant
2362               and then not Mode_Conformant (Body_Id, Spec_Id)
2363             then
2364                return;
2365             end if;
2366          end if;
2367
2368          if Spec_Id /= Body_Id then
2369             Reference_Body_Formals (Spec_Id, Body_Id);
2370          end if;
2371
2372          if Nkind (N) /= N_Subprogram_Body_Stub then
2373             Set_Corresponding_Spec (N, Spec_Id);
2374
2375             --  Ada 2005 (AI-345): If the operation is a primitive operation
2376             --  of a concurrent type, the type of the first parameter has been
2377             --  replaced with the corresponding record, which is the proper
2378             --  run-time structure to use. However, within the body there may
2379             --  be uses of the formals that depend on primitive operations
2380             --  of the type (in particular calls in prefixed form) for which
2381             --  we need the original concurrent type. The operation may have
2382             --  several controlling formals, so the replacement must be done
2383             --  for all of them.
2384
2385             if Comes_From_Source (Spec_Id)
2386               and then Present (First_Entity (Spec_Id))
2387               and then Ekind (Etype (First_Entity (Spec_Id))) = E_Record_Type
2388               and then Is_Tagged_Type (Etype (First_Entity (Spec_Id)))
2389               and then
2390                 Present (Interfaces (Etype (First_Entity (Spec_Id))))
2391               and then
2392                 Present
2393                   (Corresponding_Concurrent_Type
2394                      (Etype (First_Entity (Spec_Id))))
2395             then
2396                declare
2397                   Typ  : constant Entity_Id := Etype (First_Entity (Spec_Id));
2398                   Form : Entity_Id;
2399
2400                begin
2401                   Form := First_Formal (Spec_Id);
2402                   while Present (Form) loop
2403                      if Etype (Form) = Typ then
2404                         Set_Etype (Form, Corresponding_Concurrent_Type (Typ));
2405                      end if;
2406
2407                      Next_Formal (Form);
2408                   end loop;
2409                end;
2410             end if;
2411
2412             --  Make the formals visible, and place subprogram on scope stack.
2413             --  This is also the point at which we set Last_Real_Spec_Entity
2414             --  to mark the entities which will not be moved to the body.
2415
2416             Install_Formals (Spec_Id);
2417             Last_Real_Spec_Entity := Last_Entity (Spec_Id);
2418             Push_Scope (Spec_Id);
2419
2420             --  Make sure that the subprogram is immediately visible. For
2421             --  child units that have no separate spec this is indispensable.
2422             --  Otherwise it is safe albeit redundant.
2423
2424             Set_Is_Immediately_Visible (Spec_Id);
2425          end if;
2426
2427          Set_Corresponding_Body (Unit_Declaration_Node (Spec_Id), Body_Id);
2428          Set_Ekind (Body_Id, E_Subprogram_Body);
2429          Set_Scope (Body_Id, Scope (Spec_Id));
2430          Set_Is_Obsolescent (Body_Id, Is_Obsolescent (Spec_Id));
2431
2432       --  Case of subprogram body with no previous spec
2433
2434       else
2435          --  Check for style warning required
2436
2437          if Style_Check
2438
2439            --  Only apply check for source level subprograms for which checks
2440            --  have not been suppressed.
2441
2442            and then Comes_From_Source (Body_Id)
2443            and then not Suppress_Style_Checks (Body_Id)
2444
2445            --  No warnings within an instance
2446
2447            and then not In_Instance
2448
2449            --  No warnings for expression functions
2450
2451            and then Nkind (Original_Node (N)) /= N_Expression_Function
2452          then
2453             Style.Body_With_No_Spec (N);
2454          end if;
2455
2456          New_Overloaded_Entity (Body_Id);
2457
2458          if Nkind (N) /= N_Subprogram_Body_Stub then
2459             Set_Acts_As_Spec (N);
2460             Generate_Definition (Body_Id);
2461             Generate_Reference
2462               (Body_Id, Body_Id, 'b', Set_Ref => False, Force => True);
2463             Generate_Reference_To_Formals (Body_Id);
2464             Install_Formals (Body_Id);
2465             Push_Scope (Body_Id);
2466          end if;
2467       end if;
2468
2469       --  If the return type is an anonymous access type whose designated type
2470       --  is the limited view of a class-wide type and the non-limited view is
2471       --  available, update the return type accordingly.
2472
2473       if Ada_Version >= Ada_2005
2474         and then Comes_From_Source (N)
2475       then
2476          declare
2477             Etyp : Entity_Id;
2478             Rtyp : Entity_Id;
2479
2480          begin
2481             Rtyp := Etype (Current_Scope);
2482
2483             if Ekind (Rtyp) = E_Anonymous_Access_Type then
2484                Etyp := Directly_Designated_Type (Rtyp);
2485
2486                if Is_Class_Wide_Type (Etyp)
2487                  and then From_With_Type (Etyp)
2488                then
2489                   Set_Directly_Designated_Type
2490                     (Etype (Current_Scope), Available_View (Etyp));
2491                end if;
2492             end if;
2493          end;
2494       end if;
2495
2496       --  If this is the proper body of a stub, we must verify that the stub
2497       --  conforms to the body, and to the previous spec if one was present.
2498       --  we know already that the body conforms to that spec. This test is
2499       --  only required for subprograms that come from source.
2500
2501       if Nkind (Parent (N)) = N_Subunit
2502         and then Comes_From_Source (N)
2503         and then not Error_Posted (Body_Id)
2504         and then Nkind (Corresponding_Stub (Parent (N))) =
2505                                                 N_Subprogram_Body_Stub
2506       then
2507          declare
2508             Old_Id : constant Entity_Id :=
2509                        Defining_Entity
2510                          (Specification (Corresponding_Stub (Parent (N))));
2511
2512             Conformant : Boolean := False;
2513
2514          begin
2515             if No (Spec_Id) then
2516                Check_Fully_Conformant (Body_Id, Old_Id);
2517
2518             else
2519                Check_Conformance
2520                  (Body_Id, Old_Id, Fully_Conformant, False, Conformant);
2521
2522                if not Conformant then
2523
2524                   --  The stub was taken to be a new declaration. Indicate
2525                   --  that it lacks a body.
2526
2527                   Set_Has_Completion (Old_Id, False);
2528                end if;
2529             end if;
2530          end;
2531       end if;
2532
2533       Set_Has_Completion (Body_Id);
2534       Check_Eliminated (Body_Id);
2535
2536       if Nkind (N) = N_Subprogram_Body_Stub then
2537          return;
2538
2539       elsif Present (Spec_Id)
2540         and then Expander_Active
2541         and then
2542           (Has_Pragma_Inline_Always (Spec_Id)
2543              or else (Has_Pragma_Inline (Spec_Id) and Front_End_Inlining))
2544       then
2545          Build_Body_To_Inline (N, Spec_Id);
2546       end if;
2547
2548       --  Ada 2005 (AI-262): In library subprogram bodies, after the analysis
2549       --  if its specification we have to install the private withed units.
2550       --  This holds for child units as well.
2551
2552       if Is_Compilation_Unit (Body_Id)
2553         or else Nkind (Parent (N)) = N_Compilation_Unit
2554       then
2555          Install_Private_With_Clauses (Body_Id);
2556       end if;
2557
2558       Check_Anonymous_Return;
2559
2560       --  Set the Protected_Formal field of each extra formal of the protected
2561       --  subprogram to reference the corresponding extra formal of the
2562       --  subprogram that implements it. For regular formals this occurs when
2563       --  the protected subprogram's declaration is expanded, but the extra
2564       --  formals don't get created until the subprogram is frozen. We need to
2565       --  do this before analyzing the protected subprogram's body so that any
2566       --  references to the original subprogram's extra formals will be changed
2567       --  refer to the implementing subprogram's formals (see Expand_Formal).
2568
2569       if Present (Spec_Id)
2570         and then Is_Protected_Type (Scope (Spec_Id))
2571         and then Present (Protected_Body_Subprogram (Spec_Id))
2572       then
2573          declare
2574             Impl_Subp       : constant Entity_Id :=
2575                                 Protected_Body_Subprogram (Spec_Id);
2576             Prot_Ext_Formal : Entity_Id := Extra_Formals (Spec_Id);
2577             Impl_Ext_Formal : Entity_Id := Extra_Formals (Impl_Subp);
2578          begin
2579             while Present (Prot_Ext_Formal) loop
2580                pragma Assert (Present (Impl_Ext_Formal));
2581                Set_Protected_Formal (Prot_Ext_Formal, Impl_Ext_Formal);
2582                Next_Formal_With_Extras (Prot_Ext_Formal);
2583                Next_Formal_With_Extras (Impl_Ext_Formal);
2584             end loop;
2585          end;
2586       end if;
2587
2588       --  Now we can go on to analyze the body
2589
2590       HSS := Handled_Statement_Sequence (N);
2591       Set_Actual_Subtypes (N, Current_Scope);
2592
2593       --  Deal with preconditions and postconditions
2594
2595       Process_PPCs (N, Spec_Id, Body_Id);
2596
2597       --  Add a declaration for the Protection object, renaming declarations
2598       --  for discriminals and privals and finally a declaration for the entry
2599       --  family index (if applicable). This form of early expansion is done
2600       --  when the Expander is active because Install_Private_Data_Declarations
2601       --  references entities which were created during regular expansion.
2602
2603       if Expander_Active
2604         and then Comes_From_Source (N)
2605         and then Present (Prot_Typ)
2606         and then Present (Spec_Id)
2607         and then not Is_Eliminated (Spec_Id)
2608       then
2609          Install_Private_Data_Declarations
2610            (Sloc (N), Spec_Id, Prot_Typ, N, Declarations (N));
2611       end if;
2612
2613       --  Analyze the declarations (this call will analyze the precondition
2614       --  Check pragmas we prepended to the list, as well as the declaration
2615       --  of the _Postconditions procedure).
2616
2617       Analyze_Declarations (Declarations (N));
2618
2619       --  Check completion, and analyze the statements
2620
2621       Check_Completion;
2622       Inspect_Deferred_Constant_Completion (Declarations (N));
2623       Analyze (HSS);
2624
2625       --  Deal with end of scope processing for the body
2626
2627       Process_End_Label (HSS, 't', Current_Scope);
2628       End_Scope;
2629       Check_Subprogram_Order (N);
2630       Set_Analyzed (Body_Id);
2631
2632       --  If we have a separate spec, then the analysis of the declarations
2633       --  caused the entities in the body to be chained to the spec id, but
2634       --  we want them chained to the body id. Only the formal parameters
2635       --  end up chained to the spec id in this case.
2636
2637       if Present (Spec_Id) then
2638
2639          --  We must conform to the categorization of our spec
2640
2641          Validate_Categorization_Dependency (N, Spec_Id);
2642
2643          --  And if this is a child unit, the parent units must conform
2644
2645          if Is_Child_Unit (Spec_Id) then
2646             Validate_Categorization_Dependency
2647               (Unit_Declaration_Node (Spec_Id), Spec_Id);
2648          end if;
2649
2650          --  Here is where we move entities from the spec to the body
2651
2652          --  Case where there are entities that stay with the spec
2653
2654          if Present (Last_Real_Spec_Entity) then
2655
2656             --  No body entities (happens when the only real spec entities
2657             --  come from precondition and postcondition pragmas)
2658
2659             if No (Last_Entity (Body_Id)) then
2660                Set_First_Entity
2661                  (Body_Id, Next_Entity (Last_Real_Spec_Entity));
2662
2663             --  Body entities present (formals), so chain stuff past them
2664
2665             else
2666                Set_Next_Entity
2667                  (Last_Entity (Body_Id), Next_Entity (Last_Real_Spec_Entity));
2668             end if;
2669
2670             Set_Next_Entity (Last_Real_Spec_Entity, Empty);
2671             Set_Last_Entity (Body_Id, Last_Entity (Spec_Id));
2672             Set_Last_Entity (Spec_Id, Last_Real_Spec_Entity);
2673
2674          --  Case where there are no spec entities, in this case there can
2675          --  be no body entities either, so just move everything.
2676
2677          else
2678             pragma Assert (No (Last_Entity (Body_Id)));
2679             Set_First_Entity (Body_Id, First_Entity (Spec_Id));
2680             Set_Last_Entity  (Body_Id, Last_Entity (Spec_Id));
2681             Set_First_Entity (Spec_Id, Empty);
2682             Set_Last_Entity  (Spec_Id, Empty);
2683          end if;
2684       end if;
2685
2686       Check_Missing_Return;
2687
2688       --  Now we are going to check for variables that are never modified in
2689       --  the body of the procedure. But first we deal with a special case
2690       --  where we want to modify this check. If the body of the subprogram
2691       --  starts with a raise statement or its equivalent, or if the body
2692       --  consists entirely of a null statement, then it is pretty obvious
2693       --  that it is OK to not reference the parameters. For example, this
2694       --  might be the following common idiom for a stubbed function:
2695       --  statement of the procedure raises an exception. In particular this
2696       --  deals with the common idiom of a stubbed function, which might
2697       --  appear as something like
2698
2699       --     function F (A : Integer) return Some_Type;
2700       --        X : Some_Type;
2701       --     begin
2702       --        raise Program_Error;
2703       --        return X;
2704       --     end F;
2705
2706       --  Here the purpose of X is simply to satisfy the annoying requirement
2707       --  in Ada that there be at least one return, and we certainly do not
2708       --  want to go posting warnings on X that it is not initialized! On
2709       --  the other hand, if X is entirely unreferenced that should still
2710       --  get a warning.
2711
2712       --  What we do is to detect these cases, and if we find them, flag the
2713       --  subprogram as being Is_Trivial_Subprogram and then use that flag to
2714       --  suppress unwanted warnings. For the case of the function stub above
2715       --  we have a special test to set X as apparently assigned to suppress
2716       --  the warning.
2717
2718       declare
2719          Stm : Node_Id;
2720
2721       begin
2722          --  Skip initial labels (for one thing this occurs when we are in
2723          --  front end ZCX mode, but in any case it is irrelevant), and also
2724          --  initial Push_xxx_Error_Label nodes, which are also irrelevant.
2725
2726          Stm := First (Statements (HSS));
2727          while Nkind (Stm) = N_Label
2728            or else Nkind (Stm) in N_Push_xxx_Label
2729          loop
2730             Next (Stm);
2731          end loop;
2732
2733          --  Do the test on the original statement before expansion
2734
2735          declare
2736             Ostm : constant Node_Id := Original_Node (Stm);
2737
2738          begin
2739             --  If explicit raise statement, turn on flag
2740
2741             if Nkind (Ostm) = N_Raise_Statement then
2742                Set_Trivial_Subprogram (Stm);
2743
2744             --  If null statement, and no following statements, turn on flag
2745
2746             elsif Nkind (Stm) = N_Null_Statement
2747               and then Comes_From_Source (Stm)
2748               and then No (Next (Stm))
2749             then
2750                Set_Trivial_Subprogram (Stm);
2751
2752             --  Check for explicit call cases which likely raise an exception
2753
2754             elsif Nkind (Ostm) = N_Procedure_Call_Statement then
2755                if Is_Entity_Name (Name (Ostm)) then
2756                   declare
2757                      Ent : constant Entity_Id := Entity (Name (Ostm));
2758
2759                   begin
2760                      --  If the procedure is marked No_Return, then likely it
2761                      --  raises an exception, but in any case it is not coming
2762                      --  back here, so turn on the flag.
2763
2764                      if Ekind (Ent) = E_Procedure
2765                        and then No_Return (Ent)
2766                      then
2767                         Set_Trivial_Subprogram (Stm);
2768                      end if;
2769                   end;
2770                end if;
2771             end if;
2772          end;
2773       end;
2774
2775       --  Check for variables that are never modified
2776
2777       declare
2778          E1, E2 : Entity_Id;
2779
2780       begin
2781          --  If there is a separate spec, then transfer Never_Set_In_Source
2782          --  flags from out parameters to the corresponding entities in the
2783          --  body. The reason we do that is we want to post error flags on
2784          --  the body entities, not the spec entities.
2785
2786          if Present (Spec_Id) then
2787             E1 := First_Entity (Spec_Id);
2788             while Present (E1) loop
2789                if Ekind (E1) = E_Out_Parameter then
2790                   E2 := First_Entity (Body_Id);
2791                   while Present (E2) loop
2792                      exit when Chars (E1) = Chars (E2);
2793                      Next_Entity (E2);
2794                   end loop;
2795
2796                   if Present (E2) then
2797                      Set_Never_Set_In_Source (E2, Never_Set_In_Source (E1));
2798                   end if;
2799                end if;
2800
2801                Next_Entity (E1);
2802             end loop;
2803          end if;
2804
2805          --  Check references in body unless it was deleted. Note that the
2806          --  check of Body_Deleted here is not just for efficiency, it is
2807          --  necessary to avoid junk warnings on formal parameters.
2808
2809          if not Body_Deleted then
2810             Check_References (Body_Id);
2811          end if;
2812       end;
2813    end Analyze_Subprogram_Body_Helper;
2814
2815    ------------------------------------
2816    -- Analyze_Subprogram_Declaration --
2817    ------------------------------------
2818
2819    procedure Analyze_Subprogram_Declaration (N : Node_Id) is
2820       Loc        : constant Source_Ptr := Sloc (N);
2821       Scop       : constant Entity_Id  := Current_Scope;
2822       Designator : Entity_Id;
2823       Form       : Node_Id;
2824       Null_Body  : Node_Id := Empty;
2825
2826    --  Start of processing for Analyze_Subprogram_Declaration
2827
2828    begin
2829       --  Null procedures are not allowed in SPARK or ALFA
2830
2831       if Nkind (Specification (N)) = N_Procedure_Specification
2832         and then Null_Present (Specification (N))
2833       then
2834          Check_Formal_Restriction ("null procedure is not allowed", N);
2835       end if;
2836
2837       --  For a null procedure, capture the profile before analysis, for
2838       --  expansion at the freeze point and at each point of call. The body
2839       --  will only be used if the procedure has preconditions. In that case
2840       --  the body is analyzed at the freeze point.
2841
2842       if Nkind (Specification (N)) = N_Procedure_Specification
2843         and then Null_Present (Specification (N))
2844         and then Expander_Active
2845       then
2846          Null_Body :=
2847            Make_Subprogram_Body (Loc,
2848              Specification =>
2849                New_Copy_Tree (Specification (N)),
2850              Declarations =>
2851                New_List,
2852              Handled_Statement_Sequence =>
2853                Make_Handled_Sequence_Of_Statements (Loc,
2854                  Statements => New_List (Make_Null_Statement (Loc))));
2855
2856          --  Create new entities for body and formals
2857
2858          Set_Defining_Unit_Name (Specification (Null_Body),
2859            Make_Defining_Identifier (Loc, Chars (Defining_Entity (N))));
2860          Set_Corresponding_Body (N, Defining_Entity (Null_Body));
2861
2862          Form := First (Parameter_Specifications (Specification (Null_Body)));
2863          while Present (Form) loop
2864             Set_Defining_Identifier (Form,
2865               Make_Defining_Identifier (Loc,
2866                 Chars (Defining_Identifier (Form))));
2867
2868             --  Resolve the types of the formals now, because the freeze point
2869             --  may appear in a different context, e.g. an instantiation.
2870
2871             if Nkind (Parameter_Type (Form)) /= N_Access_Definition then
2872                Find_Type (Parameter_Type (Form));
2873
2874             elsif
2875               No (Access_To_Subprogram_Definition (Parameter_Type (Form)))
2876             then
2877                Find_Type (Subtype_Mark (Parameter_Type (Form)));
2878
2879             else
2880
2881                --  the case of a null procedure with a formal that is an
2882                --  access_to_subprogram type, and that is used as an actual
2883                --  in an instantiation is left to the enthusiastic reader.
2884
2885                null;
2886             end if;
2887
2888             Next (Form);
2889          end loop;
2890
2891          if Is_Protected_Type (Current_Scope) then
2892             Error_Msg_N ("protected operation cannot be a null procedure", N);
2893          end if;
2894       end if;
2895
2896       Designator := Analyze_Subprogram_Specification (Specification (N));
2897       Generate_Definition (Designator);
2898
2899       if Debug_Flag_C then
2900          Write_Str ("==> subprogram spec ");
2901          Write_Name (Chars (Designator));
2902          Write_Str (" from ");
2903          Write_Location (Sloc (N));
2904          Write_Eol;
2905          Indent;
2906       end if;
2907
2908       if Nkind (Specification (N)) = N_Procedure_Specification
2909         and then Null_Present (Specification (N))
2910       then
2911          Set_Has_Completion (Designator);
2912
2913          if Present (Null_Body) then
2914             Set_Corresponding_Body (N, Defining_Entity (Null_Body));
2915             Set_Body_To_Inline (N, Null_Body);
2916             Set_Is_Inlined (Designator);
2917          end if;
2918       end if;
2919
2920       Validate_RCI_Subprogram_Declaration (N);
2921       New_Overloaded_Entity (Designator);
2922       Check_Delayed_Subprogram (Designator);
2923
2924       --  If the type of the first formal of the current subprogram is a
2925       --  nongeneric tagged private type, mark the subprogram as being a
2926       --  private primitive. Ditto if this is a function with controlling
2927       --  result, and the return type is currently private. In both cases,
2928       --  the type of the controlling argument or result must be in the
2929       --  current scope for the operation to be primitive.
2930
2931       if Has_Controlling_Result (Designator)
2932         and then Is_Private_Type (Etype (Designator))
2933         and then Scope (Etype (Designator)) = Current_Scope
2934         and then not Is_Generic_Actual_Type (Etype (Designator))
2935       then
2936          Set_Is_Private_Primitive (Designator);
2937
2938       elsif Present (First_Formal (Designator)) then
2939          declare
2940             Formal_Typ : constant Entity_Id :=
2941                            Etype (First_Formal (Designator));
2942          begin
2943             Set_Is_Private_Primitive (Designator,
2944               Is_Tagged_Type (Formal_Typ)
2945                 and then Scope (Formal_Typ) = Current_Scope
2946                 and then Is_Private_Type (Formal_Typ)
2947                 and then not Is_Generic_Actual_Type (Formal_Typ));
2948          end;
2949       end if;
2950
2951       --  Ada 2005 (AI-251): Abstract interface primitives must be abstract
2952       --  or null.
2953
2954       if Ada_Version >= Ada_2005
2955         and then Comes_From_Source (N)
2956         and then Is_Dispatching_Operation (Designator)
2957       then
2958          declare
2959             E    : Entity_Id;
2960             Etyp : Entity_Id;
2961
2962          begin
2963             if Has_Controlling_Result (Designator) then
2964                Etyp := Etype (Designator);
2965
2966             else
2967                E := First_Entity (Designator);
2968                while Present (E)
2969                  and then Is_Formal (E)
2970                  and then not Is_Controlling_Formal (E)
2971                loop
2972                   Next_Entity (E);
2973                end loop;
2974
2975                Etyp := Etype (E);
2976             end if;
2977
2978             if Is_Access_Type (Etyp) then
2979                Etyp := Directly_Designated_Type (Etyp);
2980             end if;
2981
2982             if Is_Interface (Etyp)
2983               and then not Is_Abstract_Subprogram (Designator)
2984               and then not (Ekind (Designator) = E_Procedure
2985                               and then Null_Present (Specification (N)))
2986             then
2987                Error_Msg_Name_1 := Chars (Defining_Entity (N));
2988                Error_Msg_N
2989                  ("(Ada 2005) interface subprogram % must be abstract or null",
2990                   N);
2991             end if;
2992          end;
2993       end if;
2994
2995       --  What is the following code for, it used to be
2996
2997       --  ???   Set_Suppress_Elaboration_Checks
2998       --  ???     (Designator, Elaboration_Checks_Suppressed (Designator));
2999
3000       --  The following seems equivalent, but a bit dubious
3001
3002       if Elaboration_Checks_Suppressed (Designator) then
3003          Set_Kill_Elaboration_Checks (Designator);
3004       end if;
3005
3006       if Scop /= Standard_Standard
3007         and then not Is_Child_Unit (Designator)
3008       then
3009          Set_Categorization_From_Scope (Designator, Scop);
3010       else
3011          --  For a compilation unit, check for library-unit pragmas
3012
3013          Push_Scope (Designator);
3014          Set_Categorization_From_Pragmas (N);
3015          Validate_Categorization_Dependency (N, Designator);
3016          Pop_Scope;
3017       end if;
3018
3019       --  For a compilation unit, set body required. This flag will only be
3020       --  reset if a valid Import or Interface pragma is processed later on.
3021
3022       if Nkind (Parent (N)) = N_Compilation_Unit then
3023          Set_Body_Required (Parent (N), True);
3024
3025          if Ada_Version >= Ada_2005
3026            and then Nkind (Specification (N)) = N_Procedure_Specification
3027            and then Null_Present (Specification (N))
3028          then
3029             Error_Msg_N
3030               ("null procedure cannot be declared at library level", N);
3031          end if;
3032       end if;
3033
3034       Generate_Reference_To_Formals (Designator);
3035       Check_Eliminated (Designator);
3036
3037       if Debug_Flag_C then
3038          Outdent;
3039          Write_Str ("<== subprogram spec ");
3040          Write_Name (Chars (Designator));
3041          Write_Str (" from ");
3042          Write_Location (Sloc (N));
3043          Write_Eol;
3044       end if;
3045
3046       if Is_Protected_Type (Current_Scope) then
3047
3048          --  Indicate that this is a protected operation, because it may be
3049          --  used in subsequent declarations within the protected type.
3050
3051          Set_Convention (Designator, Convention_Protected);
3052       end if;
3053
3054       List_Inherited_Pre_Post_Aspects (Designator);
3055
3056       if Has_Aspects (N) then
3057          Analyze_Aspect_Specifications (N, Designator);
3058       end if;
3059    end Analyze_Subprogram_Declaration;
3060
3061    --------------------------------------
3062    -- Analyze_Subprogram_Specification --
3063    --------------------------------------
3064
3065    --  Reminder: N here really is a subprogram specification (not a subprogram
3066    --  declaration). This procedure is called to analyze the specification in
3067    --  both subprogram bodies and subprogram declarations (specs).
3068
3069    function Analyze_Subprogram_Specification (N : Node_Id) return Entity_Id is
3070       Designator : constant Entity_Id := Defining_Entity (N);
3071       Formals    : constant List_Id   := Parameter_Specifications (N);
3072
3073    --  Start of processing for Analyze_Subprogram_Specification
3074
3075    begin
3076       --  User-defined operator is not allowed in SPARK or ALFA, except as
3077       --  a renaming.
3078
3079       if Nkind (Defining_Unit_Name (N)) = N_Defining_Operator_Symbol
3080         and then Nkind (Parent (N)) /= N_Subprogram_Renaming_Declaration
3081       then
3082          Check_Formal_Restriction ("user-defined operator is not allowed", N);
3083       end if;
3084
3085       --  Proceed with analysis
3086
3087       Generate_Definition (Designator);
3088
3089       if Nkind (N) = N_Function_Specification then
3090          Set_Ekind (Designator, E_Function);
3091          Set_Mechanism (Designator, Default_Mechanism);
3092       else
3093          Set_Ekind (Designator, E_Procedure);
3094          Set_Etype (Designator, Standard_Void_Type);
3095       end if;
3096
3097       --  Introduce new scope for analysis of the formals and the return type
3098
3099       Set_Scope (Designator, Current_Scope);
3100
3101       if Present (Formals) then
3102          Push_Scope (Designator);
3103          Process_Formals (Formals, N);
3104
3105          --  Ada 2005 (AI-345): If this is an overriding operation of an
3106          --  inherited interface operation, and the controlling type is
3107          --  a synchronized type, replace the type with its corresponding
3108          --  record, to match the proper signature of an overriding operation.
3109          --  Same processing for an access parameter whose designated type is
3110          --  derived from a synchronized interface.
3111
3112          if Ada_Version >= Ada_2005 then
3113             declare
3114                Formal     : Entity_Id;
3115                Formal_Typ : Entity_Id;
3116                Rec_Typ    : Entity_Id;
3117                Desig_Typ  : Entity_Id;
3118
3119             begin
3120                Formal := First_Formal (Designator);
3121                while Present (Formal) loop
3122                   Formal_Typ := Etype (Formal);
3123
3124                   if Is_Concurrent_Type (Formal_Typ)
3125                     and then Present (Corresponding_Record_Type (Formal_Typ))
3126                   then
3127                      Rec_Typ := Corresponding_Record_Type (Formal_Typ);
3128
3129                      if Present (Interfaces (Rec_Typ)) then
3130                         Set_Etype (Formal, Rec_Typ);
3131                      end if;
3132
3133                   elsif Ekind (Formal_Typ) = E_Anonymous_Access_Type then
3134                      Desig_Typ := Designated_Type (Formal_Typ);
3135
3136                      if Is_Concurrent_Type (Desig_Typ)
3137                        and then Present (Corresponding_Record_Type (Desig_Typ))
3138                      then
3139                         Rec_Typ := Corresponding_Record_Type (Desig_Typ);
3140
3141                         if Present (Interfaces (Rec_Typ)) then
3142                            Set_Directly_Designated_Type (Formal_Typ, Rec_Typ);
3143                         end if;
3144                      end if;
3145                   end if;
3146
3147                   Next_Formal (Formal);
3148                end loop;
3149             end;
3150          end if;
3151
3152          End_Scope;
3153
3154       --  The subprogram scope is pushed and popped around the processing of
3155       --  the return type for consistency with call above to Process_Formals
3156       --  (which itself can call Analyze_Return_Type), and to ensure that any
3157       --  itype created for the return type will be associated with the proper
3158       --  scope.
3159
3160       elsif Nkind (N) = N_Function_Specification then
3161          Push_Scope (Designator);
3162          Analyze_Return_Type (N);
3163          End_Scope;
3164       end if;
3165
3166       --  Function case
3167
3168       if Nkind (N) = N_Function_Specification then
3169
3170          --  Deal with operator symbol case
3171
3172          if Nkind (Designator) = N_Defining_Operator_Symbol then
3173             Valid_Operator_Definition (Designator);
3174          end if;
3175
3176          May_Need_Actuals (Designator);
3177
3178          --  Ada 2005 (AI-251): If the return type is abstract, verify that
3179          --  the subprogram is abstract also. This does not apply to renaming
3180          --  declarations, where abstractness is inherited.
3181
3182          --  In case of primitives associated with abstract interface types
3183          --  the check is applied later (see Analyze_Subprogram_Declaration).
3184
3185          if not Nkind_In (Parent (N), N_Subprogram_Renaming_Declaration,
3186                                       N_Abstract_Subprogram_Declaration,
3187                                       N_Formal_Abstract_Subprogram_Declaration)
3188          then
3189             if Is_Abstract_Type (Etype (Designator))
3190               and then not Is_Interface (Etype (Designator))
3191             then
3192                Error_Msg_N
3193                  ("function that returns abstract type must be abstract", N);
3194
3195             --  Ada 2012 (AI-0073): Extend this test to subprograms with an
3196             --  access result whose designated type is abstract.
3197
3198             elsif Nkind (Result_Definition (N)) = N_Access_Definition
3199               and then
3200                 not Is_Class_Wide_Type (Designated_Type (Etype (Designator)))
3201               and then Is_Abstract_Type (Designated_Type (Etype (Designator)))
3202               and then Ada_Version >= Ada_2012
3203             then
3204                Error_Msg_N ("function whose access result designates "
3205                  & "abstract type must be abstract", N);
3206             end if;
3207          end if;
3208       end if;
3209
3210       return Designator;
3211    end Analyze_Subprogram_Specification;
3212
3213    --------------------------
3214    -- Build_Body_To_Inline --
3215    --------------------------
3216
3217    procedure Build_Body_To_Inline (N : Node_Id; Subp : Entity_Id) is
3218       Decl            : constant Node_Id := Unit_Declaration_Node (Subp);
3219       Original_Body   : Node_Id;
3220       Body_To_Analyze : Node_Id;
3221       Max_Size        : constant := 10;
3222       Stat_Count      : Integer := 0;
3223
3224       function Has_Excluded_Declaration (Decls : List_Id) return Boolean;
3225       --  Check for declarations that make inlining not worthwhile
3226
3227       function Has_Excluded_Statement   (Stats : List_Id) return Boolean;
3228       --  Check for statements that make inlining not worthwhile: any tasking
3229       --  statement, nested at any level. Keep track of total number of
3230       --  elementary statements, as a measure of acceptable size.
3231
3232       function Has_Pending_Instantiation return Boolean;
3233       --  If some enclosing body contains instantiations that appear before the
3234       --  corresponding generic body, the enclosing body has a freeze node so
3235       --  that it can be elaborated after the generic itself. This might
3236       --  conflict with subsequent inlinings, so that it is unsafe to try to
3237       --  inline in such a case.
3238
3239       function Has_Single_Return return Boolean;
3240       --  In general we cannot inline functions that return unconstrained type.
3241       --  However, we can handle such functions if all return statements return
3242       --  a local variable that is the only declaration in the body of the
3243       --  function. In that case the call can be replaced by that local
3244       --  variable as is done for other inlined calls.
3245
3246       procedure Remove_Pragmas;
3247       --  A pragma Unreferenced or pragma Unmodified that mentions a formal
3248       --  parameter has no meaning when the body is inlined and the formals
3249       --  are rewritten. Remove it from body to inline. The analysis of the
3250       --  non-inlined body will handle the pragma properly.
3251
3252       function Uses_Secondary_Stack (Bod : Node_Id) return Boolean;
3253       --  If the body of the subprogram includes a call that returns an
3254       --  unconstrained type, the secondary stack is involved, and it
3255       --  is not worth inlining.
3256
3257       ------------------------------
3258       -- Has_Excluded_Declaration --
3259       ------------------------------
3260
3261       function Has_Excluded_Declaration (Decls : List_Id) return Boolean is
3262          D : Node_Id;
3263
3264          function Is_Unchecked_Conversion (D : Node_Id) return Boolean;
3265          --  Nested subprograms make a given body ineligible for inlining, but
3266          --  we make an exception for instantiations of unchecked conversion.
3267          --  The body has not been analyzed yet, so check the name, and verify
3268          --  that the visible entity with that name is the predefined unit.
3269
3270          -----------------------------
3271          -- Is_Unchecked_Conversion --
3272          -----------------------------
3273
3274          function Is_Unchecked_Conversion (D : Node_Id) return Boolean is
3275             Id   : constant Node_Id := Name (D);
3276             Conv : Entity_Id;
3277
3278          begin
3279             if Nkind (Id) = N_Identifier
3280               and then Chars (Id) = Name_Unchecked_Conversion
3281             then
3282                Conv := Current_Entity (Id);
3283
3284             elsif Nkind_In (Id, N_Selected_Component, N_Expanded_Name)
3285               and then Chars (Selector_Name (Id)) = Name_Unchecked_Conversion
3286             then
3287                Conv := Current_Entity (Selector_Name (Id));
3288             else
3289                return False;
3290             end if;
3291
3292             return Present (Conv)
3293               and then Is_Predefined_File_Name
3294                          (Unit_File_Name (Get_Source_Unit (Conv)))
3295               and then Is_Intrinsic_Subprogram (Conv);
3296          end Is_Unchecked_Conversion;
3297
3298       --  Start of processing for Has_Excluded_Declaration
3299
3300       begin
3301          D := First (Decls);
3302          while Present (D) loop
3303             if (Nkind (D) = N_Function_Instantiation
3304                   and then not Is_Unchecked_Conversion (D))
3305               or else Nkind_In (D, N_Protected_Type_Declaration,
3306                                    N_Package_Declaration,
3307                                    N_Package_Instantiation,
3308                                    N_Subprogram_Body,
3309                                    N_Procedure_Instantiation,
3310                                    N_Task_Type_Declaration)
3311             then
3312                Cannot_Inline
3313                  ("cannot inline & (non-allowed declaration)?", D, Subp);
3314                return True;
3315             end if;
3316
3317             Next (D);
3318          end loop;
3319
3320          return False;
3321       end Has_Excluded_Declaration;
3322
3323       ----------------------------
3324       -- Has_Excluded_Statement --
3325       ----------------------------
3326
3327       function Has_Excluded_Statement (Stats : List_Id) return Boolean is
3328          S : Node_Id;
3329          E : Node_Id;
3330
3331       begin
3332          S := First (Stats);
3333          while Present (S) loop
3334             Stat_Count := Stat_Count + 1;
3335
3336             if Nkind_In (S, N_Abort_Statement,
3337                             N_Asynchronous_Select,
3338                             N_Conditional_Entry_Call,
3339                             N_Delay_Relative_Statement,
3340                             N_Delay_Until_Statement,
3341                             N_Selective_Accept,
3342                             N_Timed_Entry_Call)
3343             then
3344                Cannot_Inline
3345                  ("cannot inline & (non-allowed statement)?", S, Subp);
3346                return True;
3347
3348             elsif Nkind (S) = N_Block_Statement then
3349                if Present (Declarations (S))
3350                  and then Has_Excluded_Declaration (Declarations (S))
3351                then
3352                   return True;
3353
3354                elsif Present (Handled_Statement_Sequence (S))
3355                   and then
3356                     (Present
3357                       (Exception_Handlers (Handled_Statement_Sequence (S)))
3358                      or else
3359                        Has_Excluded_Statement
3360                          (Statements (Handled_Statement_Sequence (S))))
3361                then
3362                   return True;
3363                end if;
3364
3365             elsif Nkind (S) = N_Case_Statement then
3366                E := First (Alternatives (S));
3367                while Present (E) loop
3368                   if Has_Excluded_Statement (Statements (E)) then
3369                      return True;
3370                   end if;
3371
3372                   Next (E);
3373                end loop;
3374
3375             elsif Nkind (S) = N_If_Statement then
3376                if Has_Excluded_Statement (Then_Statements (S)) then
3377                   return True;
3378                end if;
3379
3380                if Present (Elsif_Parts (S)) then
3381                   E := First (Elsif_Parts (S));
3382                   while Present (E) loop
3383                      if Has_Excluded_Statement (Then_Statements (E)) then
3384                         return True;
3385                      end if;
3386                      Next (E);
3387                   end loop;
3388                end if;
3389
3390                if Present (Else_Statements (S))
3391                  and then Has_Excluded_Statement (Else_Statements (S))
3392                then
3393                   return True;
3394                end if;
3395
3396             elsif Nkind (S) = N_Loop_Statement
3397               and then Has_Excluded_Statement (Statements (S))
3398             then
3399                return True;
3400
3401             elsif Nkind (S) = N_Extended_Return_Statement then
3402                if Has_Excluded_Statement
3403                   (Statements (Handled_Statement_Sequence (S)))
3404                  or else Present
3405                    (Exception_Handlers (Handled_Statement_Sequence (S)))
3406                then
3407                   return True;
3408                end if;
3409             end if;
3410
3411             Next (S);
3412          end loop;
3413
3414          return False;
3415       end Has_Excluded_Statement;
3416
3417       -------------------------------
3418       -- Has_Pending_Instantiation --
3419       -------------------------------
3420
3421       function Has_Pending_Instantiation return Boolean is
3422          S : Entity_Id;
3423
3424       begin
3425          S := Current_Scope;
3426          while Present (S) loop
3427             if Is_Compilation_Unit (S)
3428               or else Is_Child_Unit (S)
3429             then
3430                return False;
3431
3432             elsif Ekind (S) = E_Package
3433               and then Has_Forward_Instantiation (S)
3434             then
3435                return True;
3436             end if;
3437
3438             S := Scope (S);
3439          end loop;
3440
3441          return False;
3442       end Has_Pending_Instantiation;
3443
3444       ------------------------
3445       --  Has_Single_Return --
3446       ------------------------
3447
3448       function Has_Single_Return return Boolean is
3449          Return_Statement : Node_Id := Empty;
3450
3451          function Check_Return (N : Node_Id) return Traverse_Result;
3452
3453          ------------------
3454          -- Check_Return --
3455          ------------------
3456
3457          function Check_Return (N : Node_Id) return Traverse_Result is
3458          begin
3459             if Nkind (N) = N_Simple_Return_Statement then
3460                if Present (Expression (N))
3461                  and then Is_Entity_Name (Expression (N))
3462                then
3463                   if No (Return_Statement) then
3464                      Return_Statement := N;
3465                      return OK;
3466
3467                   elsif Chars (Expression (N)) =
3468                         Chars (Expression (Return_Statement))
3469                   then
3470                      return OK;
3471
3472                   else
3473                      return Abandon;
3474                   end if;
3475
3476                --  A return statement within an extended return is a noop
3477                --  after inlining.
3478
3479                elsif No (Expression (N))
3480                  and then Nkind (Parent (Parent (N))) =
3481                  N_Extended_Return_Statement
3482                then
3483                   return OK;
3484
3485                else
3486                   --  Expression has wrong form
3487
3488                   return Abandon;
3489                end if;
3490
3491             --  We can only inline a build-in-place function if
3492             --  it has a single extended return.
3493
3494             elsif Nkind (N) = N_Extended_Return_Statement then
3495                if No (Return_Statement) then
3496                   Return_Statement := N;
3497                   return OK;
3498
3499                else
3500                   return Abandon;
3501                end if;
3502
3503             else
3504                return OK;
3505             end if;
3506          end Check_Return;
3507
3508          function Check_All_Returns is new Traverse_Func (Check_Return);
3509
3510       --  Start of processing for Has_Single_Return
3511
3512       begin
3513          if Check_All_Returns (N) /= OK then
3514             return False;
3515
3516          elsif Nkind (Return_Statement) = N_Extended_Return_Statement then
3517             return True;
3518
3519          else
3520             return Present (Declarations (N))
3521               and then Present (First (Declarations (N)))
3522               and then Chars (Expression (Return_Statement)) =
3523                  Chars (Defining_Identifier (First (Declarations (N))));
3524          end if;
3525       end Has_Single_Return;
3526
3527       --------------------
3528       -- Remove_Pragmas --
3529       --------------------
3530
3531       procedure Remove_Pragmas is
3532          Decl : Node_Id;
3533          Nxt  : Node_Id;
3534
3535       begin
3536          Decl := First (Declarations (Body_To_Analyze));
3537          while Present (Decl) loop
3538             Nxt := Next (Decl);
3539
3540             if Nkind (Decl) = N_Pragma
3541               and then (Pragma_Name (Decl) = Name_Unreferenced
3542                           or else
3543                         Pragma_Name (Decl) = Name_Unmodified)
3544             then
3545                Remove (Decl);
3546             end if;
3547
3548             Decl := Nxt;
3549          end loop;
3550       end Remove_Pragmas;
3551
3552       --------------------------
3553       -- Uses_Secondary_Stack --
3554       --------------------------
3555
3556       function Uses_Secondary_Stack (Bod : Node_Id) return Boolean is
3557          function Check_Call (N : Node_Id) return Traverse_Result;
3558          --  Look for function calls that return an unconstrained type
3559
3560          ----------------
3561          -- Check_Call --
3562          ----------------
3563
3564          function Check_Call (N : Node_Id) return Traverse_Result is
3565          begin
3566             if Nkind (N) = N_Function_Call
3567               and then Is_Entity_Name (Name (N))
3568               and then Is_Composite_Type (Etype (Entity (Name (N))))
3569               and then not Is_Constrained (Etype (Entity (Name (N))))
3570             then
3571                Cannot_Inline
3572                  ("cannot inline & (call returns unconstrained type)?",
3573                     N, Subp);
3574                return Abandon;
3575             else
3576                return OK;
3577             end if;
3578          end Check_Call;
3579
3580          function Check_Calls is new Traverse_Func (Check_Call);
3581
3582       begin
3583          return Check_Calls (Bod) = Abandon;
3584       end Uses_Secondary_Stack;
3585
3586    --  Start of processing for Build_Body_To_Inline
3587
3588    begin
3589       --  Return immediately if done already
3590
3591       if Nkind (Decl) = N_Subprogram_Declaration
3592         and then Present (Body_To_Inline (Decl))
3593       then
3594          return;
3595
3596       --  Functions that return unconstrained composite types require
3597       --  secondary stack handling, and cannot currently be inlined, unless
3598       --  all return statements return a local variable that is the first
3599       --  local declaration in the body.
3600
3601       elsif Ekind (Subp) = E_Function
3602         and then not Is_Scalar_Type (Etype (Subp))
3603         and then not Is_Access_Type (Etype (Subp))
3604         and then not Is_Constrained (Etype (Subp))
3605       then
3606          if not Has_Single_Return then
3607             Cannot_Inline
3608               ("cannot inline & (unconstrained return type)?", N, Subp);
3609             return;
3610          end if;
3611
3612       --  Ditto for functions that return controlled types, where controlled
3613       --  actions interfere in complex ways with inlining.
3614
3615       elsif Ekind (Subp) = E_Function
3616         and then Needs_Finalization (Etype (Subp))
3617       then
3618          Cannot_Inline
3619            ("cannot inline & (controlled return type)?", N, Subp);
3620          return;
3621       end if;
3622
3623       if Present (Declarations (N))
3624         and then Has_Excluded_Declaration (Declarations (N))
3625       then
3626          return;
3627       end if;
3628
3629       if Present (Handled_Statement_Sequence (N)) then
3630          if Present (Exception_Handlers (Handled_Statement_Sequence (N))) then
3631             Cannot_Inline
3632               ("cannot inline& (exception handler)?",
3633                First (Exception_Handlers (Handled_Statement_Sequence (N))),
3634                Subp);
3635             return;
3636          elsif
3637            Has_Excluded_Statement
3638              (Statements (Handled_Statement_Sequence (N)))
3639          then
3640             return;
3641          end if;
3642       end if;
3643
3644       --  We do not inline a subprogram  that is too large, unless it is
3645       --  marked Inline_Always. This pragma does not suppress the other
3646       --  checks on inlining (forbidden declarations, handlers, etc).
3647
3648       if Stat_Count > Max_Size
3649         and then not Has_Pragma_Inline_Always (Subp)
3650       then
3651          Cannot_Inline ("cannot inline& (body too large)?", N, Subp);
3652          return;
3653       end if;
3654
3655       if Has_Pending_Instantiation then
3656          Cannot_Inline
3657            ("cannot inline& (forward instance within enclosing body)?",
3658              N, Subp);
3659          return;
3660       end if;
3661
3662       --  Within an instance, the body to inline must be treated as a nested
3663       --  generic, so that the proper global references are preserved.
3664
3665       --  Note that we do not do this at the library level, because it is not
3666       --  needed, and furthermore this causes trouble if front end inlining
3667       --  is activated (-gnatN).
3668
3669       if In_Instance and then Scope (Current_Scope) /= Standard_Standard then
3670          Save_Env (Scope (Current_Scope), Scope (Current_Scope));
3671          Original_Body := Copy_Generic_Node (N, Empty, True);
3672       else
3673          Original_Body := Copy_Separate_Tree (N);
3674       end if;
3675
3676       --  We need to capture references to the formals in order to substitute
3677       --  the actuals at the point of inlining, i.e. instantiation. To treat
3678       --  the formals as globals to the body to inline, we nest it within
3679       --  a dummy parameterless subprogram, declared within the real one.
3680       --  To avoid generating an internal name (which is never public, and
3681       --  which affects serial numbers of other generated names), we use
3682       --  an internal symbol that cannot conflict with user declarations.
3683
3684       Set_Parameter_Specifications (Specification (Original_Body), No_List);
3685       Set_Defining_Unit_Name
3686         (Specification (Original_Body),
3687           Make_Defining_Identifier (Sloc (N), Name_uParent));
3688       Set_Corresponding_Spec (Original_Body, Empty);
3689
3690       Body_To_Analyze := Copy_Generic_Node (Original_Body, Empty, False);
3691
3692       --  Set return type of function, which is also global and does not need
3693       --  to be resolved.
3694
3695       if Ekind (Subp) = E_Function then
3696          Set_Result_Definition (Specification (Body_To_Analyze),
3697            New_Occurrence_Of (Etype (Subp), Sloc (N)));
3698       end if;
3699
3700       if No (Declarations (N)) then
3701          Set_Declarations (N, New_List (Body_To_Analyze));
3702       else
3703          Append (Body_To_Analyze, Declarations (N));
3704       end if;
3705
3706       Expander_Mode_Save_And_Set (False);
3707       Remove_Pragmas;
3708
3709       Analyze (Body_To_Analyze);
3710       Push_Scope (Defining_Entity (Body_To_Analyze));
3711       Save_Global_References (Original_Body);
3712       End_Scope;
3713       Remove (Body_To_Analyze);
3714
3715       Expander_Mode_Restore;
3716
3717       --  Restore environment if previously saved
3718
3719       if In_Instance and then Scope (Current_Scope) /= Standard_Standard then
3720          Restore_Env;
3721       end if;
3722
3723       --  If secondary stk used there is no point in inlining. We have
3724       --  already issued the warning in this case, so nothing to do.
3725
3726       if Uses_Secondary_Stack (Body_To_Analyze) then
3727          return;
3728       end if;
3729
3730       Set_Body_To_Inline (Decl, Original_Body);
3731       Set_Ekind (Defining_Entity (Original_Body), Ekind (Subp));
3732       Set_Is_Inlined (Subp);
3733    end Build_Body_To_Inline;
3734
3735    -------------------
3736    -- Cannot_Inline --
3737    -------------------
3738
3739    procedure Cannot_Inline (Msg : String; N : Node_Id; Subp : Entity_Id) is
3740    begin
3741       --  Do not emit warning if this is a predefined unit which is not the
3742       --  main unit. With validity checks enabled, some predefined subprograms
3743       --  may contain nested subprograms and become ineligible for inlining.
3744
3745       if Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (Subp)))
3746         and then not In_Extended_Main_Source_Unit (Subp)
3747       then
3748          null;
3749
3750       elsif Has_Pragma_Inline_Always (Subp) then
3751
3752          --  Remove last character (question mark) to make this into an error,
3753          --  because the Inline_Always pragma cannot be obeyed.
3754
3755          Error_Msg_NE (Msg (Msg'First .. Msg'Last - 1), N, Subp);
3756
3757       elsif Ineffective_Inline_Warnings then
3758          Error_Msg_NE (Msg, N, Subp);
3759       end if;
3760    end Cannot_Inline;
3761
3762    -----------------------
3763    -- Check_Conformance --
3764    -----------------------
3765
3766    procedure Check_Conformance
3767      (New_Id                   : Entity_Id;
3768       Old_Id                   : Entity_Id;
3769       Ctype                    : Conformance_Type;
3770       Errmsg                   : Boolean;
3771       Conforms                 : out Boolean;
3772       Err_Loc                  : Node_Id := Empty;
3773       Get_Inst                 : Boolean := False;
3774       Skip_Controlling_Formals : Boolean := False)
3775    is
3776       procedure Conformance_Error (Msg : String; N : Node_Id := New_Id);
3777       --  Sets Conforms to False. If Errmsg is False, then that's all it does.
3778       --  If Errmsg is True, then processing continues to post an error message
3779       --  for conformance error on given node. Two messages are output. The
3780       --  first message points to the previous declaration with a general "no
3781       --  conformance" message. The second is the detailed reason, supplied as
3782       --  Msg. The parameter N provide information for a possible & insertion
3783       --  in the message, and also provides the location for posting the
3784       --  message in the absence of a specified Err_Loc location.
3785
3786       -----------------------
3787       -- Conformance_Error --
3788       -----------------------
3789
3790       procedure Conformance_Error (Msg : String; N : Node_Id := New_Id) is
3791          Enode : Node_Id;
3792
3793       begin
3794          Conforms := False;
3795
3796          if Errmsg then
3797             if No (Err_Loc) then
3798                Enode := N;
3799             else
3800                Enode := Err_Loc;
3801             end if;
3802
3803             Error_Msg_Sloc := Sloc (Old_Id);
3804
3805             case Ctype is
3806                when Type_Conformant =>
3807                   Error_Msg_N -- CODEFIX
3808                     ("not type conformant with declaration#!", Enode);
3809
3810                when Mode_Conformant =>
3811                   if Nkind (Parent (Old_Id)) = N_Full_Type_Declaration then
3812                      Error_Msg_N
3813                        ("not mode conformant with operation inherited#!",
3814                          Enode);
3815                   else
3816                      Error_Msg_N
3817                        ("not mode conformant with declaration#!", Enode);
3818                   end if;
3819
3820                when Subtype_Conformant =>
3821                   if Nkind (Parent (Old_Id)) = N_Full_Type_Declaration then
3822                      Error_Msg_N
3823                        ("not subtype conformant with operation inherited#!",
3824                          Enode);
3825                   else
3826                      Error_Msg_N
3827                        ("not subtype conformant with declaration#!", Enode);
3828                   end if;
3829
3830                when Fully_Conformant =>
3831                   if Nkind (Parent (Old_Id)) = N_Full_Type_Declaration then
3832                      Error_Msg_N -- CODEFIX
3833                        ("not fully conformant with operation inherited#!",
3834                          Enode);
3835                   else
3836                      Error_Msg_N -- CODEFIX
3837                        ("not fully conformant with declaration#!", Enode);
3838                   end if;
3839             end case;
3840
3841             Error_Msg_NE (Msg, Enode, N);
3842          end if;
3843       end Conformance_Error;
3844
3845       --  Local Variables
3846
3847       Old_Type           : constant Entity_Id := Etype (Old_Id);
3848       New_Type           : constant Entity_Id := Etype (New_Id);
3849       Old_Formal         : Entity_Id;
3850       New_Formal         : Entity_Id;
3851       Access_Types_Match : Boolean;
3852       Old_Formal_Base    : Entity_Id;
3853       New_Formal_Base    : Entity_Id;
3854
3855    --  Start of processing for Check_Conformance
3856
3857    begin
3858       Conforms := True;
3859
3860       --  We need a special case for operators, since they don't appear
3861       --  explicitly.
3862
3863       if Ctype = Type_Conformant then
3864          if Ekind (New_Id) = E_Operator
3865            and then Operator_Matches_Spec (New_Id, Old_Id)
3866          then
3867             return;
3868          end if;
3869       end if;
3870
3871       --  If both are functions/operators, check return types conform
3872
3873       if Old_Type /= Standard_Void_Type
3874         and then New_Type /= Standard_Void_Type
3875       then
3876
3877          --  If we are checking interface conformance we omit controlling
3878          --  arguments and result, because we are only checking the conformance
3879          --  of the remaining parameters.
3880
3881          if Has_Controlling_Result (Old_Id)
3882            and then Has_Controlling_Result (New_Id)
3883            and then Skip_Controlling_Formals
3884          then
3885             null;
3886
3887          elsif not Conforming_Types (Old_Type, New_Type, Ctype, Get_Inst) then
3888             Conformance_Error ("\return type does not match!", New_Id);
3889             return;
3890          end if;
3891
3892          --  Ada 2005 (AI-231): In case of anonymous access types check the
3893          --  null-exclusion and access-to-constant attributes match.
3894
3895          if Ada_Version >= Ada_2005
3896            and then Ekind (Etype (Old_Type)) = E_Anonymous_Access_Type
3897            and then
3898              (Can_Never_Be_Null (Old_Type)
3899                 /= Can_Never_Be_Null (New_Type)
3900               or else Is_Access_Constant (Etype (Old_Type))
3901                         /= Is_Access_Constant (Etype (New_Type)))
3902          then
3903             Conformance_Error ("\return type does not match!", New_Id);
3904             return;
3905          end if;
3906
3907       --  If either is a function/operator and the other isn't, error
3908
3909       elsif Old_Type /= Standard_Void_Type
3910         or else New_Type /= Standard_Void_Type
3911       then
3912          Conformance_Error ("\functions can only match functions!", New_Id);
3913          return;
3914       end if;
3915
3916       --  In subtype conformant case, conventions must match (RM 6.3.1(16)).
3917       --  If this is a renaming as body, refine error message to indicate that
3918       --  the conflict is with the original declaration. If the entity is not
3919       --  frozen, the conventions don't have to match, the one of the renamed
3920       --  entity is inherited.
3921
3922       if Ctype >= Subtype_Conformant then
3923          if Convention (Old_Id) /= Convention (New_Id) then
3924
3925             if not Is_Frozen (New_Id) then
3926                null;
3927
3928             elsif Present (Err_Loc)
3929               and then Nkind (Err_Loc) = N_Subprogram_Renaming_Declaration
3930               and then Present (Corresponding_Spec (Err_Loc))
3931             then
3932                Error_Msg_Name_1 := Chars (New_Id);
3933                Error_Msg_Name_2 :=
3934                  Name_Ada + Convention_Id'Pos (Convention (New_Id));
3935                Conformance_Error ("\prior declaration for% has convention %!");
3936
3937             else
3938                Conformance_Error ("\calling conventions do not match!");
3939             end if;
3940
3941             return;
3942
3943          elsif Is_Formal_Subprogram (Old_Id)
3944            or else Is_Formal_Subprogram (New_Id)
3945          then
3946             Conformance_Error ("\formal subprograms not allowed!");
3947             return;
3948          end if;
3949       end if;
3950
3951       --  Deal with parameters
3952
3953       --  Note: we use the entity information, rather than going directly
3954       --  to the specification in the tree. This is not only simpler, but
3955       --  absolutely necessary for some cases of conformance tests between
3956       --  operators, where the declaration tree simply does not exist!
3957
3958       Old_Formal := First_Formal (Old_Id);
3959       New_Formal := First_Formal (New_Id);
3960       while Present (Old_Formal) and then Present (New_Formal) loop
3961          if Is_Controlling_Formal (Old_Formal)
3962            and then Is_Controlling_Formal (New_Formal)
3963            and then Skip_Controlling_Formals
3964          then
3965             --  The controlling formals will have different types when
3966             --  comparing an interface operation with its match, but both
3967             --  or neither must be access parameters.
3968
3969             if Is_Access_Type (Etype (Old_Formal))
3970                  =
3971                Is_Access_Type (Etype (New_Formal))
3972             then
3973                goto Skip_Controlling_Formal;
3974             else
3975                Conformance_Error
3976                  ("\access parameter does not match!", New_Formal);
3977             end if;
3978          end if;
3979
3980          if Ctype = Fully_Conformant then
3981
3982             --  Names must match. Error message is more accurate if we do
3983             --  this before checking that the types of the formals match.
3984
3985             if Chars (Old_Formal) /= Chars (New_Formal) then
3986                Conformance_Error ("\name & does not match!", New_Formal);
3987
3988                --  Set error posted flag on new formal as well to stop
3989                --  junk cascaded messages in some cases.
3990
3991                Set_Error_Posted (New_Formal);
3992                return;
3993             end if;
3994
3995             --  Null exclusion must match
3996
3997             if Null_Exclusion_Present (Parent (Old_Formal))
3998                  /=
3999                Null_Exclusion_Present (Parent (New_Formal))
4000             then
4001                --  Only give error if both come from source. This should be
4002                --  investigated some time, since it should not be needed ???
4003
4004                if Comes_From_Source (Old_Formal)
4005                     and then
4006                   Comes_From_Source (New_Formal)
4007                then
4008                   Conformance_Error
4009                     ("\null exclusion for & does not match", New_Formal);
4010
4011                   --  Mark error posted on the new formal to avoid duplicated
4012                   --  complaint about types not matching.
4013
4014                   Set_Error_Posted (New_Formal);
4015                end if;
4016             end if;
4017          end if;
4018
4019          --  Ada 2005 (AI-423): Possible access [sub]type and itype match. This
4020          --  case occurs whenever a subprogram is being renamed and one of its
4021          --  parameters imposes a null exclusion. For example:
4022
4023          --     type T is null record;
4024          --     type Acc_T is access T;
4025          --     subtype Acc_T_Sub is Acc_T;
4026
4027          --     procedure P     (Obj : not null Acc_T_Sub);  --  itype
4028          --     procedure Ren_P (Obj :          Acc_T_Sub)   --  subtype
4029          --       renames P;
4030
4031          Old_Formal_Base := Etype (Old_Formal);
4032          New_Formal_Base := Etype (New_Formal);
4033
4034          if Get_Inst then
4035             Old_Formal_Base := Get_Instance_Of (Old_Formal_Base);
4036             New_Formal_Base := Get_Instance_Of (New_Formal_Base);
4037          end if;
4038
4039          Access_Types_Match := Ada_Version >= Ada_2005
4040
4041             --  Ensure that this rule is only applied when New_Id is a
4042             --  renaming of Old_Id.
4043
4044            and then Nkind (Parent (Parent (New_Id))) =
4045                       N_Subprogram_Renaming_Declaration
4046            and then Nkind (Name (Parent (Parent (New_Id)))) in N_Has_Entity
4047            and then Present (Entity (Name (Parent (Parent (New_Id)))))
4048            and then Entity (Name (Parent (Parent (New_Id)))) = Old_Id
4049
4050             --  Now handle the allowed access-type case
4051
4052            and then Is_Access_Type (Old_Formal_Base)
4053            and then Is_Access_Type (New_Formal_Base)
4054
4055             --  The type kinds must match. The only exception occurs with
4056             --  multiple generics of the form:
4057
4058             --   generic                    generic
4059             --     type F is private;         type A is private;
4060             --     type F_Ptr is access F;    type A_Ptr is access A;
4061             --     with proc F_P (X : F_Ptr); with proc A_P (X : A_Ptr);
4062             --   package F_Pack is ...      package A_Pack is
4063             --                                package F_Inst is
4064             --                                  new F_Pack (A, A_Ptr, A_P);
4065
4066             --  When checking for conformance between the parameters of A_P
4067             --  and F_P, the type kinds of F_Ptr and A_Ptr will not match
4068             --  because the compiler has transformed A_Ptr into a subtype of
4069             --  F_Ptr. We catch this case in the code below.
4070
4071            and then (Ekind (Old_Formal_Base) = Ekind (New_Formal_Base)
4072                   or else
4073                     (Is_Generic_Type (Old_Formal_Base)
4074                        and then Is_Generic_Type (New_Formal_Base)
4075                        and then Is_Internal (New_Formal_Base)
4076                        and then Etype (Etype (New_Formal_Base)) =
4077                                   Old_Formal_Base))
4078            and then Directly_Designated_Type (Old_Formal_Base) =
4079                       Directly_Designated_Type (New_Formal_Base)
4080            and then ((Is_Itype (Old_Formal_Base)
4081                        and then Can_Never_Be_Null (Old_Formal_Base))
4082                     or else
4083                      (Is_Itype (New_Formal_Base)
4084                        and then Can_Never_Be_Null (New_Formal_Base)));
4085
4086          --  Types must always match. In the visible part of an instance,
4087          --  usual overloading rules for dispatching operations apply, and
4088          --  we check base types (not the actual subtypes).
4089
4090          if In_Instance_Visible_Part
4091            and then Is_Dispatching_Operation (New_Id)
4092          then
4093             if not Conforming_Types
4094                      (T1       => Base_Type (Etype (Old_Formal)),
4095                       T2       => Base_Type (Etype (New_Formal)),
4096                       Ctype    => Ctype,
4097                       Get_Inst => Get_Inst)
4098                and then not Access_Types_Match
4099             then
4100                Conformance_Error ("\type of & does not match!", New_Formal);
4101                return;
4102             end if;
4103
4104          elsif not Conforming_Types
4105                      (T1       => Old_Formal_Base,
4106                       T2       => New_Formal_Base,
4107                       Ctype    => Ctype,
4108                       Get_Inst => Get_Inst)
4109            and then not Access_Types_Match
4110          then
4111             --  Don't give error message if old type is Any_Type. This test
4112             --  avoids some cascaded errors, e.g. in case of a bad spec.
4113
4114             if Errmsg and then Old_Formal_Base = Any_Type then
4115                Conforms := False;
4116             else
4117                Conformance_Error ("\type of & does not match!", New_Formal);
4118             end if;
4119
4120             return;
4121          end if;
4122
4123          --  For mode conformance, mode must match
4124
4125          if Ctype >= Mode_Conformant then
4126             if Parameter_Mode (Old_Formal) /= Parameter_Mode (New_Formal) then
4127                Conformance_Error ("\mode of & does not match!", New_Formal);
4128                return;
4129
4130             --  Part of mode conformance for access types is having the same
4131             --  constant modifier.
4132
4133             elsif Access_Types_Match
4134               and then Is_Access_Constant (Old_Formal_Base) /=
4135                        Is_Access_Constant (New_Formal_Base)
4136             then
4137                Conformance_Error
4138                  ("\constant modifier does not match!", New_Formal);
4139                return;
4140             end if;
4141          end if;
4142
4143          if Ctype >= Subtype_Conformant then
4144
4145             --  Ada 2005 (AI-231): In case of anonymous access types check
4146             --  the null-exclusion and access-to-constant attributes must
4147             --  match. For null exclusion, we test the types rather than the
4148             --  formals themselves, since the attribute is only set reliably
4149             --  on the formals in the Ada 95 case, and we exclude the case
4150             --  where Old_Formal is marked as controlling, to avoid errors
4151             --  when matching completing bodies with dispatching declarations
4152             --  (access formals in the bodies aren't marked Can_Never_Be_Null).
4153
4154             if Ada_Version >= Ada_2005
4155               and then Ekind (Etype (Old_Formal)) = E_Anonymous_Access_Type
4156               and then Ekind (Etype (New_Formal)) = E_Anonymous_Access_Type
4157               and then
4158                 ((Can_Never_Be_Null (Etype (Old_Formal)) /=
4159                   Can_Never_Be_Null (Etype (New_Formal))
4160                     and then
4161                       not Is_Controlling_Formal (Old_Formal))
4162                    or else
4163                  Is_Access_Constant (Etype (Old_Formal)) /=
4164                  Is_Access_Constant (Etype (New_Formal)))
4165
4166               --  Do not complain if error already posted on New_Formal. This
4167               --  avoids some redundant error messages.
4168
4169               and then not Error_Posted (New_Formal)
4170             then
4171                --  It is allowed to omit the null-exclusion in case of stream
4172                --  attribute subprograms. We recognize stream subprograms
4173                --  through their TSS-generated suffix.
4174
4175                declare
4176                   TSS_Name : constant TSS_Name_Type := Get_TSS_Name (New_Id);
4177                begin
4178                   if TSS_Name /= TSS_Stream_Read
4179                     and then TSS_Name /= TSS_Stream_Write
4180                     and then TSS_Name /= TSS_Stream_Input
4181                     and then TSS_Name /= TSS_Stream_Output
4182                   then
4183                      Conformance_Error
4184                        ("\type of & does not match!", New_Formal);
4185                      return;
4186                   end if;
4187                end;
4188             end if;
4189          end if;
4190
4191          --  Full conformance checks
4192
4193          if Ctype = Fully_Conformant then
4194
4195             --  We have checked already that names match
4196
4197             if Parameter_Mode (Old_Formal) = E_In_Parameter then
4198
4199                --  Check default expressions for in parameters
4200
4201                declare
4202                   NewD : constant Boolean :=
4203                            Present (Default_Value (New_Formal));
4204                   OldD : constant Boolean :=
4205                            Present (Default_Value (Old_Formal));
4206                begin
4207                   if NewD or OldD then
4208
4209                      --  The old default value has been analyzed because the
4210                      --  current full declaration will have frozen everything
4211                      --  before. The new default value has not been analyzed,
4212                      --  so analyze it now before we check for conformance.
4213
4214                      if NewD then
4215                         Push_Scope (New_Id);
4216                         Preanalyze_Spec_Expression
4217                           (Default_Value (New_Formal), Etype (New_Formal));
4218                         End_Scope;
4219                      end if;
4220
4221                      if not (NewD and OldD)
4222                        or else not Fully_Conformant_Expressions
4223                                     (Default_Value (Old_Formal),
4224                                      Default_Value (New_Formal))
4225                      then
4226                         Conformance_Error
4227                           ("\default expression for & does not match!",
4228                            New_Formal);
4229                         return;
4230                      end if;
4231                   end if;
4232                end;
4233             end if;
4234          end if;
4235
4236          --  A couple of special checks for Ada 83 mode. These checks are
4237          --  skipped if either entity is an operator in package Standard,
4238          --  or if either old or new instance is not from the source program.
4239
4240          if Ada_Version = Ada_83
4241            and then Sloc (Old_Id) > Standard_Location
4242            and then Sloc (New_Id) > Standard_Location
4243            and then Comes_From_Source (Old_Id)
4244            and then Comes_From_Source (New_Id)
4245          then
4246             declare
4247                Old_Param : constant Node_Id := Declaration_Node (Old_Formal);
4248                New_Param : constant Node_Id := Declaration_Node (New_Formal);
4249
4250             begin
4251                --  Explicit IN must be present or absent in both cases. This
4252                --  test is required only in the full conformance case.
4253
4254                if In_Present (Old_Param) /= In_Present (New_Param)
4255                  and then Ctype = Fully_Conformant
4256                then
4257                   Conformance_Error
4258                     ("\(Ada 83) IN must appear in both declarations",
4259                      New_Formal);
4260                   return;
4261                end if;
4262
4263                --  Grouping (use of comma in param lists) must be the same
4264                --  This is where we catch a misconformance like:
4265
4266                --    A, B : Integer
4267                --    A : Integer; B : Integer
4268
4269                --  which are represented identically in the tree except
4270                --  for the setting of the flags More_Ids and Prev_Ids.
4271
4272                if More_Ids (Old_Param) /= More_Ids (New_Param)
4273                  or else Prev_Ids (Old_Param) /= Prev_Ids (New_Param)
4274                then
4275                   Conformance_Error
4276                     ("\grouping of & does not match!", New_Formal);
4277                   return;
4278                end if;
4279             end;
4280          end if;
4281
4282          --  This label is required when skipping controlling formals
4283
4284          <<Skip_Controlling_Formal>>
4285
4286          Next_Formal (Old_Formal);
4287          Next_Formal (New_Formal);
4288       end loop;
4289
4290       if Present (Old_Formal) then
4291          Conformance_Error ("\too few parameters!");
4292          return;
4293
4294       elsif Present (New_Formal) then
4295          Conformance_Error ("\too many parameters!", New_Formal);
4296          return;
4297       end if;
4298    end Check_Conformance;
4299
4300    -----------------------
4301    -- Check_Conventions --
4302    -----------------------
4303
4304    procedure Check_Conventions (Typ : Entity_Id) is
4305       Ifaces_List : Elist_Id;
4306
4307       procedure Check_Convention (Op : Entity_Id);
4308       --  Verify that the convention of inherited dispatching operation Op is
4309       --  consistent among all subprograms it overrides. In order to minimize
4310       --  the search, Search_From is utilized to designate a specific point in
4311       --  the list rather than iterating over the whole list once more.
4312
4313       ----------------------
4314       -- Check_Convention --
4315       ----------------------
4316
4317       procedure Check_Convention (Op : Entity_Id) is
4318          Iface_Elmt      : Elmt_Id;
4319          Iface_Prim_Elmt : Elmt_Id;
4320          Iface_Prim      : Entity_Id;
4321
4322       begin
4323          Iface_Elmt := First_Elmt (Ifaces_List);
4324          while Present (Iface_Elmt) loop
4325             Iface_Prim_Elmt :=
4326                First_Elmt (Primitive_Operations (Node (Iface_Elmt)));
4327             while Present (Iface_Prim_Elmt) loop
4328                Iface_Prim := Node (Iface_Prim_Elmt);
4329
4330                if Is_Interface_Conformant (Typ, Iface_Prim, Op)
4331                  and then Convention (Iface_Prim) /= Convention (Op)
4332                then
4333                   Error_Msg_N
4334                     ("inconsistent conventions in primitive operations", Typ);
4335
4336                   Error_Msg_Name_1 := Chars (Op);
4337                   Error_Msg_Name_2 := Get_Convention_Name (Convention (Op));
4338                   Error_Msg_Sloc   := Sloc (Op);
4339
4340                   if Comes_From_Source (Op) or else No (Alias (Op)) then
4341                      if not Present (Overridden_Operation (Op)) then
4342                         Error_Msg_N ("\\primitive % defined #", Typ);
4343                      else
4344                         Error_Msg_N
4345                           ("\\overriding operation % with " &
4346                            "convention % defined #", Typ);
4347                      end if;
4348
4349                   else pragma Assert (Present (Alias (Op)));
4350                      Error_Msg_Sloc := Sloc (Alias (Op));
4351                      Error_Msg_N
4352                        ("\\inherited operation % with " &
4353                         "convention % defined #", Typ);
4354                   end if;
4355
4356                   Error_Msg_Name_1 := Chars (Op);
4357                   Error_Msg_Name_2 :=
4358                     Get_Convention_Name (Convention (Iface_Prim));
4359                   Error_Msg_Sloc := Sloc (Iface_Prim);
4360                   Error_Msg_N
4361                     ("\\overridden operation % with " &
4362                      "convention % defined #", Typ);
4363
4364                   --  Avoid cascading errors
4365
4366                   return;
4367                end if;
4368
4369                Next_Elmt (Iface_Prim_Elmt);
4370             end loop;
4371
4372             Next_Elmt (Iface_Elmt);
4373          end loop;
4374       end Check_Convention;
4375
4376       --  Local variables
4377
4378       Prim_Op      : Entity_Id;
4379       Prim_Op_Elmt : Elmt_Id;
4380
4381    --  Start of processing for Check_Conventions
4382
4383    begin
4384       if not Has_Interfaces (Typ) then
4385          return;
4386       end if;
4387
4388       Collect_Interfaces (Typ, Ifaces_List);
4389
4390       --  The algorithm checks every overriding dispatching operation against
4391       --  all the corresponding overridden dispatching operations, detecting
4392       --  differences in conventions.
4393
4394       Prim_Op_Elmt := First_Elmt (Primitive_Operations (Typ));
4395       while Present (Prim_Op_Elmt) loop
4396          Prim_Op := Node (Prim_Op_Elmt);
4397
4398          --  A small optimization: skip the predefined dispatching operations
4399          --  since they always have the same convention.
4400
4401          if not Is_Predefined_Dispatching_Operation (Prim_Op) then
4402             Check_Convention (Prim_Op);
4403          end if;
4404
4405          Next_Elmt (Prim_Op_Elmt);
4406       end loop;
4407    end Check_Conventions;
4408
4409    ------------------------------
4410    -- Check_Delayed_Subprogram --
4411    ------------------------------
4412
4413    procedure Check_Delayed_Subprogram (Designator : Entity_Id) is
4414       F : Entity_Id;
4415
4416       procedure Possible_Freeze (T : Entity_Id);
4417       --  T is the type of either a formal parameter or of the return type.
4418       --  If T is not yet frozen and needs a delayed freeze, then the
4419       --  subprogram itself must be delayed. If T is the limited view of an
4420       --  incomplete type the subprogram must be frozen as well, because
4421       --  T may depend on local types that have not been frozen yet.
4422
4423       ---------------------
4424       -- Possible_Freeze --
4425       ---------------------
4426
4427       procedure Possible_Freeze (T : Entity_Id) is
4428       begin
4429          if Has_Delayed_Freeze (T) and then not Is_Frozen (T) then
4430             Set_Has_Delayed_Freeze (Designator);
4431
4432          elsif Is_Access_Type (T)
4433            and then Has_Delayed_Freeze (Designated_Type (T))
4434            and then not Is_Frozen (Designated_Type (T))
4435          then
4436             Set_Has_Delayed_Freeze (Designator);
4437
4438          elsif Ekind (T) = E_Incomplete_Type and then From_With_Type (T) then
4439             Set_Has_Delayed_Freeze (Designator);
4440          end if;
4441
4442       end Possible_Freeze;
4443
4444    --  Start of processing for Check_Delayed_Subprogram
4445
4446    begin
4447       --  All subprograms, including abstract subprograms, may need a freeze
4448       --  node if some formal type or the return type needs one.
4449
4450       Possible_Freeze (Etype (Designator));
4451       Possible_Freeze (Base_Type (Etype (Designator))); -- needed ???
4452
4453       --  Need delayed freeze if any of the formal types themselves need
4454       --  a delayed freeze and are not yet frozen.
4455
4456       F := First_Formal (Designator);
4457       while Present (F) loop
4458          Possible_Freeze (Etype (F));
4459          Possible_Freeze (Base_Type (Etype (F))); -- needed ???
4460          Next_Formal (F);
4461       end loop;
4462
4463       --  Mark functions that return by reference. Note that it cannot be
4464       --  done for delayed_freeze subprograms because the underlying
4465       --  returned type may not be known yet (for private types)
4466
4467       if not Has_Delayed_Freeze (Designator)
4468         and then Expander_Active
4469       then
4470          declare
4471             Typ  : constant Entity_Id := Etype (Designator);
4472             Utyp : constant Entity_Id := Underlying_Type (Typ);
4473
4474          begin
4475             if Is_Immutably_Limited_Type (Typ) then
4476                Set_Returns_By_Ref (Designator);
4477
4478             elsif Present (Utyp) and then CW_Or_Has_Controlled_Part (Utyp) then
4479                Set_Returns_By_Ref (Designator);
4480             end if;
4481          end;
4482       end if;
4483    end Check_Delayed_Subprogram;
4484
4485    ------------------------------------
4486    -- Check_Discriminant_Conformance --
4487    ------------------------------------
4488
4489    procedure Check_Discriminant_Conformance
4490      (N        : Node_Id;
4491       Prev     : Entity_Id;
4492       Prev_Loc : Node_Id)
4493    is
4494       Old_Discr      : Entity_Id := First_Discriminant (Prev);
4495       New_Discr      : Node_Id   := First (Discriminant_Specifications (N));
4496       New_Discr_Id   : Entity_Id;
4497       New_Discr_Type : Entity_Id;
4498
4499       procedure Conformance_Error (Msg : String; N : Node_Id);
4500       --  Post error message for conformance error on given node. Two messages
4501       --  are output. The first points to the previous declaration with a
4502       --  general "no conformance" message. The second is the detailed reason,
4503       --  supplied as Msg. The parameter N provide information for a possible
4504       --  & insertion in the message.
4505
4506       -----------------------
4507       -- Conformance_Error --
4508       -----------------------
4509
4510       procedure Conformance_Error (Msg : String; N : Node_Id) is
4511       begin
4512          Error_Msg_Sloc := Sloc (Prev_Loc);
4513          Error_Msg_N -- CODEFIX
4514            ("not fully conformant with declaration#!", N);
4515          Error_Msg_NE (Msg, N, N);
4516       end Conformance_Error;
4517
4518    --  Start of processing for Check_Discriminant_Conformance
4519
4520    begin
4521       while Present (Old_Discr) and then Present (New_Discr) loop
4522
4523          New_Discr_Id := Defining_Identifier (New_Discr);
4524
4525          --  The subtype mark of the discriminant on the full type has not
4526          --  been analyzed so we do it here. For an access discriminant a new
4527          --  type is created.
4528
4529          if Nkind (Discriminant_Type (New_Discr)) = N_Access_Definition then
4530             New_Discr_Type :=
4531               Access_Definition (N, Discriminant_Type (New_Discr));
4532
4533          else
4534             Analyze (Discriminant_Type (New_Discr));
4535             New_Discr_Type := Etype (Discriminant_Type (New_Discr));
4536
4537             --  Ada 2005: if the discriminant definition carries a null
4538             --  exclusion, create an itype to check properly for consistency
4539             --  with partial declaration.
4540
4541             if Is_Access_Type (New_Discr_Type)
4542                  and then Null_Exclusion_Present (New_Discr)
4543             then
4544                New_Discr_Type :=
4545                  Create_Null_Excluding_Itype
4546                    (T           => New_Discr_Type,
4547                     Related_Nod => New_Discr,
4548                     Scope_Id    => Current_Scope);
4549             end if;
4550          end if;
4551
4552          if not Conforming_Types
4553                   (Etype (Old_Discr), New_Discr_Type, Fully_Conformant)
4554          then
4555             Conformance_Error ("type of & does not match!", New_Discr_Id);
4556             return;
4557          else
4558             --  Treat the new discriminant as an occurrence of the old one,
4559             --  for navigation purposes, and fill in some semantic
4560             --  information, for completeness.
4561
4562             Generate_Reference (Old_Discr, New_Discr_Id, 'r');
4563             Set_Etype (New_Discr_Id, Etype (Old_Discr));
4564             Set_Scope (New_Discr_Id, Scope (Old_Discr));
4565          end if;
4566
4567          --  Names must match
4568
4569          if Chars (Old_Discr) /= Chars (Defining_Identifier (New_Discr)) then
4570             Conformance_Error ("name & does not match!", New_Discr_Id);
4571             return;
4572          end if;
4573
4574          --  Default expressions must match
4575
4576          declare
4577             NewD : constant Boolean :=
4578                      Present (Expression (New_Discr));
4579             OldD : constant Boolean :=
4580                      Present (Expression (Parent (Old_Discr)));
4581
4582          begin
4583             if NewD or OldD then
4584
4585                --  The old default value has been analyzed and expanded,
4586                --  because the current full declaration will have frozen
4587                --  everything before. The new default values have not been
4588                --  expanded, so expand now to check conformance.
4589
4590                if NewD then
4591                   Preanalyze_Spec_Expression
4592                     (Expression (New_Discr), New_Discr_Type);
4593                end if;
4594
4595                if not (NewD and OldD)
4596                  or else not Fully_Conformant_Expressions
4597                               (Expression (Parent (Old_Discr)),
4598                                Expression (New_Discr))
4599
4600                then
4601                   Conformance_Error
4602                     ("default expression for & does not match!",
4603                      New_Discr_Id);
4604                   return;
4605                end if;
4606             end if;
4607          end;
4608
4609          --  In Ada 83 case, grouping must match: (A,B : X) /= (A : X; B : X)
4610
4611          if Ada_Version = Ada_83 then
4612             declare
4613                Old_Disc : constant Node_Id := Declaration_Node (Old_Discr);
4614
4615             begin
4616                --  Grouping (use of comma in param lists) must be the same
4617                --  This is where we catch a misconformance like:
4618
4619                --    A,B : Integer
4620                --    A : Integer; B : Integer
4621
4622                --  which are represented identically in the tree except
4623                --  for the setting of the flags More_Ids and Prev_Ids.
4624
4625                if More_Ids (Old_Disc) /= More_Ids (New_Discr)
4626                  or else Prev_Ids (Old_Disc) /= Prev_Ids (New_Discr)
4627                then
4628                   Conformance_Error
4629                     ("grouping of & does not match!", New_Discr_Id);
4630                   return;
4631                end if;
4632             end;
4633          end if;
4634
4635          Next_Discriminant (Old_Discr);
4636          Next (New_Discr);
4637       end loop;
4638
4639       if Present (Old_Discr) then
4640          Conformance_Error ("too few discriminants!", Defining_Identifier (N));
4641          return;
4642
4643       elsif Present (New_Discr) then
4644          Conformance_Error
4645            ("too many discriminants!", Defining_Identifier (New_Discr));
4646          return;
4647       end if;
4648    end Check_Discriminant_Conformance;
4649
4650    ----------------------------
4651    -- Check_Fully_Conformant --
4652    ----------------------------
4653
4654    procedure Check_Fully_Conformant
4655      (New_Id  : Entity_Id;
4656       Old_Id  : Entity_Id;
4657       Err_Loc : Node_Id := Empty)
4658    is
4659       Result : Boolean;
4660       pragma Warnings (Off, Result);
4661    begin
4662       Check_Conformance
4663         (New_Id, Old_Id, Fully_Conformant, True, Result, Err_Loc);
4664    end Check_Fully_Conformant;
4665
4666    ---------------------------
4667    -- Check_Mode_Conformant --
4668    ---------------------------
4669
4670    procedure Check_Mode_Conformant
4671      (New_Id   : Entity_Id;
4672       Old_Id   : Entity_Id;
4673       Err_Loc  : Node_Id := Empty;
4674       Get_Inst : Boolean := False)
4675    is
4676       Result : Boolean;
4677       pragma Warnings (Off, Result);
4678    begin
4679       Check_Conformance
4680         (New_Id, Old_Id, Mode_Conformant, True, Result, Err_Loc, Get_Inst);
4681    end Check_Mode_Conformant;
4682
4683    --------------------------------
4684    -- Check_Overriding_Indicator --
4685    --------------------------------
4686
4687    procedure Check_Overriding_Indicator
4688      (Subp            : Entity_Id;
4689       Overridden_Subp : Entity_Id;
4690       Is_Primitive    : Boolean)
4691    is
4692       Decl : Node_Id;
4693       Spec : Node_Id;
4694
4695    begin
4696       --  No overriding indicator for literals
4697
4698       if Ekind (Subp) = E_Enumeration_Literal then
4699          return;
4700
4701       elsif Ekind (Subp) = E_Entry then
4702          Decl := Parent (Subp);
4703
4704          --  No point in analyzing a malformed operator
4705
4706       elsif Nkind (Subp) = N_Defining_Operator_Symbol
4707         and then Error_Posted (Subp)
4708       then
4709          return;
4710
4711       else
4712          Decl := Unit_Declaration_Node (Subp);
4713       end if;
4714
4715       if Nkind_In (Decl, N_Subprogram_Body,
4716                          N_Subprogram_Body_Stub,
4717                          N_Subprogram_Declaration,
4718                          N_Abstract_Subprogram_Declaration,
4719                          N_Subprogram_Renaming_Declaration)
4720       then
4721          Spec := Specification (Decl);
4722
4723       elsif Nkind (Decl) = N_Entry_Declaration then
4724          Spec := Decl;
4725
4726       else
4727          return;
4728       end if;
4729
4730       --  The overriding operation is type conformant with the overridden one,
4731       --  but the names of the formals are not required to match. If the names
4732       --  appear permuted in the overriding operation, this is a possible
4733       --  source of confusion that is worth diagnosing. Controlling formals
4734       --  often carry names that reflect the type, and it is not worthwhile
4735       --  requiring that their names match.
4736
4737       if Present (Overridden_Subp)
4738         and then Nkind (Subp) /= N_Defining_Operator_Symbol
4739       then
4740          declare
4741             Form1 : Entity_Id;
4742             Form2 : Entity_Id;
4743
4744          begin
4745             Form1 := First_Formal (Subp);
4746             Form2 := First_Formal (Overridden_Subp);
4747
4748             --  If the overriding operation is a synchronized operation, skip
4749             --  the first parameter of the overridden operation, which is
4750             --  implicit in the new one. If the operation is declared in the
4751             --  body it is not primitive and all formals must match.
4752
4753             if Is_Concurrent_Type (Scope (Subp))
4754               and then Is_Tagged_Type (Scope (Subp))
4755               and then not Has_Completion (Scope (Subp))
4756             then
4757                Form2 := Next_Formal (Form2);
4758             end if;
4759
4760             if Present (Form1) then
4761                Form1 := Next_Formal (Form1);
4762                Form2 := Next_Formal (Form2);
4763             end if;
4764
4765             while Present (Form1) loop
4766                if not Is_Controlling_Formal (Form1)
4767                  and then Present (Next_Formal (Form2))
4768                  and then Chars (Form1) = Chars (Next_Formal (Form2))
4769                then
4770                   Error_Msg_Node_2 := Alias (Overridden_Subp);
4771                   Error_Msg_Sloc := Sloc (Error_Msg_Node_2);
4772                   Error_Msg_NE
4773                     ("& does not match corresponding formal of&#",
4774                      Form1, Form1);
4775                   exit;
4776                end if;
4777
4778                Next_Formal (Form1);
4779                Next_Formal (Form2);
4780             end loop;
4781          end;
4782       end if;
4783
4784       --  If there is an overridden subprogram, then check that there is no
4785       --  "not overriding" indicator, and mark the subprogram as overriding.
4786       --  This is not done if the overridden subprogram is marked as hidden,
4787       --  which can occur for the case of inherited controlled operations
4788       --  (see Derive_Subprogram), unless the inherited subprogram's parent
4789       --  subprogram is not itself hidden. (Note: This condition could probably
4790       --  be simplified, leaving out the testing for the specific controlled
4791       --  cases, but it seems safer and clearer this way, and echoes similar
4792       --  special-case tests of this kind in other places.)
4793
4794       if Present (Overridden_Subp)
4795         and then (not Is_Hidden (Overridden_Subp)
4796                    or else
4797                      ((Chars (Overridden_Subp) = Name_Initialize
4798                          or else
4799                        Chars (Overridden_Subp) = Name_Adjust
4800                          or else
4801                        Chars (Overridden_Subp) = Name_Finalize)
4802                       and then Present (Alias (Overridden_Subp))
4803                       and then not Is_Hidden (Alias (Overridden_Subp))))
4804       then
4805          if Must_Not_Override (Spec) then
4806             Error_Msg_Sloc := Sloc (Overridden_Subp);
4807
4808             if Ekind (Subp) = E_Entry then
4809                Error_Msg_NE
4810                  ("entry & overrides inherited operation #", Spec, Subp);
4811             else
4812                Error_Msg_NE
4813                  ("subprogram & overrides inherited operation #", Spec, Subp);
4814             end if;
4815
4816          elsif Is_Subprogram (Subp) then
4817             if Is_Init_Proc (Subp) then
4818                null;
4819
4820             elsif No (Overridden_Operation (Subp)) then
4821
4822                --  For entities generated by Derive_Subprograms the overridden
4823                --  operation is the inherited primitive (which is available
4824                --  through the attribute alias)
4825
4826                if (Is_Dispatching_Operation (Subp)
4827                     or else Is_Dispatching_Operation (Overridden_Subp))
4828                  and then not Comes_From_Source (Overridden_Subp)
4829                  and then Find_Dispatching_Type (Overridden_Subp) =
4830                           Find_Dispatching_Type (Subp)
4831                  and then Present (Alias (Overridden_Subp))
4832                  and then Comes_From_Source (Alias (Overridden_Subp))
4833                then
4834                   Set_Overridden_Operation (Subp, Alias (Overridden_Subp));
4835
4836                else
4837                   Set_Overridden_Operation (Subp, Overridden_Subp);
4838                end if;
4839             end if;
4840          end if;
4841
4842          --  If primitive flag is set or this is a protected operation, then
4843          --  the operation is overriding at the point of its declaration, so
4844          --  warn if necessary. Otherwise it may have been declared before the
4845          --  operation it overrides and no check is required.
4846
4847          if Style_Check
4848            and then not Must_Override (Spec)
4849            and then (Is_Primitive
4850                       or else Ekind (Scope (Subp)) = E_Protected_Type)
4851          then
4852             Style.Missing_Overriding (Decl, Subp);
4853          end if;
4854
4855       --  If Subp is an operator, it may override a predefined operation, if
4856       --  it is defined in the same scope as the type to which it applies.
4857       --  In that case Overridden_Subp is empty because of our implicit
4858       --  representation for predefined operators. We have to check whether the
4859       --  signature of Subp matches that of a predefined operator. Note that
4860       --  first argument provides the name of the operator, and the second
4861       --  argument the signature that may match that of a standard operation.
4862       --  If the indicator is overriding, then the operator must match a
4863       --  predefined signature, because we know already that there is no
4864       --  explicit overridden operation.
4865
4866       elsif Nkind (Subp) = N_Defining_Operator_Symbol then
4867          if Must_Not_Override (Spec) then
4868
4869             --  If this is not a primitive or a protected subprogram, then
4870             --  "not overriding" is illegal.
4871
4872             if not Is_Primitive
4873               and then Ekind (Scope (Subp)) /= E_Protected_Type
4874             then
4875                Error_Msg_N
4876                  ("overriding indicator only allowed "
4877                   & "if subprogram is primitive", Subp);
4878
4879             elsif Can_Override_Operator (Subp) then
4880                Error_Msg_NE
4881                  ("subprogram& overrides predefined operator ", Spec, Subp);
4882             end if;
4883
4884          elsif Must_Override (Spec) then
4885             if No (Overridden_Operation (Subp))
4886               and then not Can_Override_Operator (Subp)
4887             then
4888                Error_Msg_NE ("subprogram & is not overriding", Spec, Subp);
4889             end if;
4890
4891          elsif not Error_Posted (Subp)
4892            and then Style_Check
4893            and then Can_Override_Operator (Subp)
4894            and then
4895              not Is_Predefined_File_Name
4896                    (Unit_File_Name (Get_Source_Unit (Subp)))
4897          then
4898             --  If style checks are enabled, indicate that the indicator is
4899             --  missing. However, at the point of declaration, the type of
4900             --  which this is a primitive operation may be private, in which
4901             --  case the indicator would be premature.
4902
4903             if Has_Private_Declaration (Etype (Subp))
4904               or else Has_Private_Declaration (Etype (First_Formal (Subp)))
4905             then
4906                null;
4907             else
4908                Style.Missing_Overriding (Decl, Subp);
4909             end if;
4910          end if;
4911
4912       elsif Must_Override (Spec) then
4913          if Ekind (Subp) = E_Entry then
4914             Error_Msg_NE ("entry & is not overriding", Spec, Subp);
4915          else
4916             Error_Msg_NE ("subprogram & is not overriding", Spec, Subp);
4917          end if;
4918
4919       --  If the operation is marked "not overriding" and it's not primitive
4920       --  then an error is issued, unless this is an operation of a task or
4921       --  protected type (RM05-8.3.1(3/2-4/2)). Error cases where "overriding"
4922       --  has been specified have already been checked above.
4923
4924       elsif Must_Not_Override (Spec)
4925         and then not Is_Primitive
4926         and then Ekind (Subp) /= E_Entry
4927         and then Ekind (Scope (Subp)) /= E_Protected_Type
4928       then
4929          Error_Msg_N
4930            ("overriding indicator only allowed if subprogram is primitive",
4931             Subp);
4932          return;
4933       end if;
4934    end Check_Overriding_Indicator;
4935
4936    -------------------
4937    -- Check_Returns --
4938    -------------------
4939
4940    --  Note: this procedure needs to know far too much about how the expander
4941    --  messes with exceptions. The use of the flag Exception_Junk and the
4942    --  incorporation of knowledge of Exp_Ch11.Expand_Local_Exception_Handlers
4943    --  works, but is not very clean. It would be better if the expansion
4944    --  routines would leave Original_Node working nicely, and we could use
4945    --  Original_Node here to ignore all the peculiar expander messing ???
4946
4947    procedure Check_Returns
4948      (HSS  : Node_Id;
4949       Mode : Character;
4950       Err  : out Boolean;
4951       Proc : Entity_Id := Empty)
4952    is
4953       Handler : Node_Id;
4954
4955       procedure Check_Statement_Sequence (L : List_Id);
4956       --  Internal recursive procedure to check a list of statements for proper
4957       --  termination by a return statement (or a transfer of control or a
4958       --  compound statement that is itself internally properly terminated).
4959
4960       ------------------------------
4961       -- Check_Statement_Sequence --
4962       ------------------------------
4963
4964       procedure Check_Statement_Sequence (L : List_Id) is
4965          Last_Stm : Node_Id;
4966          Stm      : Node_Id;
4967          Kind     : Node_Kind;
4968
4969          Raise_Exception_Call : Boolean;
4970          --  Set True if statement sequence terminated by Raise_Exception call
4971          --  or a Reraise_Occurrence call.
4972
4973       begin
4974          Raise_Exception_Call := False;
4975
4976          --  Get last real statement
4977
4978          Last_Stm := Last (L);
4979
4980          --  Deal with digging out exception handler statement sequences that
4981          --  have been transformed by the local raise to goto optimization.
4982          --  See Exp_Ch11.Expand_Local_Exception_Handlers for details. If this
4983          --  optimization has occurred, we are looking at something like:
4984
4985          --  begin
4986          --     original stmts in block
4987
4988          --  exception            \
4989          --     when excep1 =>     |
4990          --        goto L1;        | omitted if No_Exception_Propagation
4991          --     when excep2 =>     |
4992          --        goto L2;       /
4993          --  end;
4994
4995          --  goto L3;      -- skip handler when exception not raised
4996
4997          --  <<L1>>        -- target label for local exception
4998          --     begin
4999          --        estmts1
5000          --     end;
5001
5002          --     goto L3;
5003
5004          --  <<L2>>
5005          --     begin
5006          --        estmts2
5007          --     end;
5008
5009          --  <<L3>>
5010
5011          --  and what we have to do is to dig out the estmts1 and estmts2
5012          --  sequences (which were the original sequences of statements in
5013          --  the exception handlers) and check them.
5014
5015          if Nkind (Last_Stm) = N_Label
5016            and then Exception_Junk (Last_Stm)
5017          then
5018             Stm := Last_Stm;
5019             loop
5020                Prev (Stm);
5021                exit when No (Stm);
5022                exit when Nkind (Stm) /= N_Block_Statement;
5023                exit when not Exception_Junk (Stm);
5024                Prev (Stm);
5025                exit when No (Stm);
5026                exit when Nkind (Stm) /= N_Label;
5027                exit when not Exception_Junk (Stm);
5028                Check_Statement_Sequence
5029                  (Statements (Handled_Statement_Sequence (Next (Stm))));
5030
5031                Prev (Stm);
5032                Last_Stm := Stm;
5033                exit when No (Stm);
5034                exit when Nkind (Stm) /= N_Goto_Statement;
5035                exit when not Exception_Junk (Stm);
5036             end loop;
5037          end if;
5038
5039          --  Don't count pragmas
5040
5041          while Nkind (Last_Stm) = N_Pragma
5042
5043          --  Don't count call to SS_Release (can happen after Raise_Exception)
5044
5045            or else
5046              (Nkind (Last_Stm) = N_Procedure_Call_Statement
5047                 and then
5048               Nkind (Name (Last_Stm)) = N_Identifier
5049                 and then
5050               Is_RTE (Entity (Name (Last_Stm)), RE_SS_Release))
5051
5052          --  Don't count exception junk
5053
5054            or else
5055              (Nkind_In (Last_Stm, N_Goto_Statement,
5056                                    N_Label,
5057                                    N_Object_Declaration)
5058                 and then Exception_Junk (Last_Stm))
5059            or else Nkind (Last_Stm) in N_Push_xxx_Label
5060            or else Nkind (Last_Stm) in N_Pop_xxx_Label
5061          loop
5062             Prev (Last_Stm);
5063          end loop;
5064
5065          --  Here we have the "real" last statement
5066
5067          Kind := Nkind (Last_Stm);
5068
5069          --  Transfer of control, OK. Note that in the No_Return procedure
5070          --  case, we already diagnosed any explicit return statements, so
5071          --  we can treat them as OK in this context.
5072
5073          if Is_Transfer (Last_Stm) then
5074             return;
5075
5076          --  Check cases of explicit non-indirect procedure calls
5077
5078          elsif Kind = N_Procedure_Call_Statement
5079            and then Is_Entity_Name (Name (Last_Stm))
5080          then
5081             --  Check call to Raise_Exception procedure which is treated
5082             --  specially, as is a call to Reraise_Occurrence.
5083
5084             --  We suppress the warning in these cases since it is likely that
5085             --  the programmer really does not expect to deal with the case
5086             --  of Null_Occurrence, and thus would find a warning about a
5087             --  missing return curious, and raising Program_Error does not
5088             --  seem such a bad behavior if this does occur.
5089
5090             --  Note that in the Ada 2005 case for Raise_Exception, the actual
5091             --  behavior will be to raise Constraint_Error (see AI-329).
5092
5093             if Is_RTE (Entity (Name (Last_Stm)), RE_Raise_Exception)
5094                  or else
5095                Is_RTE (Entity (Name (Last_Stm)), RE_Reraise_Occurrence)
5096             then
5097                Raise_Exception_Call := True;
5098
5099                --  For Raise_Exception call, test first argument, if it is
5100                --  an attribute reference for a 'Identity call, then we know
5101                --  that the call cannot possibly return.
5102
5103                declare
5104                   Arg : constant Node_Id :=
5105                           Original_Node (First_Actual (Last_Stm));
5106                begin
5107                   if Nkind (Arg) = N_Attribute_Reference
5108                     and then Attribute_Name (Arg) = Name_Identity
5109                   then
5110                      return;
5111                   end if;
5112                end;
5113             end if;
5114
5115          --  If statement, need to look inside if there is an else and check
5116          --  each constituent statement sequence for proper termination.
5117
5118          elsif Kind = N_If_Statement
5119            and then Present (Else_Statements (Last_Stm))
5120          then
5121             Check_Statement_Sequence (Then_Statements (Last_Stm));
5122             Check_Statement_Sequence (Else_Statements (Last_Stm));
5123
5124             if Present (Elsif_Parts (Last_Stm)) then
5125                declare
5126                   Elsif_Part : Node_Id := First (Elsif_Parts (Last_Stm));
5127
5128                begin
5129                   while Present (Elsif_Part) loop
5130                      Check_Statement_Sequence (Then_Statements (Elsif_Part));
5131                      Next (Elsif_Part);
5132                   end loop;
5133                end;
5134             end if;
5135
5136             return;
5137
5138          --  Case statement, check each case for proper termination
5139
5140          elsif Kind = N_Case_Statement then
5141             declare
5142                Case_Alt : Node_Id;
5143             begin
5144                Case_Alt := First_Non_Pragma (Alternatives (Last_Stm));
5145                while Present (Case_Alt) loop
5146                   Check_Statement_Sequence (Statements (Case_Alt));
5147                   Next_Non_Pragma (Case_Alt);
5148                end loop;
5149             end;
5150
5151             return;
5152
5153          --  Block statement, check its handled sequence of statements
5154
5155          elsif Kind = N_Block_Statement then
5156             declare
5157                Err1 : Boolean;
5158
5159             begin
5160                Check_Returns
5161                  (Handled_Statement_Sequence (Last_Stm), Mode, Err1);
5162
5163                if Err1 then
5164                   Err := True;
5165                end if;
5166
5167                return;
5168             end;
5169
5170          --  Loop statement. If there is an iteration scheme, we can definitely
5171          --  fall out of the loop. Similarly if there is an exit statement, we
5172          --  can fall out. In either case we need a following return.
5173
5174          elsif Kind = N_Loop_Statement then
5175             if Present (Iteration_Scheme (Last_Stm))
5176               or else Has_Exit (Entity (Identifier (Last_Stm)))
5177             then
5178                null;
5179
5180             --  A loop with no exit statement or iteration scheme is either
5181             --  an infinite loop, or it has some other exit (raise/return).
5182             --  In either case, no warning is required.
5183
5184             else
5185                return;
5186             end if;
5187
5188          --  Timed entry call, check entry call and delay alternatives
5189
5190          --  Note: in expanded code, the timed entry call has been converted
5191          --  to a set of expanded statements on which the check will work
5192          --  correctly in any case.
5193
5194          elsif Kind = N_Timed_Entry_Call then
5195             declare
5196                ECA : constant Node_Id := Entry_Call_Alternative (Last_Stm);
5197                DCA : constant Node_Id := Delay_Alternative      (Last_Stm);
5198
5199             begin
5200                --  If statement sequence of entry call alternative is missing,
5201                --  then we can definitely fall through, and we post the error
5202                --  message on the entry call alternative itself.
5203
5204                if No (Statements (ECA)) then
5205                   Last_Stm := ECA;
5206
5207                --  If statement sequence of delay alternative is missing, then
5208                --  we can definitely fall through, and we post the error
5209                --  message on the delay alternative itself.
5210
5211                --  Note: if both ECA and DCA are missing the return, then we
5212                --  post only one message, should be enough to fix the bugs.
5213                --  If not we will get a message next time on the DCA when the
5214                --  ECA is fixed!
5215
5216                elsif No (Statements (DCA)) then
5217                   Last_Stm := DCA;
5218
5219                --  Else check both statement sequences
5220
5221                else
5222                   Check_Statement_Sequence (Statements (ECA));
5223                   Check_Statement_Sequence (Statements (DCA));
5224                   return;
5225                end if;
5226             end;
5227
5228          --  Conditional entry call, check entry call and else part
5229
5230          --  Note: in expanded code, the conditional entry call has been
5231          --  converted to a set of expanded statements on which the check
5232          --  will work correctly in any case.
5233
5234          elsif Kind = N_Conditional_Entry_Call then
5235             declare
5236                ECA : constant Node_Id := Entry_Call_Alternative (Last_Stm);
5237
5238             begin
5239                --  If statement sequence of entry call alternative is missing,
5240                --  then we can definitely fall through, and we post the error
5241                --  message on the entry call alternative itself.
5242
5243                if No (Statements (ECA)) then
5244                   Last_Stm := ECA;
5245
5246                --  Else check statement sequence and else part
5247
5248                else
5249                   Check_Statement_Sequence (Statements (ECA));
5250                   Check_Statement_Sequence (Else_Statements (Last_Stm));
5251                   return;
5252                end if;
5253             end;
5254          end if;
5255
5256          --  If we fall through, issue appropriate message
5257
5258          if Mode = 'F' then
5259             if not Raise_Exception_Call then
5260                Error_Msg_N
5261                  ("?RETURN statement missing following this statement!",
5262                   Last_Stm);
5263                Error_Msg_N
5264                  ("\?Program_Error may be raised at run time!",
5265                   Last_Stm);
5266             end if;
5267
5268             --  Note: we set Err even though we have not issued a warning
5269             --  because we still have a case of a missing return. This is
5270             --  an extremely marginal case, probably will never be noticed
5271             --  but we might as well get it right.
5272
5273             Err := True;
5274
5275          --  Otherwise we have the case of a procedure marked No_Return
5276
5277          else
5278             if not Raise_Exception_Call then
5279                Error_Msg_N
5280                  ("?implied return after this statement " &
5281                   "will raise Program_Error",
5282                   Last_Stm);
5283                Error_Msg_NE
5284                  ("\?procedure & is marked as No_Return!",
5285                   Last_Stm, Proc);
5286             end if;
5287
5288             declare
5289                RE : constant Node_Id :=
5290                       Make_Raise_Program_Error (Sloc (Last_Stm),
5291                         Reason => PE_Implicit_Return);
5292             begin
5293                Insert_After (Last_Stm, RE);
5294                Analyze (RE);
5295             end;
5296          end if;
5297       end Check_Statement_Sequence;
5298
5299    --  Start of processing for Check_Returns
5300
5301    begin
5302       Err := False;
5303       Check_Statement_Sequence (Statements (HSS));
5304
5305       if Present (Exception_Handlers (HSS)) then
5306          Handler := First_Non_Pragma (Exception_Handlers (HSS));
5307          while Present (Handler) loop
5308             Check_Statement_Sequence (Statements (Handler));
5309             Next_Non_Pragma (Handler);
5310          end loop;
5311       end if;
5312    end Check_Returns;
5313
5314    ----------------------------
5315    -- Check_Subprogram_Order --
5316    ----------------------------
5317
5318    procedure Check_Subprogram_Order (N : Node_Id) is
5319
5320       function Subprogram_Name_Greater (S1, S2 : String) return Boolean;
5321       --  This is used to check if S1 > S2 in the sense required by this
5322       --  test, for example nameab < namec, but name2 < name10.
5323
5324       -----------------------------
5325       -- Subprogram_Name_Greater --
5326       -----------------------------
5327
5328       function Subprogram_Name_Greater (S1, S2 : String) return Boolean is
5329          L1, L2 : Positive;
5330          N1, N2 : Natural;
5331
5332       begin
5333          --  Remove trailing numeric parts
5334
5335          L1 := S1'Last;
5336          while S1 (L1) in '0' .. '9' loop
5337             L1 := L1 - 1;
5338          end loop;
5339
5340          L2 := S2'Last;
5341          while S2 (L2) in '0' .. '9' loop
5342             L2 := L2 - 1;
5343          end loop;
5344
5345          --  If non-numeric parts non-equal, that's decisive
5346
5347          if S1 (S1'First .. L1) < S2 (S2'First .. L2) then
5348             return False;
5349
5350          elsif S1 (S1'First .. L1) > S2 (S2'First .. L2) then
5351             return True;
5352
5353          --  If non-numeric parts equal, compare suffixed numeric parts. Note
5354          --  that a missing suffix is treated as numeric zero in this test.
5355
5356          else
5357             N1 := 0;
5358             while L1 < S1'Last loop
5359                L1 := L1 + 1;
5360                N1 := N1 * 10 + Character'Pos (S1 (L1)) - Character'Pos ('0');
5361             end loop;
5362
5363             N2 := 0;
5364             while L2 < S2'Last loop
5365                L2 := L2 + 1;
5366                N2 := N2 * 10 + Character'Pos (S2 (L2)) - Character'Pos ('0');
5367             end loop;
5368
5369             return N1 > N2;
5370          end if;
5371       end Subprogram_Name_Greater;
5372
5373    --  Start of processing for Check_Subprogram_Order
5374
5375    begin
5376       --  Check body in alpha order if this is option
5377
5378       if Style_Check
5379         and then Style_Check_Order_Subprograms
5380         and then Nkind (N) = N_Subprogram_Body
5381         and then Comes_From_Source (N)
5382         and then In_Extended_Main_Source_Unit (N)
5383       then
5384          declare
5385             LSN : String_Ptr
5386                     renames Scope_Stack.Table
5387                               (Scope_Stack.Last).Last_Subprogram_Name;
5388
5389             Body_Id : constant Entity_Id :=
5390                         Defining_Entity (Specification (N));
5391
5392          begin
5393             Get_Decoded_Name_String (Chars (Body_Id));
5394
5395             if LSN /= null then
5396                if Subprogram_Name_Greater
5397                     (LSN.all, Name_Buffer (1 .. Name_Len))
5398                then
5399                   Style.Subprogram_Not_In_Alpha_Order (Body_Id);
5400                end if;
5401
5402                Free (LSN);
5403             end if;
5404
5405             LSN := new String'(Name_Buffer (1 .. Name_Len));
5406          end;
5407       end if;
5408    end Check_Subprogram_Order;
5409
5410    ------------------------------
5411    -- Check_Subtype_Conformant --
5412    ------------------------------
5413
5414    procedure Check_Subtype_Conformant
5415      (New_Id                   : Entity_Id;
5416       Old_Id                   : Entity_Id;
5417       Err_Loc                  : Node_Id := Empty;
5418       Skip_Controlling_Formals : Boolean := False)
5419    is
5420       Result : Boolean;
5421       pragma Warnings (Off, Result);
5422    begin
5423       Check_Conformance
5424         (New_Id, Old_Id, Subtype_Conformant, True, Result, Err_Loc,
5425          Skip_Controlling_Formals => Skip_Controlling_Formals);
5426    end Check_Subtype_Conformant;
5427
5428    ---------------------------
5429    -- Check_Type_Conformant --
5430    ---------------------------
5431
5432    procedure Check_Type_Conformant
5433      (New_Id  : Entity_Id;
5434       Old_Id  : Entity_Id;
5435       Err_Loc : Node_Id := Empty)
5436    is
5437       Result : Boolean;
5438       pragma Warnings (Off, Result);
5439    begin
5440       Check_Conformance
5441         (New_Id, Old_Id, Type_Conformant, True, Result, Err_Loc);
5442    end Check_Type_Conformant;
5443
5444    ---------------------------
5445    -- Can_Override_Operator --
5446    ---------------------------
5447
5448    function Can_Override_Operator (Subp : Entity_Id) return Boolean is
5449       Typ : Entity_Id;
5450    begin
5451       if Nkind (Subp) /= N_Defining_Operator_Symbol then
5452          return False;
5453
5454       else
5455          Typ := Base_Type (Etype (First_Formal (Subp)));
5456
5457          return Operator_Matches_Spec (Subp, Subp)
5458            and then Scope (Subp) = Scope (Typ)
5459            and then not Is_Class_Wide_Type (Typ);
5460       end if;
5461    end Can_Override_Operator;
5462
5463    ----------------------
5464    -- Conforming_Types --
5465    ----------------------
5466
5467    function Conforming_Types
5468      (T1       : Entity_Id;
5469       T2       : Entity_Id;
5470       Ctype    : Conformance_Type;
5471       Get_Inst : Boolean := False) return Boolean
5472    is
5473       Type_1 : Entity_Id := T1;
5474       Type_2 : Entity_Id := T2;
5475       Are_Anonymous_Access_To_Subprogram_Types : Boolean := False;
5476
5477       function Base_Types_Match (T1, T2 : Entity_Id) return Boolean;
5478       --  If neither T1 nor T2 are generic actual types, or if they are in
5479       --  different scopes (e.g. parent and child instances), then verify that
5480       --  the base types are equal. Otherwise T1 and T2 must be on the same
5481       --  subtype chain. The whole purpose of this procedure is to prevent
5482       --  spurious ambiguities in an instantiation that may arise if two
5483       --  distinct generic types are instantiated with the same actual.
5484
5485       function Find_Designated_Type (T : Entity_Id) return Entity_Id;
5486       --  An access parameter can designate an incomplete type. If the
5487       --  incomplete type is the limited view of a type from a limited_
5488       --  with_clause, check whether the non-limited view is available. If
5489       --  it is a (non-limited) incomplete type, get the full view.
5490
5491       function Matches_Limited_With_View (T1, T2 : Entity_Id) return Boolean;
5492       --  Returns True if and only if either T1 denotes a limited view of T2
5493       --  or T2 denotes a limited view of T1. This can arise when the limited
5494       --  with view of a type is used in a subprogram declaration and the
5495       --  subprogram body is in the scope of a regular with clause for the
5496       --  same unit. In such a case, the two type entities can be considered
5497       --  identical for purposes of conformance checking.
5498
5499       ----------------------
5500       -- Base_Types_Match --
5501       ----------------------
5502
5503       function Base_Types_Match (T1, T2 : Entity_Id) return Boolean is
5504       begin
5505          if T1 = T2 then
5506             return True;
5507
5508          elsif Base_Type (T1) = Base_Type (T2) then
5509
5510             --  The following is too permissive. A more precise test should
5511             --  check that the generic actual is an ancestor subtype of the
5512             --  other ???.
5513
5514             return not Is_Generic_Actual_Type (T1)
5515               or else not Is_Generic_Actual_Type (T2)
5516               or else Scope (T1) /= Scope (T2);
5517
5518          else
5519             return False;
5520          end if;
5521       end Base_Types_Match;
5522
5523       --------------------------
5524       -- Find_Designated_Type --
5525       --------------------------
5526
5527       function Find_Designated_Type (T : Entity_Id) return Entity_Id is
5528          Desig : Entity_Id;
5529
5530       begin
5531          Desig := Directly_Designated_Type (T);
5532
5533          if Ekind (Desig) = E_Incomplete_Type then
5534
5535             --  If regular incomplete type, get full view if available
5536
5537             if Present (Full_View (Desig)) then
5538                Desig := Full_View (Desig);
5539
5540             --  If limited view of a type, get non-limited view if available,
5541             --  and check again for a regular incomplete type.
5542
5543             elsif Present (Non_Limited_View (Desig)) then
5544                Desig := Get_Full_View (Non_Limited_View (Desig));
5545             end if;
5546          end if;
5547
5548          return Desig;
5549       end Find_Designated_Type;
5550
5551       -------------------------------
5552       -- Matches_Limited_With_View --
5553       -------------------------------
5554
5555       function Matches_Limited_With_View (T1, T2 : Entity_Id) return Boolean is
5556       begin
5557          --  In some cases a type imported through a limited_with clause, and
5558          --  its nonlimited view are both visible, for example in an anonymous
5559          --  access-to-class-wide type in a formal. Both entities designate the
5560          --  same type.
5561
5562          if From_With_Type (T1)
5563            and then T2 = Available_View (T1)
5564          then
5565             return True;
5566
5567          elsif From_With_Type (T2)
5568            and then T1 = Available_View (T2)
5569          then
5570             return True;
5571
5572          else
5573             return False;
5574          end if;
5575       end Matches_Limited_With_View;
5576
5577    --  Start of processing for Conforming_Types
5578
5579    begin
5580       --  The context is an instance association for a formal
5581       --  access-to-subprogram type; the formal parameter types require
5582       --  mapping because they may denote other formal parameters of the
5583       --  generic unit.
5584
5585       if Get_Inst then
5586          Type_1 := Get_Instance_Of (T1);
5587          Type_2 := Get_Instance_Of (T2);
5588       end if;
5589
5590       --  If one of the types is a view of the other introduced by a limited
5591       --  with clause, treat these as conforming for all purposes.
5592
5593       if Matches_Limited_With_View (T1, T2) then
5594          return True;
5595
5596       elsif Base_Types_Match (Type_1, Type_2) then
5597          return Ctype <= Mode_Conformant
5598            or else Subtypes_Statically_Match (Type_1, Type_2);
5599
5600       elsif Is_Incomplete_Or_Private_Type (Type_1)
5601         and then Present (Full_View (Type_1))
5602         and then Base_Types_Match (Full_View (Type_1), Type_2)
5603       then
5604          return Ctype <= Mode_Conformant
5605            or else Subtypes_Statically_Match (Full_View (Type_1), Type_2);
5606
5607       elsif Ekind (Type_2) = E_Incomplete_Type
5608         and then Present (Full_View (Type_2))
5609         and then Base_Types_Match (Type_1, Full_View (Type_2))
5610       then
5611          return Ctype <= Mode_Conformant
5612            or else Subtypes_Statically_Match (Type_1, Full_View (Type_2));
5613
5614       elsif Is_Private_Type (Type_2)
5615         and then In_Instance
5616         and then Present (Full_View (Type_2))
5617         and then Base_Types_Match (Type_1, Full_View (Type_2))
5618       then
5619          return Ctype <= Mode_Conformant
5620            or else Subtypes_Statically_Match (Type_1, Full_View (Type_2));
5621       end if;
5622
5623       --  Ada 2005 (AI-254): Anonymous access-to-subprogram types must be
5624       --  treated recursively because they carry a signature.
5625
5626       Are_Anonymous_Access_To_Subprogram_Types :=
5627         Ekind (Type_1) = Ekind (Type_2)
5628           and then
5629             (Ekind (Type_1) = E_Anonymous_Access_Subprogram_Type
5630              or else
5631                Ekind (Type_1) = E_Anonymous_Access_Protected_Subprogram_Type);
5632
5633       --  Test anonymous access type case. For this case, static subtype
5634       --  matching is required for mode conformance (RM 6.3.1(15)). We check
5635       --  the base types because we may have built internal subtype entities
5636       --  to handle null-excluding types (see Process_Formals).
5637
5638       if (Ekind (Base_Type (Type_1)) = E_Anonymous_Access_Type
5639             and then
5640           Ekind (Base_Type (Type_2)) = E_Anonymous_Access_Type)
5641         or else Are_Anonymous_Access_To_Subprogram_Types -- Ada 2005 (AI-254)
5642       then
5643          declare
5644             Desig_1 : Entity_Id;
5645             Desig_2 : Entity_Id;
5646
5647          begin
5648             --  In Ada2005, access constant indicators must match for
5649             --  subtype conformance.
5650
5651             if Ada_Version >= Ada_2005
5652               and then Ctype >= Subtype_Conformant
5653               and then
5654                 Is_Access_Constant (Type_1) /= Is_Access_Constant (Type_2)
5655             then
5656                return False;
5657             end if;
5658
5659             Desig_1 := Find_Designated_Type (Type_1);
5660             Desig_2 := Find_Designated_Type (Type_2);
5661
5662             --  If the context is an instance association for a formal
5663             --  access-to-subprogram type; formal access parameter designated
5664             --  types require mapping because they may denote other formal
5665             --  parameters of the generic unit.
5666
5667             if Get_Inst then
5668                Desig_1 := Get_Instance_Of (Desig_1);
5669                Desig_2 := Get_Instance_Of (Desig_2);
5670             end if;
5671
5672             --  It is possible for a Class_Wide_Type to be introduced for an
5673             --  incomplete type, in which case there is a separate class_ wide
5674             --  type for the full view. The types conform if their Etypes
5675             --  conform, i.e. one may be the full view of the other. This can
5676             --  only happen in the context of an access parameter, other uses
5677             --  of an incomplete Class_Wide_Type are illegal.
5678
5679             if Is_Class_Wide_Type (Desig_1)
5680                  and then
5681                Is_Class_Wide_Type (Desig_2)
5682             then
5683                return
5684                  Conforming_Types
5685                    (Etype (Base_Type (Desig_1)),
5686                     Etype (Base_Type (Desig_2)), Ctype);
5687
5688             elsif Are_Anonymous_Access_To_Subprogram_Types then
5689                if Ada_Version < Ada_2005 then
5690                   return Ctype = Type_Conformant
5691                     or else
5692                       Subtypes_Statically_Match (Desig_1, Desig_2);
5693
5694                --  We must check the conformance of the signatures themselves
5695
5696                else
5697                   declare
5698                      Conformant : Boolean;
5699                   begin
5700                      Check_Conformance
5701                        (Desig_1, Desig_2, Ctype, False, Conformant);
5702                      return Conformant;
5703                   end;
5704                end if;
5705
5706             else
5707                return Base_Type (Desig_1) = Base_Type (Desig_2)
5708                 and then (Ctype = Type_Conformant
5709                             or else
5710                           Subtypes_Statically_Match (Desig_1, Desig_2));
5711             end if;
5712          end;
5713
5714       --  Otherwise definitely no match
5715
5716       else
5717          if ((Ekind (Type_1) = E_Anonymous_Access_Type
5718                and then Is_Access_Type (Type_2))
5719             or else (Ekind (Type_2) = E_Anonymous_Access_Type
5720                        and then Is_Access_Type (Type_1)))
5721            and then
5722              Conforming_Types
5723                (Designated_Type (Type_1), Designated_Type (Type_2), Ctype)
5724          then
5725             May_Hide_Profile := True;
5726          end if;
5727
5728          return False;
5729       end if;
5730    end Conforming_Types;
5731
5732    --------------------------
5733    -- Create_Extra_Formals --
5734    --------------------------
5735
5736    procedure Create_Extra_Formals (E : Entity_Id) is
5737       Formal      : Entity_Id;
5738       First_Extra : Entity_Id := Empty;
5739       Last_Extra  : Entity_Id;
5740       Formal_Type : Entity_Id;
5741       P_Formal    : Entity_Id := Empty;
5742
5743       function Add_Extra_Formal
5744         (Assoc_Entity : Entity_Id;
5745          Typ          : Entity_Id;
5746          Scope        : Entity_Id;
5747          Suffix       : String) return Entity_Id;
5748       --  Add an extra formal to the current list of formals and extra formals.
5749       --  The extra formal is added to the end of the list of extra formals,
5750       --  and also returned as the result. These formals are always of mode IN.
5751       --  The new formal has the type Typ, is declared in Scope, and its name
5752       --  is given by a concatenation of the name of Assoc_Entity and Suffix.
5753       --  The following suffixes are currently used. They should not be changed
5754       --  without coordinating with CodePeer, which makes use of these to
5755       --  provide better messages.
5756
5757       --  O denotes the Constrained bit.
5758       --  L denotes the accessibility level.
5759       --  BIP_xxx denotes an extra formal for a build-in-place function. See
5760       --  the full list in exp_ch6.BIP_Formal_Kind.
5761
5762       ----------------------
5763       -- Add_Extra_Formal --
5764       ----------------------
5765
5766       function Add_Extra_Formal
5767         (Assoc_Entity : Entity_Id;
5768          Typ          : Entity_Id;
5769          Scope        : Entity_Id;
5770          Suffix       : String) return Entity_Id
5771       is
5772          EF : constant Entity_Id :=
5773                 Make_Defining_Identifier (Sloc (Assoc_Entity),
5774                   Chars  => New_External_Name (Chars (Assoc_Entity),
5775                                                Suffix => Suffix));
5776
5777       begin
5778          --  A little optimization. Never generate an extra formal for the
5779          --  _init operand of an initialization procedure, since it could
5780          --  never be used.
5781
5782          if Chars (Formal) = Name_uInit then
5783             return Empty;
5784          end if;
5785
5786          Set_Ekind           (EF, E_In_Parameter);
5787          Set_Actual_Subtype  (EF, Typ);
5788          Set_Etype           (EF, Typ);
5789          Set_Scope           (EF, Scope);
5790          Set_Mechanism       (EF, Default_Mechanism);
5791          Set_Formal_Validity (EF);
5792
5793          if No (First_Extra) then
5794             First_Extra := EF;
5795             Set_Extra_Formals (Scope, First_Extra);
5796          end if;
5797
5798          if Present (Last_Extra) then
5799             Set_Extra_Formal (Last_Extra, EF);
5800          end if;
5801
5802          Last_Extra := EF;
5803
5804          return EF;
5805       end Add_Extra_Formal;
5806
5807    --  Start of processing for Create_Extra_Formals
5808
5809    begin
5810       --  We never generate extra formals if expansion is not active
5811       --  because we don't need them unless we are generating code.
5812
5813       if not Expander_Active then
5814          return;
5815       end if;
5816
5817       --  If this is a derived subprogram then the subtypes of the parent
5818       --  subprogram's formal parameters will be used to determine the need
5819       --  for extra formals.
5820
5821       if Is_Overloadable (E) and then Present (Alias (E)) then
5822          P_Formal := First_Formal (Alias (E));
5823       end if;
5824
5825       Last_Extra := Empty;
5826       Formal := First_Formal (E);
5827       while Present (Formal) loop
5828          Last_Extra := Formal;
5829          Next_Formal (Formal);
5830       end loop;
5831
5832       --  If Extra_formals were already created, don't do it again. This
5833       --  situation may arise for subprogram types created as part of
5834       --  dispatching calls (see Expand_Dispatching_Call)
5835
5836       if Present (Last_Extra) and then
5837         Present (Extra_Formal (Last_Extra))
5838       then
5839          return;
5840       end if;
5841
5842       --  If the subprogram is a predefined dispatching subprogram then don't
5843       --  generate any extra constrained or accessibility level formals. In
5844       --  general we suppress these for internal subprograms (by not calling
5845       --  Freeze_Subprogram and Create_Extra_Formals at all), but internally
5846       --  generated stream attributes do get passed through because extra
5847       --  build-in-place formals are needed in some cases (limited 'Input).
5848
5849       if Is_Predefined_Internal_Operation (E) then
5850          goto Test_For_BIP_Extras;
5851       end if;
5852
5853       Formal := First_Formal (E);
5854       while Present (Formal) loop
5855
5856          --  Create extra formal for supporting the attribute 'Constrained.
5857          --  The case of a private type view without discriminants also
5858          --  requires the extra formal if the underlying type has defaulted
5859          --  discriminants.
5860
5861          if Ekind (Formal) /= E_In_Parameter then
5862             if Present (P_Formal) then
5863                Formal_Type := Etype (P_Formal);
5864             else
5865                Formal_Type := Etype (Formal);
5866             end if;
5867
5868             --  Do not produce extra formals for Unchecked_Union parameters.
5869             --  Jump directly to the end of the loop.
5870
5871             if Is_Unchecked_Union (Base_Type (Formal_Type)) then
5872                goto Skip_Extra_Formal_Generation;
5873             end if;
5874
5875             if not Has_Discriminants (Formal_Type)
5876               and then Ekind (Formal_Type) in Private_Kind
5877               and then Present (Underlying_Type (Formal_Type))
5878             then
5879                Formal_Type := Underlying_Type (Formal_Type);
5880             end if;
5881
5882             --  Suppress the extra formal if formal's subtype is constrained or
5883             --  indefinite, or we're compiling for Ada 2012 and the underlying
5884             --  type is tagged and limited. In Ada 2012, a limited tagged type
5885             --  can have defaulted discriminants, but 'Constrained is required
5886             --  to return True, so the formal is never needed (see AI05-0214).
5887             --  Note that this ensures consistency of calling sequences for
5888             --  dispatching operations when some types in a class have defaults
5889             --  on discriminants and others do not (and requiring the extra
5890             --  formal would introduce distributed overhead).
5891
5892             if Has_Discriminants (Formal_Type)
5893               and then not Is_Constrained (Formal_Type)
5894               and then not Is_Indefinite_Subtype (Formal_Type)
5895               and then (Ada_Version < Ada_2012
5896                          or else
5897                            not (Is_Tagged_Type (Underlying_Type (Formal_Type))
5898                                  and then Is_Limited_Type (Formal_Type)))
5899             then
5900                Set_Extra_Constrained
5901                  (Formal, Add_Extra_Formal (Formal, Standard_Boolean, E, "O"));
5902             end if;
5903          end if;
5904
5905          --  Create extra formal for supporting accessibility checking. This
5906          --  is done for both anonymous access formals and formals of named
5907          --  access types that are marked as controlling formals. The latter
5908          --  case can occur when Expand_Dispatching_Call creates a subprogram
5909          --  type and substitutes the types of access-to-class-wide actuals
5910          --  for the anonymous access-to-specific-type of controlling formals.
5911          --  Base_Type is applied because in cases where there is a null
5912          --  exclusion the formal may have an access subtype.
5913
5914          --  This is suppressed if we specifically suppress accessibility
5915          --  checks at the package level for either the subprogram, or the
5916          --  package in which it resides. However, we do not suppress it
5917          --  simply if the scope has accessibility checks suppressed, since
5918          --  this could cause trouble when clients are compiled with a
5919          --  different suppression setting. The explicit checks at the
5920          --  package level are safe from this point of view.
5921
5922          if (Ekind (Base_Type (Etype (Formal))) = E_Anonymous_Access_Type
5923               or else (Is_Controlling_Formal (Formal)
5924                         and then Is_Access_Type (Base_Type (Etype (Formal)))))
5925            and then not
5926              (Explicit_Suppress (E, Accessibility_Check)
5927                or else
5928               Explicit_Suppress (Scope (E), Accessibility_Check))
5929            and then
5930              (No (P_Formal)
5931                or else Present (Extra_Accessibility (P_Formal)))
5932          then
5933             Set_Extra_Accessibility
5934               (Formal, Add_Extra_Formal (Formal, Standard_Natural, E, "L"));
5935          end if;
5936
5937          --  This label is required when skipping extra formal generation for
5938          --  Unchecked_Union parameters.
5939
5940          <<Skip_Extra_Formal_Generation>>
5941
5942          if Present (P_Formal) then
5943             Next_Formal (P_Formal);
5944          end if;
5945
5946          Next_Formal (Formal);
5947       end loop;
5948
5949       <<Test_For_BIP_Extras>>
5950
5951       --  Ada 2005 (AI-318-02): In the case of build-in-place functions, add
5952       --  appropriate extra formals. See type Exp_Ch6.BIP_Formal_Kind.
5953
5954       if Ada_Version >= Ada_2005 and then Is_Build_In_Place_Function (E) then
5955          declare
5956             Result_Subt : constant Entity_Id := Etype (E);
5957
5958             Discard : Entity_Id;
5959             pragma Warnings (Off, Discard);
5960
5961          begin
5962             --  In the case of functions with unconstrained result subtypes,
5963             --  add a 4-state formal indicating whether the return object is
5964             --  allocated by the caller (1), or should be allocated by the
5965             --  callee on the secondary stack (2), in the global heap (3), or
5966             --  in a user-defined storage pool (4). For the moment we just use
5967             --  Natural for the type of this formal. Note that this formal
5968             --  isn't usually needed in the case where the result subtype is
5969             --  constrained, but it is needed when the function has a tagged
5970             --  result, because generally such functions can be called in a
5971             --  dispatching context and such calls must be handled like calls
5972             --  to a class-wide function.
5973
5974             if not Is_Constrained (Underlying_Type (Result_Subt))
5975               or else Is_Tagged_Type (Underlying_Type (Result_Subt))
5976             then
5977                Discard :=
5978                  Add_Extra_Formal
5979                    (E, Standard_Natural,
5980                     E, BIP_Formal_Suffix (BIP_Alloc_Form));
5981             end if;
5982
5983             --  For functions whose result type has controlled parts, we have
5984             --  an extra formal of type System.Finalization_Implementation.
5985             --  Finalizable_Ptr_Ptr. That is, we are passing a pointer to a
5986             --  finalization list (which is itself a pointer). This extra
5987             --  formal is then passed along to Move_Final_List in case of
5988             --  successful completion of a return statement. We cannot pass an
5989             --  'in out' parameter, because we need to update the finalization
5990             --  list during an abort-deferred region, rather than using
5991             --  copy-back after the function returns. This is true even if we
5992             --  are able to get away with having 'in out' parameters, which are
5993             --  normally illegal for functions. This formal is also needed when
5994             --  the function has a tagged result.
5995
5996             if Needs_BIP_Final_List (E) then
5997                Discard :=
5998                  Add_Extra_Formal
5999                    (E, RTE (RE_Finalizable_Ptr_Ptr),
6000                     E, BIP_Formal_Suffix (BIP_Final_List));
6001             end if;
6002
6003             --  If the result type contains tasks, we have two extra formals:
6004             --  the master of the tasks to be created, and the caller's
6005             --  activation chain.
6006
6007             if Has_Task (Result_Subt) then
6008                Discard :=
6009                  Add_Extra_Formal
6010                    (E, RTE (RE_Master_Id),
6011                     E, BIP_Formal_Suffix (BIP_Master));
6012                Discard :=
6013                  Add_Extra_Formal
6014                    (E, RTE (RE_Activation_Chain_Access),
6015                     E, BIP_Formal_Suffix (BIP_Activation_Chain));
6016             end if;
6017
6018             --  All build-in-place functions get an extra formal that will be
6019             --  passed the address of the return object within the caller.
6020
6021             declare
6022                Formal_Type : constant Entity_Id :=
6023                                Create_Itype
6024                                  (E_Anonymous_Access_Type, E,
6025                                   Scope_Id => Scope (E));
6026             begin
6027                Set_Directly_Designated_Type (Formal_Type, Result_Subt);
6028                Set_Etype (Formal_Type, Formal_Type);
6029                Set_Depends_On_Private
6030                  (Formal_Type, Has_Private_Component (Formal_Type));
6031                Set_Is_Public (Formal_Type, Is_Public (Scope (Formal_Type)));
6032                Set_Is_Access_Constant (Formal_Type, False);
6033
6034                --  Ada 2005 (AI-50217): Propagate the attribute that indicates
6035                --  the designated type comes from the limited view (for
6036                --  back-end purposes).
6037
6038                Set_From_With_Type (Formal_Type, From_With_Type (Result_Subt));
6039
6040                Layout_Type (Formal_Type);
6041
6042                Discard :=
6043                  Add_Extra_Formal
6044                    (E, Formal_Type, E, BIP_Formal_Suffix (BIP_Object_Access));
6045             end;
6046          end;
6047       end if;
6048    end Create_Extra_Formals;
6049
6050    -----------------------------
6051    -- Enter_Overloaded_Entity --
6052    -----------------------------
6053
6054    procedure Enter_Overloaded_Entity (S : Entity_Id) is
6055       E   : Entity_Id := Current_Entity_In_Scope (S);
6056       C_E : Entity_Id := Current_Entity (S);
6057
6058    begin
6059       if Present (E) then
6060          Set_Has_Homonym (E);
6061          Set_Has_Homonym (S);
6062       end if;
6063
6064       Set_Is_Immediately_Visible (S);
6065       Set_Scope (S, Current_Scope);
6066
6067       --  Chain new entity if front of homonym in current scope, so that
6068       --  homonyms are contiguous.
6069
6070       if Present (E)
6071         and then E /= C_E
6072       then
6073          while Homonym (C_E) /= E loop
6074             C_E := Homonym (C_E);
6075          end loop;
6076
6077          Set_Homonym (C_E, S);
6078
6079       else
6080          E := C_E;
6081          Set_Current_Entity (S);
6082       end if;
6083
6084       Set_Homonym (S, E);
6085
6086       Append_Entity (S, Current_Scope);
6087       Set_Public_Status (S);
6088
6089       if Debug_Flag_E then
6090          Write_Str ("New overloaded entity chain: ");
6091          Write_Name (Chars (S));
6092
6093          E := S;
6094          while Present (E) loop
6095             Write_Str (" "); Write_Int (Int (E));
6096             E := Homonym (E);
6097          end loop;
6098
6099          Write_Eol;
6100       end if;
6101
6102       --  Generate warning for hiding
6103
6104       if Warn_On_Hiding
6105         and then Comes_From_Source (S)
6106         and then In_Extended_Main_Source_Unit (S)
6107       then
6108          E := S;
6109          loop
6110             E := Homonym (E);
6111             exit when No (E);
6112
6113             --  Warn unless genuine overloading. Do not emit warning on
6114             --  hiding predefined operators in Standard (these are either an
6115             --  (artifact of our implicit declarations, or simple noise) but
6116             --  keep warning on a operator defined on a local subtype, because
6117             --  of the real danger that different operators may be applied in
6118             --  various parts of the program.
6119
6120             --  Note that if E and S have the same scope, there is never any
6121             --  hiding. Either the two conflict, and the program is illegal,
6122             --  or S is overriding an implicit inherited subprogram.
6123
6124             if Scope (E) /= Scope (S)
6125                   and then (not Is_Overloadable (E)
6126                              or else Subtype_Conformant (E, S))
6127                   and then (Is_Immediately_Visible (E)
6128                               or else
6129                             Is_Potentially_Use_Visible (S))
6130             then
6131                if Scope (E) /= Standard_Standard then
6132                   Error_Msg_Sloc := Sloc (E);
6133                   Error_Msg_N ("declaration of & hides one#?", S);
6134
6135                elsif Nkind (S) = N_Defining_Operator_Symbol
6136                  and then
6137                    Scope (Base_Type (Etype (First_Formal (S)))) /= Scope (S)
6138                then
6139                   Error_Msg_N
6140                     ("declaration of & hides predefined operator?", S);
6141                end if;
6142             end if;
6143          end loop;
6144       end if;
6145    end Enter_Overloaded_Entity;
6146
6147    -----------------------------
6148    -- Check_Untagged_Equality --
6149    -----------------------------
6150
6151    procedure Check_Untagged_Equality (Eq_Op : Entity_Id) is
6152       Typ      : constant Entity_Id := Etype (First_Formal (Eq_Op));
6153       Decl     : constant Node_Id   := Unit_Declaration_Node (Eq_Op);
6154       Obj_Decl : Node_Id;
6155
6156    begin
6157       if Nkind (Decl) = N_Subprogram_Declaration
6158         and then Is_Record_Type (Typ)
6159         and then not Is_Tagged_Type (Typ)
6160       then
6161          --  If the type is not declared in a package, or if we are in the
6162          --  body of the package or in some other scope, the new operation is
6163          --  not primitive, and therefore legal, though suspicious. If the
6164          --  type is a generic actual (sub)type, the operation is not primitive
6165          --  either because the base type is declared elsewhere.
6166
6167          if Is_Frozen (Typ) then
6168             if Ekind (Scope (Typ)) /= E_Package
6169               or else Scope (Typ) /= Current_Scope
6170             then
6171                null;
6172
6173             elsif Is_Generic_Actual_Type (Typ) then
6174                null;
6175
6176             elsif In_Package_Body (Scope (Typ)) then
6177                Error_Msg_NE
6178                  ("equality operator must be declared "
6179                    & "before type& is frozen", Eq_Op, Typ);
6180                Error_Msg_N
6181                  ("\move declaration to package spec", Eq_Op);
6182
6183             else
6184                Error_Msg_NE
6185                  ("equality operator must be declared "
6186                    & "before type& is frozen", Eq_Op, Typ);
6187
6188                Obj_Decl := Next (Parent (Typ));
6189                while Present (Obj_Decl)
6190                  and then Obj_Decl /= Decl
6191                loop
6192                   if Nkind (Obj_Decl) = N_Object_Declaration
6193                     and then Etype (Defining_Identifier (Obj_Decl)) = Typ
6194                   then
6195                      Error_Msg_NE ("type& is frozen by declaration?",
6196                         Obj_Decl, Typ);
6197                      Error_Msg_N
6198                        ("\an equality operator cannot be declared after this "
6199                          & "point ('R'M 4.5.2 (9.8)) (Ada 2012))?", Obj_Decl);
6200                      exit;
6201                   end if;
6202
6203                   Next (Obj_Decl);
6204                end loop;
6205             end if;
6206
6207          elsif not In_Same_List (Parent (Typ), Decl)
6208            and then not Is_Limited_Type (Typ)
6209          then
6210
6211             --  This makes it illegal to have a primitive equality declared in
6212             --  the private part if the type is visible.
6213
6214             Error_Msg_N ("equality operator appears too late", Eq_Op);
6215          end if;
6216       end if;
6217    end Check_Untagged_Equality;
6218
6219    -----------------------------
6220    -- Find_Corresponding_Spec --
6221    -----------------------------
6222
6223    function Find_Corresponding_Spec
6224      (N          : Node_Id;
6225       Post_Error : Boolean := True) return Entity_Id
6226    is
6227       Spec       : constant Node_Id   := Specification (N);
6228       Designator : constant Entity_Id := Defining_Entity (Spec);
6229
6230       E : Entity_Id;
6231
6232    begin
6233       E := Current_Entity (Designator);
6234       while Present (E) loop
6235
6236          --  We are looking for a matching spec. It must have the same scope,
6237          --  and the same name, and either be type conformant, or be the case
6238          --  of a library procedure spec and its body (which belong to one
6239          --  another regardless of whether they are type conformant or not).
6240
6241          if Scope (E) = Current_Scope then
6242             if Current_Scope = Standard_Standard
6243               or else (Ekind (E) = Ekind (Designator)
6244                          and then Type_Conformant (E, Designator))
6245             then
6246                --  Within an instantiation, we know that spec and body are
6247                --  subtype conformant, because they were subtype conformant
6248                --  in the generic. We choose the subtype-conformant entity
6249                --  here as well, to resolve spurious ambiguities in the
6250                --  instance that were not present in the generic (i.e. when
6251                --  two different types are given the same actual). If we are
6252                --  looking for a spec to match a body, full conformance is
6253                --  expected.
6254
6255                if In_Instance then
6256                   Set_Convention (Designator, Convention (E));
6257
6258                   if Nkind (N) = N_Subprogram_Body
6259                     and then Present (Homonym (E))
6260                     and then not Fully_Conformant (Designator, E)
6261                   then
6262                      goto Next_Entity;
6263
6264                   elsif not Subtype_Conformant (Designator, E) then
6265                      goto Next_Entity;
6266                   end if;
6267                end if;
6268
6269                if not Has_Completion (E) then
6270                   if Nkind (N) /= N_Subprogram_Body_Stub then
6271                      Set_Corresponding_Spec (N, E);
6272                   end if;
6273
6274                   Set_Has_Completion (E);
6275                   return E;
6276
6277                elsif Nkind (Parent (N)) = N_Subunit then
6278
6279                   --  If this is the proper body of a subunit, the completion
6280                   --  flag is set when analyzing the stub.
6281
6282                   return E;
6283
6284                --  If E is an internal function with a controlling result
6285                --  that was created for an operation inherited by a null
6286                --  extension, it may be overridden by a body without a previous
6287                --  spec (one more reason why these should be shunned). In that
6288                --  case remove the generated body if present, because the
6289                --  current one is the explicit overriding.
6290
6291                elsif Ekind (E) = E_Function
6292                  and then Ada_Version >= Ada_2005
6293                  and then not Comes_From_Source (E)
6294                  and then Has_Controlling_Result (E)
6295                  and then Is_Null_Extension (Etype (E))
6296                  and then Comes_From_Source (Spec)
6297                then
6298                   Set_Has_Completion (E, False);
6299
6300                   if Expander_Active
6301                     and then Nkind (Parent (E)) = N_Function_Specification
6302                   then
6303                      Remove
6304                        (Unit_Declaration_Node
6305                           (Corresponding_Body (Unit_Declaration_Node (E))));
6306
6307                      return E;
6308
6309                   --  If expansion is disabled, or if the wrapper function has
6310                   --  not been generated yet, this a late body overriding an
6311                   --  inherited operation, or it is an overriding by some other
6312                   --  declaration before the controlling result is frozen. In
6313                   --  either case this is a declaration of a new entity.
6314
6315                   else
6316                      return Empty;
6317                   end if;
6318
6319                --  If the body already exists, then this is an error unless
6320                --  the previous declaration is the implicit declaration of a
6321                --  derived subprogram, or this is a spurious overloading in an
6322                --  instance.
6323
6324                elsif No (Alias (E))
6325                  and then not Is_Intrinsic_Subprogram (E)
6326                  and then not In_Instance
6327                  and then Post_Error
6328                then
6329                   Error_Msg_Sloc := Sloc (E);
6330
6331                   if Is_Imported (E) then
6332                      Error_Msg_NE
6333                       ("body not allowed for imported subprogram & declared#",
6334                         N, E);
6335                   else
6336                      Error_Msg_NE ("duplicate body for & declared#", N, E);
6337                   end if;
6338                end if;
6339
6340             --  Child units cannot be overloaded, so a conformance mismatch
6341             --  between body and a previous spec is an error.
6342
6343             elsif Is_Child_Unit (E)
6344               and then
6345                 Nkind (Unit_Declaration_Node (Designator)) = N_Subprogram_Body
6346               and then
6347                 Nkind (Parent (Unit_Declaration_Node (Designator))) =
6348                   N_Compilation_Unit
6349               and then Post_Error
6350             then
6351                Error_Msg_N
6352                  ("body of child unit does not match previous declaration", N);
6353             end if;
6354          end if;
6355
6356          <<Next_Entity>>
6357             E := Homonym (E);
6358       end loop;
6359
6360       --  On exit, we know that no previous declaration of subprogram exists
6361
6362       return Empty;
6363    end Find_Corresponding_Spec;
6364
6365    ----------------------
6366    -- Fully_Conformant --
6367    ----------------------
6368
6369    function Fully_Conformant (New_Id, Old_Id : Entity_Id) return Boolean is
6370       Result : Boolean;
6371    begin
6372       Check_Conformance (New_Id, Old_Id, Fully_Conformant, False, Result);
6373       return Result;
6374    end Fully_Conformant;
6375
6376    ----------------------------------
6377    -- Fully_Conformant_Expressions --
6378    ----------------------------------
6379
6380    function Fully_Conformant_Expressions
6381      (Given_E1 : Node_Id;
6382       Given_E2 : Node_Id) return Boolean
6383    is
6384       E1 : constant Node_Id := Original_Node (Given_E1);
6385       E2 : constant Node_Id := Original_Node (Given_E2);
6386       --  We always test conformance on original nodes, since it is possible
6387       --  for analysis and/or expansion to make things look as though they
6388       --  conform when they do not, e.g. by converting 1+2 into 3.
6389
6390       function FCE (Given_E1, Given_E2 : Node_Id) return Boolean
6391         renames Fully_Conformant_Expressions;
6392
6393       function FCL (L1, L2 : List_Id) return Boolean;
6394       --  Compare elements of two lists for conformance. Elements have to
6395       --  be conformant, and actuals inserted as default parameters do not
6396       --  match explicit actuals with the same value.
6397
6398       function FCO (Op_Node, Call_Node : Node_Id) return Boolean;
6399       --  Compare an operator node with a function call
6400
6401       ---------
6402       -- FCL --
6403       ---------
6404
6405       function FCL (L1, L2 : List_Id) return Boolean is
6406          N1, N2 : Node_Id;
6407
6408       begin
6409          if L1 = No_List then
6410             N1 := Empty;
6411          else
6412             N1 := First (L1);
6413          end if;
6414
6415          if L2 = No_List then
6416             N2 := Empty;
6417          else
6418             N2 := First (L2);
6419          end if;
6420
6421          --  Compare two lists, skipping rewrite insertions (we want to
6422          --  compare the original trees, not the expanded versions!)
6423
6424          loop
6425             if Is_Rewrite_Insertion (N1) then
6426                Next (N1);
6427             elsif Is_Rewrite_Insertion (N2) then
6428                Next (N2);
6429             elsif No (N1) then
6430                return No (N2);
6431             elsif No (N2) then
6432                return False;
6433             elsif not FCE (N1, N2) then
6434                return False;
6435             else
6436                Next (N1);
6437                Next (N2);
6438             end if;
6439          end loop;
6440       end FCL;
6441
6442       ---------
6443       -- FCO --
6444       ---------
6445
6446       function FCO (Op_Node, Call_Node : Node_Id) return Boolean is
6447          Actuals : constant List_Id := Parameter_Associations (Call_Node);
6448          Act     : Node_Id;
6449
6450       begin
6451          if No (Actuals)
6452             or else Entity (Op_Node) /= Entity (Name (Call_Node))
6453          then
6454             return False;
6455
6456          else
6457             Act := First (Actuals);
6458
6459             if Nkind (Op_Node) in N_Binary_Op then
6460                if not FCE (Left_Opnd (Op_Node), Act) then
6461                   return False;
6462                end if;
6463
6464                Next (Act);
6465             end if;
6466
6467             return Present (Act)
6468               and then FCE (Right_Opnd (Op_Node), Act)
6469               and then No (Next (Act));
6470          end if;
6471       end FCO;
6472
6473    --  Start of processing for Fully_Conformant_Expressions
6474
6475    begin
6476       --  Non-conformant if paren count does not match. Note: if some idiot
6477       --  complains that we don't do this right for more than 3 levels of
6478       --  parentheses, they will be treated with the respect they deserve!
6479
6480       if Paren_Count (E1) /= Paren_Count (E2) then
6481          return False;
6482
6483       --  If same entities are referenced, then they are conformant even if
6484       --  they have different forms (RM 8.3.1(19-20)).
6485
6486       elsif Is_Entity_Name (E1) and then Is_Entity_Name (E2) then
6487          if Present (Entity (E1)) then
6488             return Entity (E1) = Entity (E2)
6489               or else (Chars (Entity (E1)) = Chars (Entity (E2))
6490                         and then Ekind (Entity (E1)) = E_Discriminant
6491                         and then Ekind (Entity (E2)) = E_In_Parameter);
6492
6493          elsif Nkind (E1) = N_Expanded_Name
6494            and then Nkind (E2) = N_Expanded_Name
6495            and then Nkind (Selector_Name (E1)) = N_Character_Literal
6496            and then Nkind (Selector_Name (E2)) = N_Character_Literal
6497          then
6498             return Chars (Selector_Name (E1)) = Chars (Selector_Name (E2));
6499
6500          else
6501             --  Identifiers in component associations don't always have
6502             --  entities, but their names must conform.
6503
6504             return Nkind  (E1) = N_Identifier
6505               and then Nkind (E2) = N_Identifier
6506               and then Chars (E1) = Chars (E2);
6507          end if;
6508
6509       elsif Nkind (E1) = N_Character_Literal
6510         and then Nkind (E2) = N_Expanded_Name
6511       then
6512          return Nkind (Selector_Name (E2)) = N_Character_Literal
6513            and then Chars (E1) = Chars (Selector_Name (E2));
6514
6515       elsif Nkind (E2) = N_Character_Literal
6516         and then Nkind (E1) = N_Expanded_Name
6517       then
6518          return Nkind (Selector_Name (E1)) = N_Character_Literal
6519            and then Chars (E2) = Chars (Selector_Name (E1));
6520
6521       elsif Nkind (E1) in N_Op
6522         and then Nkind (E2) = N_Function_Call
6523       then
6524          return FCO (E1, E2);
6525
6526       elsif Nkind (E2) in N_Op
6527         and then Nkind (E1) = N_Function_Call
6528       then
6529          return FCO (E2, E1);
6530
6531       --  Otherwise we must have the same syntactic entity
6532
6533       elsif Nkind (E1) /= Nkind (E2) then
6534          return False;
6535
6536       --  At this point, we specialize by node type
6537
6538       else
6539          case Nkind (E1) is
6540
6541             when N_Aggregate =>
6542                return
6543                  FCL (Expressions (E1), Expressions (E2))
6544                    and then
6545                  FCL (Component_Associations (E1),
6546                       Component_Associations (E2));
6547
6548             when N_Allocator =>
6549                if Nkind (Expression (E1)) = N_Qualified_Expression
6550                     or else
6551                   Nkind (Expression (E2)) = N_Qualified_Expression
6552                then
6553                   return FCE (Expression (E1), Expression (E2));
6554
6555                --  Check that the subtype marks and any constraints
6556                --  are conformant
6557
6558                else
6559                   declare
6560                      Indic1 : constant Node_Id := Expression (E1);
6561                      Indic2 : constant Node_Id := Expression (E2);
6562                      Elt1   : Node_Id;
6563                      Elt2   : Node_Id;
6564
6565                   begin
6566                      if Nkind (Indic1) /= N_Subtype_Indication then
6567                         return
6568                           Nkind (Indic2) /= N_Subtype_Indication
6569                             and then Entity (Indic1) = Entity (Indic2);
6570
6571                      elsif Nkind (Indic2) /= N_Subtype_Indication then
6572                         return
6573                           Nkind (Indic1) /= N_Subtype_Indication
6574                             and then Entity (Indic1) = Entity (Indic2);
6575
6576                      else
6577                         if Entity (Subtype_Mark (Indic1)) /=
6578                           Entity (Subtype_Mark (Indic2))
6579                         then
6580                            return False;
6581                         end if;
6582
6583                         Elt1 := First (Constraints (Constraint (Indic1)));
6584                         Elt2 := First (Constraints (Constraint (Indic2)));
6585                         while Present (Elt1) and then Present (Elt2) loop
6586                            if not FCE (Elt1, Elt2) then
6587                               return False;
6588                            end if;
6589
6590                            Next (Elt1);
6591                            Next (Elt2);
6592                         end loop;
6593
6594                         return True;
6595                      end if;
6596                   end;
6597                end if;
6598
6599             when N_Attribute_Reference =>
6600                return
6601                  Attribute_Name (E1) = Attribute_Name (E2)
6602                    and then FCL (Expressions (E1), Expressions (E2));
6603
6604             when N_Binary_Op =>
6605                return
6606                  Entity (E1) = Entity (E2)
6607                    and then FCE (Left_Opnd  (E1), Left_Opnd  (E2))
6608                    and then FCE (Right_Opnd (E1), Right_Opnd (E2));
6609
6610             when N_Short_Circuit | N_Membership_Test =>
6611                return
6612                  FCE (Left_Opnd  (E1), Left_Opnd  (E2))
6613                    and then
6614                  FCE (Right_Opnd (E1), Right_Opnd (E2));
6615
6616             when N_Case_Expression =>
6617                declare
6618                   Alt1 : Node_Id;
6619                   Alt2 : Node_Id;
6620
6621                begin
6622                   if not FCE (Expression (E1), Expression (E2)) then
6623                      return False;
6624
6625                   else
6626                      Alt1 := First (Alternatives (E1));
6627                      Alt2 := First (Alternatives (E2));
6628                      loop
6629                         if Present (Alt1) /= Present (Alt2) then
6630                            return False;
6631                         elsif No (Alt1) then
6632                            return True;
6633                         end if;
6634
6635                         if not FCE (Expression (Alt1), Expression (Alt2))
6636                           or else not FCL (Discrete_Choices (Alt1),
6637                                            Discrete_Choices (Alt2))
6638                         then
6639                            return False;
6640                         end if;
6641
6642                         Next (Alt1);
6643                         Next (Alt2);
6644                      end loop;
6645                   end if;
6646                end;
6647
6648             when N_Character_Literal =>
6649                return
6650                  Char_Literal_Value (E1) = Char_Literal_Value (E2);
6651
6652             when N_Component_Association =>
6653                return
6654                  FCL (Choices (E1), Choices (E2))
6655                    and then
6656                  FCE (Expression (E1), Expression (E2));
6657
6658             when N_Conditional_Expression =>
6659                return
6660                  FCL (Expressions (E1), Expressions (E2));
6661
6662             when N_Explicit_Dereference =>
6663                return
6664                  FCE (Prefix (E1), Prefix (E2));
6665
6666             when N_Extension_Aggregate =>
6667                return
6668                  FCL (Expressions (E1), Expressions (E2))
6669                    and then Null_Record_Present (E1) =
6670                             Null_Record_Present (E2)
6671                    and then FCL (Component_Associations (E1),
6672                                Component_Associations (E2));
6673
6674             when N_Function_Call =>
6675                return
6676                  FCE (Name (E1), Name (E2))
6677                    and then
6678                  FCL (Parameter_Associations (E1),
6679                       Parameter_Associations (E2));
6680
6681             when N_Indexed_Component =>
6682                return
6683                  FCE (Prefix (E1), Prefix (E2))
6684                    and then
6685                  FCL (Expressions (E1), Expressions (E2));
6686
6687             when N_Integer_Literal =>
6688                return (Intval (E1) = Intval (E2));
6689
6690             when N_Null =>
6691                return True;
6692
6693             when N_Operator_Symbol =>
6694                return
6695                  Chars (E1) = Chars (E2);
6696
6697             when N_Others_Choice =>
6698                return True;
6699
6700             when N_Parameter_Association =>
6701                return
6702                  Chars (Selector_Name (E1))  = Chars (Selector_Name (E2))
6703                    and then FCE (Explicit_Actual_Parameter (E1),
6704                                  Explicit_Actual_Parameter (E2));
6705
6706             when N_Qualified_Expression =>
6707                return
6708                  FCE (Subtype_Mark (E1), Subtype_Mark (E2))
6709                    and then
6710                  FCE (Expression (E1), Expression (E2));
6711
6712             when N_Quantified_Expression =>
6713                if not FCE (Condition (E1), Condition (E2)) then
6714                   return False;
6715                end if;
6716
6717                if Present (Loop_Parameter_Specification (E1))
6718                  and then Present (Loop_Parameter_Specification (E2))
6719                then
6720                   declare
6721                      L1 : constant Node_Id :=
6722                        Loop_Parameter_Specification (E1);
6723                      L2 : constant Node_Id :=
6724                        Loop_Parameter_Specification (E2);
6725
6726                   begin
6727                      return
6728                        Reverse_Present (L1) = Reverse_Present (L2)
6729                          and then
6730                            FCE (Defining_Identifier (L1),
6731                                 Defining_Identifier (L2))
6732                          and then
6733                            FCE (Discrete_Subtype_Definition (L1),
6734                                 Discrete_Subtype_Definition (L2));
6735                   end;
6736
6737                else   --  quantified expression with an iterator
6738                   declare
6739                      I1 : constant Node_Id := Iterator_Specification (E1);
6740                      I2 : constant Node_Id := Iterator_Specification (E2);
6741
6742                   begin
6743                      return
6744                        FCE (Defining_Identifier (I1),
6745                             Defining_Identifier (I2))
6746                        and then
6747                          Of_Present (I1) = Of_Present (I2)
6748                        and then
6749                          Reverse_Present (I1) = Reverse_Present (I2)
6750                        and then FCE (Name (I1), Name (I2))
6751                        and then FCE (Subtype_Indication (I1),
6752                                       Subtype_Indication (I2));
6753                   end;
6754                end if;
6755
6756             when N_Range =>
6757                return
6758                  FCE (Low_Bound (E1), Low_Bound (E2))
6759                    and then
6760                  FCE (High_Bound (E1), High_Bound (E2));
6761
6762             when N_Real_Literal =>
6763                return (Realval (E1) = Realval (E2));
6764
6765             when N_Selected_Component =>
6766                return
6767                  FCE (Prefix (E1), Prefix (E2))
6768                    and then
6769                  FCE (Selector_Name (E1), Selector_Name (E2));
6770
6771             when N_Slice =>
6772                return
6773                  FCE (Prefix (E1), Prefix (E2))
6774                    and then
6775                  FCE (Discrete_Range (E1), Discrete_Range (E2));
6776
6777             when N_String_Literal =>
6778                declare
6779                   S1 : constant String_Id := Strval (E1);
6780                   S2 : constant String_Id := Strval (E2);
6781                   L1 : constant Nat       := String_Length (S1);
6782                   L2 : constant Nat       := String_Length (S2);
6783
6784                begin
6785                   if L1 /= L2 then
6786                      return False;
6787
6788                   else
6789                      for J in 1 .. L1 loop
6790                         if Get_String_Char (S1, J) /=
6791                            Get_String_Char (S2, J)
6792                         then
6793                            return False;
6794                         end if;
6795                      end loop;
6796
6797                      return True;
6798                   end if;
6799                end;
6800
6801             when N_Type_Conversion =>
6802                return
6803                  FCE (Subtype_Mark (E1), Subtype_Mark (E2))
6804                    and then
6805                  FCE (Expression (E1), Expression (E2));
6806
6807             when N_Unary_Op =>
6808                return
6809                  Entity (E1) = Entity (E2)
6810                    and then
6811                  FCE (Right_Opnd (E1), Right_Opnd (E2));
6812
6813             when N_Unchecked_Type_Conversion =>
6814                return
6815                  FCE (Subtype_Mark (E1), Subtype_Mark (E2))
6816                    and then
6817                  FCE (Expression (E1), Expression (E2));
6818
6819             --  All other node types cannot appear in this context. Strictly
6820             --  we should raise a fatal internal error. Instead we just ignore
6821             --  the nodes. This means that if anyone makes a mistake in the
6822             --  expander and mucks an expression tree irretrievably, the
6823             --  result will be a failure to detect a (probably very obscure)
6824             --  case of non-conformance, which is better than bombing on some
6825             --  case where two expressions do in fact conform.
6826
6827             when others =>
6828                return True;
6829
6830          end case;
6831       end if;
6832    end Fully_Conformant_Expressions;
6833
6834    ----------------------------------------
6835    -- Fully_Conformant_Discrete_Subtypes --
6836    ----------------------------------------
6837
6838    function Fully_Conformant_Discrete_Subtypes
6839      (Given_S1 : Node_Id;
6840       Given_S2 : Node_Id) return Boolean
6841    is
6842       S1 : constant Node_Id := Original_Node (Given_S1);
6843       S2 : constant Node_Id := Original_Node (Given_S2);
6844
6845       function Conforming_Bounds (B1, B2 : Node_Id) return Boolean;
6846       --  Special-case for a bound given by a discriminant, which in the body
6847       --  is replaced with the discriminal of the enclosing type.
6848
6849       function Conforming_Ranges (R1, R2 : Node_Id) return Boolean;
6850       --  Check both bounds
6851
6852       -----------------------
6853       -- Conforming_Bounds --
6854       -----------------------
6855
6856       function Conforming_Bounds (B1, B2 : Node_Id) return Boolean is
6857       begin
6858          if Is_Entity_Name (B1)
6859            and then Is_Entity_Name (B2)
6860            and then Ekind (Entity (B1)) = E_Discriminant
6861          then
6862             return Chars (B1) = Chars (B2);
6863
6864          else
6865             return Fully_Conformant_Expressions (B1, B2);
6866          end if;
6867       end Conforming_Bounds;
6868
6869       -----------------------
6870       -- Conforming_Ranges --
6871       -----------------------
6872
6873       function Conforming_Ranges (R1, R2 : Node_Id) return Boolean is
6874       begin
6875          return
6876            Conforming_Bounds (Low_Bound (R1), Low_Bound (R2))
6877              and then
6878            Conforming_Bounds (High_Bound (R1), High_Bound (R2));
6879       end Conforming_Ranges;
6880
6881    --  Start of processing for Fully_Conformant_Discrete_Subtypes
6882
6883    begin
6884       if Nkind (S1) /= Nkind (S2) then
6885          return False;
6886
6887       elsif Is_Entity_Name (S1) then
6888          return Entity (S1) = Entity (S2);
6889
6890       elsif Nkind (S1) = N_Range then
6891          return Conforming_Ranges (S1, S2);
6892
6893       elsif Nkind (S1) = N_Subtype_Indication then
6894          return
6895             Entity (Subtype_Mark (S1)) = Entity (Subtype_Mark (S2))
6896               and then
6897             Conforming_Ranges
6898               (Range_Expression (Constraint (S1)),
6899                Range_Expression (Constraint (S2)));
6900       else
6901          return True;
6902       end if;
6903    end Fully_Conformant_Discrete_Subtypes;
6904
6905    --------------------
6906    -- Install_Entity --
6907    --------------------
6908
6909    procedure Install_Entity (E : Entity_Id) is
6910       Prev : constant Entity_Id := Current_Entity (E);
6911    begin
6912       Set_Is_Immediately_Visible (E);
6913       Set_Current_Entity (E);
6914       Set_Homonym (E, Prev);
6915    end Install_Entity;
6916
6917    ---------------------
6918    -- Install_Formals --
6919    ---------------------
6920
6921    procedure Install_Formals (Id : Entity_Id) is
6922       F : Entity_Id;
6923    begin
6924       F := First_Formal (Id);
6925       while Present (F) loop
6926          Install_Entity (F);
6927          Next_Formal (F);
6928       end loop;
6929    end Install_Formals;
6930
6931    -----------------------------
6932    -- Is_Interface_Conformant --
6933    -----------------------------
6934
6935    function Is_Interface_Conformant
6936      (Tagged_Type : Entity_Id;
6937       Iface_Prim  : Entity_Id;
6938       Prim        : Entity_Id) return Boolean
6939    is
6940       Iface : constant Entity_Id := Find_Dispatching_Type (Iface_Prim);
6941       Typ   : constant Entity_Id := Find_Dispatching_Type (Prim);
6942
6943    begin
6944       pragma Assert (Is_Subprogram (Iface_Prim)
6945         and then Is_Subprogram (Prim)
6946         and then Is_Dispatching_Operation (Iface_Prim)
6947         and then Is_Dispatching_Operation (Prim));
6948
6949       pragma Assert (Is_Interface (Iface)
6950         or else (Present (Alias (Iface_Prim))
6951                    and then
6952                      Is_Interface
6953                        (Find_Dispatching_Type (Ultimate_Alias (Iface_Prim)))));
6954
6955       if Prim = Iface_Prim
6956         or else not Is_Subprogram (Prim)
6957         or else Ekind (Prim) /= Ekind (Iface_Prim)
6958         or else not Is_Dispatching_Operation (Prim)
6959         or else Scope (Prim) /= Scope (Tagged_Type)
6960         or else No (Typ)
6961         or else Base_Type (Typ) /= Tagged_Type
6962         or else not Primitive_Names_Match (Iface_Prim, Prim)
6963       then
6964          return False;
6965
6966       --  Case of a procedure, or a function that does not have a controlling
6967       --  result (I or access I).
6968
6969       elsif Ekind (Iface_Prim) = E_Procedure
6970         or else Etype (Prim) = Etype (Iface_Prim)
6971         or else not Has_Controlling_Result (Prim)
6972       then
6973          return Type_Conformant
6974                   (Iface_Prim, Prim, Skip_Controlling_Formals => True);
6975
6976       --  Case of a function returning an interface, or an access to one.
6977       --  Check that the return types correspond.
6978
6979       elsif Implements_Interface (Typ, Iface) then
6980          if (Ekind (Etype (Prim)) = E_Anonymous_Access_Type)
6981               /=
6982             (Ekind (Etype (Iface_Prim)) = E_Anonymous_Access_Type)
6983          then
6984             return False;
6985          else
6986             return
6987               Type_Conformant (Prim, Iface_Prim,
6988                 Skip_Controlling_Formals => True);
6989          end if;
6990
6991       else
6992          return False;
6993       end if;
6994    end Is_Interface_Conformant;
6995
6996    ---------------------------------
6997    -- Is_Non_Overriding_Operation --
6998    ---------------------------------
6999
7000    function Is_Non_Overriding_Operation
7001      (Prev_E : Entity_Id;
7002       New_E  : Entity_Id) return Boolean
7003    is
7004       Formal : Entity_Id;
7005       F_Typ  : Entity_Id;
7006       G_Typ  : Entity_Id := Empty;
7007
7008       function Get_Generic_Parent_Type (F_Typ : Entity_Id) return Entity_Id;
7009       --  If F_Type is a derived type associated with a generic actual subtype,
7010       --  then return its Generic_Parent_Type attribute, else return Empty.
7011
7012       function Types_Correspond
7013         (P_Type : Entity_Id;
7014          N_Type : Entity_Id) return Boolean;
7015       --  Returns true if and only if the types (or designated types in the
7016       --  case of anonymous access types) are the same or N_Type is derived
7017       --  directly or indirectly from P_Type.
7018
7019       -----------------------------
7020       -- Get_Generic_Parent_Type --
7021       -----------------------------
7022
7023       function Get_Generic_Parent_Type (F_Typ : Entity_Id) return Entity_Id is
7024          G_Typ : Entity_Id;
7025          Indic : Node_Id;
7026
7027       begin
7028          if Is_Derived_Type (F_Typ)
7029            and then Nkind (Parent (F_Typ)) = N_Full_Type_Declaration
7030          then
7031             --  The tree must be traversed to determine the parent subtype in
7032             --  the generic unit, which unfortunately isn't always available
7033             --  via semantic attributes. ??? (Note: The use of Original_Node
7034             --  is needed for cases where a full derived type has been
7035             --  rewritten.)
7036
7037             Indic := Subtype_Indication
7038                        (Type_Definition (Original_Node (Parent (F_Typ))));
7039
7040             if Nkind (Indic) = N_Subtype_Indication then
7041                G_Typ := Entity (Subtype_Mark (Indic));
7042             else
7043                G_Typ := Entity (Indic);
7044             end if;
7045
7046             if Nkind (Parent (G_Typ)) = N_Subtype_Declaration
7047               and then Present (Generic_Parent_Type (Parent (G_Typ)))
7048             then
7049                return Generic_Parent_Type (Parent (G_Typ));
7050             end if;
7051          end if;
7052
7053          return Empty;
7054       end Get_Generic_Parent_Type;
7055
7056       ----------------------
7057       -- Types_Correspond --
7058       ----------------------
7059
7060       function Types_Correspond
7061         (P_Type : Entity_Id;
7062          N_Type : Entity_Id) return Boolean
7063       is
7064          Prev_Type : Entity_Id := Base_Type (P_Type);
7065          New_Type  : Entity_Id := Base_Type (N_Type);
7066
7067       begin
7068          if Ekind (Prev_Type) = E_Anonymous_Access_Type then
7069             Prev_Type := Designated_Type (Prev_Type);
7070          end if;
7071
7072          if Ekind (New_Type) = E_Anonymous_Access_Type then
7073             New_Type := Designated_Type (New_Type);
7074          end if;
7075
7076          if Prev_Type = New_Type then
7077             return True;
7078
7079          elsif not Is_Class_Wide_Type (New_Type) then
7080             while Etype (New_Type) /= New_Type loop
7081                New_Type := Etype (New_Type);
7082                if New_Type = Prev_Type then
7083                   return True;
7084                end if;
7085             end loop;
7086          end if;
7087          return False;
7088       end Types_Correspond;
7089
7090    --  Start of processing for Is_Non_Overriding_Operation
7091
7092    begin
7093       --  In the case where both operations are implicit derived subprograms
7094       --  then neither overrides the other. This can only occur in certain
7095       --  obscure cases (e.g., derivation from homographs created in a generic
7096       --  instantiation).
7097
7098       if Present (Alias (Prev_E)) and then Present (Alias (New_E)) then
7099          return True;
7100
7101       elsif Ekind (Current_Scope) = E_Package
7102         and then Is_Generic_Instance (Current_Scope)
7103         and then In_Private_Part (Current_Scope)
7104         and then Comes_From_Source (New_E)
7105       then
7106          --  We examine the formals and result subtype of the inherited
7107          --  operation, to determine whether their type is derived from (the
7108          --  instance of) a generic type.
7109
7110          Formal := First_Formal (Prev_E);
7111          while Present (Formal) loop
7112             F_Typ := Base_Type (Etype (Formal));
7113
7114             if Ekind (F_Typ) = E_Anonymous_Access_Type then
7115                F_Typ := Designated_Type (F_Typ);
7116             end if;
7117
7118             G_Typ := Get_Generic_Parent_Type (F_Typ);
7119
7120             Next_Formal (Formal);
7121          end loop;
7122
7123          if No (G_Typ) and then Ekind (Prev_E) = E_Function then
7124             G_Typ := Get_Generic_Parent_Type (Base_Type (Etype (Prev_E)));
7125          end if;
7126
7127          if No (G_Typ) then
7128             return False;
7129          end if;
7130
7131          --  If the generic type is a private type, then the original operation
7132          --  was not overriding in the generic, because there was no primitive
7133          --  operation to override.
7134
7135          if Nkind (Parent (G_Typ)) = N_Formal_Type_Declaration
7136            and then Nkind (Formal_Type_Definition (Parent (G_Typ))) =
7137                       N_Formal_Private_Type_Definition
7138          then
7139             return True;
7140
7141          --  The generic parent type is the ancestor of a formal derived
7142          --  type declaration. We need to check whether it has a primitive
7143          --  operation that should be overridden by New_E in the generic.
7144
7145          else
7146             declare
7147                P_Formal : Entity_Id;
7148                N_Formal : Entity_Id;
7149                P_Typ    : Entity_Id;
7150                N_Typ    : Entity_Id;
7151                P_Prim   : Entity_Id;
7152                Prim_Elt : Elmt_Id := First_Elmt (Primitive_Operations (G_Typ));
7153
7154             begin
7155                while Present (Prim_Elt) loop
7156                   P_Prim := Node (Prim_Elt);
7157
7158                   if Chars (P_Prim) = Chars (New_E)
7159                     and then Ekind (P_Prim) = Ekind (New_E)
7160                   then
7161                      P_Formal := First_Formal (P_Prim);
7162                      N_Formal := First_Formal (New_E);
7163                      while Present (P_Formal) and then Present (N_Formal) loop
7164                         P_Typ := Etype (P_Formal);
7165                         N_Typ := Etype (N_Formal);
7166
7167                         if not Types_Correspond (P_Typ, N_Typ) then
7168                            exit;
7169                         end if;
7170
7171                         Next_Entity (P_Formal);
7172                         Next_Entity (N_Formal);
7173                      end loop;
7174
7175                      --  Found a matching primitive operation belonging to the
7176                      --  formal ancestor type, so the new subprogram is
7177                      --  overriding.
7178
7179                      if No (P_Formal)
7180                        and then No (N_Formal)
7181                        and then (Ekind (New_E) /= E_Function
7182                                   or else
7183                                  Types_Correspond
7184                                    (Etype (P_Prim), Etype (New_E)))
7185                      then
7186                         return False;
7187                      end if;
7188                   end if;
7189
7190                   Next_Elmt (Prim_Elt);
7191                end loop;
7192
7193                --  If no match found, then the new subprogram does not
7194                --  override in the generic (nor in the instance).
7195
7196                return True;
7197             end;
7198          end if;
7199       else
7200          return False;
7201       end if;
7202    end Is_Non_Overriding_Operation;
7203
7204    -------------------------------------
7205    -- List_Inherited_Pre_Post_Aspects --
7206    -------------------------------------
7207
7208    procedure List_Inherited_Pre_Post_Aspects (E : Entity_Id) is
7209    begin
7210       if Opt.List_Inherited_Aspects
7211         and then (Is_Subprogram (E) or else Is_Generic_Subprogram (E))
7212       then
7213          declare
7214             Inherited : constant Subprogram_List :=
7215                           Inherited_Subprograms (E);
7216             P         : Node_Id;
7217
7218          begin
7219             for J in Inherited'Range loop
7220                P := Spec_PPC_List (Inherited (J));
7221                while Present (P) loop
7222                   Error_Msg_Sloc := Sloc (P);
7223
7224                   if Class_Present (P) and then not Split_PPC (P) then
7225                      if Pragma_Name (P) = Name_Precondition then
7226                         Error_Msg_N
7227                           ("?info: & inherits `Pre''Class` aspect from #", E);
7228                      else
7229                         Error_Msg_N
7230                           ("?info: & inherits `Post''Class` aspect from #", E);
7231                      end if;
7232                   end if;
7233
7234                   P := Next_Pragma (P);
7235                end loop;
7236             end loop;
7237          end;
7238       end if;
7239    end List_Inherited_Pre_Post_Aspects;
7240
7241    ------------------------------
7242    -- Make_Inequality_Operator --
7243    ------------------------------
7244
7245    --  S is the defining identifier of an equality operator. We build a
7246    --  subprogram declaration with the right signature. This operation is
7247    --  intrinsic, because it is always expanded as the negation of the
7248    --  call to the equality function.
7249
7250    procedure Make_Inequality_Operator (S : Entity_Id) is
7251       Loc     : constant Source_Ptr := Sloc (S);
7252       Decl    : Node_Id;
7253       Formals : List_Id;
7254       Op_Name : Entity_Id;
7255
7256       FF : constant Entity_Id := First_Formal (S);
7257       NF : constant Entity_Id := Next_Formal (FF);
7258
7259    begin
7260       --  Check that equality was properly defined, ignore call if not
7261
7262       if No (NF) then
7263          return;
7264       end if;
7265
7266       declare
7267          A : constant Entity_Id :=
7268                Make_Defining_Identifier (Sloc (FF),
7269                  Chars => Chars (FF));
7270
7271          B : constant Entity_Id :=
7272                Make_Defining_Identifier (Sloc (NF),
7273                  Chars => Chars (NF));
7274
7275       begin
7276          Op_Name := Make_Defining_Operator_Symbol (Loc, Name_Op_Ne);
7277
7278          Formals := New_List (
7279            Make_Parameter_Specification (Loc,
7280              Defining_Identifier => A,
7281              Parameter_Type      =>
7282                New_Reference_To (Etype (First_Formal (S)),
7283                  Sloc (Etype (First_Formal (S))))),
7284
7285            Make_Parameter_Specification (Loc,
7286              Defining_Identifier => B,
7287              Parameter_Type      =>
7288                New_Reference_To (Etype (Next_Formal (First_Formal (S))),
7289                  Sloc (Etype (Next_Formal (First_Formal (S)))))));
7290
7291          Decl :=
7292            Make_Subprogram_Declaration (Loc,
7293              Specification =>
7294                Make_Function_Specification (Loc,
7295                  Defining_Unit_Name       => Op_Name,
7296                  Parameter_Specifications => Formals,
7297                  Result_Definition        =>
7298                    New_Reference_To (Standard_Boolean, Loc)));
7299
7300          --  Insert inequality right after equality if it is explicit or after
7301          --  the derived type when implicit. These entities are created only
7302          --  for visibility purposes, and eventually replaced in the course of
7303          --  expansion, so they do not need to be attached to the tree and seen
7304          --  by the back-end. Keeping them internal also avoids spurious
7305          --  freezing problems. The declaration is inserted in the tree for
7306          --  analysis, and removed afterwards. If the equality operator comes
7307          --  from an explicit declaration, attach the inequality immediately
7308          --  after. Else the equality is inherited from a derived type
7309          --  declaration, so insert inequality after that declaration.
7310
7311          if No (Alias (S)) then
7312             Insert_After (Unit_Declaration_Node (S), Decl);
7313          elsif Is_List_Member (Parent (S)) then
7314             Insert_After (Parent (S), Decl);
7315          else
7316             Insert_After (Parent (Etype (First_Formal (S))), Decl);
7317          end if;
7318
7319          Mark_Rewrite_Insertion (Decl);
7320          Set_Is_Intrinsic_Subprogram (Op_Name);
7321          Analyze (Decl);
7322          Remove (Decl);
7323          Set_Has_Completion (Op_Name);
7324          Set_Corresponding_Equality (Op_Name, S);
7325          Set_Is_Abstract_Subprogram (Op_Name, Is_Abstract_Subprogram (S));
7326       end;
7327    end Make_Inequality_Operator;
7328
7329    ----------------------
7330    -- May_Need_Actuals --
7331    ----------------------
7332
7333    procedure May_Need_Actuals (Fun : Entity_Id) is
7334       F : Entity_Id;
7335       B : Boolean;
7336
7337    begin
7338       F := First_Formal (Fun);
7339       B := True;
7340       while Present (F) loop
7341          if No (Default_Value (F)) then
7342             B := False;
7343             exit;
7344          end if;
7345
7346          Next_Formal (F);
7347       end loop;
7348
7349       Set_Needs_No_Actuals (Fun, B);
7350    end May_Need_Actuals;
7351
7352    ---------------------
7353    -- Mode_Conformant --
7354    ---------------------
7355
7356    function Mode_Conformant (New_Id, Old_Id : Entity_Id) return Boolean is
7357       Result : Boolean;
7358    begin
7359       Check_Conformance (New_Id, Old_Id, Mode_Conformant, False, Result);
7360       return Result;
7361    end Mode_Conformant;
7362
7363    ---------------------------
7364    -- New_Overloaded_Entity --
7365    ---------------------------
7366
7367    procedure New_Overloaded_Entity
7368      (S            : Entity_Id;
7369       Derived_Type : Entity_Id := Empty)
7370    is
7371       Overridden_Subp : Entity_Id := Empty;
7372       --  Set if the current scope has an operation that is type-conformant
7373       --  with S, and becomes hidden by S.
7374
7375       Is_Primitive_Subp : Boolean;
7376       --  Set to True if the new subprogram is primitive
7377
7378       E : Entity_Id;
7379       --  Entity that S overrides
7380
7381       Prev_Vis : Entity_Id := Empty;
7382       --  Predecessor of E in Homonym chain
7383
7384       procedure Check_For_Primitive_Subprogram
7385         (Is_Primitive  : out Boolean;
7386          Is_Overriding : Boolean := False);
7387       --  If the subprogram being analyzed is a primitive operation of the type
7388       --  of a formal or result, set the Has_Primitive_Operations flag on the
7389       --  type, and set Is_Primitive to True (otherwise set to False). Set the
7390       --  corresponding flag on the entity itself for later use.
7391
7392       procedure Check_Synchronized_Overriding
7393         (Def_Id          : Entity_Id;
7394          Overridden_Subp : out Entity_Id);
7395       --  First determine if Def_Id is an entry or a subprogram either defined
7396       --  in the scope of a task or protected type, or is a primitive of such
7397       --  a type. Check whether Def_Id overrides a subprogram of an interface
7398       --  implemented by the synchronized type, return the overridden entity
7399       --  or Empty.
7400
7401       function Is_Private_Declaration (E : Entity_Id) return Boolean;
7402       --  Check that E is declared in the private part of the current package,
7403       --  or in the package body, where it may hide a previous declaration.
7404       --  We can't use In_Private_Part by itself because this flag is also
7405       --  set when freezing entities, so we must examine the place of the
7406       --  declaration in the tree, and recognize wrapper packages as well.
7407
7408       function Is_Overriding_Alias
7409         (Old_E : Entity_Id;
7410          New_E : Entity_Id) return Boolean;
7411       --  Check whether new subprogram and old subprogram are both inherited
7412       --  from subprograms that have distinct dispatch table entries. This can
7413       --  occur with derivations from instances with accidental homonyms.
7414       --  The function is conservative given that the converse is only true
7415       --  within instances that contain accidental overloadings.
7416
7417       ------------------------------------
7418       -- Check_For_Primitive_Subprogram --
7419       ------------------------------------
7420
7421       procedure Check_For_Primitive_Subprogram
7422         (Is_Primitive  : out Boolean;
7423          Is_Overriding : Boolean := False)
7424       is
7425          Formal : Entity_Id;
7426          F_Typ  : Entity_Id;
7427          B_Typ  : Entity_Id;
7428
7429          function Visible_Part_Type (T : Entity_Id) return Boolean;
7430          --  Returns true if T is declared in the visible part of the current
7431          --  package scope; otherwise returns false. Assumes that T is declared
7432          --  in a package.
7433
7434          procedure Check_Private_Overriding (T : Entity_Id);
7435          --  Checks that if a primitive abstract subprogram of a visible
7436          --  abstract type is declared in a private part, then it must override
7437          --  an abstract subprogram declared in the visible part. Also checks
7438          --  that if a primitive function with a controlling result is declared
7439          --  in a private part, then it must override a function declared in
7440          --  the visible part.
7441
7442          ------------------------------
7443          -- Check_Private_Overriding --
7444          ------------------------------
7445
7446          procedure Check_Private_Overriding (T : Entity_Id) is
7447          begin
7448             if Is_Package_Or_Generic_Package (Current_Scope)
7449               and then In_Private_Part (Current_Scope)
7450               and then Visible_Part_Type (T)
7451               and then not In_Instance
7452             then
7453                if Is_Abstract_Type (T)
7454                  and then Is_Abstract_Subprogram (S)
7455                  and then (not Is_Overriding
7456                             or else not Is_Abstract_Subprogram (E))
7457                then
7458                   Error_Msg_N
7459                     ("abstract subprograms must be visible "
7460                      & "(RM 3.9.3(10))!", S);
7461
7462                elsif Ekind (S) = E_Function
7463                  and then not Is_Overriding
7464                then
7465                   if Is_Tagged_Type (T)
7466                     and then T = Base_Type (Etype (S))
7467                   then
7468                      Error_Msg_N
7469                        ("private function with tagged result must"
7470                         & " override visible-part function", S);
7471                      Error_Msg_N
7472                        ("\move subprogram to the visible part"
7473                         & " (RM 3.9.3(10))", S);
7474
7475                   --  AI05-0073: extend this test to the case of a function
7476                   --  with a controlling access result.
7477
7478                   elsif Ekind (Etype (S)) = E_Anonymous_Access_Type
7479                     and then Is_Tagged_Type (Designated_Type (Etype (S)))
7480                     and then
7481                       not Is_Class_Wide_Type (Designated_Type (Etype (S)))
7482                     and then Ada_Version >= Ada_2012
7483                   then
7484                      Error_Msg_N
7485                        ("private function with controlling access result "
7486                           & "must override visible-part function", S);
7487                      Error_Msg_N
7488                        ("\move subprogram to the visible part"
7489                           & " (RM 3.9.3(10))", S);
7490                   end if;
7491                end if;
7492             end if;
7493          end Check_Private_Overriding;
7494
7495          -----------------------
7496          -- Visible_Part_Type --
7497          -----------------------
7498
7499          function Visible_Part_Type (T : Entity_Id) return Boolean is
7500             P : constant Node_Id := Unit_Declaration_Node (Scope (T));
7501             N : Node_Id;
7502
7503          begin
7504             --  If the entity is a private type, then it must be declared in a
7505             --  visible part.
7506
7507             if Ekind (T) in Private_Kind then
7508                return True;
7509             end if;
7510
7511             --  Otherwise, we traverse the visible part looking for its
7512             --  corresponding declaration. We cannot use the declaration
7513             --  node directly because in the private part the entity of a
7514             --  private type is the one in the full view, which does not
7515             --  indicate that it is the completion of something visible.
7516
7517             N := First (Visible_Declarations (Specification (P)));
7518             while Present (N) loop
7519                if Nkind (N) = N_Full_Type_Declaration
7520                  and then Present (Defining_Identifier (N))
7521                  and then T = Defining_Identifier (N)
7522                then
7523                   return True;
7524
7525                elsif Nkind_In (N, N_Private_Type_Declaration,
7526                                   N_Private_Extension_Declaration)
7527                  and then Present (Defining_Identifier (N))
7528                  and then T = Full_View (Defining_Identifier (N))
7529                then
7530                   return True;
7531                end if;
7532
7533                Next (N);
7534             end loop;
7535
7536             return False;
7537          end Visible_Part_Type;
7538
7539       --  Start of processing for Check_For_Primitive_Subprogram
7540
7541       begin
7542          Is_Primitive := False;
7543
7544          if not Comes_From_Source (S) then
7545             null;
7546
7547          --  If subprogram is at library level, it is not primitive operation
7548
7549          elsif Current_Scope = Standard_Standard then
7550             null;
7551
7552          elsif (Is_Package_Or_Generic_Package (Current_Scope)
7553                  and then not In_Package_Body (Current_Scope))
7554            or else Is_Overriding
7555          then
7556             --  For function, check return type
7557
7558             if Ekind (S) = E_Function then
7559                if Ekind (Etype (S)) = E_Anonymous_Access_Type then
7560                   F_Typ := Designated_Type (Etype (S));
7561                else
7562                   F_Typ := Etype (S);
7563                end if;
7564
7565                B_Typ := Base_Type (F_Typ);
7566
7567                if Scope (B_Typ) = Current_Scope
7568                  and then not Is_Class_Wide_Type (B_Typ)
7569                  and then not Is_Generic_Type (B_Typ)
7570                then
7571                   Is_Primitive := True;
7572                   Set_Has_Primitive_Operations (B_Typ);
7573                   Set_Is_Primitive (S);
7574                   Check_Private_Overriding (B_Typ);
7575                end if;
7576             end if;
7577
7578             --  For all subprograms, check formals
7579
7580             Formal := First_Formal (S);
7581             while Present (Formal) loop
7582                if Ekind (Etype (Formal)) = E_Anonymous_Access_Type then
7583                   F_Typ := Designated_Type (Etype (Formal));
7584                else
7585                   F_Typ := Etype (Formal);
7586                end if;
7587
7588                B_Typ := Base_Type (F_Typ);
7589
7590                if Ekind (B_Typ) = E_Access_Subtype then
7591                   B_Typ := Base_Type (B_Typ);
7592                end if;
7593
7594                if Scope (B_Typ) = Current_Scope
7595                  and then not Is_Class_Wide_Type (B_Typ)
7596                  and then not Is_Generic_Type (B_Typ)
7597                then
7598                   Is_Primitive := True;
7599                   Set_Is_Primitive (S);
7600                   Set_Has_Primitive_Operations (B_Typ);
7601                   Check_Private_Overriding (B_Typ);
7602                end if;
7603
7604                Next_Formal (Formal);
7605             end loop;
7606          end if;
7607       end Check_For_Primitive_Subprogram;
7608
7609       -----------------------------------
7610       -- Check_Synchronized_Overriding --
7611       -----------------------------------
7612
7613       procedure Check_Synchronized_Overriding
7614         (Def_Id          : Entity_Id;
7615          Overridden_Subp : out Entity_Id)
7616       is
7617          Ifaces_List : Elist_Id;
7618          In_Scope    : Boolean;
7619          Typ         : Entity_Id;
7620
7621          function Matches_Prefixed_View_Profile
7622            (Prim_Params  : List_Id;
7623             Iface_Params : List_Id) return Boolean;
7624          --  Determine whether a subprogram's parameter profile Prim_Params
7625          --  matches that of a potentially overridden interface subprogram
7626          --  Iface_Params. Also determine if the type of first parameter of
7627          --  Iface_Params is an implemented interface.
7628
7629          -----------------------------------
7630          -- Matches_Prefixed_View_Profile --
7631          -----------------------------------
7632
7633          function Matches_Prefixed_View_Profile
7634            (Prim_Params  : List_Id;
7635             Iface_Params : List_Id) return Boolean
7636          is
7637             Iface_Id     : Entity_Id;
7638             Iface_Param  : Node_Id;
7639             Iface_Typ    : Entity_Id;
7640             Prim_Id      : Entity_Id;
7641             Prim_Param   : Node_Id;
7642             Prim_Typ     : Entity_Id;
7643
7644             function Is_Implemented
7645               (Ifaces_List : Elist_Id;
7646                Iface       : Entity_Id) return Boolean;
7647             --  Determine if Iface is implemented by the current task or
7648             --  protected type.
7649
7650             --------------------
7651             -- Is_Implemented --
7652             --------------------
7653
7654             function Is_Implemented
7655               (Ifaces_List : Elist_Id;
7656                Iface       : Entity_Id) return Boolean
7657             is
7658                Iface_Elmt : Elmt_Id;
7659
7660             begin
7661                Iface_Elmt := First_Elmt (Ifaces_List);
7662                while Present (Iface_Elmt) loop
7663                   if Node (Iface_Elmt) = Iface then
7664                      return True;
7665                   end if;
7666
7667                   Next_Elmt (Iface_Elmt);
7668                end loop;
7669
7670                return False;
7671             end Is_Implemented;
7672
7673          --  Start of processing for Matches_Prefixed_View_Profile
7674
7675          begin
7676             Iface_Param := First (Iface_Params);
7677             Iface_Typ   := Etype (Defining_Identifier (Iface_Param));
7678
7679             if Is_Access_Type (Iface_Typ) then
7680                Iface_Typ := Designated_Type (Iface_Typ);
7681             end if;
7682
7683             Prim_Param := First (Prim_Params);
7684
7685             --  The first parameter of the potentially overridden subprogram
7686             --  must be an interface implemented by Prim.
7687
7688             if not Is_Interface (Iface_Typ)
7689               or else not Is_Implemented (Ifaces_List, Iface_Typ)
7690             then
7691                return False;
7692             end if;
7693
7694             --  The checks on the object parameters are done, move onto the
7695             --  rest of the parameters.
7696
7697             if not In_Scope then
7698                Prim_Param := Next (Prim_Param);
7699             end if;
7700
7701             Iface_Param := Next (Iface_Param);
7702             while Present (Iface_Param) and then Present (Prim_Param) loop
7703                Iface_Id  := Defining_Identifier (Iface_Param);
7704                Iface_Typ := Find_Parameter_Type (Iface_Param);
7705
7706                Prim_Id  := Defining_Identifier (Prim_Param);
7707                Prim_Typ := Find_Parameter_Type (Prim_Param);
7708
7709                if Ekind (Iface_Typ) = E_Anonymous_Access_Type
7710                  and then Ekind (Prim_Typ) = E_Anonymous_Access_Type
7711                  and then Is_Concurrent_Type (Designated_Type (Prim_Typ))
7712                then
7713                   Iface_Typ := Designated_Type (Iface_Typ);
7714                   Prim_Typ := Designated_Type (Prim_Typ);
7715                end if;
7716
7717                --  Case of multiple interface types inside a parameter profile
7718
7719                --     (Obj_Param : in out Iface; ...; Param : Iface)
7720
7721                --  If the interface type is implemented, then the matching type
7722                --  in the primitive should be the implementing record type.
7723
7724                if Ekind (Iface_Typ) = E_Record_Type
7725                  and then Is_Interface (Iface_Typ)
7726                  and then Is_Implemented (Ifaces_List, Iface_Typ)
7727                then
7728                   if Prim_Typ /= Typ then
7729                      return False;
7730                   end if;
7731
7732                --  The two parameters must be both mode and subtype conformant
7733
7734                elsif Ekind (Iface_Id) /= Ekind (Prim_Id)
7735                  or else not
7736                    Conforming_Types (Iface_Typ, Prim_Typ, Subtype_Conformant)
7737                then
7738                   return False;
7739                end if;
7740
7741                Next (Iface_Param);
7742                Next (Prim_Param);
7743             end loop;
7744
7745             --  One of the two lists contains more parameters than the other
7746
7747             if Present (Iface_Param) or else Present (Prim_Param) then
7748                return False;
7749             end if;
7750
7751             return True;
7752          end Matches_Prefixed_View_Profile;
7753
7754       --  Start of processing for Check_Synchronized_Overriding
7755
7756       begin
7757          Overridden_Subp := Empty;
7758
7759          --  Def_Id must be an entry or a subprogram. We should skip predefined
7760          --  primitives internally generated by the frontend; however at this
7761          --  stage predefined primitives are still not fully decorated. As a
7762          --  minor optimization we skip here internally generated subprograms.
7763
7764          if (Ekind (Def_Id) /= E_Entry
7765               and then Ekind (Def_Id) /= E_Function
7766               and then Ekind (Def_Id) /= E_Procedure)
7767            or else not Comes_From_Source (Def_Id)
7768          then
7769             return;
7770          end if;
7771
7772          --  Search for the concurrent declaration since it contains the list
7773          --  of all implemented interfaces. In this case, the subprogram is
7774          --  declared within the scope of a protected or a task type.
7775
7776          if Present (Scope (Def_Id))
7777            and then Is_Concurrent_Type (Scope (Def_Id))
7778            and then not Is_Generic_Actual_Type (Scope (Def_Id))
7779          then
7780             Typ := Scope (Def_Id);
7781             In_Scope := True;
7782
7783          --  The enclosing scope is not a synchronized type and the subprogram
7784          --  has no formals.
7785
7786          elsif No (First_Formal (Def_Id)) then
7787             return;
7788
7789          --  The subprogram has formals and hence it may be a primitive of a
7790          --  concurrent type.
7791
7792          else
7793             Typ := Etype (First_Formal (Def_Id));
7794
7795             if Is_Access_Type (Typ) then
7796                Typ := Directly_Designated_Type (Typ);
7797             end if;
7798
7799             if Is_Concurrent_Type (Typ)
7800               and then not Is_Generic_Actual_Type (Typ)
7801             then
7802                In_Scope := False;
7803
7804             --  This case occurs when the concurrent type is declared within
7805             --  a generic unit. As a result the corresponding record has been
7806             --  built and used as the type of the first formal, we just have
7807             --  to retrieve the corresponding concurrent type.
7808
7809             elsif Is_Concurrent_Record_Type (Typ)
7810               and then Present (Corresponding_Concurrent_Type (Typ))
7811             then
7812                Typ := Corresponding_Concurrent_Type (Typ);
7813                In_Scope := False;
7814
7815             else
7816                return;
7817             end if;
7818          end if;
7819
7820          --  There is no overriding to check if is an inherited operation in a
7821          --  type derivation on for a generic actual.
7822
7823          Collect_Interfaces (Typ, Ifaces_List);
7824
7825          if Is_Empty_Elmt_List (Ifaces_List) then
7826             return;
7827          end if;
7828
7829          --  Determine whether entry or subprogram Def_Id overrides a primitive
7830          --  operation that belongs to one of the interfaces in Ifaces_List.
7831
7832          declare
7833             Candidate : Entity_Id := Empty;
7834             Hom       : Entity_Id := Empty;
7835             Iface_Typ : Entity_Id;
7836             Subp      : Entity_Id := Empty;
7837
7838          begin
7839             --  Traverse the homonym chain, looking for a potentially
7840             --  overridden subprogram that belongs to an implemented
7841             --  interface.
7842
7843             Hom := Current_Entity_In_Scope (Def_Id);
7844             while Present (Hom) loop
7845                Subp := Hom;
7846
7847                if Subp = Def_Id
7848                  or else not Is_Overloadable (Subp)
7849                  or else not Is_Primitive (Subp)
7850                  or else not Is_Dispatching_Operation (Subp)
7851                  or else not Present (Find_Dispatching_Type (Subp))
7852                  or else not Is_Interface (Find_Dispatching_Type (Subp))
7853                then
7854                   null;
7855
7856                --  Entries and procedures can override abstract or null
7857                --  interface procedures.
7858
7859                elsif (Ekind (Def_Id) = E_Procedure
7860                         or else Ekind (Def_Id) = E_Entry)
7861                  and then Ekind (Subp) = E_Procedure
7862                  and then Matches_Prefixed_View_Profile
7863                             (Parameter_Specifications (Parent (Def_Id)),
7864                              Parameter_Specifications (Parent (Subp)))
7865                then
7866                   Candidate := Subp;
7867
7868                   --  For an overridden subprogram Subp, check whether the mode
7869                   --  of its first parameter is correct depending on the kind
7870                   --  of synchronized type.
7871
7872                   declare
7873                      Formal : constant Node_Id := First_Formal (Candidate);
7874
7875                   begin
7876                      --  In order for an entry or a protected procedure to
7877                      --  override, the first parameter of the overridden
7878                      --  routine must be of mode "out", "in out" or
7879                      --  access-to-variable.
7880
7881                      if (Ekind (Candidate) = E_Entry
7882                          or else Ekind (Candidate) = E_Procedure)
7883                        and then Is_Protected_Type (Typ)
7884                        and then Ekind (Formal) /= E_In_Out_Parameter
7885                        and then Ekind (Formal) /= E_Out_Parameter
7886                        and then Nkind (Parameter_Type (Parent (Formal)))
7887                                   /= N_Access_Definition
7888                      then
7889                         null;
7890
7891                      --  All other cases are OK since a task entry or routine
7892                      --  does not have a restriction on the mode of the first
7893                      --  parameter of the overridden interface routine.
7894
7895                      else
7896                         Overridden_Subp := Candidate;
7897                         return;
7898                      end if;
7899                   end;
7900
7901                --  Functions can override abstract interface functions
7902
7903                elsif Ekind (Def_Id) = E_Function
7904                  and then Ekind (Subp) = E_Function
7905                  and then Matches_Prefixed_View_Profile
7906                             (Parameter_Specifications (Parent (Def_Id)),
7907                              Parameter_Specifications (Parent (Subp)))
7908                  and then Etype (Result_Definition (Parent (Def_Id))) =
7909                           Etype (Result_Definition (Parent (Subp)))
7910                then
7911                   Overridden_Subp := Subp;
7912                   return;
7913                end if;
7914
7915                Hom := Homonym (Hom);
7916             end loop;
7917
7918             --  After examining all candidates for overriding, we are left with
7919             --  the best match which is a mode incompatible interface routine.
7920             --  Do not emit an error if the Expander is active since this error
7921             --  will be detected later on after all concurrent types are
7922             --  expanded and all wrappers are built. This check is meant for
7923             --  spec-only compilations.
7924
7925             if Present (Candidate) and then not Expander_Active then
7926                Iface_Typ :=
7927                  Find_Parameter_Type (Parent (First_Formal (Candidate)));
7928
7929                --  Def_Id is primitive of a protected type, declared inside the
7930                --  type, and the candidate is primitive of a limited or
7931                --  synchronized interface.
7932
7933                if In_Scope
7934                  and then Is_Protected_Type (Typ)
7935                  and then
7936                    (Is_Limited_Interface (Iface_Typ)
7937                       or else Is_Protected_Interface (Iface_Typ)
7938                       or else Is_Synchronized_Interface (Iface_Typ)
7939                       or else Is_Task_Interface (Iface_Typ))
7940                then
7941                   Error_Msg_NE
7942                     ("first formal of & must be of mode `OUT`, `IN OUT`"
7943                       & " or access-to-variable", Typ, Candidate);
7944                   Error_Msg_N
7945                     ("\in order to be overridden by protected procedure or "
7946                       & "entry (RM 9.4(11.9/2))", Typ);
7947                end if;
7948             end if;
7949
7950             Overridden_Subp := Candidate;
7951             return;
7952          end;
7953       end Check_Synchronized_Overriding;
7954
7955       ----------------------------
7956       -- Is_Private_Declaration --
7957       ----------------------------
7958
7959       function Is_Private_Declaration (E : Entity_Id) return Boolean is
7960          Priv_Decls : List_Id;
7961          Decl       : constant Node_Id := Unit_Declaration_Node (E);
7962
7963       begin
7964          if Is_Package_Or_Generic_Package (Current_Scope)
7965            and then In_Private_Part (Current_Scope)
7966          then
7967             Priv_Decls :=
7968               Private_Declarations (
7969                 Specification (Unit_Declaration_Node (Current_Scope)));
7970
7971             return In_Package_Body (Current_Scope)
7972               or else
7973                 (Is_List_Member (Decl)
7974                    and then List_Containing (Decl) = Priv_Decls)
7975               or else (Nkind (Parent (Decl)) = N_Package_Specification
7976                          and then not
7977                            Is_Compilation_Unit
7978                              (Defining_Entity (Parent (Decl)))
7979                          and then List_Containing (Parent (Parent (Decl)))
7980                                     = Priv_Decls);
7981          else
7982             return False;
7983          end if;
7984       end Is_Private_Declaration;
7985
7986       --------------------------
7987       -- Is_Overriding_Alias --
7988       --------------------------
7989
7990       function Is_Overriding_Alias
7991         (Old_E : Entity_Id;
7992          New_E : Entity_Id) return Boolean
7993       is
7994          AO : constant Entity_Id := Alias (Old_E);
7995          AN : constant Entity_Id := Alias (New_E);
7996
7997       begin
7998          return Scope (AO) /= Scope (AN)
7999            or else No (DTC_Entity (AO))
8000            or else No (DTC_Entity (AN))
8001            or else DT_Position (AO) = DT_Position (AN);
8002       end Is_Overriding_Alias;
8003
8004    --  Start of processing for New_Overloaded_Entity
8005
8006    begin
8007       --  We need to look for an entity that S may override. This must be a
8008       --  homonym in the current scope, so we look for the first homonym of
8009       --  S in the current scope as the starting point for the search.
8010
8011       E := Current_Entity_In_Scope (S);
8012
8013       --  Ada 2005 (AI-251): Derivation of abstract interface primitives.
8014       --  They are directly added to the list of primitive operations of
8015       --  Derived_Type, unless this is a rederivation in the private part
8016       --  of an operation that was already derived in the visible part of
8017       --  the current package.
8018
8019       if Ada_Version >= Ada_2005
8020         and then Present (Derived_Type)
8021         and then Present (Alias (S))
8022         and then Is_Dispatching_Operation (Alias (S))
8023         and then Present (Find_Dispatching_Type (Alias (S)))
8024         and then Is_Interface (Find_Dispatching_Type (Alias (S)))
8025       then
8026          --  For private types, when the full-view is processed we propagate to
8027          --  the full view the non-overridden entities whose attribute "alias"
8028          --  references an interface primitive. These entities were added by
8029          --  Derive_Subprograms to ensure that interface primitives are
8030          --  covered.
8031
8032          --  Inside_Freeze_Actions is non zero when S corresponds with an
8033          --  internal entity that links an interface primitive with its
8034          --  covering primitive through attribute Interface_Alias (see
8035          --  Add_Internal_Interface_Entities).
8036
8037          if Inside_Freezing_Actions = 0
8038            and then Is_Package_Or_Generic_Package (Current_Scope)
8039            and then In_Private_Part (Current_Scope)
8040            and then Nkind (Parent (E)) = N_Private_Extension_Declaration
8041            and then Nkind (Parent (S)) = N_Full_Type_Declaration
8042            and then Full_View (Defining_Identifier (Parent (E)))
8043                       = Defining_Identifier (Parent (S))
8044            and then Alias (E) = Alias (S)
8045          then
8046             Check_Operation_From_Private_View (S, E);
8047             Set_Is_Dispatching_Operation (S);
8048
8049          --  Common case
8050
8051          else
8052             Enter_Overloaded_Entity (S);
8053             Check_Dispatching_Operation (S, Empty);
8054             Check_For_Primitive_Subprogram (Is_Primitive_Subp);
8055          end if;
8056
8057          return;
8058       end if;
8059
8060       --  If there is no homonym then this is definitely not overriding
8061
8062       if No (E) then
8063          Enter_Overloaded_Entity (S);
8064          Check_Dispatching_Operation (S, Empty);
8065          Check_For_Primitive_Subprogram (Is_Primitive_Subp);
8066
8067          --  If subprogram has an explicit declaration, check whether it
8068          --  has an overriding indicator.
8069
8070          if Comes_From_Source (S) then
8071             Check_Synchronized_Overriding (S, Overridden_Subp);
8072
8073             --  (Ada 2012: AI05-0125-1): If S is a dispatching operation then
8074             --  it may have overridden some hidden inherited primitive. Update
8075             --  Overridden_Subp to avoid spurious errors when checking the
8076             --  overriding indicator.
8077
8078             if Ada_Version >= Ada_2012
8079               and then No (Overridden_Subp)
8080               and then Is_Dispatching_Operation (S)
8081               and then Present (Overridden_Operation (S))
8082             then
8083                Overridden_Subp := Overridden_Operation (S);
8084             end if;
8085
8086             Check_Overriding_Indicator
8087               (S, Overridden_Subp, Is_Primitive => Is_Primitive_Subp);
8088          end if;
8089
8090       --  If there is a homonym that is not overloadable, then we have an
8091       --  error, except for the special cases checked explicitly below.
8092
8093       elsif not Is_Overloadable (E) then
8094
8095          --  Check for spurious conflict produced by a subprogram that has the
8096          --  same name as that of the enclosing generic package. The conflict
8097          --  occurs within an instance, between the subprogram and the renaming
8098          --  declaration for the package. After the subprogram, the package
8099          --  renaming declaration becomes hidden.
8100
8101          if Ekind (E) = E_Package
8102            and then Present (Renamed_Object (E))
8103            and then Renamed_Object (E) = Current_Scope
8104            and then Nkind (Parent (Renamed_Object (E))) =
8105                                                      N_Package_Specification
8106            and then Present (Generic_Parent (Parent (Renamed_Object (E))))
8107          then
8108             Set_Is_Hidden (E);
8109             Set_Is_Immediately_Visible (E, False);
8110             Enter_Overloaded_Entity (S);
8111             Set_Homonym (S, Homonym (E));
8112             Check_Dispatching_Operation (S, Empty);
8113             Check_Overriding_Indicator (S, Empty, Is_Primitive => False);
8114
8115          --  If the subprogram is implicit it is hidden by the previous
8116          --  declaration. However if it is dispatching, it must appear in the
8117          --  dispatch table anyway, because it can be dispatched to even if it
8118          --  cannot be called directly.
8119
8120          elsif Present (Alias (S)) and then not Comes_From_Source (S) then
8121             Set_Scope (S, Current_Scope);
8122
8123             if Is_Dispatching_Operation (Alias (S)) then
8124                Check_Dispatching_Operation (S, Empty);
8125             end if;
8126
8127             return;
8128
8129          else
8130             Error_Msg_Sloc := Sloc (E);
8131
8132             --  Generate message, with useful additional warning if in generic
8133
8134             if Is_Generic_Unit (E) then
8135                Error_Msg_N ("previous generic unit cannot be overloaded", S);
8136                Error_Msg_N ("\& conflicts with declaration#", S);
8137             else
8138                Error_Msg_N ("& conflicts with declaration#", S);
8139             end if;
8140
8141             return;
8142          end if;
8143
8144       --  E exists and is overloadable
8145
8146       else
8147          Check_Synchronized_Overriding (S, Overridden_Subp);
8148
8149          --  Loop through E and its homonyms to determine if any of them is
8150          --  the candidate for overriding by S.
8151
8152          while Present (E) loop
8153
8154             --  Definitely not interesting if not in the current scope
8155
8156             if Scope (E) /= Current_Scope then
8157                null;
8158
8159             --  Check if we have type conformance
8160
8161             elsif Type_Conformant (E, S) then
8162
8163                --  If the old and new entities have the same profile and one
8164                --  is not the body of the other, then this is an error, unless
8165                --  one of them is implicitly declared.
8166
8167                --  There are some cases when both can be implicit, for example
8168                --  when both a literal and a function that overrides it are
8169                --  inherited in a derivation, or when an inherited operation
8170                --  of a tagged full type overrides the inherited operation of
8171                --  a private extension. Ada 83 had a special rule for the
8172                --  literal case. In Ada95, the later implicit operation hides
8173                --  the former, and the literal is always the former. In the
8174                --  odd case where both are derived operations declared at the
8175                --  same point, both operations should be declared, and in that
8176                --  case we bypass the following test and proceed to the next
8177                --  part. This can only occur for certain obscure cases in
8178                --  instances, when an operation on a type derived from a formal
8179                --  private type does not override a homograph inherited from
8180                --  the actual. In subsequent derivations of such a type, the
8181                --  DT positions of these operations remain distinct, if they
8182                --  have been set.
8183
8184                if Present (Alias (S))
8185                  and then (No (Alias (E))
8186                             or else Comes_From_Source (E)
8187                             or else Is_Abstract_Subprogram (S)
8188                             or else
8189                               (Is_Dispatching_Operation (E)
8190                                  and then Is_Overriding_Alias (E, S)))
8191                  and then Ekind (E) /= E_Enumeration_Literal
8192                then
8193                   --  When an derived operation is overloaded it may be due to
8194                   --  the fact that the full view of a private extension
8195                   --  re-inherits. It has to be dealt with.
8196
8197                   if Is_Package_Or_Generic_Package (Current_Scope)
8198                     and then In_Private_Part (Current_Scope)
8199                   then
8200                      Check_Operation_From_Private_View (S, E);
8201                   end if;
8202
8203                   --  In any case the implicit operation remains hidden by the
8204                   --  existing declaration, which is overriding. Indicate that
8205                   --  E overrides the operation from which S is inherited.
8206
8207                   if Present (Alias (S)) then
8208                      Set_Overridden_Operation (E, Alias (S));
8209                   else
8210                      Set_Overridden_Operation (E, S);
8211                   end if;
8212
8213                   if Comes_From_Source (E) then
8214                      Check_Overriding_Indicator (E, S, Is_Primitive => False);
8215                   end if;
8216
8217                   return;
8218
8219                --  Within an instance, the renaming declarations for actual
8220                --  subprograms may become ambiguous, but they do not hide each
8221                --  other.
8222
8223                elsif Ekind (E) /= E_Entry
8224                  and then not Comes_From_Source (E)
8225                  and then not Is_Generic_Instance (E)
8226                  and then (Present (Alias (E))
8227                             or else Is_Intrinsic_Subprogram (E))
8228                  and then (not In_Instance
8229                             or else No (Parent (E))
8230                             or else Nkind (Unit_Declaration_Node (E)) /=
8231                                       N_Subprogram_Renaming_Declaration)
8232                then
8233                   --  A subprogram child unit is not allowed to override an
8234                   --  inherited subprogram (10.1.1(20)).
8235
8236                   if Is_Child_Unit (S) then
8237                      Error_Msg_N
8238                        ("child unit overrides inherited subprogram in parent",
8239                         S);
8240                      return;
8241                   end if;
8242
8243                   if Is_Non_Overriding_Operation (E, S) then
8244                      Enter_Overloaded_Entity (S);
8245
8246                      if No (Derived_Type)
8247                        or else Is_Tagged_Type (Derived_Type)
8248                      then
8249                         Check_Dispatching_Operation (S, Empty);
8250                      end if;
8251
8252                      return;
8253                   end if;
8254
8255                   --  E is a derived operation or an internal operator which
8256                   --  is being overridden. Remove E from further visibility.
8257                   --  Furthermore, if E is a dispatching operation, it must be
8258                   --  replaced in the list of primitive operations of its type
8259                   --  (see Override_Dispatching_Operation).
8260
8261                   Overridden_Subp := E;
8262
8263                   declare
8264                      Prev : Entity_Id;
8265
8266                   begin
8267                      Prev := First_Entity (Current_Scope);
8268                      while Present (Prev)
8269                        and then Next_Entity (Prev) /= E
8270                      loop
8271                         Next_Entity (Prev);
8272                      end loop;
8273
8274                      --  It is possible for E to be in the current scope and
8275                      --  yet not in the entity chain. This can only occur in a
8276                      --  generic context where E is an implicit concatenation
8277                      --  in the formal part, because in a generic body the
8278                      --  entity chain starts with the formals.
8279
8280                      pragma Assert
8281                        (Present (Prev) or else Chars (E) = Name_Op_Concat);
8282
8283                      --  E must be removed both from the entity_list of the
8284                      --  current scope, and from the visibility chain
8285
8286                      if Debug_Flag_E then
8287                         Write_Str ("Override implicit operation ");
8288                         Write_Int (Int (E));
8289                         Write_Eol;
8290                      end if;
8291
8292                      --  If E is a predefined concatenation, it stands for four
8293                      --  different operations. As a result, a single explicit
8294                      --  declaration does not hide it. In a possible ambiguous
8295                      --  situation, Disambiguate chooses the user-defined op,
8296                      --  so it is correct to retain the previous internal one.
8297
8298                      if Chars (E) /= Name_Op_Concat
8299                        or else Ekind (E) /= E_Operator
8300                      then
8301                         --  For nondispatching derived operations that are
8302                         --  overridden by a subprogram declared in the private
8303                         --  part of a package, we retain the derived subprogram
8304                         --  but mark it as not immediately visible. If the
8305                         --  derived operation was declared in the visible part
8306                         --  then this ensures that it will still be visible
8307                         --  outside the package with the proper signature
8308                         --  (calls from outside must also be directed to this
8309                         --  version rather than the overriding one, unlike the
8310                         --  dispatching case). Calls from inside the package
8311                         --  will still resolve to the overriding subprogram
8312                         --  since the derived one is marked as not visible
8313                         --  within the package.
8314
8315                         --  If the private operation is dispatching, we achieve
8316                         --  the overriding by keeping the implicit operation
8317                         --  but setting its alias to be the overriding one. In
8318                         --  this fashion the proper body is executed in all
8319                         --  cases, but the original signature is used outside
8320                         --  of the package.
8321
8322                         --  If the overriding is not in the private part, we
8323                         --  remove the implicit operation altogether.
8324
8325                         if Is_Private_Declaration (S) then
8326                            if not Is_Dispatching_Operation (E) then
8327                               Set_Is_Immediately_Visible (E, False);
8328                            else
8329                               --  Work done in Override_Dispatching_Operation,
8330                               --  so nothing else need to be done here.
8331
8332                               null;
8333                            end if;
8334
8335                         else
8336                            --  Find predecessor of E in Homonym chain
8337
8338                            if E = Current_Entity (E) then
8339                               Prev_Vis := Empty;
8340                            else
8341                               Prev_Vis := Current_Entity (E);
8342                               while Homonym (Prev_Vis) /= E loop
8343                                  Prev_Vis := Homonym (Prev_Vis);
8344                               end loop;
8345                            end if;
8346
8347                            if Prev_Vis /= Empty then
8348
8349                               --  Skip E in the visibility chain
8350
8351                               Set_Homonym (Prev_Vis, Homonym (E));
8352
8353                            else
8354                               Set_Name_Entity_Id (Chars (E), Homonym (E));
8355                            end if;
8356
8357                            Set_Next_Entity (Prev, Next_Entity (E));
8358
8359                            if No (Next_Entity (Prev)) then
8360                               Set_Last_Entity (Current_Scope, Prev);
8361                            end if;
8362                         end if;
8363                      end if;
8364
8365                      Enter_Overloaded_Entity (S);
8366
8367                      --  For entities generated by Derive_Subprograms the
8368                      --  overridden operation is the inherited primitive
8369                      --  (which is available through the attribute alias).
8370
8371                      if not (Comes_From_Source (E))
8372                        and then Is_Dispatching_Operation (E)
8373                        and then Find_Dispatching_Type (E) =
8374                                 Find_Dispatching_Type (S)
8375                        and then Present (Alias (E))
8376                        and then Comes_From_Source (Alias (E))
8377                      then
8378                         Set_Overridden_Operation (S, Alias (E));
8379
8380                      --  Normal case of setting entity as overridden
8381
8382                      --  Note: Static_Initialization and Overridden_Operation
8383                      --  attributes use the same field in subprogram entities.
8384                      --  Static_Initialization is only defined for internal
8385                      --  initialization procedures, where Overridden_Operation
8386                      --  is irrelevant. Therefore the setting of this attribute
8387                      --  must check whether the target is an init_proc.
8388
8389                      elsif not Is_Init_Proc (S) then
8390                         Set_Overridden_Operation (S, E);
8391                      end if;
8392
8393                      Check_Overriding_Indicator (S, E, Is_Primitive => True);
8394
8395                      --  If S is a user-defined subprogram or a null procedure
8396                      --  expanded to override an inherited null procedure, or a
8397                      --  predefined dispatching primitive then indicate that E
8398                      --  overrides the operation from which S is inherited.
8399
8400                      if Comes_From_Source (S)
8401                        or else
8402                          (Present (Parent (S))
8403                            and then
8404                              Nkind (Parent (S)) = N_Procedure_Specification
8405                            and then
8406                              Null_Present (Parent (S)))
8407                        or else
8408                          (Present (Alias (E))
8409                            and then
8410                              Is_Predefined_Dispatching_Operation (Alias (E)))
8411                      then
8412                         if Present (Alias (E)) then
8413                            Set_Overridden_Operation (S, Alias (E));
8414                         end if;
8415                      end if;
8416
8417                      if Is_Dispatching_Operation (E) then
8418
8419                         --  An overriding dispatching subprogram inherits the
8420                         --  convention of the overridden subprogram (AI-117).
8421
8422                         Set_Convention (S, Convention (E));
8423                         Check_Dispatching_Operation (S, E);
8424
8425                      else
8426                         Check_Dispatching_Operation (S, Empty);
8427                      end if;
8428
8429                      Check_For_Primitive_Subprogram
8430                        (Is_Primitive_Subp, Is_Overriding => True);
8431                      goto Check_Inequality;
8432                   end;
8433
8434                --  Apparent redeclarations in instances can occur when two
8435                --  formal types get the same actual type. The subprograms in
8436                --  in the instance are legal,  even if not callable from the
8437                --  outside. Calls from within are disambiguated elsewhere.
8438                --  For dispatching operations in the visible part, the usual
8439                --  rules apply, and operations with the same profile are not
8440                --  legal (B830001).
8441
8442                elsif (In_Instance_Visible_Part
8443                        and then not Is_Dispatching_Operation (E))
8444                  or else In_Instance_Not_Visible
8445                then
8446                   null;
8447
8448                --  Here we have a real error (identical profile)
8449
8450                else
8451                   Error_Msg_Sloc := Sloc (E);
8452
8453                   --  Avoid cascaded errors if the entity appears in
8454                   --  subsequent calls.
8455
8456                   Set_Scope (S, Current_Scope);
8457
8458                   --  Generate error, with extra useful warning for the case
8459                   --  of a generic instance with no completion.
8460
8461                   if Is_Generic_Instance (S)
8462                     and then not Has_Completion (E)
8463                   then
8464                      Error_Msg_N
8465                        ("instantiation cannot provide body for&", S);
8466                      Error_Msg_N ("\& conflicts with declaration#", S);
8467                   else
8468                      Error_Msg_N ("& conflicts with declaration#", S);
8469                   end if;
8470
8471                   return;
8472                end if;
8473
8474             else
8475                --  If one subprogram has an access parameter and the other
8476                --  a parameter of an access type, calls to either might be
8477                --  ambiguous. Verify that parameters match except for the
8478                --  access parameter.
8479
8480                if May_Hide_Profile then
8481                   declare
8482                      F1 : Entity_Id;
8483                      F2 : Entity_Id;
8484
8485                   begin
8486                      F1 := First_Formal (S);
8487                      F2 := First_Formal (E);
8488                      while Present (F1) and then Present (F2) loop
8489                         if Is_Access_Type (Etype (F1)) then
8490                            if not Is_Access_Type (Etype (F2))
8491                               or else not Conforming_Types
8492                                 (Designated_Type (Etype (F1)),
8493                                  Designated_Type (Etype (F2)),
8494                                  Type_Conformant)
8495                            then
8496                               May_Hide_Profile := False;
8497                            end if;
8498
8499                         elsif
8500                           not Conforming_Types
8501                             (Etype (F1), Etype (F2), Type_Conformant)
8502                         then
8503                            May_Hide_Profile := False;
8504                         end if;
8505
8506                         Next_Formal (F1);
8507                         Next_Formal (F2);
8508                      end loop;
8509
8510                      if May_Hide_Profile
8511                        and then No (F1)
8512                        and then No (F2)
8513                      then
8514                         Error_Msg_NE ("calls to& may be ambiguous?", S, S);
8515                      end if;
8516                   end;
8517                end if;
8518             end if;
8519
8520             E := Homonym (E);
8521          end loop;
8522
8523          --  On exit, we know that S is a new entity
8524
8525          Enter_Overloaded_Entity (S);
8526          Check_For_Primitive_Subprogram (Is_Primitive_Subp);
8527          Check_Overriding_Indicator
8528            (S, Overridden_Subp, Is_Primitive => Is_Primitive_Subp);
8529
8530          --  Overloading is not allowed in SPARK or ALFA
8531
8532          Error_Msg_Sloc := Sloc (Homonym (S));
8533          Check_Formal_Restriction ("overloading not allowed with entity#", S);
8534
8535          --  If S is a derived operation for an untagged type then by
8536          --  definition it's not a dispatching operation (even if the parent
8537          --  operation was dispatching), so we don't call
8538          --  Check_Dispatching_Operation in that case.
8539
8540          if No (Derived_Type)
8541            or else Is_Tagged_Type (Derived_Type)
8542          then
8543             Check_Dispatching_Operation (S, Empty);
8544          end if;
8545       end if;
8546
8547       --  If this is a user-defined equality operator that is not a derived
8548       --  subprogram, create the corresponding inequality. If the operation is
8549       --  dispatching, the expansion is done elsewhere, and we do not create
8550       --  an explicit inequality operation.
8551
8552       <<Check_Inequality>>
8553          if Chars (S) = Name_Op_Eq
8554            and then Etype (S) = Standard_Boolean
8555            and then Present (Parent (S))
8556            and then not Is_Dispatching_Operation (S)
8557          then
8558             Make_Inequality_Operator (S);
8559
8560             if Ada_Version >= Ada_2012 then
8561                Check_Untagged_Equality (S);
8562             end if;
8563          end if;
8564    end New_Overloaded_Entity;
8565
8566    ---------------------
8567    -- Process_Formals --
8568    ---------------------
8569
8570    procedure Process_Formals
8571      (T           : List_Id;
8572       Related_Nod : Node_Id)
8573    is
8574       Param_Spec  : Node_Id;
8575       Formal      : Entity_Id;
8576       Formal_Type : Entity_Id;
8577       Default     : Node_Id;
8578       Ptype       : Entity_Id;
8579
8580       Num_Out_Params  : Nat       := 0;
8581       First_Out_Param : Entity_Id := Empty;
8582       --  Used for setting Is_Only_Out_Parameter
8583
8584       function Designates_From_With_Type (Typ : Entity_Id) return Boolean;
8585       --  Determine whether an access type designates a type coming from a
8586       --  limited view.
8587
8588       function Is_Class_Wide_Default (D : Node_Id) return Boolean;
8589       --  Check whether the default has a class-wide type. After analysis the
8590       --  default has the type of the formal, so we must also check explicitly
8591       --  for an access attribute.
8592
8593       -------------------------------
8594       -- Designates_From_With_Type --
8595       -------------------------------
8596
8597       function Designates_From_With_Type (Typ : Entity_Id) return Boolean is
8598          Desig : Entity_Id := Typ;
8599
8600       begin
8601          if Is_Access_Type (Desig) then
8602             Desig := Directly_Designated_Type (Desig);
8603          end if;
8604
8605          if Is_Class_Wide_Type (Desig) then
8606             Desig := Root_Type (Desig);
8607          end if;
8608
8609          return
8610            Ekind (Desig) = E_Incomplete_Type
8611              and then From_With_Type (Desig);
8612       end Designates_From_With_Type;
8613
8614       ---------------------------
8615       -- Is_Class_Wide_Default --
8616       ---------------------------
8617
8618       function Is_Class_Wide_Default (D : Node_Id) return Boolean is
8619       begin
8620          return Is_Class_Wide_Type (Designated_Type (Etype (D)))
8621            or else (Nkind (D) =  N_Attribute_Reference
8622                       and then Attribute_Name (D) = Name_Access
8623                       and then Is_Class_Wide_Type (Etype (Prefix (D))));
8624       end Is_Class_Wide_Default;
8625
8626    --  Start of processing for Process_Formals
8627
8628    begin
8629       --  In order to prevent premature use of the formals in the same formal
8630       --  part, the Ekind is left undefined until all default expressions are
8631       --  analyzed. The Ekind is established in a separate loop at the end.
8632
8633       Param_Spec := First (T);
8634       while Present (Param_Spec) loop
8635          Formal := Defining_Identifier (Param_Spec);
8636          Set_Never_Set_In_Source (Formal, True);
8637          Enter_Name (Formal);
8638
8639          --  Case of ordinary parameters
8640
8641          if Nkind (Parameter_Type (Param_Spec)) /= N_Access_Definition then
8642             Find_Type (Parameter_Type (Param_Spec));
8643             Ptype := Parameter_Type (Param_Spec);
8644
8645             if Ptype = Error then
8646                goto Continue;
8647             end if;
8648
8649             Formal_Type := Entity (Ptype);
8650
8651             if Is_Incomplete_Type (Formal_Type)
8652               or else
8653                (Is_Class_Wide_Type (Formal_Type)
8654                   and then Is_Incomplete_Type (Root_Type (Formal_Type)))
8655             then
8656                --  Ada 2005 (AI-326): Tagged incomplete types allowed in
8657                --  primitive operations, as long as their completion is
8658                --  in the same declarative part. If in the private part
8659                --  this means that the type cannot be a Taft-amendment type.
8660                --  Check is done on package exit. For access to subprograms,
8661                --  the use is legal for Taft-amendment types.
8662
8663                if Is_Tagged_Type (Formal_Type) then
8664                   if Ekind (Scope (Current_Scope)) = E_Package
8665                     and then not From_With_Type (Formal_Type)
8666                     and then not Is_Class_Wide_Type (Formal_Type)
8667                   then
8668                      if not Nkind_In
8669                        (Parent (T), N_Access_Function_Definition,
8670                                     N_Access_Procedure_Definition)
8671                      then
8672                         Append_Elmt
8673                           (Current_Scope,
8674                              Private_Dependents (Base_Type (Formal_Type)));
8675
8676                         --  Freezing is delayed to ensure that Register_Prim
8677                         --  will get called for this operation, which is needed
8678                         --  in cases where static dispatch tables aren't built.
8679                         --  (Note that the same is done for controlling access
8680                         --  parameter cases in function Access_Definition.)
8681
8682                         Set_Has_Delayed_Freeze (Current_Scope);
8683                      end if;
8684                   end if;
8685
8686                --  Special handling of Value_Type for CIL case
8687
8688                elsif Is_Value_Type (Formal_Type) then
8689                   null;
8690
8691                elsif not Nkind_In (Parent (T), N_Access_Function_Definition,
8692                                                N_Access_Procedure_Definition)
8693                then
8694
8695                   --  AI05-0151: Tagged incomplete types are allowed in all
8696                   --  formal parts. Untagged incomplete types are not allowed
8697                   --  in bodies.
8698
8699                   if Ada_Version >= Ada_2012 then
8700                      if Is_Tagged_Type (Formal_Type) then
8701                         null;
8702
8703                      elsif Nkind_In (Parent (Parent (T)), N_Accept_Statement,
8704                                                           N_Entry_Body,
8705                                                           N_Subprogram_Body)
8706                      then
8707                         Error_Msg_NE
8708                           ("invalid use of untagged incomplete type&",
8709                            Ptype, Formal_Type);
8710                      end if;
8711
8712                   else
8713                      Error_Msg_NE
8714                        ("invalid use of incomplete type&",
8715                         Param_Spec, Formal_Type);
8716
8717                      --  Further checks on the legality of incomplete types
8718                      --  in formal parts are delayed until the freeze point
8719                      --  of the enclosing subprogram or access to subprogram.
8720                   end if;
8721                end if;
8722
8723             elsif Ekind (Formal_Type) = E_Void then
8724                Error_Msg_NE
8725                  ("premature use of&",
8726                   Parameter_Type (Param_Spec), Formal_Type);
8727             end if;
8728
8729             --  Ada 2005 (AI-231): Create and decorate an internal subtype
8730             --  declaration corresponding to the null-excluding type of the
8731             --  formal in the enclosing scope. Finally, replace the parameter
8732             --  type of the formal with the internal subtype.
8733
8734             if Ada_Version >= Ada_2005
8735               and then Null_Exclusion_Present (Param_Spec)
8736             then
8737                if not Is_Access_Type (Formal_Type) then
8738                   Error_Msg_N
8739                     ("`NOT NULL` allowed only for an access type", Param_Spec);
8740
8741                else
8742                   if Can_Never_Be_Null (Formal_Type)
8743                     and then Comes_From_Source (Related_Nod)
8744                   then
8745                      Error_Msg_NE
8746                        ("`NOT NULL` not allowed (& already excludes null)",
8747                         Param_Spec, Formal_Type);
8748                   end if;
8749
8750                   Formal_Type :=
8751                     Create_Null_Excluding_Itype
8752                       (T           => Formal_Type,
8753                        Related_Nod => Related_Nod,
8754                        Scope_Id    => Scope (Current_Scope));
8755
8756                   --  If the designated type of the itype is an itype we
8757                   --  decorate it with the Has_Delayed_Freeze attribute to
8758                   --  avoid problems with the backend.
8759
8760                   --  Example:
8761                   --     type T is access procedure;
8762                   --     procedure Op (O : not null T);
8763
8764                   if Is_Itype (Directly_Designated_Type (Formal_Type)) then
8765                      Set_Has_Delayed_Freeze (Formal_Type);
8766                   end if;
8767                end if;
8768             end if;
8769
8770          --  An access formal type
8771
8772          else
8773             Formal_Type :=
8774               Access_Definition (Related_Nod, Parameter_Type (Param_Spec));
8775
8776             --  No need to continue if we already notified errors
8777
8778             if not Present (Formal_Type) then
8779                return;
8780             end if;
8781
8782             --  Ada 2005 (AI-254)
8783
8784             declare
8785                AD : constant Node_Id :=
8786                       Access_To_Subprogram_Definition
8787                         (Parameter_Type (Param_Spec));
8788             begin
8789                if Present (AD) and then Protected_Present (AD) then
8790                   Formal_Type :=
8791                     Replace_Anonymous_Access_To_Protected_Subprogram
8792                       (Param_Spec);
8793                end if;
8794             end;
8795          end if;
8796
8797          Set_Etype (Formal, Formal_Type);
8798          Default := Expression (Param_Spec);
8799
8800          if Present (Default) then
8801             Check_Formal_Restriction
8802               ("default expression is not allowed", Default);
8803
8804             if Out_Present (Param_Spec) then
8805                Error_Msg_N
8806                  ("default initialization only allowed for IN parameters",
8807                   Param_Spec);
8808             end if;
8809
8810             --  Do the special preanalysis of the expression (see section on
8811             --  "Handling of Default Expressions" in the spec of package Sem).
8812
8813             Preanalyze_Spec_Expression (Default, Formal_Type);
8814
8815             --  An access to constant cannot be the default for
8816             --  an access parameter that is an access to variable.
8817
8818             if Ekind (Formal_Type) = E_Anonymous_Access_Type
8819               and then not Is_Access_Constant (Formal_Type)
8820               and then Is_Access_Type (Etype (Default))
8821               and then Is_Access_Constant (Etype (Default))
8822             then
8823                Error_Msg_N
8824                  ("formal that is access to variable cannot be initialized " &
8825                     "with an access-to-constant expression", Default);
8826             end if;
8827
8828             --  Check that the designated type of an access parameter's default
8829             --  is not a class-wide type unless the parameter's designated type
8830             --  is also class-wide.
8831
8832             if Ekind (Formal_Type) = E_Anonymous_Access_Type
8833               and then not Designates_From_With_Type (Formal_Type)
8834               and then Is_Class_Wide_Default (Default)
8835               and then not Is_Class_Wide_Type (Designated_Type (Formal_Type))
8836             then
8837                Error_Msg_N
8838                  ("access to class-wide expression not allowed here", Default);
8839             end if;
8840
8841             --  Check incorrect use of dynamically tagged expressions
8842
8843             if Is_Tagged_Type (Formal_Type) then
8844                Check_Dynamically_Tagged_Expression
8845                  (Expr        => Default,
8846                   Typ         => Formal_Type,
8847                   Related_Nod => Default);
8848             end if;
8849          end if;
8850
8851          --  Ada 2005 (AI-231): Static checks
8852
8853          if Ada_Version >= Ada_2005
8854            and then Is_Access_Type (Etype (Formal))
8855            and then Can_Never_Be_Null (Etype (Formal))
8856          then
8857             Null_Exclusion_Static_Checks (Param_Spec);
8858          end if;
8859
8860       <<Continue>>
8861          Next (Param_Spec);
8862       end loop;
8863
8864       --  If this is the formal part of a function specification, analyze the
8865       --  subtype mark in the context where the formals are visible but not
8866       --  yet usable, and may hide outer homographs.
8867
8868       if Nkind (Related_Nod) = N_Function_Specification then
8869          Analyze_Return_Type (Related_Nod);
8870       end if;
8871
8872       --  Now set the kind (mode) of each formal
8873
8874       Param_Spec := First (T);
8875       while Present (Param_Spec) loop
8876          Formal := Defining_Identifier (Param_Spec);
8877          Set_Formal_Mode (Formal);
8878
8879          if Ekind (Formal) = E_In_Parameter then
8880             Set_Default_Value (Formal, Expression (Param_Spec));
8881
8882             if Present (Expression (Param_Spec)) then
8883                Default :=  Expression (Param_Spec);
8884
8885                if Is_Scalar_Type (Etype (Default)) then
8886                   if Nkind
8887                        (Parameter_Type (Param_Spec)) /= N_Access_Definition
8888                   then
8889                      Formal_Type := Entity (Parameter_Type (Param_Spec));
8890
8891                   else
8892                      Formal_Type := Access_Definition
8893                        (Related_Nod, Parameter_Type (Param_Spec));
8894                   end if;
8895
8896                   Apply_Scalar_Range_Check (Default, Formal_Type);
8897                end if;
8898             end if;
8899
8900          elsif Ekind (Formal) = E_Out_Parameter then
8901             Num_Out_Params := Num_Out_Params + 1;
8902
8903             if Num_Out_Params = 1 then
8904                First_Out_Param := Formal;
8905             end if;
8906
8907          elsif Ekind (Formal) = E_In_Out_Parameter then
8908             Num_Out_Params := Num_Out_Params + 1;
8909          end if;
8910
8911          Next (Param_Spec);
8912       end loop;
8913
8914       if Present (First_Out_Param) and then Num_Out_Params = 1 then
8915          Set_Is_Only_Out_Parameter (First_Out_Param);
8916       end if;
8917    end Process_Formals;
8918
8919    ------------------
8920    -- Process_PPCs --
8921    ------------------
8922
8923    procedure Process_PPCs
8924      (N       : Node_Id;
8925       Spec_Id : Entity_Id;
8926       Body_Id : Entity_Id)
8927    is
8928       Loc   : constant Source_Ptr := Sloc (N);
8929       Prag  : Node_Id;
8930       Parms : List_Id;
8931
8932       Designator : Entity_Id;
8933       --  Subprogram designator, set from Spec_Id if present, else Body_Id
8934
8935       Precond : Node_Id := Empty;
8936       --  Set non-Empty if we prepend precondition to the declarations. This
8937       --  is used to hook up inherited preconditions (adding the condition
8938       --  expression with OR ELSE, and adding the message).
8939
8940       Inherited_Precond : Node_Id;
8941       --  Precondition inherited from parent subprogram
8942
8943       Inherited : constant Subprogram_List :=
8944                      Inherited_Subprograms (Spec_Id);
8945       --  List of subprograms inherited by this subprogram
8946
8947       Plist : List_Id := No_List;
8948       --  List of generated postconditions
8949
8950       function Grab_PPC (Pspec : Entity_Id := Empty) return Node_Id;
8951       --  Prag contains an analyzed precondition or postcondition pragma. This
8952       --  function copies the pragma, changes it to the corresponding Check
8953       --  pragma and returns the Check pragma as the result. If Pspec is non-
8954       --  empty, this is the case of inheriting a PPC, where we must change
8955       --  references to parameters of the inherited subprogram to point to the
8956       --  corresponding parameters of the current subprogram.
8957
8958       function Invariants_Or_Predicates_Present return Boolean;
8959       --  Determines if any invariants or predicates are present for any OUT
8960       --  or IN OUT parameters of the subprogram, or (for a function) if the
8961       --  return value has an invariant.
8962
8963       --------------
8964       -- Grab_PPC --
8965       --------------
8966
8967       function Grab_PPC (Pspec : Entity_Id := Empty) return Node_Id is
8968          Nam : constant Name_Id := Pragma_Name (Prag);
8969          Map : Elist_Id;
8970          CP  : Node_Id;
8971
8972       begin
8973          --  Prepare map if this is the case where we have to map entities of
8974          --  arguments in the overridden subprogram to corresponding entities
8975          --  of the current subprogram.
8976
8977          if No (Pspec) then
8978             Map := No_Elist;
8979
8980          else
8981             declare
8982                PF : Entity_Id;
8983                CF : Entity_Id;
8984
8985             begin
8986                Map := New_Elmt_List;
8987                PF := First_Formal (Pspec);
8988                CF := First_Formal (Designator);
8989                while Present (PF) loop
8990                   Append_Elmt (PF, Map);
8991                   Append_Elmt (CF, Map);
8992                   Next_Formal (PF);
8993                   Next_Formal (CF);
8994                end loop;
8995             end;
8996          end if;
8997
8998          --  Now we can copy the tree, doing any required substitutions
8999
9000          CP := New_Copy_Tree (Prag, Map => Map, New_Scope => Current_Scope);
9001
9002          --  Set Analyzed to false, since we want to reanalyze the check
9003          --  procedure. Note that it is only at the outer level that we
9004          --  do this fiddling, for the spec cases, the already preanalyzed
9005          --  parameters are not affected.
9006
9007          Set_Analyzed (CP, False);
9008
9009          --  We also make sure Comes_From_Source is False for the copy
9010
9011          Set_Comes_From_Source (CP, False);
9012
9013          --  For a postcondition pragma within a generic, preserve the pragma
9014          --  for later expansion.
9015
9016          if Nam = Name_Postcondition
9017            and then not Expander_Active
9018          then
9019             return CP;
9020          end if;
9021
9022          --  Change copy of pragma into corresponding pragma Check
9023
9024          Prepend_To (Pragma_Argument_Associations (CP),
9025            Make_Pragma_Argument_Association (Sloc (Prag),
9026              Expression => Make_Identifier (Loc, Nam)));
9027          Set_Pragma_Identifier (CP, Make_Identifier (Sloc (Prag), Name_Check));
9028
9029          --  If this is inherited case and the current message starts with
9030          --  "failed p", we change it to "failed inherited p...".
9031
9032          if Present (Pspec) then
9033             declare
9034                Msg : constant Node_Id :=
9035                        Last (Pragma_Argument_Associations (CP));
9036
9037             begin
9038                if Chars (Msg) = Name_Message then
9039                   String_To_Name_Buffer (Strval (Expression (Msg)));
9040
9041                   if Name_Buffer (1 .. 8) = "failed p" then
9042                      Insert_Str_In_Name_Buffer ("inherited ", 8);
9043                      Set_Strval
9044                        (Expression (Last (Pragma_Argument_Associations (CP))),
9045                         String_From_Name_Buffer);
9046                   end if;
9047                end if;
9048             end;
9049          end if;
9050
9051          --  Return the check pragma
9052
9053          return CP;
9054       end Grab_PPC;
9055
9056       --------------------------------------
9057       -- Invariants_Or_Predicates_Present --
9058       --------------------------------------
9059
9060       function Invariants_Or_Predicates_Present return Boolean is
9061          Formal : Entity_Id;
9062
9063       begin
9064          --  Check function return result
9065
9066          if Ekind (Designator) /= E_Procedure
9067            and then Has_Invariants (Etype (Designator))
9068          then
9069             return True;
9070          end if;
9071
9072          --  Check parameters
9073
9074          Formal := First_Formal (Designator);
9075          while Present (Formal) loop
9076             if Ekind (Formal) /= E_In_Parameter
9077               and then
9078                 (Has_Invariants (Etype (Formal))
9079                   or else Present (Predicate_Function (Etype (Formal))))
9080             then
9081                return True;
9082             end if;
9083
9084             Next_Formal (Formal);
9085          end loop;
9086
9087          return False;
9088       end Invariants_Or_Predicates_Present;
9089
9090    --  Start of processing for Process_PPCs
9091
9092    begin
9093       --  Capture designator from spec if present, else from body
9094
9095       if Present (Spec_Id) then
9096          Designator := Spec_Id;
9097       else
9098          Designator := Body_Id;
9099       end if;
9100
9101       --  Grab preconditions from spec
9102
9103       if Present (Spec_Id) then
9104
9105          --  Loop through PPC pragmas from spec. Note that preconditions from
9106          --  the body will be analyzed and converted when we scan the body
9107          --  declarations below.
9108
9109          Prag := Spec_PPC_List (Spec_Id);
9110          while Present (Prag) loop
9111             if Pragma_Name (Prag) = Name_Precondition then
9112
9113                --  For Pre (or Precondition pragma), we simply prepend the
9114                --  pragma to the list of declarations right away so that it
9115                --  will be executed at the start of the procedure. Note that
9116                --  this processing reverses the order of the list, which is
9117                --  what we want since new entries were chained to the head of
9118                --  the list. There can be more then one precondition when we
9119                --  use pragma Precondition
9120
9121                if not Class_Present (Prag) then
9122                   Prepend (Grab_PPC, Declarations (N));
9123
9124                --  For Pre'Class there can only be one pragma, and we save
9125                --  it in Precond for now. We will add inherited Pre'Class
9126                --  stuff before inserting this pragma in the declarations.
9127                else
9128                   Precond := Grab_PPC;
9129                end if;
9130             end if;
9131
9132             Prag := Next_Pragma (Prag);
9133          end loop;
9134
9135          --  Now deal with inherited preconditions
9136
9137          for J in Inherited'Range loop
9138             Prag := Spec_PPC_List (Inherited (J));
9139
9140             while Present (Prag) loop
9141                if Pragma_Name (Prag) = Name_Precondition
9142                  and then Class_Present (Prag)
9143                then
9144                   Inherited_Precond := Grab_PPC (Inherited (J));
9145
9146                   --  No precondition so far, so establish this as the first
9147
9148                   if No (Precond) then
9149                      Precond := Inherited_Precond;
9150
9151                   --  Here we already have a precondition, add inherited one
9152
9153                   else
9154                      --  Add new precondition to old one using OR ELSE
9155
9156                      declare
9157                         New_Expr : constant Node_Id :=
9158                                      Get_Pragma_Arg
9159                                        (Next
9160                                          (First
9161                                            (Pragma_Argument_Associations
9162                                              (Inherited_Precond))));
9163                         Old_Expr : constant Node_Id :=
9164                                      Get_Pragma_Arg
9165                                        (Next
9166                                          (First
9167                                            (Pragma_Argument_Associations
9168                                              (Precond))));
9169
9170                      begin
9171                         if Paren_Count (Old_Expr) = 0 then
9172                            Set_Paren_Count (Old_Expr, 1);
9173                         end if;
9174
9175                         if Paren_Count (New_Expr) = 0 then
9176                            Set_Paren_Count (New_Expr, 1);
9177                         end if;
9178
9179                         Rewrite (Old_Expr,
9180                           Make_Or_Else (Sloc (Old_Expr),
9181                             Left_Opnd  => Relocate_Node (Old_Expr),
9182                             Right_Opnd => New_Expr));
9183                      end;
9184
9185                      --  Add new message in the form:
9186
9187                      --     failed precondition from bla
9188                      --       also failed inherited precondition from bla
9189                      --       ...
9190
9191                      --  Skip this if exception locations are suppressed
9192
9193                      if not Exception_Locations_Suppressed then
9194                         declare
9195                            New_Msg : constant Node_Id :=
9196                                        Get_Pragma_Arg
9197                                          (Last
9198                                             (Pragma_Argument_Associations
9199                                                (Inherited_Precond)));
9200                            Old_Msg : constant Node_Id :=
9201                                        Get_Pragma_Arg
9202                                          (Last
9203                                             (Pragma_Argument_Associations
9204                                                (Precond)));
9205                         begin
9206                            Start_String (Strval (Old_Msg));
9207                            Store_String_Chars (ASCII.LF & "  also ");
9208                            Store_String_Chars (Strval (New_Msg));
9209                            Set_Strval (Old_Msg, End_String);
9210                         end;
9211                      end if;
9212                   end if;
9213                end if;
9214
9215                Prag := Next_Pragma (Prag);
9216             end loop;
9217          end loop;
9218
9219          --  If we have built a precondition for Pre'Class (including any
9220          --  Pre'Class aspects inherited from parent subprograms), then we
9221          --  insert this composite precondition at this stage.
9222
9223          if Present (Precond) then
9224             Prepend (Precond, Declarations (N));
9225          end if;
9226       end if;
9227
9228       --  Build postconditions procedure if needed and prepend the following
9229       --  declaration to the start of the declarations for the subprogram.
9230
9231       --     procedure _postconditions [(_Result : resulttype)] is
9232       --     begin
9233       --        pragma Check (Postcondition, condition [,message]);
9234       --        pragma Check (Postcondition, condition [,message]);
9235       --        ...
9236       --        Invariant_Procedure (_Result) ...
9237       --        Invariant_Procedure (Arg1)
9238       --        ...
9239       --     end;
9240
9241       --  First we deal with the postconditions in the body
9242
9243       if Is_Non_Empty_List (Declarations (N)) then
9244
9245          --  Loop through declarations
9246
9247          Prag := First (Declarations (N));
9248          while Present (Prag) loop
9249             if Nkind (Prag) = N_Pragma then
9250
9251                --  If pragma, capture if enabled postcondition, else ignore
9252
9253                if Pragma_Name (Prag) = Name_Postcondition
9254                  and then Check_Enabled (Name_Postcondition)
9255                then
9256                   if Plist = No_List then
9257                      Plist := Empty_List;
9258                   end if;
9259
9260                   Analyze (Prag);
9261
9262                   --  If expansion is disabled, as in a generic unit, save
9263                   --  pragma for later expansion.
9264
9265                   if not Expander_Active then
9266                      Prepend (Grab_PPC, Declarations (N));
9267                   else
9268                      Append (Grab_PPC, Plist);
9269                   end if;
9270                end if;
9271
9272                Next (Prag);
9273
9274             --  Not a pragma, if comes from source, then end scan
9275
9276             elsif Comes_From_Source (Prag) then
9277                exit;
9278
9279             --  Skip stuff not coming from source
9280
9281             else
9282                Next (Prag);
9283             end if;
9284          end loop;
9285       end if;
9286
9287       --  Now deal with any postconditions from the spec
9288
9289       if Present (Spec_Id) then
9290          Spec_Postconditions : declare
9291             procedure Process_Post_Conditions
9292               (Spec  : Node_Id;
9293                Class : Boolean);
9294             --  This processes the Spec_PPC_List from Spec, processing any
9295             --  postconditions from the list. If Class is True, then only
9296             --  postconditions marked with Class_Present are considered.
9297             --  The caller has checked that Spec_PPC_List is non-Empty.
9298
9299             -----------------------------
9300             -- Process_Post_Conditions --
9301             -----------------------------
9302
9303             procedure Process_Post_Conditions
9304               (Spec  : Node_Id;
9305                Class : Boolean)
9306             is
9307                Pspec : Node_Id;
9308
9309             begin
9310                if Class then
9311                   Pspec := Spec;
9312                else
9313                   Pspec := Empty;
9314                end if;
9315
9316                --  Loop through PPC pragmas from spec
9317
9318                Prag := Spec_PPC_List (Spec);
9319                loop
9320                   if Pragma_Name (Prag) = Name_Postcondition
9321                     and then (not Class or else Class_Present (Prag))
9322                   then
9323                      if Plist = No_List then
9324                         Plist := Empty_List;
9325                      end if;
9326
9327                      if not Expander_Active then
9328                         Prepend
9329                           (Grab_PPC (Pspec), Declarations (N));
9330                      else
9331                         Append (Grab_PPC (Pspec), Plist);
9332                      end if;
9333                   end if;
9334
9335                   Prag := Next_Pragma (Prag);
9336                   exit when No (Prag);
9337                end loop;
9338             end Process_Post_Conditions;
9339
9340          --  Start of processing for Spec_Postconditions
9341
9342          begin
9343             if Present (Spec_PPC_List (Spec_Id)) then
9344                Process_Post_Conditions (Spec_Id, Class => False);
9345             end if;
9346
9347             --  Process inherited postconditions
9348
9349             for J in Inherited'Range loop
9350                if Present (Spec_PPC_List (Inherited (J))) then
9351                   Process_Post_Conditions (Inherited (J), Class => True);
9352                end if;
9353             end loop;
9354          end Spec_Postconditions;
9355       end if;
9356
9357       --  If we had any postconditions and expansion is enabled, or if the
9358       --  procedure has invariants, then build the _Postconditions procedure.
9359
9360       if (Present (Plist) or else Invariants_Or_Predicates_Present)
9361         and then Expander_Active
9362       then
9363          if No (Plist) then
9364             Plist := Empty_List;
9365          end if;
9366
9367          --  Special processing for function case
9368
9369          if Ekind (Designator) /= E_Procedure then
9370             declare
9371                Rent : constant Entity_Id :=
9372                         Make_Defining_Identifier (Loc,
9373                           Chars => Name_uResult);
9374                Ftyp : constant Entity_Id := Etype (Designator);
9375
9376             begin
9377                Set_Etype (Rent, Ftyp);
9378
9379                --  Add argument for return
9380
9381                Parms :=
9382                  New_List (
9383                    Make_Parameter_Specification (Loc,
9384                      Parameter_Type      => New_Occurrence_Of (Ftyp, Loc),
9385                      Defining_Identifier => Rent));
9386
9387                --  Add invariant call if returning type with invariants
9388
9389                if Has_Invariants (Etype (Rent))
9390                  and then Present (Invariant_Procedure (Etype (Rent)))
9391                then
9392                   Append_To (Plist,
9393                     Make_Invariant_Call (New_Occurrence_Of (Rent, Loc)));
9394                end if;
9395             end;
9396
9397          --  Procedure rather than a function
9398
9399          else
9400             Parms := No_List;
9401          end if;
9402
9403          --  Add invariant calls and predicate calls for parameters. Note that
9404          --  this is done for functions as well, since in Ada 2012 they can
9405          --  have IN OUT args.
9406
9407          declare
9408             Formal : Entity_Id;
9409             Ftype  : Entity_Id;
9410
9411          begin
9412             Formal := First_Formal (Designator);
9413             while Present (Formal) loop
9414                if Ekind (Formal) /= E_In_Parameter then
9415                   Ftype := Etype (Formal);
9416
9417                   if Has_Invariants (Ftype)
9418                     and then Present (Invariant_Procedure (Ftype))
9419                   then
9420                      Append_To (Plist,
9421                        Make_Invariant_Call
9422                          (New_Occurrence_Of (Formal, Loc)));
9423                   end if;
9424
9425                   if Present (Predicate_Function (Ftype)) then
9426                      Append_To (Plist,
9427                        Make_Predicate_Check
9428                          (Ftype, New_Occurrence_Of (Formal, Loc)));
9429                   end if;
9430                end if;
9431
9432                Next_Formal (Formal);
9433             end loop;
9434          end;
9435
9436          --  Build and insert postcondition procedure
9437
9438          declare
9439             Post_Proc : constant Entity_Id :=
9440                           Make_Defining_Identifier (Loc,
9441                             Chars => Name_uPostconditions);
9442             --  The entity for the _Postconditions procedure
9443
9444          begin
9445             Prepend_To (Declarations (N),
9446               Make_Subprogram_Body (Loc,
9447                 Specification =>
9448                   Make_Procedure_Specification (Loc,
9449                     Defining_Unit_Name => Post_Proc,
9450                     Parameter_Specifications => Parms),
9451
9452                 Declarations => Empty_List,
9453
9454                 Handled_Statement_Sequence =>
9455                   Make_Handled_Sequence_Of_Statements (Loc,
9456                     Statements => Plist)));
9457
9458             --  If this is a procedure, set the Postcondition_Proc attribute on
9459             --  the proper defining entity for the subprogram.
9460
9461             if Ekind (Designator) = E_Procedure then
9462                Set_Postcondition_Proc (Designator, Post_Proc);
9463             end if;
9464          end;
9465
9466          Set_Has_Postconditions (Designator);
9467       end if;
9468    end Process_PPCs;
9469
9470    ----------------------------
9471    -- Reference_Body_Formals --
9472    ----------------------------
9473
9474    procedure Reference_Body_Formals (Spec : Entity_Id; Bod : Entity_Id) is
9475       Fs : Entity_Id;
9476       Fb : Entity_Id;
9477
9478    begin
9479       if Error_Posted (Spec) then
9480          return;
9481       end if;
9482
9483       --  Iterate over both lists. They may be of different lengths if the two
9484       --  specs are not conformant.
9485
9486       Fs := First_Formal (Spec);
9487       Fb := First_Formal (Bod);
9488       while Present (Fs) and then Present (Fb) loop
9489          Generate_Reference (Fs, Fb, 'b');
9490
9491          if Style_Check then
9492             Style.Check_Identifier (Fb, Fs);
9493          end if;
9494
9495          Set_Spec_Entity (Fb, Fs);
9496          Set_Referenced (Fs, False);
9497          Next_Formal (Fs);
9498          Next_Formal (Fb);
9499       end loop;
9500    end Reference_Body_Formals;
9501
9502    -------------------------
9503    -- Set_Actual_Subtypes --
9504    -------------------------
9505
9506    procedure Set_Actual_Subtypes (N : Node_Id; Subp : Entity_Id) is
9507       Decl           : Node_Id;
9508       Formal         : Entity_Id;
9509       T              : Entity_Id;
9510       First_Stmt     : Node_Id := Empty;
9511       AS_Needed      : Boolean;
9512
9513    begin
9514       --  If this is an empty initialization procedure, no need to create
9515       --  actual subtypes (small optimization).
9516
9517       if Ekind (Subp) = E_Procedure
9518         and then Is_Null_Init_Proc (Subp)
9519       then
9520          return;
9521       end if;
9522
9523       Formal := First_Formal (Subp);
9524       while Present (Formal) loop
9525          T := Etype (Formal);
9526
9527          --  We never need an actual subtype for a constrained formal
9528
9529          if Is_Constrained (T) then
9530             AS_Needed := False;
9531
9532          --  If we have unknown discriminants, then we do not need an actual
9533          --  subtype, or more accurately we cannot figure it out! Note that
9534          --  all class-wide types have unknown discriminants.
9535
9536          elsif Has_Unknown_Discriminants (T) then
9537             AS_Needed := False;
9538
9539          --  At this stage we have an unconstrained type that may need an
9540          --  actual subtype. For sure the actual subtype is needed if we have
9541          --  an unconstrained array type.
9542
9543          elsif Is_Array_Type (T) then
9544             AS_Needed := True;
9545
9546          --  The only other case needing an actual subtype is an unconstrained
9547          --  record type which is an IN parameter (we cannot generate actual
9548          --  subtypes for the OUT or IN OUT case, since an assignment can
9549          --  change the discriminant values. However we exclude the case of
9550          --  initialization procedures, since discriminants are handled very
9551          --  specially in this context, see the section entitled "Handling of
9552          --  Discriminants" in Einfo.
9553
9554          --  We also exclude the case of Discrim_SO_Functions (functions used
9555          --  in front end layout mode for size/offset values), since in such
9556          --  functions only discriminants are referenced, and not only are such
9557          --  subtypes not needed, but they cannot always be generated, because
9558          --  of order of elaboration issues.
9559
9560          elsif Is_Record_Type (T)
9561            and then Ekind (Formal) = E_In_Parameter
9562            and then Chars (Formal) /= Name_uInit
9563            and then not Is_Unchecked_Union (T)
9564            and then not Is_Discrim_SO_Function (Subp)
9565          then
9566             AS_Needed := True;
9567
9568          --  All other cases do not need an actual subtype
9569
9570          else
9571             AS_Needed := False;
9572          end if;
9573
9574          --  Generate actual subtypes for unconstrained arrays and
9575          --  unconstrained discriminated records.
9576
9577          if AS_Needed then
9578             if Nkind (N) = N_Accept_Statement then
9579
9580                --  If expansion is active, The formal is replaced by a local
9581                --  variable that renames the corresponding entry of the
9582                --  parameter block, and it is this local variable that may
9583                --  require an actual subtype.
9584
9585                if Expander_Active then
9586                   Decl := Build_Actual_Subtype (T, Renamed_Object (Formal));
9587                else
9588                   Decl := Build_Actual_Subtype (T, Formal);
9589                end if;
9590
9591                if Present (Handled_Statement_Sequence (N)) then
9592                   First_Stmt :=
9593                     First (Statements (Handled_Statement_Sequence (N)));
9594                   Prepend (Decl, Statements (Handled_Statement_Sequence (N)));
9595                   Mark_Rewrite_Insertion (Decl);
9596                else
9597                   --  If the accept statement has no body, there will be no
9598                   --  reference to the actuals, so no need to compute actual
9599                   --  subtypes.
9600
9601                   return;
9602                end if;
9603
9604             else
9605                Decl := Build_Actual_Subtype (T, Formal);
9606                Prepend (Decl, Declarations (N));
9607                Mark_Rewrite_Insertion (Decl);
9608             end if;
9609
9610             --  The declaration uses the bounds of an existing object, and
9611             --  therefore needs no constraint checks.
9612
9613             Analyze (Decl, Suppress => All_Checks);
9614
9615             --  We need to freeze manually the generated type when it is
9616             --  inserted anywhere else than in a declarative part.
9617
9618             if Present (First_Stmt) then
9619                Insert_List_Before_And_Analyze (First_Stmt,
9620                  Freeze_Entity (Defining_Identifier (Decl), N));
9621             end if;
9622
9623             if Nkind (N) = N_Accept_Statement
9624               and then Expander_Active
9625             then
9626                Set_Actual_Subtype (Renamed_Object (Formal),
9627                  Defining_Identifier (Decl));
9628             else
9629                Set_Actual_Subtype (Formal, Defining_Identifier (Decl));
9630             end if;
9631          end if;
9632
9633          Next_Formal (Formal);
9634       end loop;
9635    end Set_Actual_Subtypes;
9636
9637    ---------------------
9638    -- Set_Formal_Mode --
9639    ---------------------
9640
9641    procedure Set_Formal_Mode (Formal_Id : Entity_Id) is
9642       Spec : constant Node_Id := Parent (Formal_Id);
9643
9644    begin
9645       --  Note: we set Is_Known_Valid for IN parameters and IN OUT parameters
9646       --  since we ensure that corresponding actuals are always valid at the
9647       --  point of the call.
9648
9649       if Out_Present (Spec) then
9650          if Ekind (Scope (Formal_Id)) = E_Function
9651            or else Ekind (Scope (Formal_Id)) = E_Generic_Function
9652          then
9653             --  [IN] OUT parameters allowed for functions in Ada 2012
9654
9655             if Ada_Version >= Ada_2012 then
9656                if In_Present (Spec) then
9657                   Set_Ekind (Formal_Id, E_In_Out_Parameter);
9658                else
9659                   Set_Ekind (Formal_Id, E_Out_Parameter);
9660                end if;
9661
9662             --  But not in earlier versions of Ada
9663
9664             else
9665                Error_Msg_N ("functions can only have IN parameters", Spec);
9666                Set_Ekind (Formal_Id, E_In_Parameter);
9667             end if;
9668
9669          elsif In_Present (Spec) then
9670             Set_Ekind (Formal_Id, E_In_Out_Parameter);
9671
9672          else
9673             Set_Ekind               (Formal_Id, E_Out_Parameter);
9674             Set_Never_Set_In_Source (Formal_Id, True);
9675             Set_Is_True_Constant    (Formal_Id, False);
9676             Set_Current_Value       (Formal_Id, Empty);
9677          end if;
9678
9679       else
9680          Set_Ekind (Formal_Id, E_In_Parameter);
9681       end if;
9682
9683       --  Set Is_Known_Non_Null for access parameters since the language
9684       --  guarantees that access parameters are always non-null. We also set
9685       --  Can_Never_Be_Null, since there is no way to change the value.
9686
9687       if Nkind (Parameter_Type (Spec)) = N_Access_Definition then
9688
9689          --  Ada 2005 (AI-231): In Ada95, access parameters are always non-
9690          --  null; In Ada 2005, only if then null_exclusion is explicit.
9691
9692          if Ada_Version < Ada_2005
9693            or else Can_Never_Be_Null (Etype (Formal_Id))
9694          then
9695             Set_Is_Known_Non_Null (Formal_Id);
9696             Set_Can_Never_Be_Null (Formal_Id);
9697          end if;
9698
9699       --  Ada 2005 (AI-231): Null-exclusion access subtype
9700
9701       elsif Is_Access_Type (Etype (Formal_Id))
9702         and then Can_Never_Be_Null (Etype (Formal_Id))
9703       then
9704          Set_Is_Known_Non_Null (Formal_Id);
9705       end if;
9706
9707       Set_Mechanism (Formal_Id, Default_Mechanism);
9708       Set_Formal_Validity (Formal_Id);
9709    end Set_Formal_Mode;
9710
9711    -------------------------
9712    -- Set_Formal_Validity --
9713    -------------------------
9714
9715    procedure Set_Formal_Validity (Formal_Id : Entity_Id) is
9716    begin
9717       --  If no validity checking, then we cannot assume anything about the
9718       --  validity of parameters, since we do not know there is any checking
9719       --  of the validity on the call side.
9720
9721       if not Validity_Checks_On then
9722          return;
9723
9724       --  If validity checking for parameters is enabled, this means we are
9725       --  not supposed to make any assumptions about argument values.
9726
9727       elsif Validity_Check_Parameters then
9728          return;
9729
9730       --  If we are checking in parameters, we will assume that the caller is
9731       --  also checking parameters, so we can assume the parameter is valid.
9732
9733       elsif Ekind (Formal_Id) = E_In_Parameter
9734         and then Validity_Check_In_Params
9735       then
9736          Set_Is_Known_Valid (Formal_Id, True);
9737
9738       --  Similar treatment for IN OUT parameters
9739
9740       elsif Ekind (Formal_Id) = E_In_Out_Parameter
9741         and then Validity_Check_In_Out_Params
9742       then
9743          Set_Is_Known_Valid (Formal_Id, True);
9744       end if;
9745    end Set_Formal_Validity;
9746
9747    ------------------------
9748    -- Subtype_Conformant --
9749    ------------------------
9750
9751    function Subtype_Conformant
9752      (New_Id                   : Entity_Id;
9753       Old_Id                   : Entity_Id;
9754       Skip_Controlling_Formals : Boolean := False) return Boolean
9755    is
9756       Result : Boolean;
9757    begin
9758       Check_Conformance (New_Id, Old_Id, Subtype_Conformant, False, Result,
9759         Skip_Controlling_Formals => Skip_Controlling_Formals);
9760       return Result;
9761    end Subtype_Conformant;
9762
9763    ---------------------
9764    -- Type_Conformant --
9765    ---------------------
9766
9767    function Type_Conformant
9768      (New_Id                   : Entity_Id;
9769       Old_Id                   : Entity_Id;
9770       Skip_Controlling_Formals : Boolean := False) return Boolean
9771    is
9772       Result : Boolean;
9773    begin
9774       May_Hide_Profile := False;
9775
9776       Check_Conformance
9777         (New_Id, Old_Id, Type_Conformant, False, Result,
9778          Skip_Controlling_Formals => Skip_Controlling_Formals);
9779       return Result;
9780    end Type_Conformant;
9781
9782    -------------------------------
9783    -- Valid_Operator_Definition --
9784    -------------------------------
9785
9786    procedure Valid_Operator_Definition (Designator : Entity_Id) is
9787       N    : Integer := 0;
9788       F    : Entity_Id;
9789       Id   : constant Name_Id := Chars (Designator);
9790       N_OK : Boolean;
9791
9792    begin
9793       F := First_Formal (Designator);
9794       while Present (F) loop
9795          N := N + 1;
9796
9797          if Present (Default_Value (F)) then
9798             Error_Msg_N
9799               ("default values not allowed for operator parameters",
9800                Parent (F));
9801          end if;
9802
9803          Next_Formal (F);
9804       end loop;
9805
9806       --  Verify that user-defined operators have proper number of arguments
9807       --  First case of operators which can only be unary
9808
9809       if Id = Name_Op_Not
9810         or else Id = Name_Op_Abs
9811       then
9812          N_OK := (N = 1);
9813
9814       --  Case of operators which can be unary or binary
9815
9816       elsif Id = Name_Op_Add
9817         or Id = Name_Op_Subtract
9818       then
9819          N_OK := (N in 1 .. 2);
9820
9821       --  All other operators can only be binary
9822
9823       else
9824          N_OK := (N = 2);
9825       end if;
9826
9827       if not N_OK then
9828          Error_Msg_N
9829            ("incorrect number of arguments for operator", Designator);
9830       end if;
9831
9832       if Id = Name_Op_Ne
9833         and then Base_Type (Etype (Designator)) = Standard_Boolean
9834         and then not Is_Intrinsic_Subprogram (Designator)
9835       then
9836          Error_Msg_N
9837             ("explicit definition of inequality not allowed", Designator);
9838       end if;
9839    end Valid_Operator_Definition;
9840
9841 end Sem_Ch6;