OSDN Git Service

2005-03-08 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_ch6.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              E X P _ C H 6                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2005, 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 2,  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 COPYING.  If not, write --
19 -- to  the Free Software Foundation,  59 Temple Place - Suite 330,  Boston, --
20 -- MA 02111-1307, USA.                                                      --
21 --                                                                          --
22 -- GNAT was originally developed  by the GNAT team at  New York University. --
23 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
24 --                                                                          --
25 ------------------------------------------------------------------------------
26
27 with Atree;    use Atree;
28 with Checks;   use Checks;
29 with Debug;    use Debug;
30 with Einfo;    use Einfo;
31 with Errout;   use Errout;
32 with Elists;   use Elists;
33 with Exp_Ch2;  use Exp_Ch2;
34 with Exp_Ch3;  use Exp_Ch3;
35 with Exp_Ch7;  use Exp_Ch7;
36 with Exp_Ch9;  use Exp_Ch9;
37 with Exp_Ch11; use Exp_Ch11;
38 with Exp_Dbug; use Exp_Dbug;
39 with Exp_Disp; use Exp_Disp;
40 with Exp_Dist; use Exp_Dist;
41 with Exp_Intr; use Exp_Intr;
42 with Exp_Pakd; use Exp_Pakd;
43 with Exp_Tss;  use Exp_Tss;
44 with Exp_Util; use Exp_Util;
45 with Fname;    use Fname;
46 with Freeze;   use Freeze;
47 with Hostparm; use Hostparm;
48 with Inline;   use Inline;
49 with Lib;      use Lib;
50 with Nlists;   use Nlists;
51 with Nmake;    use Nmake;
52 with Opt;      use Opt;
53 with Restrict; use Restrict;
54 with Rident;   use Rident;
55 with Rtsfind;  use Rtsfind;
56 with Sem;      use Sem;
57 with Sem_Ch6;  use Sem_Ch6;
58 with Sem_Ch8;  use Sem_Ch8;
59 with Sem_Ch12; use Sem_Ch12;
60 with Sem_Ch13; use Sem_Ch13;
61 with Sem_Disp; use Sem_Disp;
62 with Sem_Dist; use Sem_Dist;
63 with Sem_Res;  use Sem_Res;
64 with Sem_Util; use Sem_Util;
65 with Sinfo;    use Sinfo;
66 with Snames;   use Snames;
67 with Stand;    use Stand;
68 with Tbuild;   use Tbuild;
69 with Ttypes;   use Ttypes;
70 with Uintp;    use Uintp;
71 with Validsw;  use Validsw;
72
73 package body Exp_Ch6 is
74
75    -----------------------
76    -- Local Subprograms --
77    -----------------------
78
79    procedure Check_Overriding_Operation (Subp : Entity_Id);
80    --  Subp is a dispatching operation. Check whether it may override an
81    --  inherited private operation, in which case its DT entry is that of
82    --  the hidden operation, not the one it may have received earlier.
83    --  This must be done before emitting the code to set the corresponding
84    --  DT to the address of the subprogram. The actual placement of Subp in
85    --  the proper place in the list of primitive operations is done in
86    --  Declare_Inherited_Private_Subprograms, which also has to deal with
87    --  implicit operations. This duplication is unavoidable for now???
88
89    procedure Detect_Infinite_Recursion (N : Node_Id; Spec : Entity_Id);
90    --  This procedure is called only if the subprogram body N, whose spec
91    --  has the given entity Spec, contains a parameterless recursive call.
92    --  It attempts to generate runtime code to detect if this a case of
93    --  infinite recursion.
94    --
95    --  The body is scanned to determine dependencies. If the only external
96    --  dependencies are on a small set of scalar variables, then the values
97    --  of these variables are captured on entry to the subprogram, and if
98    --  the values are not changed for the call, we know immediately that
99    --  we have an infinite recursion.
100
101    procedure Expand_Actuals (N : Node_Id; Subp : Entity_Id);
102    --  For each actual of an in-out parameter which is a numeric conversion
103    --  of the form T(A), where A denotes a variable, we insert the declaration:
104    --
105    --    Temp : T := T (A);
106    --
107    --  prior to the call. Then we replace the actual with a reference to Temp,
108    --  and append the assignment:
109    --
110    --    A := TypeA (Temp);
111    --
112    --  after the call. Here TypeA is the actual type of variable A.
113    --  For out parameters, the initial declaration has no expression.
114    --  If A is not an entity name, we generate instead:
115    --
116    --    Var  : TypeA renames A;
117    --    Temp : T := Var;       --  omitting expression for out parameter.
118    --    ...
119    --    Var := TypeA (Temp);
120    --
121    --  For other in-out parameters, we emit the required constraint checks
122    --  before and/or after the call.
123    --
124    --  For all parameter modes, actuals that denote components and slices
125    --  of packed arrays are expanded into suitable temporaries.
126    --
127    --  For non-scalar objects that are possibly unaligned, add call by copy
128    --  code (copy in for IN and IN OUT, copy out for OUT and IN OUT).
129
130    procedure Expand_Inlined_Call
131     (N         : Node_Id;
132      Subp      : Entity_Id;
133      Orig_Subp : Entity_Id);
134    --  If called subprogram can be inlined by the front-end, retrieve the
135    --  analyzed body, replace formals with actuals and expand call in place.
136    --  Generate thunks for actuals that are expressions, and insert the
137    --  corresponding constant declarations before the call. If the original
138    --  call is to a derived operation, the return type is the one of the
139    --  derived operation, but the body is that of the original, so return
140    --  expressions in the body must be converted to the desired type (which
141    --  is simply not noted in the tree without inline expansion).
142
143    function Expand_Protected_Object_Reference
144      (N    : Node_Id;
145       Scop : Entity_Id)
146       return Node_Id;
147
148    procedure Expand_Protected_Subprogram_Call
149      (N    : Node_Id;
150       Subp : Entity_Id;
151       Scop : Entity_Id);
152    --  A call to a protected subprogram within the protected object may appear
153    --  as a regular call. The list of actuals must be expanded to contain a
154    --  reference to the object itself, and the call becomes a call to the
155    --  corresponding protected subprogram.
156
157    --------------------------------
158    -- Check_Overriding_Operation --
159    --------------------------------
160
161    procedure Check_Overriding_Operation (Subp : Entity_Id) is
162       Typ     : constant Entity_Id := Find_Dispatching_Type (Subp);
163       Op_List : constant Elist_Id  := Primitive_Operations (Typ);
164       Op_Elmt : Elmt_Id;
165       Prim_Op : Entity_Id;
166       Par_Op  : Entity_Id;
167
168    begin
169       if Is_Derived_Type (Typ)
170         and then not Is_Private_Type (Typ)
171         and then In_Open_Scopes (Scope (Etype (Typ)))
172         and then Typ = Base_Type (Typ)
173       then
174          --  Subp overrides an inherited private operation if there is
175          --  an inherited operation with a different name than Subp (see
176          --  Derive_Subprogram) whose Alias is a hidden  subprogram with
177          --  the same name as Subp.
178
179          Op_Elmt := First_Elmt (Op_List);
180          while Present (Op_Elmt) loop
181             Prim_Op := Node (Op_Elmt);
182             Par_Op  := Alias (Prim_Op);
183
184             if Present (Par_Op)
185               and then not Comes_From_Source (Prim_Op)
186               and then Chars (Prim_Op) /= Chars (Par_Op)
187               and then Chars (Par_Op) = Chars (Subp)
188               and then Is_Hidden (Par_Op)
189               and then Type_Conformant (Prim_Op, Subp)
190             then
191                Set_DT_Position (Subp, DT_Position (Prim_Op));
192             end if;
193
194             Next_Elmt (Op_Elmt);
195          end loop;
196       end if;
197    end Check_Overriding_Operation;
198
199    -------------------------------
200    -- Detect_Infinite_Recursion --
201    -------------------------------
202
203    procedure Detect_Infinite_Recursion (N : Node_Id; Spec : Entity_Id) is
204       Loc : constant Source_Ptr := Sloc (N);
205
206       Var_List : constant Elist_Id := New_Elmt_List;
207       --  List of globals referenced by body of procedure
208
209       Call_List : constant Elist_Id := New_Elmt_List;
210       --  List of recursive calls in body of procedure
211
212       Shad_List : constant Elist_Id := New_Elmt_List;
213       --  List of entity id's for entities created to capture the
214       --  value of referenced globals on entry to the procedure.
215
216       Scop : constant Uint := Scope_Depth (Spec);
217       --  This is used to record the scope depth of the current
218       --  procedure, so that we can identify global references.
219
220       Max_Vars : constant := 4;
221       --  Do not test more than four global variables
222
223       Count_Vars : Natural := 0;
224       --  Count variables found so far
225
226       Var  : Entity_Id;
227       Elm  : Elmt_Id;
228       Ent  : Entity_Id;
229       Call : Elmt_Id;
230       Decl : Node_Id;
231       Test : Node_Id;
232       Elm1 : Elmt_Id;
233       Elm2 : Elmt_Id;
234       Last : Node_Id;
235
236       function Process (Nod : Node_Id) return Traverse_Result;
237       --  Function to traverse the subprogram body (using Traverse_Func)
238
239       -------------
240       -- Process --
241       -------------
242
243       function Process (Nod : Node_Id) return Traverse_Result is
244       begin
245          --  Procedure call
246
247          if Nkind (Nod) = N_Procedure_Call_Statement then
248
249             --  Case of one of the detected recursive calls
250
251             if Is_Entity_Name (Name (Nod))
252               and then Has_Recursive_Call (Entity (Name (Nod)))
253               and then Entity (Name (Nod)) = Spec
254             then
255                Append_Elmt (Nod, Call_List);
256                return Skip;
257
258             --  Any other procedure call may have side effects
259
260             else
261                return Abandon;
262             end if;
263
264          --  A call to a pure function can always be ignored
265
266          elsif Nkind (Nod) = N_Function_Call
267            and then Is_Entity_Name (Name (Nod))
268            and then Is_Pure (Entity (Name (Nod)))
269          then
270             return Skip;
271
272          --  Case of an identifier reference
273
274          elsif Nkind (Nod) = N_Identifier then
275             Ent := Entity (Nod);
276
277             --  If no entity, then ignore the reference
278
279             --  Not clear why this can happen. To investigate, remove this
280             --  test and look at the crash that occurs here in 3401-004 ???
281
282             if No (Ent) then
283                return Skip;
284
285             --  Ignore entities with no Scope, again not clear how this
286             --  can happen, to investigate, look at 4108-008 ???
287
288             elsif No (Scope (Ent)) then
289                return Skip;
290
291             --  Ignore the reference if not to a more global object
292
293             elsif Scope_Depth (Scope (Ent)) >= Scop then
294                return Skip;
295
296             --  References to types, exceptions and constants are always OK
297
298             elsif Is_Type (Ent)
299               or else Ekind (Ent) = E_Exception
300               or else Ekind (Ent) = E_Constant
301             then
302                return Skip;
303
304             --  If other than a non-volatile scalar variable, we have some
305             --  kind of global reference (e.g. to a function) that we cannot
306             --  deal with so we forget the attempt.
307
308             elsif Ekind (Ent) /= E_Variable
309               or else not Is_Scalar_Type (Etype (Ent))
310               or else Treat_As_Volatile (Ent)
311             then
312                return Abandon;
313
314             --  Otherwise we have a reference to a global scalar
315
316             else
317                --  Loop through global entities already detected
318
319                Elm := First_Elmt (Var_List);
320                loop
321                   --  If not detected before, record this new global reference
322
323                   if No (Elm) then
324                      Count_Vars := Count_Vars + 1;
325
326                      if Count_Vars <= Max_Vars then
327                         Append_Elmt (Entity (Nod), Var_List);
328                      else
329                         return Abandon;
330                      end if;
331
332                      exit;
333
334                   --  If recorded before, ignore
335
336                   elsif Node (Elm) = Entity (Nod) then
337                      return Skip;
338
339                   --  Otherwise keep looking
340
341                   else
342                      Next_Elmt (Elm);
343                   end if;
344                end loop;
345
346                return Skip;
347             end if;
348
349          --  For all other node kinds, recursively visit syntactic children
350
351          else
352             return OK;
353          end if;
354       end Process;
355
356       function Traverse_Body is new Traverse_Func;
357
358    --  Start of processing for Detect_Infinite_Recursion
359
360    begin
361       --  Do not attempt detection in No_Implicit_Conditional mode,
362       --  since we won't be able to generate the code to handle the
363       --  recursion in any case.
364
365       if Restriction_Active (No_Implicit_Conditionals) then
366          return;
367       end if;
368
369       --  Otherwise do traversal and quit if we get abandon signal
370
371       if Traverse_Body (N) = Abandon then
372          return;
373
374       --  We must have a call, since Has_Recursive_Call was set. If not
375       --  just ignore (this is only an error check, so if we have a funny
376       --  situation, due to bugs or errors, we do not want to bomb!)
377
378       elsif Is_Empty_Elmt_List (Call_List) then
379          return;
380       end if;
381
382       --  Here is the case where we detect recursion at compile time
383
384       --  Push our current scope for analyzing the declarations and
385       --  code that we will insert for the checking.
386
387       New_Scope (Spec);
388
389       --  This loop builds temporary variables for each of the
390       --  referenced globals, so that at the end of the loop the
391       --  list Shad_List contains these temporaries in one-to-one
392       --  correspondence with the elements in Var_List.
393
394       Last := Empty;
395       Elm := First_Elmt (Var_List);
396       while Present (Elm) loop
397          Var := Node (Elm);
398          Ent :=
399            Make_Defining_Identifier (Loc,
400              Chars => New_Internal_Name ('S'));
401          Append_Elmt (Ent, Shad_List);
402
403          --  Insert a declaration for this temporary at the start of
404          --  the declarations for the procedure. The temporaries are
405          --  declared as constant objects initialized to the current
406          --  values of the corresponding temporaries.
407
408          Decl :=
409            Make_Object_Declaration (Loc,
410              Defining_Identifier => Ent,
411              Object_Definition   => New_Occurrence_Of (Etype (Var), Loc),
412              Constant_Present    => True,
413              Expression          => New_Occurrence_Of (Var, Loc));
414
415          if No (Last) then
416             Prepend (Decl, Declarations (N));
417          else
418             Insert_After (Last, Decl);
419          end if;
420
421          Last := Decl;
422          Analyze (Decl);
423          Next_Elmt (Elm);
424       end loop;
425
426       --  Loop through calls
427
428       Call := First_Elmt (Call_List);
429       while Present (Call) loop
430
431          --  Build a predicate expression of the form
432
433          --    True
434          --      and then global1 = temp1
435          --      and then global2 = temp2
436          --      ...
437
438          --  This predicate determines if any of the global values
439          --  referenced by the procedure have changed since the
440          --  current call, if not an infinite recursion is assured.
441
442          Test := New_Occurrence_Of (Standard_True, Loc);
443
444          Elm1 := First_Elmt (Var_List);
445          Elm2 := First_Elmt (Shad_List);
446          while Present (Elm1) loop
447             Test :=
448               Make_And_Then (Loc,
449                 Left_Opnd  => Test,
450                 Right_Opnd =>
451                   Make_Op_Eq (Loc,
452                     Left_Opnd  => New_Occurrence_Of (Node (Elm1), Loc),
453                     Right_Opnd => New_Occurrence_Of (Node (Elm2), Loc)));
454
455             Next_Elmt (Elm1);
456             Next_Elmt (Elm2);
457          end loop;
458
459          --  Now we replace the call with the sequence
460
461          --    if no-changes (see above) then
462          --       raise Storage_Error;
463          --    else
464          --       original-call
465          --    end if;
466
467          Rewrite (Node (Call),
468            Make_If_Statement (Loc,
469              Condition       => Test,
470              Then_Statements => New_List (
471                Make_Raise_Storage_Error (Loc,
472                  Reason => SE_Infinite_Recursion)),
473
474              Else_Statements => New_List (
475                Relocate_Node (Node (Call)))));
476
477          Analyze (Node (Call));
478
479          Next_Elmt (Call);
480       end loop;
481
482       --  Remove temporary scope stack entry used for analysis
483
484       Pop_Scope;
485    end Detect_Infinite_Recursion;
486
487    --------------------
488    -- Expand_Actuals --
489    --------------------
490
491    procedure Expand_Actuals (N : Node_Id; Subp : Entity_Id) is
492       Loc       : constant Source_Ptr := Sloc (N);
493       Actual    : Node_Id;
494       Formal    : Entity_Id;
495       N_Node    : Node_Id;
496       Post_Call : List_Id;
497       E_Formal  : Entity_Id;
498
499       procedure Add_Call_By_Copy_Code;
500       --  For cases where the parameter must be passed by copy, this routine
501       --  generates a temporary variable into which the actual is copied and
502       --  then passes this as the parameter. For an OUT or IN OUT parameter,
503       --  an assignment is also generated to copy the result back. The call
504       --  also takes care of any constraint checks required for the type
505       --  conversion case (on both the way in and the way out).
506
507       procedure Add_Simple_Call_By_Copy_Code;
508       --  This is similar to the above, but is used in cases where we know
509       --  that all that is needed is to simply create a temporary and copy
510       --  the value in and out of the temporary.
511
512       procedure Check_Fortran_Logical;
513       --  A value of type Logical that is passed through a formal parameter
514       --  must be normalized because .TRUE. usually does not have the same
515       --  representation as True. We assume that .FALSE. = False = 0.
516       --  What about functions that return a logical type ???
517
518       function Make_Var (Actual : Node_Id) return Entity_Id;
519       --  Returns an entity that refers to the given actual parameter,
520       --  Actual (not including any type conversion). If Actual is an
521       --  entity name, then this entity is returned unchanged, otherwise
522       --  a renaming is created to provide an entity for the actual.
523
524       procedure Reset_Packed_Prefix;
525       --  The expansion of a packed array component reference is delayed in
526       --  the context of a call. Now we need to complete the expansion, so we
527       --  unmark the analyzed bits in all prefixes.
528
529       ---------------------------
530       -- Add_Call_By_Copy_Code --
531       ---------------------------
532
533       procedure Add_Call_By_Copy_Code is
534          Expr  : Node_Id;
535          Init  : Node_Id;
536          Temp  : Entity_Id;
537          Indic : Node_Id;
538          Var   : Entity_Id;
539          F_Typ : constant Entity_Id := Etype (Formal);
540          V_Typ : Entity_Id;
541          Crep  : Boolean;
542
543       begin
544          Temp := Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
545
546          --  Use formal type for temp, unless formal type is an unconstrained
547          --  array, in which case we don't have to worry about bounds checks,
548          --  and we use the actual type, since that has appropriate bonds.
549
550          if Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ) then
551             Indic := New_Occurrence_Of (Etype (Actual), Loc);
552          else
553             Indic := New_Occurrence_Of (Etype (Formal), Loc);
554          end if;
555
556
557          if Nkind (Actual) = N_Type_Conversion then
558             V_Typ := Etype (Expression (Actual));
559
560             --  If the formal is an (in-)out parameter, capture the name
561             --  of the variable in order to build the post-call assignment.
562
563             Var := Make_Var (Expression (Actual));
564
565             Crep := not Same_Representation
566                           (F_Typ, Etype (Expression (Actual)));
567
568          else
569             V_Typ := Etype (Actual);
570             Var   := Make_Var (Actual);
571             Crep  := False;
572          end if;
573
574          --  Setup initialization for case of in out parameter, or an out
575          --  parameter where the formal is an unconstrained array (in the
576          --  latter case, we have to pass in an object with bounds).
577
578          --  If this is an out parameter, the initial copy is wasteful, so as
579          --  an optimization for the one-dimensional case we extract the
580          --  bounds of the actual and build an uninitialized temporary of the
581          --  right size.
582
583          if Ekind (Formal) = E_In_Out_Parameter
584            or else (Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ))
585          then
586             if Nkind (Actual) = N_Type_Conversion then
587                if Conversion_OK (Actual) then
588                   Init := OK_Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
589                else
590                   Init := Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
591                end if;
592
593             elsif Ekind (Formal) = E_Out_Parameter
594               and then Is_Array_Type (F_Typ)
595               and then Number_Dimensions (F_Typ) = 1
596               and then not Has_Non_Null_Base_Init_Proc (F_Typ)
597             then
598                --  Actual is a one-dimensional array or slice, and the type
599                --  requires no initialization. Create a temporary of the
600                --  right size, but do not copy actual into it (optimization).
601
602                Init := Empty;
603                Indic :=
604                  Make_Subtype_Indication (Loc,
605                    Subtype_Mark =>
606                      New_Occurrence_Of (F_Typ, Loc),
607                    Constraint   =>
608                      Make_Index_Or_Discriminant_Constraint (Loc,
609                        Constraints => New_List (
610                          Make_Range (Loc,
611                            Low_Bound  =>
612                              Make_Attribute_Reference (Loc,
613                                Prefix => New_Occurrence_Of (Var, Loc),
614                                Attribute_name => Name_First),
615                            High_Bound =>
616                              Make_Attribute_Reference (Loc,
617                                Prefix => New_Occurrence_Of (Var, Loc),
618                                Attribute_Name => Name_Last)))));
619
620             else
621                Init := New_Occurrence_Of (Var, Loc);
622             end if;
623
624          --  An initialization is created for packed conversions as
625          --  actuals for out parameters to enable Make_Object_Declaration
626          --  to determine the proper subtype for N_Node. Note that this
627          --  is wasteful because the extra copying on the call side is
628          --  not required for such out parameters. ???
629
630          elsif Ekind (Formal) = E_Out_Parameter
631            and then Nkind (Actual) = N_Type_Conversion
632            and then (Is_Bit_Packed_Array (F_Typ)
633                        or else
634                      Is_Bit_Packed_Array (Etype (Expression (Actual))))
635          then
636             if Conversion_OK (Actual) then
637                Init := OK_Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
638             else
639                Init := Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
640             end if;
641
642          elsif Ekind (Formal) = E_In_Parameter then
643             Init := New_Occurrence_Of (Var, Loc);
644
645          else
646             Init := Empty;
647          end if;
648
649          N_Node :=
650            Make_Object_Declaration (Loc,
651              Defining_Identifier => Temp,
652              Object_Definition   => Indic,
653              Expression          => Init);
654          Set_Assignment_OK (N_Node);
655          Insert_Action (N, N_Node);
656
657          --  Now, normally the deal here is that we use the defining
658          --  identifier created by that object declaration. There is
659          --  one exception to this. In the change of representation case
660          --  the above declaration will end up looking like:
661
662          --    temp : type := identifier;
663
664          --  And in this case we might as well use the identifier directly
665          --  and eliminate the temporary. Note that the analysis of the
666          --  declaration was not a waste of time in that case, since it is
667          --  what generated the necessary change of representation code. If
668          --  the change of representation introduced additional code, as in
669          --  a fixed-integer conversion, the expression is not an identifier
670          --  and must be kept.
671
672          if Crep
673            and then Present (Expression (N_Node))
674            and then Is_Entity_Name (Expression (N_Node))
675          then
676             Temp := Entity (Expression (N_Node));
677             Rewrite (N_Node, Make_Null_Statement (Loc));
678          end if;
679
680          --  For IN parameter, all we do is to replace the actual
681
682          if Ekind (Formal) = E_In_Parameter then
683             Rewrite (Actual, New_Reference_To (Temp, Loc));
684             Analyze (Actual);
685
686          --  Processing for OUT or IN OUT parameter
687
688          else
689             --  If type conversion, use reverse conversion on exit
690
691             if Nkind (Actual) = N_Type_Conversion then
692                if Conversion_OK (Actual) then
693                   Expr := OK_Convert_To (V_Typ, New_Occurrence_Of (Temp, Loc));
694                else
695                   Expr := Convert_To (V_Typ, New_Occurrence_Of (Temp, Loc));
696                end if;
697             else
698                Expr := New_Occurrence_Of (Temp, Loc);
699             end if;
700
701             Rewrite (Actual, New_Reference_To (Temp, Loc));
702             Analyze (Actual);
703
704             Append_To (Post_Call,
705               Make_Assignment_Statement (Loc,
706                 Name       => New_Occurrence_Of (Var, Loc),
707                 Expression => Expr));
708
709             Set_Assignment_OK (Name (Last (Post_Call)));
710          end if;
711       end Add_Call_By_Copy_Code;
712
713       ----------------------------------
714       -- Add_Simple_Call_By_Copy_Code --
715       ----------------------------------
716
717       procedure Add_Simple_Call_By_Copy_Code is
718          Temp   : Entity_Id;
719          Incod  : Node_Id;
720          Outcod : Node_Id;
721          Lhs    : Node_Id;
722          Rhs    : Node_Id;
723          Indic  : Node_Id;
724          F_Typ  : constant Entity_Id := Etype (Formal);
725
726       begin
727          --  Use formal type for temp, unless formal type is an unconstrained
728          --  array, in which case we don't have to worry about bounds checks,
729          --  and we use the actual type, since that has appropriate bonds.
730
731          if Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ) then
732             Indic := New_Occurrence_Of (Etype (Actual), Loc);
733          else
734             Indic := New_Occurrence_Of (Etype (Formal), Loc);
735          end if;
736
737          --  Prepare to generate code
738
739          Reset_Packed_Prefix;
740
741          Temp := Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
742          Incod  := Relocate_Node (Actual);
743          Outcod := New_Copy_Tree (Incod);
744
745          --  Generate declaration of temporary variable, initializing it
746          --  with the input parameter unless we have an OUT variable.
747
748          if Ekind (Formal) = E_Out_Parameter then
749             Incod := Empty;
750          end if;
751
752          Insert_Action (N,
753            Make_Object_Declaration (Loc,
754              Defining_Identifier => Temp,
755              Object_Definition   => Indic,
756              Expression          => Incod));
757
758          --  The actual is simply a reference to the temporary
759
760          Rewrite (Actual, New_Occurrence_Of (Temp, Loc));
761
762          --  Generate copy out if OUT or IN OUT parameter
763
764          if Ekind (Formal) /= E_In_Parameter then
765             Lhs := Outcod;
766             Rhs := New_Occurrence_Of (Temp, Loc);
767
768             --  Deal with conversion
769
770             if Nkind (Lhs) = N_Type_Conversion then
771                Lhs := Expression (Lhs);
772                Rhs := Convert_To (Etype (Actual), Rhs);
773             end if;
774
775             Append_To (Post_Call,
776               Make_Assignment_Statement (Loc,
777                 Name       => Lhs,
778                 Expression => Rhs));
779             Set_Assignment_OK (Name (Last (Post_Call)));
780          end if;
781       end Add_Simple_Call_By_Copy_Code;
782
783       ---------------------------
784       -- Check_Fortran_Logical --
785       ---------------------------
786
787       procedure Check_Fortran_Logical is
788          Logical : constant Entity_Id := Etype (Formal);
789          Var     : Entity_Id;
790
791       --  Note: this is very incomplete, e.g. it does not handle arrays
792       --  of logical values. This is really not the right approach at all???)
793
794       begin
795          if Convention (Subp) = Convention_Fortran
796            and then Root_Type (Etype (Formal)) = Standard_Boolean
797            and then Ekind (Formal) /= E_In_Parameter
798          then
799             Var := Make_Var (Actual);
800             Append_To (Post_Call,
801               Make_Assignment_Statement (Loc,
802                 Name => New_Occurrence_Of (Var, Loc),
803                 Expression =>
804                   Unchecked_Convert_To (
805                     Logical,
806                     Make_Op_Ne (Loc,
807                       Left_Opnd  => New_Occurrence_Of (Var, Loc),
808                       Right_Opnd =>
809                         Unchecked_Convert_To (
810                           Logical,
811                           New_Occurrence_Of (Standard_False, Loc))))));
812          end if;
813       end Check_Fortran_Logical;
814
815       --------------
816       -- Make_Var --
817       --------------
818
819       function Make_Var (Actual : Node_Id) return Entity_Id is
820          Var : Entity_Id;
821
822       begin
823          if Is_Entity_Name (Actual) then
824             return Entity (Actual);
825
826          else
827             Var := Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
828
829             N_Node :=
830               Make_Object_Renaming_Declaration (Loc,
831                 Defining_Identifier => Var,
832                 Subtype_Mark        =>
833                   New_Occurrence_Of (Etype (Actual), Loc),
834                 Name                => Relocate_Node (Actual));
835
836             Insert_Action (N, N_Node);
837             return Var;
838          end if;
839       end Make_Var;
840
841       -------------------------
842       -- Reset_Packed_Prefix --
843       -------------------------
844
845       procedure Reset_Packed_Prefix is
846          Pfx : Node_Id := Actual;
847
848       begin
849          loop
850             Set_Analyzed (Pfx, False);
851             exit when Nkind (Pfx) /= N_Selected_Component
852               and then Nkind (Pfx) /= N_Indexed_Component;
853             Pfx := Prefix (Pfx);
854          end loop;
855       end Reset_Packed_Prefix;
856
857    --  Start of processing for Expand_Actuals
858
859    begin
860       Formal := First_Formal (Subp);
861       Actual := First_Actual (N);
862
863       Post_Call := New_List;
864
865       while Present (Formal) loop
866          E_Formal := Etype (Formal);
867
868          if Is_Scalar_Type (E_Formal)
869            or else Nkind (Actual) = N_Slice
870          then
871             Check_Fortran_Logical;
872
873          --  RM 6.4.1 (11)
874
875          elsif Ekind (Formal) /= E_Out_Parameter then
876
877             --  The unusual case of the current instance of a protected type
878             --  requires special handling. This can only occur in the context
879             --  of a call within the body of a protected operation.
880
881             if Is_Entity_Name (Actual)
882               and then Ekind (Entity (Actual)) = E_Protected_Type
883               and then In_Open_Scopes (Entity (Actual))
884             then
885                if Scope (Subp) /= Entity (Actual) then
886                   Error_Msg_N ("operation outside protected type may not "
887                     & "call back its protected operations?", Actual);
888                end if;
889
890                Rewrite (Actual,
891                  Expand_Protected_Object_Reference (N, Entity (Actual)));
892             end if;
893
894             Apply_Constraint_Check (Actual, E_Formal);
895
896          --  Out parameter case. No constraint checks on access type
897          --  RM 6.4.1 (13)
898
899          elsif Is_Access_Type (E_Formal) then
900             null;
901
902          --  RM 6.4.1 (14)
903
904          elsif Has_Discriminants (Base_Type (E_Formal))
905            or else Has_Non_Null_Base_Init_Proc (E_Formal)
906          then
907             Apply_Constraint_Check (Actual, E_Formal);
908
909          --  RM 6.4.1 (15)
910
911          else
912             Apply_Constraint_Check (Actual, Base_Type (E_Formal));
913          end if;
914
915          --  Processing for IN-OUT and OUT parameters
916
917          if Ekind (Formal) /= E_In_Parameter then
918
919             --  For type conversions of arrays, apply length/range checks
920
921             if Is_Array_Type (E_Formal)
922               and then Nkind (Actual) = N_Type_Conversion
923             then
924                if Is_Constrained (E_Formal) then
925                   Apply_Length_Check (Expression (Actual), E_Formal);
926                else
927                   Apply_Range_Check (Expression (Actual), E_Formal);
928                end if;
929             end if;
930
931             --  If argument is a type conversion for a type that is passed
932             --  by copy, then we must pass the parameter by copy.
933
934             if Nkind (Actual) = N_Type_Conversion
935               and then
936                 (Is_Numeric_Type (E_Formal)
937                   or else Is_Access_Type (E_Formal)
938                   or else Is_Enumeration_Type (E_Formal)
939                   or else Is_Bit_Packed_Array (Etype (Formal))
940                   or else Is_Bit_Packed_Array (Etype (Expression (Actual)))
941
942                   --  Also pass by copy if change of representation
943
944                   or else not Same_Representation
945                                (Etype (Formal),
946                                 Etype (Expression (Actual))))
947             then
948                Add_Call_By_Copy_Code;
949
950             --  References to components of bit packed arrays are expanded
951             --  at this point, rather than at the point of analysis of the
952             --  actuals, to handle the expansion of the assignment to
953             --  [in] out parameters.
954
955             elsif Is_Ref_To_Bit_Packed_Array (Actual) then
956                Add_Simple_Call_By_Copy_Code;
957
958             --  If a non-scalar actual is possibly unaligned, we need a copy
959
960             elsif Is_Possibly_Unaligned_Object (Actual)
961               and then not Represented_As_Scalar (Etype (Formal))
962             then
963                Add_Simple_Call_By_Copy_Code;
964
965             --  References to slices of bit packed arrays are expanded
966
967             elsif Is_Ref_To_Bit_Packed_Slice (Actual) then
968                Add_Call_By_Copy_Code;
969
970             --  References to possibly unaligned slices of arrays are expanded
971
972             elsif Is_Possibly_Unaligned_Slice (Actual) then
973                Add_Call_By_Copy_Code;
974
975             --  Deal with access types where the actual subtpe and the
976             --  formal subtype are not the same, requiring a check.
977
978             --  It is necessary to exclude tagged types because of "downward
979             --  conversion" errors and a strange assertion error in namet
980             --  from gnatf in bug 1215-001 ???
981
982             elsif Is_Access_Type (E_Formal)
983               and then not Same_Type (E_Formal, Etype (Actual))
984               and then not Is_Tagged_Type (Designated_Type (E_Formal))
985             then
986                Add_Call_By_Copy_Code;
987
988             --  If the actual is not a scalar and is marked for volatile
989             --  treatment, whereas the formal is not volatile, then pass
990             --  by copy unless it is a by-reference type.
991
992             elsif Is_Entity_Name (Actual)
993               and then Treat_As_Volatile (Entity (Actual))
994               and then not Is_By_Reference_Type (Etype (Actual))
995               and then not Is_Scalar_Type (Etype (Entity (Actual)))
996               and then not Treat_As_Volatile (E_Formal)
997             then
998                Add_Call_By_Copy_Code;
999
1000             elsif Nkind (Actual) = N_Indexed_Component
1001               and then Is_Entity_Name (Prefix (Actual))
1002               and then Has_Volatile_Components (Entity (Prefix (Actual)))
1003             then
1004                Add_Call_By_Copy_Code;
1005             end if;
1006
1007          --  Processing for IN parameters
1008
1009          else
1010             --  For IN parameters is in the packed array case, we expand an
1011             --  indexed component (the circuit in Exp_Ch4 deliberately left
1012             --  indexed components appearing as actuals untouched, so that
1013             --  the special processing above for the OUT and IN OUT cases
1014             --  could be performed. We could make the test in Exp_Ch4 more
1015             --  complex and have it detect the parameter mode, but it is
1016             --  easier simply to handle all cases here.)
1017
1018             if Nkind (Actual) = N_Indexed_Component
1019               and then Is_Packed (Etype (Prefix (Actual)))
1020             then
1021                Reset_Packed_Prefix;
1022                Expand_Packed_Element_Reference (Actual);
1023
1024             --  If we have a reference to a bit packed array, we copy it,
1025             --  since the actual must be byte aligned.
1026
1027             --  Is this really necessary in all cases???
1028
1029             elsif Is_Ref_To_Bit_Packed_Array (Actual) then
1030                Add_Simple_Call_By_Copy_Code;
1031
1032             --  If a non-scalar actual is possibly unaligned, we need a copy
1033
1034             elsif Is_Possibly_Unaligned_Object (Actual)
1035               and then not Represented_As_Scalar (Etype (Formal))
1036             then
1037                Add_Simple_Call_By_Copy_Code;
1038
1039             --  Similarly, we have to expand slices of packed arrays here
1040             --  because the result must be byte aligned.
1041
1042             elsif Is_Ref_To_Bit_Packed_Slice (Actual) then
1043                Add_Call_By_Copy_Code;
1044
1045             --  Only processing remaining is to pass by copy if this is a
1046             --  reference to a possibly unaligned slice, since the caller
1047             --  expects an appropriately aligned argument.
1048
1049             elsif Is_Possibly_Unaligned_Slice (Actual) then
1050                Add_Call_By_Copy_Code;
1051             end if;
1052          end if;
1053
1054          Next_Formal (Formal);
1055          Next_Actual (Actual);
1056       end loop;
1057
1058       --  Find right place to put post call stuff if it is present
1059
1060       if not Is_Empty_List (Post_Call) then
1061
1062          --  If call is not a list member, it must be the triggering
1063          --  statement of a triggering alternative or an entry call
1064          --  alternative, and we can add the post call stuff to the
1065          --  corresponding statement list.
1066
1067          if not Is_List_Member (N) then
1068             declare
1069                P : constant Node_Id := Parent (N);
1070
1071             begin
1072                pragma Assert (Nkind (P) = N_Triggering_Alternative
1073                  or else Nkind (P) = N_Entry_Call_Alternative);
1074
1075                if Is_Non_Empty_List (Statements (P)) then
1076                   Insert_List_Before_And_Analyze
1077                     (First (Statements (P)), Post_Call);
1078                else
1079                   Set_Statements (P, Post_Call);
1080                end if;
1081             end;
1082
1083          --  Otherwise, normal case where N is in a statement sequence,
1084          --  just put the post-call stuff after the call statement.
1085
1086          else
1087             Insert_Actions_After (N, Post_Call);
1088          end if;
1089       end if;
1090
1091       --  The call node itself is re-analyzed in Expand_Call
1092
1093    end Expand_Actuals;
1094
1095    -----------------
1096    -- Expand_Call --
1097    -----------------
1098
1099    --  This procedure handles expansion of function calls and procedure call
1100    --  statements (i.e. it serves as the body for Expand_N_Function_Call and
1101    --  Expand_N_Procedure_Call_Statement. Processing for calls includes:
1102
1103    --    Replace call to Raise_Exception by Raise_Exception always if possible
1104    --    Provide values of actuals for all formals in Extra_Formals list
1105    --    Replace "call" to enumeration literal function by literal itself
1106    --    Rewrite call to predefined operator as operator
1107    --    Replace actuals to in-out parameters that are numeric conversions,
1108    --     with explicit assignment to temporaries before and after the call.
1109    --    Remove optional actuals if First_Optional_Parameter specified.
1110
1111    --   Note that the list of actuals has been filled with default expressions
1112    --   during semantic analysis of the call. Only the extra actuals required
1113    --   for the 'Constrained attribute and for accessibility checks are added
1114    --   at this point.
1115
1116    procedure Expand_Call (N : Node_Id) is
1117       Loc           : constant Source_Ptr := Sloc (N);
1118       Remote        : constant Boolean    := Is_Remote_Call (N);
1119       Subp          : Entity_Id;
1120       Orig_Subp     : Entity_Id := Empty;
1121       Parent_Subp   : Entity_Id;
1122       Parent_Formal : Entity_Id;
1123       Actual        : Node_Id;
1124       Formal        : Entity_Id;
1125       Prev          : Node_Id := Empty;
1126       Prev_Orig     : Node_Id;
1127       Scop          : Entity_Id;
1128       Extra_Actuals : List_Id := No_List;
1129       Cond          : Node_Id;
1130
1131       procedure Add_Actual_Parameter (Insert_Param : Node_Id);
1132       --  Adds one entry to the end of the actual parameter list. Used for
1133       --  default parameters and for extra actuals (for Extra_Formals).
1134       --  The argument is an N_Parameter_Association node.
1135
1136       procedure Add_Extra_Actual (Expr : Node_Id; EF : Entity_Id);
1137       --  Adds an extra actual to the list of extra actuals. Expr
1138       --  is the expression for the value of the actual, EF is the
1139       --  entity for the extra formal.
1140
1141       function Inherited_From_Formal (S : Entity_Id) return Entity_Id;
1142       --  Within an instance, a type derived from a non-tagged formal derived
1143       --  type inherits from the original parent, not from the actual. This is
1144       --  tested in 4723-003. The current derivation mechanism has the derived
1145       --  type inherit from the actual, which is only correct outside of the
1146       --  instance. If the subprogram is inherited, we test for this particular
1147       --  case through a convoluted tree traversal before setting the proper
1148       --  subprogram to be called.
1149
1150       --------------------------
1151       -- Add_Actual_Parameter --
1152       --------------------------
1153
1154       procedure Add_Actual_Parameter (Insert_Param : Node_Id) is
1155          Actual_Expr : constant Node_Id :=
1156                          Explicit_Actual_Parameter (Insert_Param);
1157
1158       begin
1159          --  Case of insertion is first named actual
1160
1161          if No (Prev) or else
1162             Nkind (Parent (Prev)) /= N_Parameter_Association
1163          then
1164             Set_Next_Named_Actual (Insert_Param, First_Named_Actual (N));
1165             Set_First_Named_Actual (N, Actual_Expr);
1166
1167             if No (Prev) then
1168                if not Present (Parameter_Associations (N)) then
1169                   Set_Parameter_Associations (N, New_List);
1170                   Append (Insert_Param, Parameter_Associations (N));
1171                end if;
1172             else
1173                Insert_After (Prev, Insert_Param);
1174             end if;
1175
1176          --  Case of insertion is not first named actual
1177
1178          else
1179             Set_Next_Named_Actual
1180               (Insert_Param, Next_Named_Actual (Parent (Prev)));
1181             Set_Next_Named_Actual (Parent (Prev), Actual_Expr);
1182             Append (Insert_Param, Parameter_Associations (N));
1183          end if;
1184
1185          Prev := Actual_Expr;
1186       end Add_Actual_Parameter;
1187
1188       ----------------------
1189       -- Add_Extra_Actual --
1190       ----------------------
1191
1192       procedure Add_Extra_Actual (Expr : Node_Id; EF : Entity_Id) is
1193          Loc : constant Source_Ptr := Sloc (Expr);
1194
1195       begin
1196          if Extra_Actuals = No_List then
1197             Extra_Actuals := New_List;
1198             Set_Parent (Extra_Actuals, N);
1199          end if;
1200
1201          Append_To (Extra_Actuals,
1202            Make_Parameter_Association (Loc,
1203              Explicit_Actual_Parameter => Expr,
1204              Selector_Name =>
1205                Make_Identifier (Loc, Chars (EF))));
1206
1207          Analyze_And_Resolve (Expr, Etype (EF));
1208       end Add_Extra_Actual;
1209
1210       ---------------------------
1211       -- Inherited_From_Formal --
1212       ---------------------------
1213
1214       function Inherited_From_Formal (S : Entity_Id) return Entity_Id is
1215          Par      : Entity_Id;
1216          Gen_Par  : Entity_Id;
1217          Gen_Prim : Elist_Id;
1218          Elmt     : Elmt_Id;
1219          Indic    : Node_Id;
1220
1221       begin
1222          --  If the operation is inherited, it is attached to the corresponding
1223          --  type derivation. If the parent in the derivation is a generic
1224          --  actual, it is a subtype of the actual, and we have to recover the
1225          --  original derived type declaration to find the proper parent.
1226
1227          if Nkind (Parent (S)) /= N_Full_Type_Declaration
1228            or else not Is_Derived_Type (Defining_Identifier (Parent (S)))
1229            or else Nkind (Type_Definition (Original_Node (Parent (S))))
1230              /= N_Derived_Type_Definition
1231            or else not In_Instance
1232          then
1233             return Empty;
1234
1235          else
1236             Indic :=
1237               (Subtype_Indication
1238                 (Type_Definition (Original_Node (Parent (S)))));
1239
1240             if Nkind (Indic) = N_Subtype_Indication then
1241                Par := Entity (Subtype_Mark (Indic));
1242             else
1243                Par := Entity (Indic);
1244             end if;
1245          end if;
1246
1247          if not Is_Generic_Actual_Type (Par)
1248            or else Is_Tagged_Type (Par)
1249            or else Nkind (Parent (Par)) /= N_Subtype_Declaration
1250            or else not In_Open_Scopes (Scope (Par))
1251          then
1252             return Empty;
1253
1254          else
1255             Gen_Par := Generic_Parent_Type (Parent (Par));
1256          end if;
1257
1258          --  If the generic parent type is still the generic type, this
1259          --  is a private formal, not a derived formal, and there are no
1260          --  operations inherited from the formal.
1261
1262          if Nkind (Parent (Gen_Par)) = N_Formal_Type_Declaration then
1263             return Empty;
1264          end if;
1265
1266          Gen_Prim := Collect_Primitive_Operations (Gen_Par);
1267          Elmt := First_Elmt (Gen_Prim);
1268
1269          while Present (Elmt) loop
1270             if Chars (Node (Elmt)) = Chars (S) then
1271                declare
1272                   F1 : Entity_Id;
1273                   F2 : Entity_Id;
1274                begin
1275
1276                   F1 := First_Formal (S);
1277                   F2 := First_Formal (Node (Elmt));
1278
1279                   while Present (F1)
1280                     and then Present (F2)
1281                   loop
1282
1283                      if Etype (F1) = Etype (F2)
1284                        or else Etype (F2) = Gen_Par
1285                      then
1286                         Next_Formal (F1);
1287                         Next_Formal (F2);
1288                      else
1289                         Next_Elmt (Elmt);
1290                         exit;   --  not the right subprogram
1291                      end if;
1292
1293                      return Node (Elmt);
1294                   end loop;
1295                end;
1296
1297             else
1298                Next_Elmt (Elmt);
1299             end if;
1300          end loop;
1301
1302          raise Program_Error;
1303       end Inherited_From_Formal;
1304
1305    --  Start of processing for Expand_Call
1306
1307    begin
1308       --  Ignore if previous error
1309
1310       if Nkind (N) in N_Has_Etype and then Etype (N) = Any_Type then
1311          return;
1312       end if;
1313
1314       --  Call using access to subprogram with explicit dereference
1315
1316       if Nkind (Name (N)) = N_Explicit_Dereference then
1317          Subp        := Etype (Name (N));
1318          Parent_Subp := Empty;
1319
1320       --  Case of call to simple entry, where the Name is a selected component
1321       --  whose prefix is the task, and whose selector name is the entry name
1322
1323       elsif Nkind (Name (N)) = N_Selected_Component then
1324          Subp        := Entity (Selector_Name (Name (N)));
1325          Parent_Subp := Empty;
1326
1327       --  Case of call to member of entry family, where Name is an indexed
1328       --  component, with the prefix being a selected component giving the
1329       --  task and entry family name, and the index being the entry index.
1330
1331       elsif Nkind (Name (N)) = N_Indexed_Component then
1332          Subp        := Entity (Selector_Name (Prefix (Name (N))));
1333          Parent_Subp := Empty;
1334
1335       --  Normal case
1336
1337       else
1338          Subp        := Entity (Name (N));
1339          Parent_Subp := Alias (Subp);
1340
1341          --  Replace call to Raise_Exception by call to Raise_Exception_Always
1342          --  if we can tell that the first parameter cannot possibly be null.
1343          --  This helps optimization and also generation of warnings.
1344
1345          if not Restriction_Active (No_Exception_Handlers)
1346            and then Is_RTE (Subp, RE_Raise_Exception)
1347          then
1348             declare
1349                FA : constant Node_Id := Original_Node (First_Actual (N));
1350
1351             begin
1352                --  The case we catch is where the first argument is obtained
1353                --  using the Identity attribute (which must always be non-null)
1354
1355                if Nkind (FA) = N_Attribute_Reference
1356                  and then Attribute_Name (FA) = Name_Identity
1357                then
1358                   Subp := RTE (RE_Raise_Exception_Always);
1359                   Set_Entity (Name (N), Subp);
1360                end if;
1361             end;
1362          end if;
1363
1364          if Ekind (Subp) = E_Entry then
1365             Parent_Subp := Empty;
1366          end if;
1367       end if;
1368
1369       --  First step, compute extra actuals, corresponding to any
1370       --  Extra_Formals present. Note that we do not access Extra_Formals
1371       --  directly, instead we simply note the presence of the extra
1372       --  formals as we process the regular formals and collect the
1373       --  corresponding actuals in Extra_Actuals.
1374
1375       --  We also generate any required range checks for actuals as we go
1376       --  through the loop, since this is a convenient place to do this.
1377
1378       Formal := First_Formal (Subp);
1379       Actual := First_Actual (N);
1380       while Present (Formal) loop
1381
1382          --  Generate range check if required (not activated yet ???)
1383
1384 --         if Do_Range_Check (Actual) then
1385 --            Set_Do_Range_Check (Actual, False);
1386 --            Generate_Range_Check
1387 --              (Actual, Etype (Formal), CE_Range_Check_Failed);
1388 --         end if;
1389
1390          --  Prepare to examine current entry
1391
1392          Prev := Actual;
1393          Prev_Orig := Original_Node (Prev);
1394
1395          --  Create possible extra actual for constrained case. Usually,
1396          --  the extra actual is of the form actual'constrained, but since
1397          --  this attribute is only available for unconstrained records,
1398          --  TRUE is expanded if the type of the formal happens to be
1399          --  constrained (for instance when this procedure is inherited
1400          --  from an unconstrained record to a constrained one) or if the
1401          --  actual has no discriminant (its type is constrained). An
1402          --  exception to this is the case of a private type without
1403          --  discriminants. In this case we pass FALSE because the
1404          --  object has underlying discriminants with defaults.
1405
1406          if Present (Extra_Constrained (Formal)) then
1407             if Ekind (Etype (Prev)) in Private_Kind
1408               and then not Has_Discriminants (Base_Type (Etype (Prev)))
1409             then
1410                Add_Extra_Actual (
1411                  New_Occurrence_Of (Standard_False, Loc),
1412                  Extra_Constrained (Formal));
1413
1414             elsif Is_Constrained (Etype (Formal))
1415               or else not Has_Discriminants (Etype (Prev))
1416             then
1417                Add_Extra_Actual (
1418                  New_Occurrence_Of (Standard_True, Loc),
1419                  Extra_Constrained (Formal));
1420
1421             --  Do not produce extra actuals for Unchecked_Union parameters.
1422             --  Jump directly to the end of the loop.
1423
1424             elsif Is_Unchecked_Union (Base_Type (Etype (Actual))) then
1425                goto Skip_Extra_Actual_Generation;
1426
1427             else
1428                --  If the actual is a type conversion, then the constrained
1429                --  test applies to the actual, not the target type.
1430
1431                declare
1432                   Act_Prev : Node_Id := Prev;
1433
1434                begin
1435                   --  Test for unchecked conversions as well, which can
1436                   --  occur as out parameter actuals on calls to stream
1437                   --  procedures.
1438
1439                   while Nkind (Act_Prev) = N_Type_Conversion
1440                     or else Nkind (Act_Prev) = N_Unchecked_Type_Conversion
1441                   loop
1442                      Act_Prev := Expression (Act_Prev);
1443                   end loop;
1444
1445                   Add_Extra_Actual (
1446                     Make_Attribute_Reference (Sloc (Prev),
1447                       Prefix =>
1448                         Duplicate_Subexpr_No_Checks
1449                           (Act_Prev, Name_Req => True),
1450                       Attribute_Name => Name_Constrained),
1451                     Extra_Constrained (Formal));
1452                end;
1453             end if;
1454          end if;
1455
1456          --  Create possible extra actual for accessibility level
1457
1458          if Present (Extra_Accessibility (Formal)) then
1459             if Is_Entity_Name (Prev_Orig) then
1460
1461                --  When passing an access parameter as the actual to another
1462                --  access parameter we need to pass along the actual's own
1463                --  associated access level parameter. This is done if we are
1464                --  in the scope of the formal access parameter (if this is an
1465                --  inlined body the extra formal is irrelevant).
1466
1467                if Ekind (Entity (Prev_Orig)) in Formal_Kind
1468                  and then Ekind (Etype (Prev_Orig)) = E_Anonymous_Access_Type
1469                  and then In_Open_Scopes (Scope (Entity (Prev_Orig)))
1470                then
1471                   declare
1472                      Parm_Ent : constant Entity_Id := Param_Entity (Prev_Orig);
1473
1474                   begin
1475                      pragma Assert (Present (Parm_Ent));
1476
1477                      if Present (Extra_Accessibility (Parm_Ent)) then
1478                         Add_Extra_Actual (
1479                           New_Occurrence_Of
1480                             (Extra_Accessibility (Parm_Ent), Loc),
1481                           Extra_Accessibility (Formal));
1482
1483                      --  If the actual access parameter does not have an
1484                      --  associated extra formal providing its scope level,
1485                      --  then treat the actual as having library-level
1486                      --  accessibility.
1487
1488                      else
1489                         Add_Extra_Actual (
1490                           Make_Integer_Literal (Loc,
1491                             Intval => Scope_Depth (Standard_Standard)),
1492                           Extra_Accessibility (Formal));
1493                      end if;
1494                   end;
1495
1496                --  The actual is a normal access value, so just pass the
1497                --  level of the actual's access type.
1498
1499                else
1500                   Add_Extra_Actual (
1501                     Make_Integer_Literal (Loc,
1502                       Intval => Type_Access_Level (Etype (Prev_Orig))),
1503                     Extra_Accessibility (Formal));
1504                end if;
1505
1506             else
1507                case Nkind (Prev_Orig) is
1508
1509                   when N_Attribute_Reference =>
1510
1511                      case Get_Attribute_Id (Attribute_Name (Prev_Orig)) is
1512
1513                         --  For X'Access, pass on the level of the prefix X
1514
1515                         when Attribute_Access =>
1516                            Add_Extra_Actual (
1517                              Make_Integer_Literal (Loc,
1518                                Intval =>
1519                                  Object_Access_Level (Prefix (Prev_Orig))),
1520                              Extra_Accessibility (Formal));
1521
1522                         --  Treat the unchecked attributes as library-level
1523
1524                         when Attribute_Unchecked_Access |
1525                            Attribute_Unrestricted_Access =>
1526                            Add_Extra_Actual (
1527                              Make_Integer_Literal (Loc,
1528                                Intval => Scope_Depth (Standard_Standard)),
1529                              Extra_Accessibility (Formal));
1530
1531                         --  No other cases of attributes returning access
1532                         --  values that can be passed to access parameters
1533
1534                         when others =>
1535                            raise Program_Error;
1536
1537                      end case;
1538
1539                   --  For allocators we pass the level of the execution of
1540                   --  the called subprogram, which is one greater than the
1541                   --  current scope level.
1542
1543                   when N_Allocator =>
1544                      Add_Extra_Actual (
1545                        Make_Integer_Literal (Loc,
1546                         Scope_Depth (Current_Scope) + 1),
1547                        Extra_Accessibility (Formal));
1548
1549                   --  For other cases we simply pass the level of the
1550                   --  actual's access type.
1551
1552                   when others =>
1553                      Add_Extra_Actual (
1554                        Make_Integer_Literal (Loc,
1555                          Intval => Type_Access_Level (Etype (Prev_Orig))),
1556                        Extra_Accessibility (Formal));
1557
1558                end case;
1559             end if;
1560          end if;
1561
1562          --  Perform the check of 4.6(49) that prevents a null value
1563          --  from being passed as an actual to an access parameter.
1564          --  Note that the check is elided in the common cases of
1565          --  passing an access attribute or access parameter as an
1566          --  actual. Also, we currently don't enforce this check for
1567          --  expander-generated actuals and when -gnatdj is set.
1568
1569          if Ekind (Etype (Formal)) /= E_Anonymous_Access_Type
1570            or else Access_Checks_Suppressed (Subp)
1571          then
1572             null;
1573
1574          elsif Debug_Flag_J then
1575             null;
1576
1577          elsif not Comes_From_Source (Prev) then
1578             null;
1579
1580          elsif Is_Entity_Name (Prev)
1581            and then Ekind (Etype (Prev)) = E_Anonymous_Access_Type
1582          then
1583             null;
1584
1585          elsif Nkind (Prev) = N_Allocator
1586            or else Nkind (Prev) = N_Attribute_Reference
1587          then
1588             null;
1589
1590          --  Suppress null checks when passing to access parameters
1591          --  of Java subprograms. (Should this be done for other
1592          --  foreign conventions as well ???)
1593
1594          elsif Convention (Subp) = Convention_Java then
1595             null;
1596
1597             --  Ada 2005 (AI-231): do not force the check in case of Ada 2005
1598             --  unless it is a null-excluding type
1599
1600          elsif Ada_Version < Ada_05
1601            or else Can_Never_Be_Null (Etype (Prev))
1602          then
1603             Cond :=
1604               Make_Op_Eq (Loc,
1605                 Left_Opnd => Duplicate_Subexpr_No_Checks (Prev),
1606                 Right_Opnd => Make_Null (Loc));
1607             Insert_Action (Prev,
1608               Make_Raise_Constraint_Error (Loc,
1609                 Condition => Cond,
1610                 Reason    => CE_Access_Parameter_Is_Null));
1611          end if;
1612
1613          --  Perform appropriate validity checks on parameters that
1614          --  are entities.
1615
1616          if Validity_Checks_On then
1617             if  (Ekind (Formal) = E_In_Parameter
1618                    and then Validity_Check_In_Params)
1619               or else
1620                 (Ekind (Formal) = E_In_Out_Parameter
1621                    and then Validity_Check_In_Out_Params)
1622             then
1623                --  If the actual is an indexed component of a packed
1624                --  type, it has not been expanded yet. It will be
1625                --  copied in the validity code that follows, and has
1626                --  to be expanded appropriately, so reanalyze it.
1627
1628                if Nkind (Actual) = N_Indexed_Component then
1629                   Set_Analyzed (Actual, False);
1630                end if;
1631
1632                Ensure_Valid (Actual);
1633             end if;
1634          end if;
1635
1636          --  For IN OUT and OUT parameters, ensure that subscripts are valid
1637          --  since this is a left side reference. We only do this for calls
1638          --  from the source program since we assume that compiler generated
1639          --  calls explicitly generate any required checks. We also need it
1640          --  only if we are doing standard validity checks, since clearly it
1641          --  is not needed if validity checks are off, and in subscript
1642          --  validity checking mode, all indexed components are checked with
1643          --  a call directly from Expand_N_Indexed_Component.
1644
1645          if Comes_From_Source (N)
1646            and then Ekind (Formal) /= E_In_Parameter
1647            and then Validity_Checks_On
1648            and then Validity_Check_Default
1649            and then not Validity_Check_Subscripts
1650          then
1651             Check_Valid_Lvalue_Subscripts (Actual);
1652          end if;
1653
1654          --  Mark any scalar OUT parameter that is a simple variable
1655          --  as no longer known to be valid (unless the type is always
1656          --  valid). This reflects the fact that if an OUT parameter
1657          --  is never set in a procedure, then it can become invalid
1658          --  on return from the procedure.
1659
1660          if Ekind (Formal) = E_Out_Parameter
1661            and then Is_Entity_Name (Actual)
1662            and then Ekind (Entity (Actual)) = E_Variable
1663            and then not Is_Known_Valid (Etype (Actual))
1664          then
1665             Set_Is_Known_Valid (Entity (Actual), False);
1666          end if;
1667
1668          --  For an OUT or IN OUT parameter of an access type, if the
1669          --  actual is an entity, then it is no longer known to be non-null.
1670
1671          if Ekind (Formal) /= E_In_Parameter
1672            and then Is_Entity_Name (Actual)
1673            and then Is_Access_Type (Etype (Actual))
1674          then
1675             Set_Is_Known_Non_Null (Entity (Actual), False);
1676          end if;
1677
1678          --  If the formal is class wide and the actual is an aggregate, force
1679          --  evaluation so that the back end who does not know about class-wide
1680          --  type, does not generate a temporary of the wrong size.
1681
1682          if not Is_Class_Wide_Type (Etype (Formal)) then
1683             null;
1684
1685          elsif Nkind (Actual) = N_Aggregate
1686            or else (Nkind (Actual) = N_Qualified_Expression
1687                      and then Nkind (Expression (Actual)) = N_Aggregate)
1688          then
1689             Force_Evaluation (Actual);
1690          end if;
1691
1692          --  In a remote call, if the formal is of a class-wide type, check
1693          --  that the actual meets the requirements described in E.4(18).
1694
1695          if Remote
1696            and then Is_Class_Wide_Type (Etype (Formal))
1697          then
1698             Insert_Action (Actual,
1699               Make_Implicit_If_Statement (N,
1700                 Condition       =>
1701                   Make_Op_Not (Loc,
1702                     Get_Remotely_Callable
1703                       (Duplicate_Subexpr_Move_Checks (Actual))),
1704                 Then_Statements => New_List (
1705                   Make_Raise_Program_Error (Loc,
1706                     Reason => PE_Illegal_RACW_E_4_18))));
1707          end if;
1708
1709          --  This label is required when skipping extra actual generation for
1710          --  Unchecked_Union parameters.
1711
1712          <<Skip_Extra_Actual_Generation>>
1713
1714          Next_Actual (Actual);
1715          Next_Formal (Formal);
1716       end loop;
1717
1718       --  If we are expanding a rhs of an assignement we need to check if
1719       --  tag propagation is needed. This code belongs theorically in Analyze
1720       --  Assignment but has to be done earlier (bottom-up) because the
1721       --  assignment might be transformed into a declaration for an uncons-
1722       --  trained value, if the expression is classwide.
1723
1724       if Nkind (N) = N_Function_Call
1725         and then Is_Tag_Indeterminate (N)
1726         and then Is_Entity_Name (Name (N))
1727       then
1728          declare
1729             Ass : Node_Id := Empty;
1730
1731          begin
1732             if Nkind (Parent (N)) = N_Assignment_Statement then
1733                Ass := Parent (N);
1734
1735             elsif Nkind (Parent (N)) = N_Qualified_Expression
1736               and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
1737             then
1738                Ass := Parent (Parent (N));
1739             end if;
1740
1741             if Present (Ass)
1742               and then Is_Class_Wide_Type (Etype (Name (Ass)))
1743             then
1744                if Etype (N) /= Root_Type (Etype (Name (Ass))) then
1745                   Error_Msg_NE
1746                     ("tag-indeterminate expression must have type&"
1747                       & "('R'M 5.2 (6))", N, Root_Type (Etype (Name (Ass))));
1748                else
1749                   Propagate_Tag (Name (Ass), N);
1750                end if;
1751
1752                --  The call will be rewritten as a dispatching call, and
1753                --  expanded as such.
1754
1755                return;
1756             end if;
1757          end;
1758       end if;
1759
1760       --  Deals with Dispatch_Call if we still have a call, before expanding
1761       --  extra actuals since this will be done on the re-analysis of the
1762       --  dispatching call. Note that we do not try to shorten the actual
1763       --  list for a dispatching call, it would not make sense to do so.
1764       --  Expansion of dispatching calls is suppressed when Java_VM, because
1765       --  the JVM back end directly handles the generation of dispatching
1766       --  calls and would have to undo any expansion to an indirect call.
1767
1768       if (Nkind (N) = N_Function_Call
1769            or else Nkind (N) =  N_Procedure_Call_Statement)
1770         and then Present (Controlling_Argument (N))
1771         and then not Java_VM
1772       then
1773          Expand_Dispatching_Call (N);
1774
1775          --  The following return is worrisome. Is it really OK to
1776          --  skip all remaining processing in this procedure ???
1777
1778          return;
1779
1780       --  Similarly, expand calls to RCI subprograms on which pragma
1781       --  All_Calls_Remote applies. The rewriting will be reanalyzed
1782       --  later. Do this only when the call comes from source since we do
1783       --  not want such a rewritting to occur in expanded code.
1784
1785       elsif Is_All_Remote_Call (N) then
1786          Expand_All_Calls_Remote_Subprogram_Call (N);
1787
1788       --  Similarly, do not add extra actuals for an entry call whose entity
1789       --  is a protected procedure, or for an internal protected subprogram
1790       --  call, because it will be rewritten as a protected subprogram call
1791       --  and reanalyzed (see Expand_Protected_Subprogram_Call).
1792
1793       elsif Is_Protected_Type (Scope (Subp))
1794          and then (Ekind (Subp) = E_Procedure
1795                     or else Ekind (Subp) = E_Function)
1796       then
1797          null;
1798
1799       --  During that loop we gathered the extra actuals (the ones that
1800       --  correspond to Extra_Formals), so now they can be appended.
1801
1802       else
1803          while Is_Non_Empty_List (Extra_Actuals) loop
1804             Add_Actual_Parameter (Remove_Head (Extra_Actuals));
1805          end loop;
1806       end if;
1807
1808       --  At this point we have all the actuals, so this is the point at
1809       --  which the various expansion activities for actuals is carried out.
1810
1811       Expand_Actuals (N, Subp);
1812
1813       --  If the subprogram is a renaming, or if it is inherited, replace it
1814       --  in the call with the name of the actual subprogram being called.
1815       --  If this is a dispatching call, the run-time decides what to call.
1816       --  The Alias attribute does not apply to entries.
1817
1818       if Nkind (N) /= N_Entry_Call_Statement
1819         and then No (Controlling_Argument (N))
1820         and then Present (Parent_Subp)
1821       then
1822          if Present (Inherited_From_Formal (Subp)) then
1823             Parent_Subp := Inherited_From_Formal (Subp);
1824          else
1825             while Present (Alias (Parent_Subp)) loop
1826                Parent_Subp := Alias (Parent_Subp);
1827             end loop;
1828          end if;
1829
1830          Set_Entity (Name (N), Parent_Subp);
1831
1832          if Is_Abstract (Parent_Subp)
1833            and then not In_Instance
1834          then
1835             Error_Msg_NE
1836               ("cannot call abstract subprogram &!", Name (N), Parent_Subp);
1837          end if;
1838
1839          --  Add an explicit conversion for parameter of the derived type.
1840          --  This is only done for scalar and access in-parameters. Others
1841          --  have been expanded in expand_actuals.
1842
1843          Formal := First_Formal (Subp);
1844          Parent_Formal := First_Formal (Parent_Subp);
1845          Actual := First_Actual (N);
1846
1847          --  It is not clear that conversion is needed for intrinsic
1848          --  subprograms, but it certainly is for those that are user-
1849          --  defined, and that can be inherited on derivation, namely
1850          --  unchecked conversion and deallocation.
1851          --  General case needs study ???
1852
1853          if not Is_Intrinsic_Subprogram (Parent_Subp)
1854            or else Is_Generic_Instance (Parent_Subp)
1855          then
1856             while Present (Formal) loop
1857
1858                if Etype (Formal) /= Etype (Parent_Formal)
1859                  and then Is_Scalar_Type (Etype (Formal))
1860                  and then Ekind (Formal) = E_In_Parameter
1861                  and then not Raises_Constraint_Error (Actual)
1862                then
1863                   Rewrite (Actual,
1864                     OK_Convert_To (Etype (Parent_Formal),
1865                       Relocate_Node (Actual)));
1866
1867                   Analyze (Actual);
1868                   Resolve (Actual, Etype (Parent_Formal));
1869                   Enable_Range_Check (Actual);
1870
1871                elsif Is_Access_Type (Etype (Formal))
1872                  and then Base_Type (Etype (Parent_Formal))
1873                    /= Base_Type (Etype (Actual))
1874                then
1875                   if Ekind (Formal) /= E_In_Parameter then
1876                      Rewrite (Actual,
1877                        Convert_To (Etype (Parent_Formal),
1878                          Relocate_Node (Actual)));
1879
1880                      Analyze (Actual);
1881                      Resolve (Actual, Etype (Parent_Formal));
1882
1883                   elsif
1884                     Ekind (Etype (Parent_Formal)) = E_Anonymous_Access_Type
1885                       and then Designated_Type (Etype (Parent_Formal))
1886                                  /=
1887                                Designated_Type (Etype (Actual))
1888                       and then not Is_Controlling_Formal (Formal)
1889                   then
1890                      --  This unchecked conversion is not necessary unless
1891                      --  inlining is enabled, because in that case the type
1892                      --  mismatch may become visible in the body about to be
1893                      --  inlined.
1894
1895                      Rewrite (Actual,
1896                        Unchecked_Convert_To (Etype (Parent_Formal),
1897                          Relocate_Node (Actual)));
1898
1899                      Analyze (Actual);
1900                      Resolve (Actual, Etype (Parent_Formal));
1901                   end if;
1902                end if;
1903
1904                Next_Formal (Formal);
1905                Next_Formal (Parent_Formal);
1906                Next_Actual (Actual);
1907             end loop;
1908          end if;
1909
1910          Orig_Subp := Subp;
1911          Subp := Parent_Subp;
1912       end if;
1913
1914       --  Check for violation of No_Abort_Statements
1915
1916       if Is_RTE (Subp, RE_Abort_Task) then
1917          Check_Restriction (No_Abort_Statements, N);
1918
1919       --  Check for violation of No_Dynamic_Attachment
1920
1921       elsif RTU_Loaded (Ada_Interrupts)
1922         and then (Is_RTE (Subp, RE_Is_Reserved)      or else
1923                   Is_RTE (Subp, RE_Is_Attached)      or else
1924                   Is_RTE (Subp, RE_Current_Handler)  or else
1925                   Is_RTE (Subp, RE_Attach_Handler)   or else
1926                   Is_RTE (Subp, RE_Exchange_Handler) or else
1927                   Is_RTE (Subp, RE_Detach_Handler)   or else
1928                   Is_RTE (Subp, RE_Reference))
1929       then
1930          Check_Restriction (No_Dynamic_Attachment, N);
1931       end if;
1932
1933       --  Deal with case where call is an explicit dereference
1934
1935       if Nkind (Name (N)) = N_Explicit_Dereference then
1936
1937       --  Handle case of access to protected subprogram type
1938
1939          if Ekind (Base_Type (Etype (Prefix (Name (N))))) =
1940                                E_Access_Protected_Subprogram_Type
1941          then
1942             --  If this is a call through an access to protected operation,
1943             --  the prefix has the form (object'address, operation'access).
1944             --  Rewrite as a for other protected calls: the object is the
1945             --  first parameter of the list of actuals.
1946
1947             declare
1948                Call : Node_Id;
1949                Parm : List_Id;
1950                Nam  : Node_Id;
1951                Obj  : Node_Id;
1952                Ptr  : constant Node_Id := Prefix (Name (N));
1953
1954                T : constant Entity_Id :=
1955                      Equivalent_Type (Base_Type (Etype (Ptr)));
1956
1957                D_T : constant Entity_Id :=
1958                        Designated_Type (Base_Type (Etype (Ptr)));
1959
1960             begin
1961                Obj :=
1962                  Make_Selected_Component (Loc,
1963                    Prefix        => Unchecked_Convert_To (T, Ptr),
1964                    Selector_Name =>
1965                      New_Occurrence_Of (First_Entity (T), Loc));
1966
1967                Nam :=
1968                  Make_Selected_Component (Loc,
1969                    Prefix        => Unchecked_Convert_To (T, Ptr),
1970                    Selector_Name =>
1971                      New_Occurrence_Of (Next_Entity (First_Entity (T)), Loc));
1972
1973                Nam := Make_Explicit_Dereference (Loc, Nam);
1974
1975                if Present (Parameter_Associations (N))  then
1976                   Parm := Parameter_Associations (N);
1977                else
1978                   Parm := New_List;
1979                end if;
1980
1981                Prepend (Obj, Parm);
1982
1983                if Etype (D_T) = Standard_Void_Type then
1984                   Call := Make_Procedure_Call_Statement (Loc,
1985                     Name => Nam,
1986                     Parameter_Associations => Parm);
1987                else
1988                   Call := Make_Function_Call (Loc,
1989                     Name => Nam,
1990                     Parameter_Associations => Parm);
1991                end if;
1992
1993                Set_First_Named_Actual (Call, First_Named_Actual (N));
1994                Set_Etype (Call, Etype (D_T));
1995
1996                --  We do not re-analyze the call to avoid infinite recursion.
1997                --  We analyze separately the prefix and the object, and set
1998                --  the checks on the prefix that would otherwise be emitted
1999                --  when resolving a call.
2000
2001                Rewrite (N, Call);
2002                Analyze (Nam);
2003                Apply_Access_Check (Nam);
2004                Analyze (Obj);
2005                return;
2006             end;
2007          end if;
2008       end if;
2009
2010       --  If this is a call to an intrinsic subprogram, then perform the
2011       --  appropriate expansion to the corresponding tree node and we
2012       --  are all done (since after that the call is gone!)
2013
2014       --  In the case where the intrinsic is to be processed by the back end,
2015       --  the call to Expand_Intrinsic_Call will do nothing, which is fine,
2016       --  since the idea in this case is to pass the call unchanged.
2017
2018       if Is_Intrinsic_Subprogram (Subp) then
2019          Expand_Intrinsic_Call (N, Subp);
2020          return;
2021       end if;
2022
2023       if Ekind (Subp) = E_Function
2024         or else Ekind (Subp) = E_Procedure
2025       then
2026          if Is_Inlined (Subp) then
2027
2028             Inlined_Subprogram : declare
2029                Bod         : Node_Id;
2030                Must_Inline : Boolean := False;
2031                Spec        : constant Node_Id := Unit_Declaration_Node (Subp);
2032                Scop        : constant Entity_Id := Scope (Subp);
2033
2034                function In_Unfrozen_Instance return Boolean;
2035                --  If the subprogram comes from an instance in the same
2036                --  unit, and the instance is not yet frozen, inlining might
2037                --  trigger order-of-elaboration problems in gigi.
2038
2039                --------------------------
2040                -- In_Unfrozen_Instance --
2041                --------------------------
2042
2043                function In_Unfrozen_Instance return Boolean is
2044                   S : Entity_Id := Scop;
2045
2046                begin
2047                   while Present (S)
2048                     and then S /= Standard_Standard
2049                   loop
2050                      if Is_Generic_Instance (S)
2051                        and then Present (Freeze_Node (S))
2052                        and then not Analyzed (Freeze_Node (S))
2053                      then
2054                         return True;
2055                      end if;
2056
2057                      S := Scope (S);
2058                   end loop;
2059
2060                   return False;
2061                end In_Unfrozen_Instance;
2062
2063             --  Start of processing for Inlined_Subprogram
2064
2065             begin
2066                --  Verify that the body to inline has already been seen,
2067                --  and that if the body is in the current unit the inlining
2068                --  does not occur earlier. This avoids order-of-elaboration
2069                --  problems in gigi.
2070
2071                if No (Spec)
2072                  or else Nkind (Spec) /= N_Subprogram_Declaration
2073                  or else No (Body_To_Inline (Spec))
2074                then
2075                   Must_Inline := False;
2076
2077                --  If this an inherited function that returns a private
2078                --  type, do not inline if the full view is an unconstrained
2079                --  array, because such calls cannot be inlined.
2080
2081                elsif Present (Orig_Subp)
2082                  and then Is_Array_Type (Etype (Orig_Subp))
2083                  and then not Is_Constrained (Etype (Orig_Subp))
2084                then
2085                   Must_Inline := False;
2086
2087                elsif In_Unfrozen_Instance then
2088                   Must_Inline := False;
2089
2090                else
2091                   Bod := Body_To_Inline (Spec);
2092
2093                   if (In_Extended_Main_Code_Unit (N)
2094                         or else In_Extended_Main_Code_Unit (Parent (N))
2095                         or else Is_Always_Inlined (Subp))
2096                     and then (not In_Same_Extended_Unit (Sloc (Bod), Loc)
2097                                or else
2098                                  Earlier_In_Extended_Unit (Sloc (Bod), Loc))
2099                   then
2100                      Must_Inline := True;
2101
2102                   --  If we are compiling a package body that is not the main
2103                   --  unit, it must be for inlining/instantiation purposes,
2104                   --  in which case we inline the call to insure that the same
2105                   --  temporaries are generated when compiling the body by
2106                   --  itself. Otherwise link errors can occur.
2107
2108                   --  If the function being called is itself in the main unit,
2109                   --  we cannot inline, because there is a risk of double
2110                   --  elaboration and/or circularity: the inlining can make
2111                   --  visible a private entity in the body of the main unit,
2112                   --  that gigi will see before its sees its proper definition.
2113
2114                   elsif not (In_Extended_Main_Code_Unit (N))
2115                     and then In_Package_Body
2116                   then
2117                      Must_Inline := not In_Extended_Main_Source_Unit (Subp);
2118                   end if;
2119                end if;
2120
2121                if Must_Inline then
2122                   Expand_Inlined_Call (N, Subp, Orig_Subp);
2123
2124                else
2125                   --  Let the back end handle it
2126
2127                   Add_Inlined_Body (Subp);
2128
2129                   if Front_End_Inlining
2130                     and then Nkind (Spec) = N_Subprogram_Declaration
2131                     and then (In_Extended_Main_Code_Unit (N))
2132                     and then No (Body_To_Inline (Spec))
2133                     and then not Has_Completion (Subp)
2134                     and then In_Same_Extended_Unit (Sloc (Spec), Loc)
2135                   then
2136                      Cannot_Inline
2137                       ("cannot inline& (body not seen yet)?",
2138                        N, Subp);
2139                   end if;
2140                end if;
2141             end Inlined_Subprogram;
2142          end if;
2143       end if;
2144
2145       --  Check for a protected subprogram. This is either an intra-object
2146       --  call, or a protected function call. Protected procedure calls are
2147       --  rewritten as entry calls and handled accordingly.
2148
2149       Scop := Scope (Subp);
2150
2151       if Nkind (N) /= N_Entry_Call_Statement
2152         and then Is_Protected_Type (Scop)
2153       then
2154          --  If the call is an internal one, it is rewritten as a call to
2155          --  to the corresponding unprotected subprogram.
2156
2157          Expand_Protected_Subprogram_Call (N, Subp, Scop);
2158       end if;
2159
2160       --  Functions returning controlled objects need special attention
2161
2162       if Controlled_Type (Etype (Subp))
2163         and then not Is_Return_By_Reference_Type (Etype (Subp))
2164       then
2165          Expand_Ctrl_Function_Call (N);
2166       end if;
2167
2168       --  Test for First_Optional_Parameter, and if so, truncate parameter
2169       --  list if there are optional parameters at the trailing end.
2170       --  Note we never delete procedures for call via a pointer.
2171
2172       if (Ekind (Subp) = E_Procedure or else Ekind (Subp) = E_Function)
2173         and then Present (First_Optional_Parameter (Subp))
2174       then
2175          declare
2176             Last_Keep_Arg : Node_Id;
2177
2178          begin
2179             --  Last_Keep_Arg will hold the last actual that should be
2180             --  retained. If it remains empty at the end, it means that
2181             --  all parameters are optional.
2182
2183             Last_Keep_Arg := Empty;
2184
2185             --  Find first optional parameter, must be present since we
2186             --  checked the validity of the parameter before setting it.
2187
2188             Formal := First_Formal (Subp);
2189             Actual := First_Actual (N);
2190             while Formal /= First_Optional_Parameter (Subp) loop
2191                Last_Keep_Arg := Actual;
2192                Next_Formal (Formal);
2193                Next_Actual (Actual);
2194             end loop;
2195
2196             --  We have Formal and Actual pointing to the first potentially
2197             --  droppable argument. We can drop all the trailing arguments
2198             --  whose actual matches the default. Note that we know that all
2199             --  remaining formals have defaults, because we checked that this
2200             --  requirement was met before setting First_Optional_Parameter.
2201
2202             --  We use Fully_Conformant_Expressions to check for identity
2203             --  between formals and actuals, which may miss some cases, but
2204             --  on the other hand, this is only an optimization (if we fail
2205             --  to truncate a parameter it does not affect functionality).
2206             --  So if the default is 3 and the actual is 1+2, we consider
2207             --  them unequal, which hardly seems worrisome.
2208
2209             while Present (Formal) loop
2210                if not Fully_Conformant_Expressions
2211                     (Actual, Default_Value (Formal))
2212                then
2213                   Last_Keep_Arg := Actual;
2214                end if;
2215
2216                Next_Formal (Formal);
2217                Next_Actual (Actual);
2218             end loop;
2219
2220             --  If no arguments, delete entire list, this is the easy case
2221
2222             if No (Last_Keep_Arg) then
2223                while Is_Non_Empty_List (Parameter_Associations (N)) loop
2224                   Delete_Tree (Remove_Head (Parameter_Associations (N)));
2225                end loop;
2226
2227                Set_Parameter_Associations (N, No_List);
2228                Set_First_Named_Actual (N, Empty);
2229
2230             --  Case where at the last retained argument is positional. This
2231             --  is also an easy case, since the retained arguments are already
2232             --  in the right form, and we don't need to worry about the order
2233             --  of arguments that get eliminated.
2234
2235             elsif Is_List_Member (Last_Keep_Arg) then
2236                while Present (Next (Last_Keep_Arg)) loop
2237                   Delete_Tree (Remove_Next (Last_Keep_Arg));
2238                end loop;
2239
2240                Set_First_Named_Actual (N, Empty);
2241
2242             --  This is the annoying case where the last retained argument
2243             --  is a named parameter. Since the original arguments are not
2244             --  in declaration order, we may have to delete some fairly
2245             --  random collection of arguments.
2246
2247             else
2248                declare
2249                   Temp   : Node_Id;
2250                   Passoc : Node_Id;
2251
2252                   Discard : Node_Id;
2253                   pragma Warnings (Off, Discard);
2254
2255                begin
2256                   --  First step, remove all the named parameters from the
2257                   --  list (they are still chained using First_Named_Actual
2258                   --  and Next_Named_Actual, so we have not lost them!)
2259
2260                   Temp := First (Parameter_Associations (N));
2261
2262                   --  Case of all parameters named, remove them all
2263
2264                   if Nkind (Temp) = N_Parameter_Association then
2265                      while Is_Non_Empty_List (Parameter_Associations (N)) loop
2266                         Temp := Remove_Head (Parameter_Associations (N));
2267                      end loop;
2268
2269                   --  Case of mixed positional/named, remove named parameters
2270
2271                   else
2272                      while Nkind (Next (Temp)) /= N_Parameter_Association loop
2273                         Next (Temp);
2274                      end loop;
2275
2276                      while Present (Next (Temp)) loop
2277                         Discard := Remove_Next (Temp);
2278                      end loop;
2279                   end if;
2280
2281                   --  Now we loop through the named parameters, till we get
2282                   --  to the last one to be retained, adding them to the list.
2283                   --  Note that the Next_Named_Actual list does not need to be
2284                   --  touched since we are only reordering them on the actual
2285                   --  parameter association list.
2286
2287                   Passoc := Parent (First_Named_Actual (N));
2288                   loop
2289                      Temp := Relocate_Node (Passoc);
2290                      Append_To
2291                        (Parameter_Associations (N), Temp);
2292                      exit when
2293                        Last_Keep_Arg = Explicit_Actual_Parameter (Passoc);
2294                      Passoc := Parent (Next_Named_Actual (Passoc));
2295                   end loop;
2296
2297                   Set_Next_Named_Actual (Temp, Empty);
2298
2299                   loop
2300                      Temp := Next_Named_Actual (Passoc);
2301                      exit when No (Temp);
2302                      Set_Next_Named_Actual
2303                        (Passoc, Next_Named_Actual (Parent (Temp)));
2304                      Delete_Tree (Temp);
2305                   end loop;
2306                end;
2307             end if;
2308          end;
2309       end if;
2310    end Expand_Call;
2311
2312    --------------------------
2313    -- Expand_Inlined_Call --
2314    --------------------------
2315
2316    procedure Expand_Inlined_Call
2317     (N         : Node_Id;
2318      Subp      : Entity_Id;
2319      Orig_Subp : Entity_Id)
2320    is
2321       Loc       : constant Source_Ptr := Sloc (N);
2322       Is_Predef : constant Boolean :=
2323                    Is_Predefined_File_Name
2324                      (Unit_File_Name (Get_Source_Unit (Subp)));
2325       Orig_Bod  : constant Node_Id :=
2326                     Body_To_Inline (Unit_Declaration_Node (Subp));
2327
2328       Blk      : Node_Id;
2329       Bod      : Node_Id;
2330       Decl     : Node_Id;
2331       Exit_Lab : Entity_Id := Empty;
2332       F        : Entity_Id;
2333       A        : Node_Id;
2334       Lab_Decl : Node_Id;
2335       Lab_Id   : Node_Id;
2336       New_A    : Node_Id;
2337       Num_Ret  : Int := 0;
2338       Ret_Type : Entity_Id;
2339       Targ     : Node_Id;
2340       Temp     : Entity_Id;
2341       Temp_Typ : Entity_Id;
2342
2343       procedure Make_Exit_Label;
2344       --  Build declaration for exit label to be used in Return statements
2345
2346       function Process_Formals (N : Node_Id) return Traverse_Result;
2347       --  Replace occurrence of a formal with the corresponding actual, or
2348       --  the thunk generated for it.
2349
2350       function Process_Sloc (Nod : Node_Id) return Traverse_Result;
2351       --  If the call being expanded is that of an internal subprogram,
2352       --  set the sloc of the generated block to that of the call itself,
2353       --  so that the expansion is skipped by the -next- command in gdb.
2354       --  Same processing for a subprogram in a predefined file, e.g.
2355       --  Ada.Tags. If Debug_Generated_Code is true, suppress this change
2356       --  to simplify our own development.
2357
2358       procedure Rewrite_Function_Call (N : Node_Id; Blk : Node_Id);
2359       --  If the function body is a single expression, replace call with
2360       --  expression, else insert block appropriately.
2361
2362       procedure Rewrite_Procedure_Call (N : Node_Id; Blk : Node_Id);
2363       --  If procedure body has no local variables, inline body without
2364       --  creating block,  otherwise rewrite call with block.
2365
2366       function Formal_Is_Used_Once (Formal : Entity_Id) return Boolean;
2367       --  Determine whether a formal parameter is used only once in Orig_Bod
2368
2369       ---------------------
2370       -- Make_Exit_Label --
2371       ---------------------
2372
2373       procedure Make_Exit_Label is
2374       begin
2375          --  Create exit label for subprogram if one does not exist yet
2376
2377          if No (Exit_Lab) then
2378             Lab_Id := Make_Identifier (Loc, New_Internal_Name ('L'));
2379             Set_Entity (Lab_Id,
2380               Make_Defining_Identifier (Loc, Chars (Lab_Id)));
2381             Exit_Lab := Make_Label (Loc, Lab_Id);
2382
2383             Lab_Decl :=
2384               Make_Implicit_Label_Declaration (Loc,
2385                 Defining_Identifier  => Entity (Lab_Id),
2386                 Label_Construct      => Exit_Lab);
2387          end if;
2388       end Make_Exit_Label;
2389
2390       ---------------------
2391       -- Process_Formals --
2392       ---------------------
2393
2394       function Process_Formals (N : Node_Id) return Traverse_Result is
2395          A   : Entity_Id;
2396          E   : Entity_Id;
2397          Ret : Node_Id;
2398
2399       begin
2400          if Is_Entity_Name (N)
2401            and then Present (Entity (N))
2402          then
2403             E := Entity (N);
2404
2405             if Is_Formal (E)
2406               and then Scope (E) = Subp
2407             then
2408                A := Renamed_Object (E);
2409
2410                if Is_Entity_Name (A) then
2411                   Rewrite (N, New_Occurrence_Of (Entity (A), Loc));
2412
2413                elsif Nkind (A) = N_Defining_Identifier then
2414                   Rewrite (N, New_Occurrence_Of (A, Loc));
2415
2416                else   --  numeric literal
2417                   Rewrite (N, New_Copy (A));
2418                end if;
2419             end if;
2420
2421             return Skip;
2422
2423          elsif Nkind (N) = N_Return_Statement then
2424
2425             if No (Expression (N)) then
2426                Make_Exit_Label;
2427                Rewrite (N, Make_Goto_Statement (Loc,
2428                  Name => New_Copy (Lab_Id)));
2429
2430             else
2431                if Nkind (Parent (N)) = N_Handled_Sequence_Of_Statements
2432                  and then Nkind (Parent (Parent (N))) = N_Subprogram_Body
2433                then
2434                   --  Function body is a single expression. No need for
2435                   --  exit label.
2436
2437                   null;
2438
2439                else
2440                   Num_Ret := Num_Ret + 1;
2441                   Make_Exit_Label;
2442                end if;
2443
2444                --  Because of the presence of private types, the views of the
2445                --  expression and the context may be different, so place an
2446                --  unchecked conversion to the context type to avoid spurious
2447                --  errors, eg. when the expression is a numeric literal and
2448                --  the context is private. If the expression is an aggregate,
2449                --  use a qualified expression, because an aggregate is not a
2450                --  legal argument of a conversion.
2451
2452                if Nkind (Expression (N)) = N_Aggregate
2453                  or else Nkind (Expression (N)) = N_Null
2454                then
2455                   Ret :=
2456                     Make_Qualified_Expression (Sloc (N),
2457                        Subtype_Mark => New_Occurrence_Of (Ret_Type, Sloc (N)),
2458                        Expression => Relocate_Node (Expression (N)));
2459                else
2460                   Ret :=
2461                     Unchecked_Convert_To
2462                       (Ret_Type, Relocate_Node (Expression (N)));
2463                end if;
2464
2465                if Nkind (Targ) = N_Defining_Identifier then
2466                   Rewrite (N,
2467                     Make_Assignment_Statement (Loc,
2468                       Name => New_Occurrence_Of (Targ, Loc),
2469                       Expression => Ret));
2470                else
2471                   Rewrite (N,
2472                     Make_Assignment_Statement (Loc,
2473                       Name => New_Copy (Targ),
2474                       Expression => Ret));
2475                end if;
2476
2477                Set_Assignment_OK (Name (N));
2478
2479                if Present (Exit_Lab) then
2480                   Insert_After (N,
2481                     Make_Goto_Statement (Loc,
2482                       Name => New_Copy (Lab_Id)));
2483                end if;
2484             end if;
2485
2486             return OK;
2487
2488          --  Remove pragma Unreferenced since it may refer to formals that
2489          --  are not visible in the inlined body, and in any case we will
2490          --  not be posting warnings on the inlined body so it is unneeded.
2491
2492          elsif Nkind (N) = N_Pragma
2493            and then Chars (N) = Name_Unreferenced
2494          then
2495             Rewrite (N, Make_Null_Statement (Sloc (N)));
2496             return OK;
2497
2498          else
2499             return OK;
2500          end if;
2501       end Process_Formals;
2502
2503       procedure Replace_Formals is new Traverse_Proc (Process_Formals);
2504
2505       ------------------
2506       -- Process_Sloc --
2507       ------------------
2508
2509       function Process_Sloc (Nod : Node_Id) return Traverse_Result is
2510       begin
2511          if not Debug_Generated_Code then
2512             Set_Sloc (Nod, Sloc (N));
2513             Set_Comes_From_Source (Nod, False);
2514          end if;
2515
2516          return OK;
2517       end Process_Sloc;
2518
2519       procedure Reset_Slocs is new Traverse_Proc (Process_Sloc);
2520
2521       ---------------------------
2522       -- Rewrite_Function_Call --
2523       ---------------------------
2524
2525       procedure Rewrite_Function_Call (N : Node_Id; Blk : Node_Id) is
2526          HSS : constant Node_Id := Handled_Statement_Sequence (Blk);
2527          Fst : constant Node_Id := First (Statements (HSS));
2528
2529       begin
2530          --  Optimize simple case: function body is a single return statement,
2531          --  which has been expanded into an assignment.
2532
2533          if Is_Empty_List (Declarations (Blk))
2534            and then Nkind (Fst) = N_Assignment_Statement
2535            and then No (Next (Fst))
2536          then
2537
2538             --  The function call may have been rewritten as the temporary
2539             --  that holds the result of the call, in which case remove the
2540             --  now useless declaration.
2541
2542             if Nkind (N) = N_Identifier
2543               and then Nkind (Parent (Entity (N))) = N_Object_Declaration
2544             then
2545                Rewrite (Parent (Entity (N)), Make_Null_Statement (Loc));
2546             end if;
2547
2548             Rewrite (N, Expression (Fst));
2549
2550          elsif Nkind (N) = N_Identifier
2551            and then Nkind (Parent (Entity (N))) = N_Object_Declaration
2552          then
2553             --  The block assigns the result of the call to the temporary
2554
2555             Insert_After (Parent (Entity (N)), Blk);
2556
2557          elsif Nkind (Parent (N)) = N_Assignment_Statement
2558            and then Is_Entity_Name (Name (Parent (N)))
2559          then
2560             --  Replace assignment with the block
2561
2562             declare
2563                Original_Assignment : constant Node_Id := Parent (N);
2564
2565             begin
2566                --  Preserve the original assignment node to keep the
2567                --  complete assignment subtree consistent enough for
2568                --  Analyze_Assignment to proceed (specifically, the
2569                --  original Lhs node must still have an assignment
2570                --  statement as its parent).
2571
2572                --  We cannot rely on Original_Node to go back from the
2573                --  block node to the assignment node, because the
2574                --  assignment might already be a rewrite substitution.
2575
2576                Discard_Node (Relocate_Node (Original_Assignment));
2577                Rewrite (Original_Assignment, Blk);
2578             end;
2579
2580          elsif Nkind (Parent (N)) = N_Object_Declaration then
2581             Set_Expression (Parent (N), Empty);
2582             Insert_After (Parent (N), Blk);
2583          end if;
2584       end Rewrite_Function_Call;
2585
2586       ----------------------------
2587       -- Rewrite_Procedure_Call --
2588       ----------------------------
2589
2590       procedure Rewrite_Procedure_Call (N : Node_Id; Blk : Node_Id) is
2591          HSS  : constant Node_Id := Handled_Statement_Sequence (Blk);
2592       begin
2593          if Is_Empty_List (Declarations (Blk)) then
2594             Insert_List_After (N, Statements (HSS));
2595             Rewrite (N, Make_Null_Statement (Loc));
2596          else
2597             Rewrite (N, Blk);
2598          end if;
2599       end Rewrite_Procedure_Call;
2600
2601       -------------------------
2602       -- Formal_Is_Used_Once --
2603       ------------------------
2604
2605       function Formal_Is_Used_Once (Formal : Entity_Id) return Boolean is
2606          Use_Counter : Int := 0;
2607
2608          function Count_Uses (N : Node_Id) return Traverse_Result;
2609          --  Traverse the tree and count the uses of the formal parameter.
2610          --  In this case, for optimization purposes, we do not need to
2611          --  continue the traversal once more than one use is encountered.
2612
2613          ----------------
2614          -- Count_Uses --
2615          ----------------
2616
2617          function Count_Uses (N : Node_Id) return Traverse_Result is
2618          begin
2619             --  The original node is an identifier
2620
2621             if Nkind (N) = N_Identifier
2622               and then Present (Entity (N))
2623
2624                --  The original node's entity points to the one in the
2625                --  copied body.
2626
2627               and then Nkind (Entity (N)) = N_Identifier
2628               and then Present (Entity (Entity (N)))
2629
2630                --  The entity of the copied node is the formal parameter
2631
2632               and then Entity (Entity (N)) = Formal
2633             then
2634                Use_Counter := Use_Counter + 1;
2635
2636                if Use_Counter > 1 then
2637
2638                   --  Denote more than one use and abandon the traversal
2639
2640                   Use_Counter := 2;
2641                   return Abandon;
2642
2643                end if;
2644             end if;
2645
2646             return OK;
2647          end Count_Uses;
2648
2649          procedure Count_Formal_Uses is new Traverse_Proc (Count_Uses);
2650
2651       --  Start of processing for Formal_Is_Used_Once
2652
2653       begin
2654          Count_Formal_Uses (Orig_Bod);
2655          return Use_Counter = 1;
2656       end Formal_Is_Used_Once;
2657
2658    --  Start of processing for Expand_Inlined_Call
2659
2660    begin
2661       --  Check for special case of To_Address call, and if so, just do an
2662       --  unchecked conversion instead of expanding the call. Not only is this
2663       --  more efficient, but it also avoids problem with order of elaboration
2664       --  when address clauses are inlined (address expr elaborated at wrong
2665       --  point).
2666
2667       if Subp = RTE (RE_To_Address) then
2668          Rewrite (N,
2669            Unchecked_Convert_To
2670             (RTE (RE_Address),
2671              Relocate_Node (First_Actual (N))));
2672          return;
2673       end if;
2674
2675       --  Check for an illegal attempt to inline a recursive procedure. If the
2676       --  subprogram has parameters this is detected when trying to supply a
2677       --  binding for parameters that already have one. For parameterless
2678       --  subprograms this must be done explicitly.
2679
2680       if In_Open_Scopes (Subp) then
2681          Error_Msg_N ("call to recursive subprogram cannot be inlined?", N);
2682          Set_Is_Inlined (Subp, False);
2683          return;
2684       end if;
2685
2686       if Nkind (Orig_Bod) = N_Defining_Identifier then
2687
2688          --  Subprogram is a renaming_as_body. Calls appearing after the
2689          --  renaming can be replaced with calls to the renamed entity
2690          --  directly, because the subprograms are subtype conformant. If
2691          --  the renamed subprogram is an inherited operation, we must redo
2692          --  the expansion because implicit conversions may be needed.
2693
2694          Set_Name (N, New_Occurrence_Of (Orig_Bod, Loc));
2695
2696          if Present (Alias (Orig_Bod)) then
2697             Expand_Call (N);
2698          end if;
2699
2700          return;
2701       end if;
2702
2703       --  Use generic machinery to copy body of inlined subprogram, as if it
2704       --  were an instantiation, resetting source locations appropriately, so
2705       --  that nested inlined calls appear in the main unit.
2706
2707       Save_Env (Subp, Empty);
2708       Set_Copied_Sloc_For_Inlined_Body (N, Defining_Entity (Orig_Bod));
2709
2710       Bod := Copy_Generic_Node (Orig_Bod, Empty, Instantiating => True);
2711       Blk :=
2712         Make_Block_Statement (Loc,
2713           Declarations => Declarations (Bod),
2714           Handled_Statement_Sequence => Handled_Statement_Sequence (Bod));
2715
2716       if No (Declarations (Bod)) then
2717          Set_Declarations (Blk, New_List);
2718       end if;
2719
2720       --  If this is a derived function, establish the proper return type
2721
2722       if Present (Orig_Subp)
2723         and then Orig_Subp /= Subp
2724       then
2725          Ret_Type := Etype (Orig_Subp);
2726       else
2727          Ret_Type := Etype (Subp);
2728       end if;
2729
2730       F := First_Formal (Subp);
2731       A := First_Actual (N);
2732
2733       --  Create temporaries for the actuals that are expressions, or that
2734       --  are scalars and require copying to preserve semantics.
2735
2736       while Present (F) loop
2737          if Present (Renamed_Object (F)) then
2738             Error_Msg_N (" cannot inline call to recursive subprogram", N);
2739             return;
2740          end if;
2741
2742          --  If the argument may be a controlling argument in a call within
2743          --  the inlined body, we must preserve its classwide nature to insure
2744          --  that dynamic dispatching take place subsequently. If the formal
2745          --  has a constraint it must be preserved to retain the semantics of
2746          --  the body.
2747
2748          if Is_Class_Wide_Type (Etype (F))
2749            or else (Is_Access_Type (Etype (F))
2750                       and then
2751                     Is_Class_Wide_Type (Designated_Type (Etype (F))))
2752          then
2753             Temp_Typ := Etype (F);
2754
2755          elsif Base_Type (Etype (F)) = Base_Type (Etype (A))
2756            and then Etype (F) /= Base_Type (Etype (F))
2757          then
2758             Temp_Typ := Etype (F);
2759
2760          else
2761             Temp_Typ := Etype (A);
2762          end if;
2763
2764          --  If the actual is a simple name or a literal, no need to
2765          --  create a temporary, object can be used directly.
2766
2767          if (Is_Entity_Name (A)
2768               and then
2769                (not Is_Scalar_Type (Etype (A))
2770                  or else Ekind (Entity (A)) = E_Enumeration_Literal))
2771
2772          --  When the actual is an identifier and the corresponding formal
2773          --  is used only once in the original body, the formal can be
2774          --  substituted directly with the actual parameter.
2775
2776            or else (Nkind (A) = N_Identifier
2777              and then Formal_Is_Used_Once (F))
2778
2779            or else Nkind (A) = N_Real_Literal
2780            or else Nkind (A) = N_Integer_Literal
2781            or else Nkind (A) = N_Character_Literal
2782          then
2783             if Etype (F) /= Etype (A) then
2784                Set_Renamed_Object
2785                 (F, Unchecked_Convert_To (Etype (F), Relocate_Node (A)));
2786             else
2787                Set_Renamed_Object (F, A);
2788             end if;
2789
2790          else
2791             Temp :=
2792               Make_Defining_Identifier (Loc,
2793                 Chars => New_Internal_Name ('C'));
2794
2795             --  If the actual for an in/in-out parameter is a view conversion,
2796             --  make it into an unchecked conversion, given that an untagged
2797             --  type conversion is not a proper object for a renaming.
2798
2799             --  In-out conversions that involve real conversions have already
2800             --  been transformed in Expand_Actuals.
2801
2802             if Nkind (A) = N_Type_Conversion
2803               and then Ekind (F) /= E_In_Parameter
2804             then
2805                New_A := Make_Unchecked_Type_Conversion (Loc,
2806                  Subtype_Mark => New_Occurrence_Of (Etype (F), Loc),
2807                  Expression   => Relocate_Node (Expression (A)));
2808
2809             elsif Etype (F) /= Etype (A) then
2810                New_A := Unchecked_Convert_To (Etype (F), Relocate_Node (A));
2811                Temp_Typ := Etype (F);
2812
2813             else
2814                New_A := Relocate_Node (A);
2815             end if;
2816
2817             Set_Sloc (New_A, Sloc (N));
2818
2819             if Ekind (F) = E_In_Parameter
2820               and then not Is_Limited_Type (Etype (A))
2821             then
2822                Decl :=
2823                  Make_Object_Declaration (Loc,
2824                    Defining_Identifier => Temp,
2825                    Constant_Present => True,
2826                    Object_Definition => New_Occurrence_Of (Temp_Typ, Loc),
2827                    Expression => New_A);
2828             else
2829                Decl :=
2830                  Make_Object_Renaming_Declaration (Loc,
2831                    Defining_Identifier => Temp,
2832                    Subtype_Mark        => New_Occurrence_Of (Temp_Typ, Loc),
2833                    Name                => New_A);
2834             end if;
2835
2836             Prepend (Decl, Declarations (Blk));
2837             Set_Renamed_Object (F, Temp);
2838          end if;
2839
2840          Next_Formal (F);
2841          Next_Actual (A);
2842       end loop;
2843
2844       --  Establish target of function call. If context is not assignment or
2845       --  declaration, create a temporary as a target. The declaration for
2846       --  the temporary may be subsequently optimized away if the body is a
2847       --  single expression, or if the left-hand side of the assignment is
2848       --  simple enough.
2849
2850       if Ekind (Subp) = E_Function then
2851          if Nkind (Parent (N)) = N_Assignment_Statement
2852            and then Is_Entity_Name (Name (Parent (N)))
2853          then
2854             Targ := Name (Parent (N));
2855
2856          else
2857             --  Replace call with temporary and create its declaration
2858
2859             Temp :=
2860               Make_Defining_Identifier (Loc, New_Internal_Name ('C'));
2861
2862             Decl :=
2863               Make_Object_Declaration (Loc,
2864                 Defining_Identifier => Temp,
2865                 Object_Definition =>
2866                   New_Occurrence_Of (Ret_Type, Loc));
2867
2868             Set_No_Initialization (Decl);
2869             Insert_Action (N, Decl);
2870             Rewrite (N, New_Occurrence_Of (Temp, Loc));
2871             Targ := Temp;
2872          end if;
2873       end if;
2874
2875       --  Traverse the tree and replace formals with actuals or their thunks.
2876       --  Attach block to tree before analysis and rewriting.
2877
2878       Replace_Formals (Blk);
2879       Set_Parent (Blk, N);
2880
2881       if not Comes_From_Source (Subp)
2882         or else Is_Predef
2883       then
2884          Reset_Slocs (Blk);
2885       end if;
2886
2887       if Present (Exit_Lab) then
2888
2889          --  If the body was a single expression, the single return statement
2890          --  and the corresponding label are useless.
2891
2892          if Num_Ret = 1
2893            and then
2894              Nkind (Last (Statements (Handled_Statement_Sequence (Blk)))) =
2895                N_Goto_Statement
2896          then
2897             Remove (Last (Statements (Handled_Statement_Sequence (Blk))));
2898          else
2899             Append (Lab_Decl, (Declarations (Blk)));
2900             Append (Exit_Lab, Statements (Handled_Statement_Sequence (Blk)));
2901          end if;
2902       end if;
2903
2904       --  Analyze Blk with In_Inlined_Body set, to avoid spurious errors on
2905       --  conflicting private views that Gigi would ignore. If this is
2906       --  predefined unit, analyze with checks off, as is done in the non-
2907       --  inlined run-time units.
2908
2909       declare
2910          I_Flag : constant Boolean := In_Inlined_Body;
2911
2912       begin
2913          In_Inlined_Body := True;
2914
2915          if Is_Predef then
2916             declare
2917                Style : constant Boolean := Style_Check;
2918             begin
2919                Style_Check := False;
2920                Analyze (Blk, Suppress => All_Checks);
2921                Style_Check := Style;
2922             end;
2923
2924          else
2925             Analyze (Blk);
2926          end if;
2927
2928          In_Inlined_Body := I_Flag;
2929       end;
2930
2931       if Ekind (Subp) = E_Procedure then
2932          Rewrite_Procedure_Call (N, Blk);
2933       else
2934          Rewrite_Function_Call (N, Blk);
2935       end if;
2936
2937       Restore_Env;
2938
2939       --  Cleanup mapping between formals and actuals for other expansions
2940
2941       F := First_Formal (Subp);
2942
2943       while Present (F) loop
2944          Set_Renamed_Object (F, Empty);
2945          Next_Formal (F);
2946       end loop;
2947    end Expand_Inlined_Call;
2948
2949    ----------------------------
2950    -- Expand_N_Function_Call --
2951    ----------------------------
2952
2953    procedure Expand_N_Function_Call (N : Node_Id) is
2954       Typ   : constant Entity_Id := Etype (N);
2955
2956       function Returned_By_Reference return Boolean;
2957       --  If the return type is returned through the secondary stack. that is
2958       --  by reference, we don't want to create a temp to force stack checking.
2959       --  Shouldn't this function be moved to exp_util???
2960
2961       function Rhs_Of_Assign_Or_Decl (N : Node_Id) return Boolean;
2962       --  If the call is the right side of an assignment or the expression in
2963       --  an object declaration, we don't need to create a temp as the left
2964       --  side will already trigger stack checking if necessary.
2965
2966       ---------------------------
2967       -- Returned_By_Reference --
2968       ---------------------------
2969
2970       function Returned_By_Reference return Boolean is
2971          S : Entity_Id := Current_Scope;
2972
2973       begin
2974          if Is_Return_By_Reference_Type (Typ) then
2975             return True;
2976
2977          elsif Nkind (Parent (N)) /= N_Return_Statement then
2978             return False;
2979
2980          elsif Requires_Transient_Scope (Typ) then
2981
2982             --  Verify that the return type of the enclosing function has the
2983             --  same constrained status as that of the expression.
2984
2985             while Ekind (S) /= E_Function loop
2986                S := Scope (S);
2987             end loop;
2988
2989             return Is_Constrained (Typ) = Is_Constrained (Etype (S));
2990          else
2991             return False;
2992          end if;
2993       end Returned_By_Reference;
2994
2995       ---------------------------
2996       -- Rhs_Of_Assign_Or_Decl --
2997       ---------------------------
2998
2999       function Rhs_Of_Assign_Or_Decl (N : Node_Id) return Boolean is
3000       begin
3001          if (Nkind (Parent (N)) = N_Assignment_Statement
3002                and then Expression (Parent (N)) = N)
3003            or else
3004              (Nkind (Parent (N)) = N_Qualified_Expression
3005                 and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
3006                   and then Expression (Parent (Parent (N))) = Parent (N))
3007            or else
3008              (Nkind (Parent (N)) = N_Object_Declaration
3009                 and then Expression (Parent (N)) = N)
3010            or else
3011              (Nkind (Parent (N)) = N_Component_Association
3012                 and then Expression (Parent (N)) = N
3013                   and then Nkind (Parent (Parent (N))) = N_Aggregate
3014                     and then Rhs_Of_Assign_Or_Decl (Parent (Parent (N))))
3015          then
3016             return True;
3017          else
3018             return False;
3019          end if;
3020       end Rhs_Of_Assign_Or_Decl;
3021
3022    --  Start of processing for Expand_N_Function_Call
3023
3024    begin
3025       --  A special check. If stack checking is enabled, and the return type
3026       --  might generate a large temporary, and the call is not the right side
3027       --  of an assignment, then generate an explicit temporary. We do this
3028       --  because otherwise gigi may generate a large temporary on the fly and
3029       --  this can cause trouble with stack checking.
3030
3031       --  This is unecessary if the call is the expression in an object
3032       --  declaration, or if it appears outside of any library unit. This can
3033       --  only happen if it appears as an actual in a library-level instance,
3034       --  in which case a temporary will be generated for it once the instance
3035       --  itself is installed.
3036
3037       if May_Generate_Large_Temp (Typ)
3038         and then not Rhs_Of_Assign_Or_Decl (N)
3039         and then not Returned_By_Reference
3040         and then Current_Scope /= Standard_Standard
3041       then
3042          if Stack_Checking_Enabled then
3043
3044             --  Note: it might be thought that it would be OK to use a call to
3045             --  Force_Evaluation here, but that's not good enough, because
3046             --  that can results in a 'Reference construct that may still need
3047             --  a temporary.
3048
3049             declare
3050                Loc      : constant Source_Ptr := Sloc (N);
3051                Temp_Obj : constant Entity_Id :=
3052                             Make_Defining_Identifier (Loc,
3053                               Chars => New_Internal_Name ('F'));
3054                Temp_Typ : Entity_Id := Typ;
3055                Decl     : Node_Id;
3056                A        : Node_Id;
3057                F        : Entity_Id;
3058                Proc     : Entity_Id;
3059
3060             begin
3061                if Is_Tagged_Type (Typ)
3062                  and then Present (Controlling_Argument (N))
3063                then
3064                   if Nkind (Parent (N)) /= N_Procedure_Call_Statement
3065                     and then Nkind (Parent (N)) /= N_Function_Call
3066                   then
3067                      --  If this is a tag-indeterminate call, the object must
3068                      --  be classwide.
3069
3070                      if Is_Tag_Indeterminate (N) then
3071                         Temp_Typ := Class_Wide_Type (Typ);
3072                      end if;
3073
3074                   else
3075                      --  If this is a dispatching call that is itself the
3076                      --  controlling argument of an enclosing call, the
3077                      --  nominal subtype of the object that replaces it must
3078                      --  be classwide, so that dispatching will take place
3079                      --  properly. If it is not a controlling argument, the
3080                      --  object is not classwide.
3081
3082                      Proc := Entity (Name (Parent (N)));
3083                      F    := First_Formal (Proc);
3084                      A    := First_Actual (Parent (N));
3085
3086                      while A /= N loop
3087                         Next_Formal (F);
3088                         Next_Actual (A);
3089                      end loop;
3090
3091                      if Is_Controlling_Formal (F) then
3092                         Temp_Typ := Class_Wide_Type (Typ);
3093                      end if;
3094                   end if;
3095                end if;
3096
3097                Decl :=
3098                  Make_Object_Declaration (Loc,
3099                    Defining_Identifier => Temp_Obj,
3100                    Object_Definition   => New_Occurrence_Of (Temp_Typ, Loc),
3101                    Constant_Present    => True,
3102                    Expression          => Relocate_Node (N));
3103                Set_Assignment_OK (Decl);
3104
3105                Insert_Actions (N, New_List (Decl));
3106                Rewrite (N, New_Occurrence_Of (Temp_Obj, Loc));
3107             end;
3108
3109          else
3110             --  If stack-checking is not enabled, increment serial number
3111             --  for internal names, so that subsequent symbols are consistent
3112             --  with and without stack-checking.
3113
3114             Synchronize_Serial_Number;
3115
3116             --  Now we can expand the call with consistent symbol names
3117
3118             Expand_Call (N);
3119          end if;
3120
3121       --  Normal case, expand the call
3122
3123       else
3124          Expand_Call (N);
3125       end if;
3126    end Expand_N_Function_Call;
3127
3128    ---------------------------------------
3129    -- Expand_N_Procedure_Call_Statement --
3130    ---------------------------------------
3131
3132    procedure Expand_N_Procedure_Call_Statement (N : Node_Id) is
3133    begin
3134       Expand_Call (N);
3135    end Expand_N_Procedure_Call_Statement;
3136
3137    ------------------------------
3138    -- Expand_N_Subprogram_Body --
3139    ------------------------------
3140
3141    --  Add poll call if ATC polling is enabled, unless the body will be
3142    --  inlined by the back-end.
3143
3144    --  Add return statement if last statement in body is not a return statement
3145    --  (this makes things easier on Gigi which does not want to have to handle
3146    --  a missing return).
3147
3148    --  Add call to Activate_Tasks if body is a task activator
3149
3150    --  Deal with possible detection of infinite recursion
3151
3152    --  Eliminate body completely if convention stubbed
3153
3154    --  Encode entity names within body, since we will not need to reference
3155    --  these entities any longer in the front end.
3156
3157    --  Initialize scalar out parameters if Initialize/Normalize_Scalars
3158
3159    --  Reset Pure indication if any parameter has root type System.Address
3160
3161    --  Wrap thread body
3162
3163    procedure Expand_N_Subprogram_Body (N : Node_Id) is
3164       Loc      : constant Source_Ptr := Sloc (N);
3165       H        : constant Node_Id    := Handled_Statement_Sequence (N);
3166       Body_Id  : Entity_Id;
3167       Spec_Id  : Entity_Id;
3168       Except_H : Node_Id;
3169       Scop     : Entity_Id;
3170       Dec      : Node_Id;
3171       Next_Op  : Node_Id;
3172       L        : List_Id;
3173
3174       procedure Add_Return (S : List_Id);
3175       --  Append a return statement to the statement sequence S if the last
3176       --  statement is not already a return or a goto statement. Note that
3177       --  the latter test is not critical, it does not matter if we add a
3178       --  few extra returns, since they get eliminated anyway later on.
3179
3180       procedure Expand_Thread_Body;
3181       --  Perform required expansion of a thread body
3182
3183       ----------------
3184       -- Add_Return --
3185       ----------------
3186
3187       procedure Add_Return (S : List_Id) is
3188       begin
3189          if not Is_Transfer (Last (S)) then
3190
3191             --  The source location for the return is the end label
3192             --  of the procedure in all cases. This is a bit odd when
3193             --  there are exception handlers, but not much else we can do.
3194
3195             Append_To (S, Make_Return_Statement (Sloc (End_Label (H))));
3196          end if;
3197       end Add_Return;
3198
3199       ------------------------
3200       -- Expand_Thread_Body --
3201       ------------------------
3202
3203       --  The required expansion of a thread body is as follows
3204
3205       --  procedure <thread body procedure name> is
3206
3207       --    _Secondary_Stack : aliased
3208       --       Storage_Elements.Storage_Array
3209       --         (1 .. Storage_Offset (Sec_Stack_Size));
3210       --    for _Secondary_Stack'Alignment use Standard'Maximum_Alignment;
3211
3212       --    _Process_ATSD : aliased System.Threads.ATSD;
3213
3214       --  begin
3215       --     System.Threads.Thread_Body_Enter;
3216       --       (_Secondary_Stack'Address,
3217       --        _Secondary_Stack'Length,
3218       --        _Process_ATSD'Address);
3219
3220       --     declare
3221       --        <user declarations>
3222       --     begin
3223       --        <user statements>
3224       --     <user exception handlers>
3225       --     end;
3226
3227       --    System.Threads.Thread_Body_Leave;
3228
3229       --  exception
3230       --     when E : others =>
3231       --       System.Threads.Thread_Body_Exceptional_Exit (E);
3232       --  end;
3233
3234       --  Note the exception handler is omitted if pragma Restriction
3235       --  No_Exception_Handlers is currently active.
3236
3237       procedure Expand_Thread_Body is
3238          User_Decls    : constant List_Id := Declarations (N);
3239          Sec_Stack_Len : Node_Id;
3240
3241          TB_Pragma  : constant Node_Id :=
3242                         Get_Rep_Pragma (Spec_Id, Name_Thread_Body);
3243
3244          Ent_SS   : Entity_Id;
3245          Ent_ATSD : Entity_Id;
3246          Ent_EO   : Entity_Id;
3247
3248          Decl_SS   : Node_Id;
3249          Decl_ATSD : Node_Id;
3250
3251          Excep_Handlers : List_Id;
3252
3253       begin
3254          New_Scope (Spec_Id);
3255
3256          --  Get proper setting for secondary stack size
3257
3258          if List_Length (Pragma_Argument_Associations (TB_Pragma)) = 2 then
3259             Sec_Stack_Len :=
3260               Expression (Last (Pragma_Argument_Associations (TB_Pragma)));
3261          else
3262             Sec_Stack_Len :=
3263               New_Occurrence_Of (RTE (RE_Default_Secondary_Stack_Size), Loc);
3264          end if;
3265
3266          Sec_Stack_Len := Convert_To (RTE (RE_Storage_Offset), Sec_Stack_Len);
3267
3268          --  Build and set declarations for the wrapped thread body
3269
3270          Ent_SS   := Make_Defining_Identifier (Loc, Name_uSecondary_Stack);
3271          Ent_ATSD := Make_Defining_Identifier (Loc, Name_uProcess_ATSD);
3272
3273          Decl_SS :=
3274            Make_Object_Declaration (Loc,
3275              Defining_Identifier => Ent_SS,
3276              Aliased_Present     => True,
3277              Object_Definition   =>
3278                Make_Subtype_Indication (Loc,
3279                  Subtype_Mark =>
3280                    New_Occurrence_Of (RTE (RE_Storage_Array), Loc),
3281                  Constraint   =>
3282                    Make_Index_Or_Discriminant_Constraint (Loc,
3283                      Constraints => New_List (
3284                        Make_Range (Loc,
3285                          Low_Bound  => Make_Integer_Literal (Loc, 1),
3286                          High_Bound => Sec_Stack_Len)))));
3287
3288          Decl_ATSD :=
3289            Make_Object_Declaration (Loc,
3290              Defining_Identifier => Ent_ATSD,
3291              Aliased_Present     => True,
3292              Object_Definition   => New_Occurrence_Of (RTE (RE_ATSD), Loc));
3293
3294          Set_Declarations (N, New_List (Decl_SS, Decl_ATSD));
3295          Analyze (Decl_SS);
3296          Analyze (Decl_ATSD);
3297          Set_Alignment (Ent_SS, UI_From_Int (Maximum_Alignment));
3298
3299          --  Create new exception handler
3300
3301          if Restriction_Active (No_Exception_Handlers) then
3302             Excep_Handlers := No_List;
3303
3304          else
3305             Check_Restriction (No_Exception_Handlers, N);
3306
3307             Ent_EO := Make_Defining_Identifier (Loc, Name_uE);
3308
3309             Excep_Handlers := New_List (
3310               Make_Exception_Handler (Loc,
3311                 Choice_Parameter => Ent_EO,
3312                 Exception_Choices => New_List (
3313                   Make_Others_Choice (Loc)),
3314                 Statements => New_List (
3315                   Make_Procedure_Call_Statement (Loc,
3316                     Name =>
3317                       New_Occurrence_Of
3318                         (RTE (RE_Thread_Body_Exceptional_Exit), Loc),
3319                     Parameter_Associations => New_List (
3320                       New_Occurrence_Of (Ent_EO, Loc))))));
3321          end if;
3322
3323          --  Now build new handled statement sequence and analyze it
3324
3325          Set_Handled_Statement_Sequence (N,
3326            Make_Handled_Sequence_Of_Statements (Loc,
3327              Statements => New_List (
3328
3329                Make_Procedure_Call_Statement (Loc,
3330                  Name => New_Occurrence_Of (RTE (RE_Thread_Body_Enter), Loc),
3331                  Parameter_Associations => New_List (
3332
3333                    Make_Attribute_Reference (Loc,
3334                      Prefix => New_Occurrence_Of (Ent_SS, Loc),
3335                      Attribute_Name => Name_Address),
3336
3337                    Make_Attribute_Reference (Loc,
3338                      Prefix => New_Occurrence_Of (Ent_SS, Loc),
3339                      Attribute_Name => Name_Length),
3340
3341                    Make_Attribute_Reference (Loc,
3342                      Prefix => New_Occurrence_Of (Ent_ATSD, Loc),
3343                      Attribute_Name => Name_Address))),
3344
3345                Make_Block_Statement (Loc,
3346                  Declarations => User_Decls,
3347                  Handled_Statement_Sequence => H),
3348
3349                Make_Procedure_Call_Statement (Loc,
3350                  Name => New_Occurrence_Of (RTE (RE_Thread_Body_Leave), Loc))),
3351
3352              Exception_Handlers => Excep_Handlers));
3353
3354          Analyze (Handled_Statement_Sequence (N));
3355          End_Scope;
3356       end Expand_Thread_Body;
3357
3358    --  Start of processing for Expand_N_Subprogram_Body
3359
3360    begin
3361       --  Set L to either the list of declarations if present, or
3362       --  to the list of statements if no declarations are present.
3363       --  This is used to insert new stuff at the start.
3364
3365       if Is_Non_Empty_List (Declarations (N)) then
3366          L := Declarations (N);
3367       else
3368          L := Statements (Handled_Statement_Sequence (N));
3369       end if;
3370
3371       --  Find entity for subprogram
3372
3373       Body_Id := Defining_Entity (N);
3374
3375       if Present (Corresponding_Spec (N)) then
3376          Spec_Id := Corresponding_Spec (N);
3377       else
3378          Spec_Id := Body_Id;
3379       end if;
3380
3381       --  Need poll on entry to subprogram if polling enabled. We only
3382       --  do this for non-empty subprograms, since it does not seem
3383       --  necessary to poll for a dummy null subprogram. Do not add polling
3384       --  point if calls to this subprogram will be inlined by the back-end,
3385       --  to avoid repeated polling points in nested inlinings.
3386
3387       if Is_Non_Empty_List (L) then
3388          if Is_Inlined (Spec_Id)
3389            and then Front_End_Inlining
3390            and then Optimization_Level > 1
3391          then
3392             null;
3393          else
3394             Generate_Poll_Call (First (L));
3395          end if;
3396       end if;
3397
3398       --  If this is a Pure function which has any parameters whose root
3399       --  type is System.Address, reset the Pure indication, since it will
3400       --  likely cause incorrect code to be generated as the parameter is
3401       --  probably a pointer, and the fact that the same pointer is passed
3402       --  does not mean that the same value is being referenced.
3403
3404       --  Note that if the programmer gave an explicit Pure_Function pragma,
3405       --  then we believe the programmer, and leave the subprogram Pure.
3406
3407       --  This code should probably be at the freeze point, so that it
3408       --  happens even on a -gnatc (or more importantly -gnatt) compile
3409       --  so that the semantic tree has Is_Pure set properly ???
3410
3411       if Is_Pure (Spec_Id)
3412         and then Is_Subprogram (Spec_Id)
3413         and then not Has_Pragma_Pure_Function (Spec_Id)
3414       then
3415          declare
3416             F : Entity_Id := First_Formal (Spec_Id);
3417
3418          begin
3419             while Present (F) loop
3420                if Is_Descendent_Of_Address (Etype (F)) then
3421                   Set_Is_Pure (Spec_Id, False);
3422
3423                   if Spec_Id /= Body_Id then
3424                      Set_Is_Pure (Body_Id, False);
3425                   end if;
3426
3427                   exit;
3428                end if;
3429
3430                Next_Formal (F);
3431             end loop;
3432          end;
3433       end if;
3434
3435       --  Initialize any scalar OUT args if Initialize/Normalize_Scalars
3436
3437       if Init_Or_Norm_Scalars and then Is_Subprogram (Spec_Id) then
3438          declare
3439             F : Entity_Id        := First_Formal (Spec_Id);
3440             V : constant Boolean := Validity_Checks_On;
3441
3442          begin
3443             --  We turn off validity checking, since we do not want any
3444             --  check on the initializing value itself (which we know
3445             --  may well be invalid!)
3446
3447             Validity_Checks_On := False;
3448
3449             --  Loop through formals
3450
3451             while Present (F) loop
3452                if Is_Scalar_Type (Etype (F))
3453                  and then Ekind (F) = E_Out_Parameter
3454                then
3455                   Insert_Before_And_Analyze (First (L),
3456                     Make_Assignment_Statement (Loc,
3457                       Name => New_Occurrence_Of (F, Loc),
3458                       Expression => Get_Simple_Init_Val (Etype (F), Loc)));
3459                end if;
3460
3461                Next_Formal (F);
3462             end loop;
3463
3464             Validity_Checks_On := V;
3465          end;
3466       end if;
3467
3468       Scop := Scope (Spec_Id);
3469
3470       --  Add discriminal renamings to protected subprograms.
3471       --  Install new discriminals for expansion of the next
3472       --  subprogram of this protected type, if any.
3473
3474       if Is_List_Member (N)
3475         and then Present (Parent (List_Containing (N)))
3476         and then Nkind (Parent (List_Containing (N))) = N_Protected_Body
3477       then
3478          Add_Discriminal_Declarations
3479            (Declarations (N), Scop, Name_uObject, Loc);
3480          Add_Private_Declarations (Declarations (N), Scop, Name_uObject, Loc);
3481
3482          --  Associate privals and discriminals with the next protected
3483          --  operation body to be expanded. These are used to expand
3484          --  references to private data objects and discriminants,
3485          --  respectively.
3486
3487          Next_Op := Next_Protected_Operation (N);
3488
3489          if Present (Next_Op) then
3490             Dec := Parent (Base_Type (Scop));
3491             Set_Privals (Dec, Next_Op, Loc);
3492             Set_Discriminals (Dec);
3493          end if;
3494       end if;
3495
3496       --  Clear out statement list for stubbed procedure
3497
3498       if Present (Corresponding_Spec (N)) then
3499          Set_Elaboration_Flag (N, Spec_Id);
3500
3501          if Convention (Spec_Id) = Convention_Stubbed
3502            or else Is_Eliminated (Spec_Id)
3503          then
3504             Set_Declarations (N, Empty_List);
3505             Set_Handled_Statement_Sequence (N,
3506               Make_Handled_Sequence_Of_Statements (Loc,
3507                 Statements => New_List (
3508                   Make_Null_Statement (Loc))));
3509             return;
3510          end if;
3511       end if;
3512
3513       --  Returns_By_Ref flag is normally set when the subprogram is frozen
3514       --  but subprograms with no specs are not frozen
3515
3516       declare
3517          Typ  : constant Entity_Id := Etype (Spec_Id);
3518          Utyp : constant Entity_Id := Underlying_Type (Typ);
3519
3520       begin
3521          if not Acts_As_Spec (N)
3522            and then Nkind (Parent (Parent (Spec_Id))) /=
3523              N_Subprogram_Body_Stub
3524          then
3525             null;
3526
3527          elsif Is_Return_By_Reference_Type (Typ) then
3528             Set_Returns_By_Ref (Spec_Id);
3529
3530          elsif Present (Utyp) and then Controlled_Type (Utyp) then
3531             Set_Returns_By_Ref (Spec_Id);
3532          end if;
3533       end;
3534
3535       --  For a procedure, we add a return for all possible syntactic ends
3536       --  of the subprogram. Note that reanalysis is not necessary in this
3537       --  case since it would require a lot of work and accomplish nothing.
3538
3539       if Ekind (Spec_Id) = E_Procedure
3540         or else Ekind (Spec_Id) = E_Generic_Procedure
3541       then
3542          Add_Return (Statements (H));
3543
3544          if Present (Exception_Handlers (H)) then
3545             Except_H := First_Non_Pragma (Exception_Handlers (H));
3546
3547             while Present (Except_H) loop
3548                Add_Return (Statements (Except_H));
3549                Next_Non_Pragma (Except_H);
3550             end loop;
3551          end if;
3552
3553       --  For a function, we must deal with the case where there is at least
3554       --  one missing return. What we do is to wrap the entire body of the
3555       --  function in a block:
3556
3557       --    begin
3558       --      ...
3559       --    end;
3560
3561       --  becomes
3562
3563       --    begin
3564       --       begin
3565       --          ...
3566       --       end;
3567
3568       --       raise Program_Error;
3569       --    end;
3570
3571       --  This approach is necessary because the raise must be signalled
3572       --  to the caller, not handled by any local handler (RM 6.4(11)).
3573
3574       --  Note: we do not need to analyze the constructed sequence here,
3575       --  since it has no handler, and an attempt to analyze the handled
3576       --  statement sequence twice is risky in various ways (e.g. the
3577       --  issue of expanding cleanup actions twice).
3578
3579       elsif Has_Missing_Return (Spec_Id) then
3580          declare
3581             Hloc : constant Source_Ptr := Sloc (H);
3582             Blok : constant Node_Id    :=
3583                      Make_Block_Statement (Hloc,
3584                        Handled_Statement_Sequence => H);
3585             Rais : constant Node_Id    :=
3586                      Make_Raise_Program_Error (Hloc,
3587                        Reason => PE_Missing_Return);
3588
3589          begin
3590             Set_Handled_Statement_Sequence (N,
3591               Make_Handled_Sequence_Of_Statements (Hloc,
3592                 Statements => New_List (Blok, Rais)));
3593
3594             New_Scope (Spec_Id);
3595             Analyze (Blok);
3596             Analyze (Rais);
3597             Pop_Scope;
3598          end;
3599       end if;
3600
3601       --  If subprogram contains a parameterless recursive call, then we may
3602       --  have an infinite recursion, so see if we can generate code to check
3603       --  for this possibility if storage checks are not suppressed.
3604
3605       if Ekind (Spec_Id) = E_Procedure
3606         and then Has_Recursive_Call (Spec_Id)
3607         and then not Storage_Checks_Suppressed (Spec_Id)
3608       then
3609          Detect_Infinite_Recursion (N, Spec_Id);
3610       end if;
3611
3612       --  Finally, if we are in Normalize_Scalars mode, then any scalar out
3613       --  parameters must be initialized to the appropriate default value.
3614
3615       if Ekind (Spec_Id) = E_Procedure and then Normalize_Scalars then
3616          declare
3617             Floc   : Source_Ptr;
3618             Formal : Entity_Id;
3619             Stm    : Node_Id;
3620
3621          begin
3622             Formal := First_Formal (Spec_Id);
3623
3624             while Present (Formal) loop
3625                Floc := Sloc (Formal);
3626
3627                if Ekind (Formal) = E_Out_Parameter
3628                  and then Is_Scalar_Type (Etype (Formal))
3629                then
3630                   Stm :=
3631                     Make_Assignment_Statement (Floc,
3632                       Name => New_Occurrence_Of (Formal, Floc),
3633                       Expression =>
3634                         Get_Simple_Init_Val (Etype (Formal), Floc));
3635                   Prepend (Stm, Declarations (N));
3636                   Analyze (Stm);
3637                end if;
3638
3639                Next_Formal (Formal);
3640             end loop;
3641          end;
3642       end if;
3643
3644       --  Deal with thread body
3645
3646       if Is_Thread_Body (Spec_Id) then
3647          Expand_Thread_Body;
3648       end if;
3649
3650       --  If the subprogram does not have pending instantiations, then we
3651       --  must generate the subprogram descriptor now, since the code for
3652       --  the subprogram is complete, and this is our last chance. However
3653       --  if there are pending instantiations, then the code is not
3654       --  complete, and we will delay the generation.
3655
3656       if Is_Subprogram (Spec_Id)
3657         and then not Delay_Subprogram_Descriptors (Spec_Id)
3658       then
3659          Generate_Subprogram_Descriptor_For_Subprogram (N, Spec_Id);
3660       end if;
3661
3662       --  Set to encode entity names in package body before gigi is called
3663
3664       Qualify_Entity_Names (N);
3665    end Expand_N_Subprogram_Body;
3666
3667    -----------------------------------
3668    -- Expand_N_Subprogram_Body_Stub --
3669    -----------------------------------
3670
3671    procedure Expand_N_Subprogram_Body_Stub (N : Node_Id) is
3672    begin
3673       if Present (Corresponding_Body (N)) then
3674          Expand_N_Subprogram_Body (
3675            Unit_Declaration_Node (Corresponding_Body (N)));
3676       end if;
3677    end Expand_N_Subprogram_Body_Stub;
3678
3679    -------------------------------------
3680    -- Expand_N_Subprogram_Declaration --
3681    -------------------------------------
3682
3683    --  If the declaration appears within a protected body, it is a private
3684    --  operation of the protected type. We must create the corresponding
3685    --  protected subprogram an associated formals. For a normal protected
3686    --  operation, this is done when expanding the protected type declaration.
3687
3688    procedure Expand_N_Subprogram_Declaration (N : Node_Id) is
3689       Loc       : constant Source_Ptr := Sloc (N);
3690       Subp      : constant Entity_Id  := Defining_Entity (N);
3691       Scop      : constant Entity_Id  := Scope (Subp);
3692       Prot_Decl : Node_Id;
3693       Prot_Bod  : Node_Id;
3694       Prot_Id   : Entity_Id;
3695
3696    begin
3697       --  Deal with case of protected subprogram. Do not generate
3698       --  protected operation if operation is flagged as eliminated.
3699
3700       if Is_List_Member (N)
3701         and then Present (Parent (List_Containing (N)))
3702         and then Nkind (Parent (List_Containing (N))) = N_Protected_Body
3703         and then Is_Protected_Type (Scop)
3704       then
3705          if No (Protected_Body_Subprogram (Subp))
3706            and then not Is_Eliminated (Subp)
3707          then
3708             Prot_Decl :=
3709               Make_Subprogram_Declaration (Loc,
3710                 Specification =>
3711                   Build_Protected_Sub_Specification
3712                     (N, Scop, Unprotected => True));
3713
3714             --  The protected subprogram is declared outside of the protected
3715             --  body. Given that the body has frozen all entities so far, we
3716             --  analyze the subprogram and perform freezing actions explicitly.
3717             --  If the body is a subunit, the insertion point is before the
3718             --  stub in the parent.
3719
3720             Prot_Bod := Parent (List_Containing (N));
3721
3722             if Nkind (Parent (Prot_Bod)) = N_Subunit then
3723                Prot_Bod := Corresponding_Stub (Parent (Prot_Bod));
3724             end if;
3725
3726             Insert_Before (Prot_Bod, Prot_Decl);
3727             Prot_Id := Defining_Unit_Name (Specification (Prot_Decl));
3728
3729             New_Scope (Scope (Scop));
3730             Analyze (Prot_Decl);
3731             Create_Extra_Formals (Prot_Id);
3732             Set_Protected_Body_Subprogram (Subp, Prot_Id);
3733             Pop_Scope;
3734          end if;
3735       end if;
3736    end Expand_N_Subprogram_Declaration;
3737
3738    ---------------------------------------
3739    -- Expand_Protected_Object_Reference --
3740    ---------------------------------------
3741
3742    function Expand_Protected_Object_Reference
3743      (N    : Node_Id;
3744       Scop : Entity_Id)
3745      return Node_Id
3746    is
3747       Loc   : constant Source_Ptr := Sloc (N);
3748       Corr  : Entity_Id;
3749       Rec   : Node_Id;
3750       Param : Entity_Id;
3751       Proc  : Entity_Id;
3752
3753    begin
3754       Rec := Make_Identifier (Loc, Name_uObject);
3755       Set_Etype (Rec, Corresponding_Record_Type (Scop));
3756
3757       --  Find enclosing protected operation, and retrieve its first
3758       --  parameter, which denotes the enclosing protected object.
3759       --  If the enclosing operation is an entry, we are immediately
3760       --  within the protected body, and we can retrieve the object
3761       --  from the service entries procedure. A barrier function has
3762       --  has the same signature as an entry. A barrier function is
3763       --  compiled within the protected object, but unlike protected
3764       --  operations its never needs locks, so that its protected body
3765       --  subprogram points to itself.
3766
3767       Proc := Current_Scope;
3768
3769       while Present (Proc)
3770         and then Scope (Proc) /= Scop
3771       loop
3772          Proc := Scope (Proc);
3773       end loop;
3774
3775       Corr := Protected_Body_Subprogram (Proc);
3776
3777       if No (Corr) then
3778
3779          --  Previous error left expansion incomplete.
3780          --  Nothing to do on this call.
3781
3782          return Empty;
3783       end if;
3784
3785       Param :=
3786         Defining_Identifier
3787           (First (Parameter_Specifications (Parent (Corr))));
3788
3789       if Is_Subprogram (Proc)
3790         and then Proc /= Corr
3791       then
3792          --  Protected function or procedure
3793
3794          Set_Entity (Rec, Param);
3795
3796          --  Rec is a reference to an entity which will not be in scope
3797          --  when the call is reanalyzed, and needs no further analysis.
3798
3799          Set_Analyzed (Rec);
3800
3801       else
3802          --  Entry or barrier function for entry body.
3803          --  The first parameter of the entry body procedure is a
3804          --  pointer to the object. We create a local variable
3805          --  of the proper type, duplicating what is done to define
3806          --  _object later on.
3807
3808          declare
3809             Decls : List_Id;
3810             Obj_Ptr : constant Entity_Id :=  Make_Defining_Identifier (Loc,
3811                                                Chars =>
3812                                                  New_Internal_Name ('T'));
3813
3814          begin
3815             Decls := New_List (
3816               Make_Full_Type_Declaration (Loc,
3817                 Defining_Identifier => Obj_Ptr,
3818                   Type_Definition =>
3819                      Make_Access_To_Object_Definition (Loc,
3820                        Subtype_Indication =>
3821                          New_Reference_To
3822                       (Corresponding_Record_Type (Scop), Loc))));
3823
3824             Insert_Actions (N, Decls);
3825             Insert_Actions (N, Freeze_Entity (Obj_Ptr, Sloc (N)));
3826
3827             Rec :=
3828               Make_Explicit_Dereference (Loc,
3829                 Unchecked_Convert_To (Obj_Ptr,
3830                   New_Occurrence_Of (Param, Loc)));
3831
3832             --  Analyze new actual. Other actuals in calls are already
3833             --  analyzed and the list of actuals is not renalyzed after
3834             --  rewriting.
3835
3836             Set_Parent (Rec, N);
3837             Analyze (Rec);
3838          end;
3839       end if;
3840
3841       return Rec;
3842    end Expand_Protected_Object_Reference;
3843
3844    --------------------------------------
3845    -- Expand_Protected_Subprogram_Call --
3846    --------------------------------------
3847
3848    procedure Expand_Protected_Subprogram_Call
3849      (N    : Node_Id;
3850       Subp : Entity_Id;
3851       Scop : Entity_Id)
3852    is
3853       Rec   : Node_Id;
3854
3855    begin
3856       --  If the protected object is not an enclosing scope, this is
3857       --  an inter-object function call. Inter-object procedure
3858       --  calls are expanded by Exp_Ch9.Build_Simple_Entry_Call.
3859       --  The call is intra-object only if the subprogram being
3860       --  called is in the protected body being compiled, and if the
3861       --  protected object in the call is statically the enclosing type.
3862       --  The object may be an component of some other data structure,
3863       --  in which case this must be handled as an inter-object call.
3864
3865       if not In_Open_Scopes (Scop)
3866         or else not Is_Entity_Name (Name (N))
3867       then
3868          if Nkind (Name (N)) = N_Selected_Component then
3869             Rec := Prefix (Name (N));
3870
3871          else
3872             pragma Assert (Nkind (Name (N)) = N_Indexed_Component);
3873             Rec := Prefix (Prefix (Name (N)));
3874          end if;
3875
3876          Build_Protected_Subprogram_Call (N,
3877            Name => New_Occurrence_Of (Subp, Sloc (N)),
3878            Rec =>  Convert_Concurrent (Rec, Etype (Rec)),
3879            External => True);
3880
3881       else
3882          Rec := Expand_Protected_Object_Reference (N, Scop);
3883
3884          if No (Rec) then
3885             return;
3886          end if;
3887
3888          Build_Protected_Subprogram_Call (N,
3889            Name     => Name (N),
3890            Rec      => Rec,
3891            External => False);
3892
3893       end if;
3894
3895       Analyze (N);
3896
3897       --  If it is a function call it can appear in elaboration code and
3898       --  the called entity must be frozen here.
3899
3900       if Ekind (Subp) = E_Function then
3901          Freeze_Expression (Name (N));
3902       end if;
3903    end Expand_Protected_Subprogram_Call;
3904
3905    -----------------------
3906    -- Freeze_Subprogram --
3907    -----------------------
3908
3909    procedure Freeze_Subprogram (N : Node_Id) is
3910       E : constant Entity_Id := Entity (N);
3911
3912    begin
3913       --  When a primitive is frozen, enter its name in the corresponding
3914       --  dispatch table. If the DTC_Entity field is not set this is an
3915       --  overridden primitive that can be ignored. We suppress the
3916       --  initialization of the dispatch table entry when Java_VM because
3917       --  the dispatching mechanism is handled internally by the JVM.
3918
3919       if Is_Dispatching_Operation (E)
3920         and then not Is_Abstract (E)
3921         and then Present (DTC_Entity (E))
3922         and then not Is_CPP_Class (Scope (DTC_Entity (E)))
3923         and then not Java_VM
3924       then
3925          Check_Overriding_Operation (E);
3926          Insert_After (N, Fill_DT_Entry (Sloc (N), E));
3927       end if;
3928
3929       --  Mark functions that return by reference. Note that it cannot be
3930       --  part of the normal semantic analysis of the spec since the
3931       --  underlying returned type may not be known yet (for private types)
3932
3933       declare
3934          Typ  : constant Entity_Id := Etype (E);
3935          Utyp : constant Entity_Id := Underlying_Type (Typ);
3936
3937       begin
3938          if Is_Return_By_Reference_Type (Typ) then
3939             Set_Returns_By_Ref (E);
3940
3941          elsif Present (Utyp) and then Controlled_Type (Utyp) then
3942             Set_Returns_By_Ref (E);
3943          end if;
3944       end;
3945    end Freeze_Subprogram;
3946
3947 end Exp_Ch6;