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