OSDN Git Service

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