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