OSDN Git Service

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