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