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