OSDN Git Service

2009-04-16 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-2008, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Checks;   use Checks;
28 with Debug;    use Debug;
29 with Einfo;    use Einfo;
30 with Errout;   use Errout;
31 with Elists;   use Elists;
32 with Exp_Atag; use Exp_Atag;
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_Dbug; use Exp_Dbug;
38 with Exp_Disp; use Exp_Disp;
39 with Exp_Dist; use Exp_Dist;
40 with Exp_Intr; use Exp_Intr;
41 with Exp_Pakd; use Exp_Pakd;
42 with Exp_Tss;  use Exp_Tss;
43 with Exp_Util; use Exp_Util;
44 with Exp_VFpt; use Exp_VFpt;
45 with Fname;    use Fname;
46 with Freeze;   use Freeze;
47 with Inline;   use Inline;
48 with Lib;      use Lib;
49 with Namet;    use Namet;
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_Aux;  use Sem_Aux;
58 with Sem_Ch6;  use Sem_Ch6;
59 with Sem_Ch8;  use Sem_Ch8;
60 with Sem_Ch12; use Sem_Ch12;
61 with Sem_Ch13; use Sem_Ch13;
62 with Sem_Eval; use Sem_Eval;
63 with Sem_Disp; use Sem_Disp;
64 with Sem_Dist; use Sem_Dist;
65 with Sem_Mech; use Sem_Mech;
66 with Sem_Res;  use Sem_Res;
67 with Sem_Util; use Sem_Util;
68 with Sinfo;    use Sinfo;
69 with Snames;   use Snames;
70 with Stand;    use Stand;
71 with Targparm; use Targparm;
72 with Tbuild;   use Tbuild;
73 with Uintp;    use Uintp;
74 with Validsw;  use Validsw;
75
76 package body Exp_Ch6 is
77
78    -----------------------
79    -- Local Subprograms --
80    -----------------------
81
82    procedure Add_Access_Actual_To_Build_In_Place_Call
83      (Function_Call : Node_Id;
84       Function_Id   : Entity_Id;
85       Return_Object : Node_Id;
86       Is_Access     : Boolean := False);
87    --  Ada 2005 (AI-318-02): Apply the Unrestricted_Access attribute to the
88    --  object name given by Return_Object and add the attribute to the end of
89    --  the actual parameter list associated with the build-in-place function
90    --  call denoted by Function_Call. However, if Is_Access is True, then
91    --  Return_Object is already an access expression, in which case it's passed
92    --  along directly to the build-in-place function. Finally, if Return_Object
93    --  is empty, then pass a null literal as the actual.
94
95    procedure Add_Alloc_Form_Actual_To_Build_In_Place_Call
96      (Function_Call  : Node_Id;
97       Function_Id    : Entity_Id;
98       Alloc_Form     : BIP_Allocation_Form := Unspecified;
99       Alloc_Form_Exp : Node_Id             := Empty);
100    --  Ada 2005 (AI-318-02): Add an actual indicating the form of allocation,
101    --  if any, to be done by a build-in-place function. If Alloc_Form_Exp is
102    --  present, then use it, otherwise pass a literal corresponding to the
103    --  Alloc_Form parameter (which must not be Unspecified in that case).
104
105    procedure Add_Extra_Actual_To_Call
106      (Subprogram_Call : Node_Id;
107       Extra_Formal    : Entity_Id;
108       Extra_Actual    : Node_Id);
109    --  Adds Extra_Actual as a named parameter association for the formal
110    --  Extra_Formal in Subprogram_Call.
111
112    procedure Add_Final_List_Actual_To_Build_In_Place_Call
113      (Function_Call : Node_Id;
114       Function_Id   : Entity_Id;
115       Acc_Type      : Entity_Id;
116       Sel_Comp      : Node_Id := Empty);
117    --  Ada 2005 (AI-318-02): For a build-in-place call, if the result type has
118    --  controlled parts, add an actual parameter that is a pointer to
119    --  appropriate finalization list. The finalization list is that of the
120    --  current scope, except for "new Acc'(F(...))" in which case it's the
121    --  finalization list of the access type returned by the allocator. Acc_Type
122    --  is that type in the allocator case; Empty otherwise. If Sel_Comp is
123    --  not Empty, then it denotes a selected component and the finalization
124    --  list is obtained from the _controller list of the prefix object.
125
126    procedure Add_Task_Actuals_To_Build_In_Place_Call
127      (Function_Call : Node_Id;
128       Function_Id   : Entity_Id;
129       Master_Actual : Node_Id);
130    --  Ada 2005 (AI-318-02): For a build-in-place call, if the result type
131    --  contains tasks, add two actual parameters: the master, and a pointer to
132    --  the caller's activation chain. Master_Actual is the actual parameter
133    --  expression to pass for the master. In most cases, this is the current
134    --  master (_master). The two exceptions are: If the function call is the
135    --  initialization expression for an allocator, we pass the master of the
136    --  access type. If the function call is the initialization expression for
137    --  a return object, we pass along the master passed in by the caller. The
138    --  activation chain to pass is always the local one.
139
140    procedure Check_Overriding_Operation (Subp : Entity_Id);
141    --  Subp is a dispatching operation. Check whether it may override an
142    --  inherited private operation, in which case its DT entry is that of
143    --  the hidden operation, not the one it may have received earlier.
144    --  This must be done before emitting the code to set the corresponding
145    --  DT to the address of the subprogram. The actual placement of Subp in
146    --  the proper place in the list of primitive operations is done in
147    --  Declare_Inherited_Private_Subprograms, which also has to deal with
148    --  implicit operations. This duplication is unavoidable for now???
149
150    procedure Detect_Infinite_Recursion (N : Node_Id; Spec : Entity_Id);
151    --  This procedure is called only if the subprogram body N, whose spec
152    --  has the given entity Spec, contains a parameterless recursive call.
153    --  It attempts to generate runtime code to detect if this a case of
154    --  infinite recursion.
155    --
156    --  The body is scanned to determine dependencies. If the only external
157    --  dependencies are on a small set of scalar variables, then the values
158    --  of these variables are captured on entry to the subprogram, and if
159    --  the values are not changed for the call, we know immediately that
160    --  we have an infinite recursion.
161
162    procedure Expand_Actuals (N : Node_Id; Subp : Entity_Id);
163    --  For each actual of an in-out or out parameter which is a numeric
164    --  (view) conversion of the form T (A), where A denotes a variable,
165    --  we insert the declaration:
166    --
167    --    Temp : T[ := T (A)];
168    --
169    --  prior to the call. Then we replace the actual with a reference to Temp,
170    --  and append the assignment:
171    --
172    --    A := TypeA (Temp);
173    --
174    --  after the call. Here TypeA is the actual type of variable A.
175    --  For out parameters, the initial declaration has no expression.
176    --  If A is not an entity name, we generate instead:
177    --
178    --    Var  : TypeA renames A;
179    --    Temp : T := Var;       --  omitting expression for out parameter.
180    --    ...
181    --    Var := TypeA (Temp);
182    --
183    --  For other in-out parameters, we emit the required constraint checks
184    --  before and/or after the call.
185    --
186    --  For all parameter modes, actuals that denote components and slices
187    --  of packed arrays are expanded into suitable temporaries.
188    --
189    --  For non-scalar objects that are possibly unaligned, add call by copy
190    --  code (copy in for IN and IN OUT, copy out for OUT and IN OUT).
191
192    procedure Expand_Inlined_Call
193     (N         : Node_Id;
194      Subp      : Entity_Id;
195      Orig_Subp : Entity_Id);
196    --  If called subprogram can be inlined by the front-end, retrieve the
197    --  analyzed body, replace formals with actuals and expand call in place.
198    --  Generate thunks for actuals that are expressions, and insert the
199    --  corresponding constant declarations before the call. If the original
200    --  call is to a derived operation, the return type is the one of the
201    --  derived operation, but the body is that of the original, so return
202    --  expressions in the body must be converted to the desired type (which
203    --  is simply not noted in the tree without inline expansion).
204
205    function Expand_Protected_Object_Reference
206      (N    : Node_Id;
207       Scop : Entity_Id) return Node_Id;
208
209    procedure Expand_Protected_Subprogram_Call
210      (N    : Node_Id;
211       Subp : Entity_Id;
212       Scop : Entity_Id);
213    --  A call to a protected subprogram within the protected object may appear
214    --  as a regular call. The list of actuals must be expanded to contain a
215    --  reference to the object itself, and the call becomes a call to the
216    --  corresponding protected subprogram.
217
218    ----------------------------------------------
219    -- Add_Access_Actual_To_Build_In_Place_Call --
220    ----------------------------------------------
221
222    procedure Add_Access_Actual_To_Build_In_Place_Call
223      (Function_Call : Node_Id;
224       Function_Id   : Entity_Id;
225       Return_Object : Node_Id;
226       Is_Access     : Boolean := False)
227    is
228       Loc            : constant Source_Ptr := Sloc (Function_Call);
229       Obj_Address    : Node_Id;
230       Obj_Acc_Formal : Entity_Id;
231
232    begin
233       --  Locate the implicit access parameter in the called function
234
235       Obj_Acc_Formal := Build_In_Place_Formal (Function_Id, BIP_Object_Access);
236
237       --  If no return object is provided, then pass null
238
239       if not Present (Return_Object) then
240          Obj_Address := Make_Null (Loc);
241          Set_Parent (Obj_Address, Function_Call);
242
243       --  If Return_Object is already an expression of an access type, then use
244       --  it directly, since it must be an access value denoting the return
245       --  object, and couldn't possibly be the return object itself.
246
247       elsif Is_Access then
248          Obj_Address := Return_Object;
249          Set_Parent (Obj_Address, Function_Call);
250
251       --  Apply Unrestricted_Access to caller's return object
252
253       else
254          Obj_Address :=
255             Make_Attribute_Reference (Loc,
256               Prefix         => Return_Object,
257               Attribute_Name => Name_Unrestricted_Access);
258
259          Set_Parent (Return_Object, Obj_Address);
260          Set_Parent (Obj_Address, Function_Call);
261       end if;
262
263       Analyze_And_Resolve (Obj_Address, Etype (Obj_Acc_Formal));
264
265       --  Build the parameter association for the new actual and add it to the
266       --  end of the function's actuals.
267
268       Add_Extra_Actual_To_Call (Function_Call, Obj_Acc_Formal, Obj_Address);
269    end Add_Access_Actual_To_Build_In_Place_Call;
270
271    --------------------------------------------------
272    -- Add_Alloc_Form_Actual_To_Build_In_Place_Call --
273    --------------------------------------------------
274
275    procedure Add_Alloc_Form_Actual_To_Build_In_Place_Call
276      (Function_Call  : Node_Id;
277       Function_Id    : Entity_Id;
278       Alloc_Form     : BIP_Allocation_Form := Unspecified;
279       Alloc_Form_Exp : Node_Id             := Empty)
280    is
281       Loc               : constant Source_Ptr := Sloc (Function_Call);
282       Alloc_Form_Actual : Node_Id;
283       Alloc_Form_Formal : Node_Id;
284
285    begin
286       --  The allocation form generally doesn't need to be passed in the case
287       --  of a constrained result subtype, since normally the caller performs
288       --  the allocation in that case. However this formal is still needed in
289       --  the case where the function has a tagged result, because generally
290       --  such functions can be called in a dispatching context and such calls
291       --  must be handled like calls to class-wide functions.
292
293       if Is_Constrained (Underlying_Type (Etype (Function_Id)))
294         and then not Is_Tagged_Type (Underlying_Type (Etype (Function_Id)))
295       then
296          return;
297       end if;
298
299       --  Locate the implicit allocation form parameter in the called function.
300       --  Maybe it would be better for each implicit formal of a build-in-place
301       --  function to have a flag or a Uint attribute to identify it. ???
302
303       Alloc_Form_Formal := Build_In_Place_Formal (Function_Id, BIP_Alloc_Form);
304
305       if Present (Alloc_Form_Exp) then
306          pragma Assert (Alloc_Form = Unspecified);
307
308          Alloc_Form_Actual := Alloc_Form_Exp;
309
310       else
311          pragma Assert (Alloc_Form /= Unspecified);
312
313          Alloc_Form_Actual :=
314            Make_Integer_Literal (Loc,
315              Intval => UI_From_Int (BIP_Allocation_Form'Pos (Alloc_Form)));
316       end if;
317
318       Analyze_And_Resolve (Alloc_Form_Actual, Etype (Alloc_Form_Formal));
319
320       --  Build the parameter association for the new actual and add it to the
321       --  end of the function's actuals.
322
323       Add_Extra_Actual_To_Call
324         (Function_Call, Alloc_Form_Formal, Alloc_Form_Actual);
325    end Add_Alloc_Form_Actual_To_Build_In_Place_Call;
326
327    ------------------------------
328    -- Add_Extra_Actual_To_Call --
329    ------------------------------
330
331    procedure Add_Extra_Actual_To_Call
332      (Subprogram_Call : Node_Id;
333       Extra_Formal    : Entity_Id;
334       Extra_Actual    : Node_Id)
335    is
336       Loc         : constant Source_Ptr := Sloc (Subprogram_Call);
337       Param_Assoc : Node_Id;
338
339    begin
340       Param_Assoc :=
341         Make_Parameter_Association (Loc,
342           Selector_Name             => New_Occurrence_Of (Extra_Formal, Loc),
343           Explicit_Actual_Parameter => Extra_Actual);
344
345       Set_Parent (Param_Assoc, Subprogram_Call);
346       Set_Parent (Extra_Actual, Param_Assoc);
347
348       if Present (Parameter_Associations (Subprogram_Call)) then
349          if Nkind (Last (Parameter_Associations (Subprogram_Call))) =
350               N_Parameter_Association
351          then
352
353             --  Find last named actual, and append
354
355             declare
356                L : Node_Id;
357             begin
358                L := First_Actual (Subprogram_Call);
359                while Present (L) loop
360                   if No (Next_Actual (L)) then
361                      Set_Next_Named_Actual (Parent (L), Extra_Actual);
362                      exit;
363                   end if;
364                   Next_Actual (L);
365                end loop;
366             end;
367
368          else
369             Set_First_Named_Actual (Subprogram_Call, Extra_Actual);
370          end if;
371
372          Append (Param_Assoc, To => Parameter_Associations (Subprogram_Call));
373
374       else
375          Set_Parameter_Associations (Subprogram_Call, New_List (Param_Assoc));
376          Set_First_Named_Actual (Subprogram_Call, Extra_Actual);
377       end if;
378    end Add_Extra_Actual_To_Call;
379
380    --------------------------------------------------
381    -- Add_Final_List_Actual_To_Build_In_Place_Call --
382    --------------------------------------------------
383
384    procedure Add_Final_List_Actual_To_Build_In_Place_Call
385      (Function_Call : Node_Id;
386       Function_Id   : Entity_Id;
387       Acc_Type      : Entity_Id;
388       Sel_Comp      : Node_Id := Empty)
389    is
390       Loc               : constant Source_Ptr := Sloc (Function_Call);
391       Final_List        : Node_Id;
392       Final_List_Actual : Node_Id;
393       Final_List_Formal : Node_Id;
394       Is_Ctrl_Result    : constant Boolean :=
395                             Needs_Finalization
396                               (Underlying_Type (Etype (Function_Id)));
397
398    begin
399       --  No such extra parameter is needed if there are no controlled parts.
400       --  The test for Needs_Finalization accounts for class-wide results
401       --  (which potentially have controlled parts, even if the root type
402       --  doesn't), and the test for a tagged result type is needed because
403       --  calls to such a function can in general occur in dispatching
404       --  contexts, which must be treated the same as a call to class-wide
405       --  functions. Both of these situations require that a finalization list
406       --  be passed.
407
408       if not Needs_BIP_Final_List (Function_Id) then
409          return;
410       end if;
411
412       --  Locate implicit finalization list parameter in the called function
413
414       Final_List_Formal := Build_In_Place_Formal (Function_Id, BIP_Final_List);
415
416       --  Create the actual which is a pointer to the appropriate finalization
417       --  list. Acc_Type is present if and only if this call is the
418       --  initialization of an allocator. Use the Current_Scope or the Acc_Type
419       --  as appropriate.
420
421       if Present (Acc_Type)
422         and then (Ekind (Acc_Type) = E_Anonymous_Access_Type
423                    or else
424                      Present (Associated_Final_Chain (Base_Type (Acc_Type))))
425       then
426          Final_List := Find_Final_List (Acc_Type);
427
428       --  If Sel_Comp is present and the function result is controlled, then
429       --  the finalization list will be obtained from the _controller list of
430       --  the selected component's prefix object.
431
432       elsif Present (Sel_Comp) and then Is_Ctrl_Result then
433          Final_List := Find_Final_List (Current_Scope, Sel_Comp);
434
435       else
436          Final_List := Find_Final_List (Current_Scope);
437       end if;
438
439       Final_List_Actual :=
440         Make_Attribute_Reference (Loc,
441           Prefix         => Final_List,
442           Attribute_Name => Name_Unrestricted_Access);
443
444       Analyze_And_Resolve (Final_List_Actual, Etype (Final_List_Formal));
445
446       --  Build the parameter association for the new actual and add it to the
447       --  end of the function's actuals.
448
449       Add_Extra_Actual_To_Call
450         (Function_Call, Final_List_Formal, Final_List_Actual);
451    end Add_Final_List_Actual_To_Build_In_Place_Call;
452
453    ---------------------------------------------
454    -- Add_Task_Actuals_To_Build_In_Place_Call --
455    ---------------------------------------------
456
457    procedure Add_Task_Actuals_To_Build_In_Place_Call
458      (Function_Call : Node_Id;
459       Function_Id   : Entity_Id;
460       Master_Actual : Node_Id)
461       --  Note: Master_Actual can be Empty, but only if there are no tasks
462    is
463       Loc               : constant Source_Ptr := Sloc (Function_Call);
464
465    begin
466       --  No such extra parameters are needed if there are no tasks
467
468       if not Has_Task (Etype (Function_Id)) then
469          return;
470       end if;
471
472       --  The master
473
474       declare
475          Master_Formal : Node_Id;
476       begin
477          --  Locate implicit master parameter in the called function
478
479          Master_Formal := Build_In_Place_Formal (Function_Id, BIP_Master);
480
481          Analyze_And_Resolve (Master_Actual, Etype (Master_Formal));
482
483          --  Build the parameter association for the new actual and add it to
484          --  the end of the function's actuals.
485
486          Add_Extra_Actual_To_Call
487            (Function_Call, Master_Formal, Master_Actual);
488       end;
489
490       --  The activation chain
491
492       declare
493          Activation_Chain_Actual : Node_Id;
494          Activation_Chain_Formal : Node_Id;
495       begin
496          --  Locate implicit activation chain parameter in the called function
497
498          Activation_Chain_Formal := Build_In_Place_Formal
499            (Function_Id, BIP_Activation_Chain);
500
501          --  Create the actual which is a pointer to the current activation
502          --  chain
503
504          Activation_Chain_Actual :=
505            Make_Attribute_Reference (Loc,
506              Prefix         => Make_Identifier (Loc, Name_uChain),
507              Attribute_Name => Name_Unrestricted_Access);
508
509          Analyze_And_Resolve
510            (Activation_Chain_Actual, Etype (Activation_Chain_Formal));
511
512          --  Build the parameter association for the new actual and add it to
513          --  the end of the function's actuals.
514
515          Add_Extra_Actual_To_Call
516            (Function_Call, Activation_Chain_Formal, Activation_Chain_Actual);
517       end;
518    end Add_Task_Actuals_To_Build_In_Place_Call;
519
520    -----------------------
521    -- BIP_Formal_Suffix --
522    -----------------------
523
524    function BIP_Formal_Suffix (Kind : BIP_Formal_Kind) return String is
525    begin
526       case Kind is
527          when BIP_Alloc_Form       =>
528             return "BIPalloc";
529          when BIP_Final_List       =>
530             return "BIPfinallist";
531          when BIP_Master           =>
532             return "BIPmaster";
533          when BIP_Activation_Chain =>
534             return "BIPactivationchain";
535          when BIP_Object_Access    =>
536             return "BIPaccess";
537       end case;
538    end BIP_Formal_Suffix;
539
540    ---------------------------
541    -- Build_In_Place_Formal --
542    ---------------------------
543
544    function Build_In_Place_Formal
545      (Func : Entity_Id;
546       Kind : BIP_Formal_Kind) return Entity_Id
547    is
548       Extra_Formal : Entity_Id := Extra_Formals (Func);
549
550    begin
551       --  Maybe it would be better for each implicit formal of a build-in-place
552       --  function to have a flag or a Uint attribute to identify it. ???
553
554       loop
555          pragma Assert (Present (Extra_Formal));
556          exit when
557            Chars (Extra_Formal) =
558              New_External_Name (Chars (Func), BIP_Formal_Suffix (Kind));
559          Next_Formal_With_Extras (Extra_Formal);
560       end loop;
561
562       return Extra_Formal;
563    end Build_In_Place_Formal;
564
565    --------------------------------
566    -- Check_Overriding_Operation --
567    --------------------------------
568
569    procedure Check_Overriding_Operation (Subp : Entity_Id) is
570       Typ     : constant Entity_Id := Find_Dispatching_Type (Subp);
571       Op_List : constant Elist_Id  := Primitive_Operations (Typ);
572       Op_Elmt : Elmt_Id;
573       Prim_Op : Entity_Id;
574       Par_Op  : Entity_Id;
575
576    begin
577       if Is_Derived_Type (Typ)
578         and then not Is_Private_Type (Typ)
579         and then In_Open_Scopes (Scope (Etype (Typ)))
580         and then Typ = Base_Type (Typ)
581       then
582          --  Subp overrides an inherited private operation if there is an
583          --  inherited operation with a different name than Subp (see
584          --  Derive_Subprogram) whose Alias is a hidden subprogram with the
585          --  same name as Subp.
586
587          Op_Elmt := First_Elmt (Op_List);
588          while Present (Op_Elmt) loop
589             Prim_Op := Node (Op_Elmt);
590             Par_Op  := Alias (Prim_Op);
591
592             if Present (Par_Op)
593               and then not Comes_From_Source (Prim_Op)
594               and then Chars (Prim_Op) /= Chars (Par_Op)
595               and then Chars (Par_Op) = Chars (Subp)
596               and then Is_Hidden (Par_Op)
597               and then Type_Conformant (Prim_Op, Subp)
598             then
599                Set_DT_Position (Subp, DT_Position (Prim_Op));
600             end if;
601
602             Next_Elmt (Op_Elmt);
603          end loop;
604       end if;
605    end Check_Overriding_Operation;
606
607    -------------------------------
608    -- Detect_Infinite_Recursion --
609    -------------------------------
610
611    procedure Detect_Infinite_Recursion (N : Node_Id; Spec : Entity_Id) is
612       Loc : constant Source_Ptr := Sloc (N);
613
614       Var_List : constant Elist_Id := New_Elmt_List;
615       --  List of globals referenced by body of procedure
616
617       Call_List : constant Elist_Id := New_Elmt_List;
618       --  List of recursive calls in body of procedure
619
620       Shad_List : constant Elist_Id := New_Elmt_List;
621       --  List of entity id's for entities created to capture the value of
622       --  referenced globals on entry to the procedure.
623
624       Scop : constant Uint := Scope_Depth (Spec);
625       --  This is used to record the scope depth of the current procedure, so
626       --  that we can identify global references.
627
628       Max_Vars : constant := 4;
629       --  Do not test more than four global variables
630
631       Count_Vars : Natural := 0;
632       --  Count variables found so far
633
634       Var  : Entity_Id;
635       Elm  : Elmt_Id;
636       Ent  : Entity_Id;
637       Call : Elmt_Id;
638       Decl : Node_Id;
639       Test : Node_Id;
640       Elm1 : Elmt_Id;
641       Elm2 : Elmt_Id;
642       Last : Node_Id;
643
644       function Process (Nod : Node_Id) return Traverse_Result;
645       --  Function to traverse the subprogram body (using Traverse_Func)
646
647       -------------
648       -- Process --
649       -------------
650
651       function Process (Nod : Node_Id) return Traverse_Result is
652       begin
653          --  Procedure call
654
655          if Nkind (Nod) = N_Procedure_Call_Statement then
656
657             --  Case of one of the detected recursive calls
658
659             if Is_Entity_Name (Name (Nod))
660               and then Has_Recursive_Call (Entity (Name (Nod)))
661               and then Entity (Name (Nod)) = Spec
662             then
663                Append_Elmt (Nod, Call_List);
664                return Skip;
665
666             --  Any other procedure call may have side effects
667
668             else
669                return Abandon;
670             end if;
671
672          --  A call to a pure function can always be ignored
673
674          elsif Nkind (Nod) = N_Function_Call
675            and then Is_Entity_Name (Name (Nod))
676            and then Is_Pure (Entity (Name (Nod)))
677          then
678             return Skip;
679
680          --  Case of an identifier reference
681
682          elsif Nkind (Nod) = N_Identifier then
683             Ent := Entity (Nod);
684
685             --  If no entity, then ignore the reference
686
687             --  Not clear why this can happen. To investigate, remove this
688             --  test and look at the crash that occurs here in 3401-004 ???
689
690             if No (Ent) then
691                return Skip;
692
693             --  Ignore entities with no Scope, again not clear how this
694             --  can happen, to investigate, look at 4108-008 ???
695
696             elsif No (Scope (Ent)) then
697                return Skip;
698
699             --  Ignore the reference if not to a more global object
700
701             elsif Scope_Depth (Scope (Ent)) >= Scop then
702                return Skip;
703
704             --  References to types, exceptions and constants are always OK
705
706             elsif Is_Type (Ent)
707               or else Ekind (Ent) = E_Exception
708               or else Ekind (Ent) = E_Constant
709             then
710                return Skip;
711
712             --  If other than a non-volatile scalar variable, we have some
713             --  kind of global reference (e.g. to a function) that we cannot
714             --  deal with so we forget the attempt.
715
716             elsif Ekind (Ent) /= E_Variable
717               or else not Is_Scalar_Type (Etype (Ent))
718               or else Treat_As_Volatile (Ent)
719             then
720                return Abandon;
721
722             --  Otherwise we have a reference to a global scalar
723
724             else
725                --  Loop through global entities already detected
726
727                Elm := First_Elmt (Var_List);
728                loop
729                   --  If not detected before, record this new global reference
730
731                   if No (Elm) then
732                      Count_Vars := Count_Vars + 1;
733
734                      if Count_Vars <= Max_Vars then
735                         Append_Elmt (Entity (Nod), Var_List);
736                      else
737                         return Abandon;
738                      end if;
739
740                      exit;
741
742                   --  If recorded before, ignore
743
744                   elsif Node (Elm) = Entity (Nod) then
745                      return Skip;
746
747                   --  Otherwise keep looking
748
749                   else
750                      Next_Elmt (Elm);
751                   end if;
752                end loop;
753
754                return Skip;
755             end if;
756
757          --  For all other node kinds, recursively visit syntactic children
758
759          else
760             return OK;
761          end if;
762       end Process;
763
764       function Traverse_Body is new Traverse_Func (Process);
765
766    --  Start of processing for Detect_Infinite_Recursion
767
768    begin
769       --  Do not attempt detection in No_Implicit_Conditional mode, since we
770       --  won't be able to generate the code to handle the recursion in any
771       --  case.
772
773       if Restriction_Active (No_Implicit_Conditionals) then
774          return;
775       end if;
776
777       --  Otherwise do traversal and quit if we get abandon signal
778
779       if Traverse_Body (N) = Abandon then
780          return;
781
782       --  We must have a call, since Has_Recursive_Call was set. If not just
783       --  ignore (this is only an error check, so if we have a funny situation,
784       --  due to bugs or errors, we do not want to bomb!)
785
786       elsif Is_Empty_Elmt_List (Call_List) then
787          return;
788       end if;
789
790       --  Here is the case where we detect recursion at compile time
791
792       --  Push our current scope for analyzing the declarations and code that
793       --  we will insert for the checking.
794
795       Push_Scope (Spec);
796
797       --  This loop builds temporary variables for each of the referenced
798       --  globals, so that at the end of the loop the list Shad_List contains
799       --  these temporaries in one-to-one correspondence with the elements in
800       --  Var_List.
801
802       Last := Empty;
803       Elm := First_Elmt (Var_List);
804       while Present (Elm) loop
805          Var := Node (Elm);
806          Ent :=
807            Make_Defining_Identifier (Loc,
808              Chars => New_Internal_Name ('S'));
809          Append_Elmt (Ent, Shad_List);
810
811          --  Insert a declaration for this temporary at the start of the
812          --  declarations for the procedure. The temporaries are declared as
813          --  constant objects initialized to the current values of the
814          --  corresponding temporaries.
815
816          Decl :=
817            Make_Object_Declaration (Loc,
818              Defining_Identifier => Ent,
819              Object_Definition   => New_Occurrence_Of (Etype (Var), Loc),
820              Constant_Present    => True,
821              Expression          => New_Occurrence_Of (Var, Loc));
822
823          if No (Last) then
824             Prepend (Decl, Declarations (N));
825          else
826             Insert_After (Last, Decl);
827          end if;
828
829          Last := Decl;
830          Analyze (Decl);
831          Next_Elmt (Elm);
832       end loop;
833
834       --  Loop through calls
835
836       Call := First_Elmt (Call_List);
837       while Present (Call) loop
838
839          --  Build a predicate expression of the form
840
841          --    True
842          --      and then global1 = temp1
843          --      and then global2 = temp2
844          --      ...
845
846          --  This predicate determines if any of the global values
847          --  referenced by the procedure have changed since the
848          --  current call, if not an infinite recursion is assured.
849
850          Test := New_Occurrence_Of (Standard_True, Loc);
851
852          Elm1 := First_Elmt (Var_List);
853          Elm2 := First_Elmt (Shad_List);
854          while Present (Elm1) loop
855             Test :=
856               Make_And_Then (Loc,
857                 Left_Opnd  => Test,
858                 Right_Opnd =>
859                   Make_Op_Eq (Loc,
860                     Left_Opnd  => New_Occurrence_Of (Node (Elm1), Loc),
861                     Right_Opnd => New_Occurrence_Of (Node (Elm2), Loc)));
862
863             Next_Elmt (Elm1);
864             Next_Elmt (Elm2);
865          end loop;
866
867          --  Now we replace the call with the sequence
868
869          --    if no-changes (see above) then
870          --       raise Storage_Error;
871          --    else
872          --       original-call
873          --    end if;
874
875          Rewrite (Node (Call),
876            Make_If_Statement (Loc,
877              Condition       => Test,
878              Then_Statements => New_List (
879                Make_Raise_Storage_Error (Loc,
880                  Reason => SE_Infinite_Recursion)),
881
882              Else_Statements => New_List (
883                Relocate_Node (Node (Call)))));
884
885          Analyze (Node (Call));
886
887          Next_Elmt (Call);
888       end loop;
889
890       --  Remove temporary scope stack entry used for analysis
891
892       Pop_Scope;
893    end Detect_Infinite_Recursion;
894
895    --------------------
896    -- Expand_Actuals --
897    --------------------
898
899    procedure Expand_Actuals (N : Node_Id; Subp : Entity_Id) is
900       Loc       : constant Source_Ptr := Sloc (N);
901       Actual    : Node_Id;
902       Formal    : Entity_Id;
903       N_Node    : Node_Id;
904       Post_Call : List_Id;
905       E_Formal  : Entity_Id;
906
907       procedure Add_Call_By_Copy_Code;
908       --  For cases where the parameter must be passed by copy, this routine
909       --  generates a temporary variable into which the actual is copied and
910       --  then passes this as the parameter. For an OUT or IN OUT parameter,
911       --  an assignment is also generated to copy the result back. The call
912       --  also takes care of any constraint checks required for the type
913       --  conversion case (on both the way in and the way out).
914
915       procedure Add_Simple_Call_By_Copy_Code;
916       --  This is similar to the above, but is used in cases where we know
917       --  that all that is needed is to simply create a temporary and copy
918       --  the value in and out of the temporary.
919
920       procedure Check_Fortran_Logical;
921       --  A value of type Logical that is passed through a formal parameter
922       --  must be normalized because .TRUE. usually does not have the same
923       --  representation as True. We assume that .FALSE. = False = 0.
924       --  What about functions that return a logical type ???
925
926       function Is_Legal_Copy return Boolean;
927       --  Check that an actual can be copied before generating the temporary
928       --  to be used in the call. If the actual is of a by_reference type then
929       --  the program is illegal (this can only happen in the presence of
930       --  rep. clauses that force an incorrect alignment). If the formal is
931       --  a by_reference parameter imposed by a DEC pragma, emit a warning to
932       --  the effect that this might lead to unaligned arguments.
933
934       function Make_Var (Actual : Node_Id) return Entity_Id;
935       --  Returns an entity that refers to the given actual parameter,
936       --  Actual (not including any type conversion). If Actual is an
937       --  entity name, then this entity is returned unchanged, otherwise
938       --  a renaming is created to provide an entity for the actual.
939
940       procedure Reset_Packed_Prefix;
941       --  The expansion of a packed array component reference is delayed in
942       --  the context of a call. Now we need to complete the expansion, so we
943       --  unmark the analyzed bits in all prefixes.
944
945       ---------------------------
946       -- Add_Call_By_Copy_Code --
947       ---------------------------
948
949       procedure Add_Call_By_Copy_Code is
950          Expr  : Node_Id;
951          Init  : Node_Id;
952          Temp  : Entity_Id;
953          Indic : Node_Id;
954          Var   : Entity_Id;
955          F_Typ : constant Entity_Id := Etype (Formal);
956          V_Typ : Entity_Id;
957          Crep  : Boolean;
958
959       begin
960          if not Is_Legal_Copy then
961             return;
962          end if;
963
964          Temp :=
965            Make_Defining_Identifier (Loc,
966              Chars => New_Internal_Name ('T'));
967
968          --  Use formal type for temp, unless formal type is an unconstrained
969          --  array, in which case we don't have to worry about bounds checks,
970          --  and we use the actual type, since that has appropriate bounds.
971
972          if Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ) then
973             Indic := New_Occurrence_Of (Etype (Actual), Loc);
974          else
975             Indic := New_Occurrence_Of (Etype (Formal), Loc);
976          end if;
977
978          if Nkind (Actual) = N_Type_Conversion then
979             V_Typ := Etype (Expression (Actual));
980
981             --  If the formal is an (in-)out parameter, capture the name
982             --  of the variable in order to build the post-call assignment.
983
984             Var := Make_Var (Expression (Actual));
985
986             Crep := not Same_Representation
987                           (F_Typ, Etype (Expression (Actual)));
988
989          else
990             V_Typ := Etype (Actual);
991             Var   := Make_Var (Actual);
992             Crep  := False;
993          end if;
994
995          --  Setup initialization for case of in out parameter, or an out
996          --  parameter where the formal is an unconstrained array (in the
997          --  latter case, we have to pass in an object with bounds).
998
999          --  If this is an out parameter, the initial copy is wasteful, so as
1000          --  an optimization for the one-dimensional case we extract the
1001          --  bounds of the actual and build an uninitialized temporary of the
1002          --  right size.
1003
1004          if Ekind (Formal) = E_In_Out_Parameter
1005            or else (Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ))
1006          then
1007             if Nkind (Actual) = N_Type_Conversion then
1008                if Conversion_OK (Actual) then
1009                   Init := OK_Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1010                else
1011                   Init := Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1012                end if;
1013
1014             elsif Ekind (Formal) = E_Out_Parameter
1015               and then Is_Array_Type (F_Typ)
1016               and then Number_Dimensions (F_Typ) = 1
1017               and then not Has_Non_Null_Base_Init_Proc (F_Typ)
1018             then
1019                --  Actual is a one-dimensional array or slice, and the type
1020                --  requires no initialization. Create a temporary of the
1021                --  right size, but do not copy actual into it (optimization).
1022
1023                Init := Empty;
1024                Indic :=
1025                  Make_Subtype_Indication (Loc,
1026                    Subtype_Mark =>
1027                      New_Occurrence_Of (F_Typ, Loc),
1028                    Constraint   =>
1029                      Make_Index_Or_Discriminant_Constraint (Loc,
1030                        Constraints => New_List (
1031                          Make_Range (Loc,
1032                            Low_Bound  =>
1033                              Make_Attribute_Reference (Loc,
1034                                Prefix => New_Occurrence_Of (Var, Loc),
1035                                Attribute_Name => Name_First),
1036                            High_Bound =>
1037                              Make_Attribute_Reference (Loc,
1038                                Prefix => New_Occurrence_Of (Var, Loc),
1039                                Attribute_Name => Name_Last)))));
1040
1041             else
1042                Init := New_Occurrence_Of (Var, Loc);
1043             end if;
1044
1045          --  An initialization is created for packed conversions as
1046          --  actuals for out parameters to enable Make_Object_Declaration
1047          --  to determine the proper subtype for N_Node. Note that this
1048          --  is wasteful because the extra copying on the call side is
1049          --  not required for such out parameters. ???
1050
1051          elsif Ekind (Formal) = E_Out_Parameter
1052            and then Nkind (Actual) = N_Type_Conversion
1053            and then (Is_Bit_Packed_Array (F_Typ)
1054                        or else
1055                      Is_Bit_Packed_Array (Etype (Expression (Actual))))
1056          then
1057             if Conversion_OK (Actual) then
1058                Init := OK_Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1059             else
1060                Init := Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1061             end if;
1062
1063          elsif Ekind (Formal) = E_In_Parameter then
1064
1065             --  Handle the case in which the actual is a type conversion
1066
1067             if Nkind (Actual) = N_Type_Conversion then
1068                if Conversion_OK (Actual) then
1069                   Init := OK_Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1070                else
1071                   Init := Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1072                end if;
1073             else
1074                Init := New_Occurrence_Of (Var, Loc);
1075             end if;
1076
1077          else
1078             Init := Empty;
1079          end if;
1080
1081          N_Node :=
1082            Make_Object_Declaration (Loc,
1083              Defining_Identifier => Temp,
1084              Object_Definition   => Indic,
1085              Expression          => Init);
1086          Set_Assignment_OK (N_Node);
1087          Insert_Action (N, N_Node);
1088
1089          --  Now, normally the deal here is that we use the defining
1090          --  identifier created by that object declaration. There is
1091          --  one exception to this. In the change of representation case
1092          --  the above declaration will end up looking like:
1093
1094          --    temp : type := identifier;
1095
1096          --  And in this case we might as well use the identifier directly
1097          --  and eliminate the temporary. Note that the analysis of the
1098          --  declaration was not a waste of time in that case, since it is
1099          --  what generated the necessary change of representation code. If
1100          --  the change of representation introduced additional code, as in
1101          --  a fixed-integer conversion, the expression is not an identifier
1102          --  and must be kept.
1103
1104          if Crep
1105            and then Present (Expression (N_Node))
1106            and then Is_Entity_Name (Expression (N_Node))
1107          then
1108             Temp := Entity (Expression (N_Node));
1109             Rewrite (N_Node, Make_Null_Statement (Loc));
1110          end if;
1111
1112          --  For IN parameter, all we do is to replace the actual
1113
1114          if Ekind (Formal) = E_In_Parameter then
1115             Rewrite (Actual, New_Reference_To (Temp, Loc));
1116             Analyze (Actual);
1117
1118          --  Processing for OUT or IN OUT parameter
1119
1120          else
1121             --  Kill current value indications for the temporary variable we
1122             --  created, since we just passed it as an OUT parameter.
1123
1124             Kill_Current_Values (Temp);
1125
1126             --  If type conversion, use reverse conversion on exit
1127
1128             if Nkind (Actual) = N_Type_Conversion then
1129                if Conversion_OK (Actual) then
1130                   Expr := OK_Convert_To (V_Typ, New_Occurrence_Of (Temp, Loc));
1131                else
1132                   Expr := Convert_To (V_Typ, New_Occurrence_Of (Temp, Loc));
1133                end if;
1134             else
1135                Expr := New_Occurrence_Of (Temp, Loc);
1136             end if;
1137
1138             Rewrite (Actual, New_Reference_To (Temp, Loc));
1139             Analyze (Actual);
1140
1141             --  If the actual is a conversion of a packed reference, it may
1142             --  already have been expanded by Remove_Side_Effects, and the
1143             --  resulting variable is a temporary which does not designate
1144             --  the proper out-parameter, which may not be addressable. In
1145             --  that case, generate an assignment to the original expression
1146             --  (before expansion of the  packed reference) so that the proper
1147             --  expansion of assignment to a packed component can take place.
1148
1149             declare
1150                Obj : Node_Id;
1151                Lhs : Node_Id;
1152
1153             begin
1154                if Is_Renaming_Of_Object (Var)
1155                  and then Nkind (Renamed_Object (Var)) = N_Selected_Component
1156                  and then Is_Entity_Name (Prefix (Renamed_Object (Var)))
1157                  and then Nkind (Original_Node (Prefix (Renamed_Object (Var))))
1158                    = N_Indexed_Component
1159                  and then
1160                    Has_Non_Standard_Rep (Etype (Prefix (Renamed_Object (Var))))
1161                then
1162                   Obj := Renamed_Object (Var);
1163                   Lhs :=
1164                     Make_Selected_Component (Loc,
1165                       Prefix        =>
1166                         New_Copy_Tree (Original_Node (Prefix (Obj))),
1167                       Selector_Name => New_Copy (Selector_Name (Obj)));
1168                   Reset_Analyzed_Flags (Lhs);
1169
1170                else
1171                   Lhs :=  New_Occurrence_Of (Var, Loc);
1172                end if;
1173
1174                Set_Assignment_OK (Lhs);
1175
1176                Append_To (Post_Call,
1177                  Make_Assignment_Statement (Loc,
1178                    Name       => Lhs,
1179                    Expression => Expr));
1180             end;
1181          end if;
1182
1183       end Add_Call_By_Copy_Code;
1184
1185       ----------------------------------
1186       -- Add_Simple_Call_By_Copy_Code --
1187       ----------------------------------
1188
1189       procedure Add_Simple_Call_By_Copy_Code is
1190          Temp   : Entity_Id;
1191          Decl   : Node_Id;
1192          Incod  : Node_Id;
1193          Outcod : Node_Id;
1194          Lhs    : Node_Id;
1195          Rhs    : Node_Id;
1196          Indic  : Node_Id;
1197          F_Typ  : constant Entity_Id := Etype (Formal);
1198
1199       begin
1200          if not Is_Legal_Copy then
1201             return;
1202          end if;
1203
1204          --  Use formal type for temp, unless formal type is an unconstrained
1205          --  array, in which case we don't have to worry about bounds checks,
1206          --  and we use the actual type, since that has appropriate bounds.
1207
1208          if Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ) then
1209             Indic := New_Occurrence_Of (Etype (Actual), Loc);
1210          else
1211             Indic := New_Occurrence_Of (Etype (Formal), Loc);
1212          end if;
1213
1214          --  Prepare to generate code
1215
1216          Reset_Packed_Prefix;
1217
1218          Temp :=
1219            Make_Defining_Identifier (Loc,
1220              Chars => New_Internal_Name ('T'));
1221          Incod  := Relocate_Node (Actual);
1222          Outcod := New_Copy_Tree (Incod);
1223
1224          --  Generate declaration of temporary variable, initializing it
1225          --  with the input parameter unless we have an OUT formal or
1226          --  this is an initialization call.
1227
1228          --  If the formal is an out parameter with discriminants, the
1229          --  discriminants must be captured even if the rest of the object
1230          --  is in principle uninitialized, because the discriminants may
1231          --  be read by the called subprogram.
1232
1233          if Ekind (Formal) = E_Out_Parameter then
1234             Incod := Empty;
1235
1236             if Has_Discriminants (Etype (Formal)) then
1237                Indic := New_Occurrence_Of (Etype (Actual), Loc);
1238             end if;
1239
1240          elsif Inside_Init_Proc then
1241
1242             --  Could use a comment here to match comment below ???
1243
1244             if Nkind (Actual) /= N_Selected_Component
1245               or else
1246                 not Has_Discriminant_Dependent_Constraint
1247                   (Entity (Selector_Name (Actual)))
1248             then
1249                Incod := Empty;
1250
1251             --  Otherwise, keep the component in order to generate the proper
1252             --  actual subtype, that depends on enclosing discriminants.
1253
1254             else
1255                null;
1256             end if;
1257          end if;
1258
1259          Decl :=
1260            Make_Object_Declaration (Loc,
1261              Defining_Identifier => Temp,
1262              Object_Definition   => Indic,
1263              Expression          => Incod);
1264
1265          if Inside_Init_Proc
1266            and then No (Incod)
1267          then
1268             --  If the call is to initialize a component of a composite type,
1269             --  and the component does not depend on discriminants, use the
1270             --  actual type of the component. This is required in case the
1271             --  component is constrained, because in general the formal of the
1272             --  initialization procedure will be unconstrained. Note that if
1273             --  the component being initialized is constrained by an enclosing
1274             --  discriminant, the presence of the initialization in the
1275             --  declaration will generate an expression for the actual subtype.
1276
1277             Set_No_Initialization (Decl);
1278             Set_Object_Definition (Decl,
1279               New_Occurrence_Of (Etype (Actual), Loc));
1280          end if;
1281
1282          Insert_Action (N, Decl);
1283
1284          --  The actual is simply a reference to the temporary
1285
1286          Rewrite (Actual, New_Occurrence_Of (Temp, Loc));
1287
1288          --  Generate copy out if OUT or IN OUT parameter
1289
1290          if Ekind (Formal) /= E_In_Parameter then
1291             Lhs := Outcod;
1292             Rhs := New_Occurrence_Of (Temp, Loc);
1293
1294             --  Deal with conversion
1295
1296             if Nkind (Lhs) = N_Type_Conversion then
1297                Lhs := Expression (Lhs);
1298                Rhs := Convert_To (Etype (Actual), Rhs);
1299             end if;
1300
1301             Append_To (Post_Call,
1302               Make_Assignment_Statement (Loc,
1303                 Name       => Lhs,
1304                 Expression => Rhs));
1305             Set_Assignment_OK (Name (Last (Post_Call)));
1306          end if;
1307       end Add_Simple_Call_By_Copy_Code;
1308
1309       ---------------------------
1310       -- Check_Fortran_Logical --
1311       ---------------------------
1312
1313       procedure Check_Fortran_Logical is
1314          Logical : constant Entity_Id := Etype (Formal);
1315          Var     : Entity_Id;
1316
1317       --  Note: this is very incomplete, e.g. it does not handle arrays
1318       --  of logical values. This is really not the right approach at all???)
1319
1320       begin
1321          if Convention (Subp) = Convention_Fortran
1322            and then Root_Type (Etype (Formal)) = Standard_Boolean
1323            and then Ekind (Formal) /= E_In_Parameter
1324          then
1325             Var := Make_Var (Actual);
1326             Append_To (Post_Call,
1327               Make_Assignment_Statement (Loc,
1328                 Name => New_Occurrence_Of (Var, Loc),
1329                 Expression =>
1330                   Unchecked_Convert_To (
1331                     Logical,
1332                     Make_Op_Ne (Loc,
1333                       Left_Opnd  => New_Occurrence_Of (Var, Loc),
1334                       Right_Opnd =>
1335                         Unchecked_Convert_To (
1336                           Logical,
1337                           New_Occurrence_Of (Standard_False, Loc))))));
1338          end if;
1339       end Check_Fortran_Logical;
1340
1341       -------------------
1342       -- Is_Legal_Copy --
1343       -------------------
1344
1345       function Is_Legal_Copy return Boolean is
1346       begin
1347          --  An attempt to copy a value of such a type can only occur if
1348          --  representation clauses give the actual a misaligned address.
1349
1350          if Is_By_Reference_Type (Etype (Formal)) then
1351             Error_Msg_N
1352               ("misaligned actual cannot be passed by reference", Actual);
1353             return False;
1354
1355          --  For users of Starlet, we assume that the specification of by-
1356          --  reference mechanism is mandatory. This may lead to unaligned
1357          --  objects but at least for DEC legacy code it is known to work.
1358          --  The warning will alert users of this code that a problem may
1359          --  be lurking.
1360
1361          elsif Mechanism (Formal) = By_Reference
1362            and then Is_Valued_Procedure (Scope (Formal))
1363          then
1364             Error_Msg_N
1365               ("by_reference actual may be misaligned?", Actual);
1366             return False;
1367
1368          else
1369             return True;
1370          end if;
1371       end Is_Legal_Copy;
1372
1373       --------------
1374       -- Make_Var --
1375       --------------
1376
1377       function Make_Var (Actual : Node_Id) return Entity_Id is
1378          Var : Entity_Id;
1379
1380       begin
1381          if Is_Entity_Name (Actual) then
1382             return Entity (Actual);
1383
1384          else
1385             Var :=
1386               Make_Defining_Identifier (Loc,
1387                 Chars => New_Internal_Name ('T'));
1388
1389             N_Node :=
1390               Make_Object_Renaming_Declaration (Loc,
1391                 Defining_Identifier => Var,
1392                 Subtype_Mark        =>
1393                   New_Occurrence_Of (Etype (Actual), Loc),
1394                 Name                => Relocate_Node (Actual));
1395
1396             Insert_Action (N, N_Node);
1397             return Var;
1398          end if;
1399       end Make_Var;
1400
1401       -------------------------
1402       -- Reset_Packed_Prefix --
1403       -------------------------
1404
1405       procedure Reset_Packed_Prefix is
1406          Pfx : Node_Id := Actual;
1407       begin
1408          loop
1409             Set_Analyzed (Pfx, False);
1410             exit when
1411               not Nkind_In (Pfx, N_Selected_Component, N_Indexed_Component);
1412             Pfx := Prefix (Pfx);
1413          end loop;
1414       end Reset_Packed_Prefix;
1415
1416    --  Start of processing for Expand_Actuals
1417
1418    begin
1419       Post_Call := New_List;
1420
1421       Formal := First_Formal (Subp);
1422       Actual := First_Actual (N);
1423       while Present (Formal) loop
1424          E_Formal := Etype (Formal);
1425
1426          if Is_Scalar_Type (E_Formal)
1427            or else Nkind (Actual) = N_Slice
1428          then
1429             Check_Fortran_Logical;
1430
1431          --  RM 6.4.1 (11)
1432
1433          elsif Ekind (Formal) /= E_Out_Parameter then
1434
1435             --  The unusual case of the current instance of a protected type
1436             --  requires special handling. This can only occur in the context
1437             --  of a call within the body of a protected operation.
1438
1439             if Is_Entity_Name (Actual)
1440               and then Ekind (Entity (Actual)) = E_Protected_Type
1441               and then In_Open_Scopes (Entity (Actual))
1442             then
1443                if Scope (Subp) /= Entity (Actual) then
1444                   Error_Msg_N ("operation outside protected type may not "
1445                     & "call back its protected operations?", Actual);
1446                end if;
1447
1448                Rewrite (Actual,
1449                  Expand_Protected_Object_Reference (N, Entity (Actual)));
1450             end if;
1451
1452             --  Ada 2005 (AI-318-02): If the actual parameter is a call to a
1453             --  build-in-place function, then a temporary return object needs
1454             --  to be created and access to it must be passed to the function.
1455             --  Currently we limit such functions to those with inherently
1456             --  limited result subtypes, but eventually we plan to expand the
1457             --  functions that are treated as build-in-place to include other
1458             --  composite result types.
1459
1460             if Ada_Version >= Ada_05
1461               and then Is_Build_In_Place_Function_Call (Actual)
1462             then
1463                Make_Build_In_Place_Call_In_Anonymous_Context (Actual);
1464             end if;
1465
1466             Apply_Constraint_Check (Actual, E_Formal);
1467
1468          --  Out parameter case. No constraint checks on access type
1469          --  RM 6.4.1 (13)
1470
1471          elsif Is_Access_Type (E_Formal) then
1472             null;
1473
1474          --  RM 6.4.1 (14)
1475
1476          elsif Has_Discriminants (Base_Type (E_Formal))
1477            or else Has_Non_Null_Base_Init_Proc (E_Formal)
1478          then
1479             Apply_Constraint_Check (Actual, E_Formal);
1480
1481          --  RM 6.4.1 (15)
1482
1483          else
1484             Apply_Constraint_Check (Actual, Base_Type (E_Formal));
1485          end if;
1486
1487          --  Processing for IN-OUT and OUT parameters
1488
1489          if Ekind (Formal) /= E_In_Parameter then
1490
1491             --  For type conversions of arrays, apply length/range checks
1492
1493             if Is_Array_Type (E_Formal)
1494               and then Nkind (Actual) = N_Type_Conversion
1495             then
1496                if Is_Constrained (E_Formal) then
1497                   Apply_Length_Check (Expression (Actual), E_Formal);
1498                else
1499                   Apply_Range_Check (Expression (Actual), E_Formal);
1500                end if;
1501             end if;
1502
1503             --  If argument is a type conversion for a type that is passed
1504             --  by copy, then we must pass the parameter by copy.
1505
1506             if Nkind (Actual) = N_Type_Conversion
1507               and then
1508                 (Is_Numeric_Type (E_Formal)
1509                   or else Is_Access_Type (E_Formal)
1510                   or else Is_Enumeration_Type (E_Formal)
1511                   or else Is_Bit_Packed_Array (Etype (Formal))
1512                   or else Is_Bit_Packed_Array (Etype (Expression (Actual)))
1513
1514                   --  Also pass by copy if change of representation
1515
1516                   or else not Same_Representation
1517                                (Etype (Formal),
1518                                 Etype (Expression (Actual))))
1519             then
1520                Add_Call_By_Copy_Code;
1521
1522             --  References to components of bit packed arrays are expanded
1523             --  at this point, rather than at the point of analysis of the
1524             --  actuals, to handle the expansion of the assignment to
1525             --  [in] out parameters.
1526
1527             elsif Is_Ref_To_Bit_Packed_Array (Actual) then
1528                Add_Simple_Call_By_Copy_Code;
1529
1530             --  If a non-scalar actual is possibly bit-aligned, we need a copy
1531             --  because the back-end cannot cope with such objects. In other
1532             --  cases where alignment forces a copy, the back-end generates
1533             --  it properly. It should not be generated unconditionally in the
1534             --  front-end because it does not know precisely the alignment
1535             --  requirements of the target, and makes too conservative an
1536             --  estimate, leading to superfluous copies or spurious errors
1537             --  on by-reference parameters.
1538
1539             elsif Nkind (Actual) = N_Selected_Component
1540               and then
1541                 Component_May_Be_Bit_Aligned (Entity (Selector_Name (Actual)))
1542               and then not Represented_As_Scalar (Etype (Formal))
1543             then
1544                Add_Simple_Call_By_Copy_Code;
1545
1546             --  References to slices of bit packed arrays are expanded
1547
1548             elsif Is_Ref_To_Bit_Packed_Slice (Actual) then
1549                Add_Call_By_Copy_Code;
1550
1551             --  References to possibly unaligned slices of arrays are expanded
1552
1553             elsif Is_Possibly_Unaligned_Slice (Actual) then
1554                Add_Call_By_Copy_Code;
1555
1556             --  Deal with access types where the actual subtype and the
1557             --  formal subtype are not the same, requiring a check.
1558
1559             --  It is necessary to exclude tagged types because of "downward
1560             --  conversion" errors.
1561
1562             elsif Is_Access_Type (E_Formal)
1563               and then not Same_Type (E_Formal, Etype (Actual))
1564               and then not Is_Tagged_Type (Designated_Type (E_Formal))
1565             then
1566                Add_Call_By_Copy_Code;
1567
1568             --  If the actual is not a scalar and is marked for volatile
1569             --  treatment, whereas the formal is not volatile, then pass
1570             --  by copy unless it is a by-reference type.
1571
1572             elsif Is_Entity_Name (Actual)
1573               and then Treat_As_Volatile (Entity (Actual))
1574               and then not Is_By_Reference_Type (Etype (Actual))
1575               and then not Is_Scalar_Type (Etype (Entity (Actual)))
1576               and then not Treat_As_Volatile (E_Formal)
1577             then
1578                Add_Call_By_Copy_Code;
1579
1580             elsif Nkind (Actual) = N_Indexed_Component
1581               and then Is_Entity_Name (Prefix (Actual))
1582               and then Has_Volatile_Components (Entity (Prefix (Actual)))
1583             then
1584                Add_Call_By_Copy_Code;
1585             end if;
1586
1587          --  Processing for IN parameters
1588
1589          else
1590             --  For IN parameters is in the packed array case, we expand an
1591             --  indexed component (the circuit in Exp_Ch4 deliberately left
1592             --  indexed components appearing as actuals untouched, so that
1593             --  the special processing above for the OUT and IN OUT cases
1594             --  could be performed. We could make the test in Exp_Ch4 more
1595             --  complex and have it detect the parameter mode, but it is
1596             --  easier simply to handle all cases here.)
1597
1598             if Nkind (Actual) = N_Indexed_Component
1599               and then Is_Packed (Etype (Prefix (Actual)))
1600             then
1601                Reset_Packed_Prefix;
1602                Expand_Packed_Element_Reference (Actual);
1603
1604             --  If we have a reference to a bit packed array, we copy it,
1605             --  since the actual must be byte aligned.
1606
1607             --  Is this really necessary in all cases???
1608
1609             elsif Is_Ref_To_Bit_Packed_Array (Actual) then
1610                Add_Simple_Call_By_Copy_Code;
1611
1612             --  If a non-scalar actual is possibly unaligned, we need a copy
1613
1614             elsif Is_Possibly_Unaligned_Object (Actual)
1615               and then not Represented_As_Scalar (Etype (Formal))
1616             then
1617                Add_Simple_Call_By_Copy_Code;
1618
1619             --  Similarly, we have to expand slices of packed arrays here
1620             --  because the result must be byte aligned.
1621
1622             elsif Is_Ref_To_Bit_Packed_Slice (Actual) then
1623                Add_Call_By_Copy_Code;
1624
1625             --  Only processing remaining is to pass by copy if this is a
1626             --  reference to a possibly unaligned slice, since the caller
1627             --  expects an appropriately aligned argument.
1628
1629             elsif Is_Possibly_Unaligned_Slice (Actual) then
1630                Add_Call_By_Copy_Code;
1631             end if;
1632          end if;
1633
1634          Next_Formal (Formal);
1635          Next_Actual (Actual);
1636       end loop;
1637
1638       --  Find right place to put post call stuff if it is present
1639
1640       if not Is_Empty_List (Post_Call) then
1641
1642          --  If call is not a list member, it must be the triggering statement
1643          --  of a triggering alternative or an entry call alternative, and we
1644          --  can add the post call stuff to the corresponding statement list.
1645
1646          if not Is_List_Member (N) then
1647             declare
1648                P : constant Node_Id := Parent (N);
1649
1650             begin
1651                pragma Assert (Nkind_In (P, N_Triggering_Alternative,
1652                                            N_Entry_Call_Alternative));
1653
1654                if Is_Non_Empty_List (Statements (P)) then
1655                   Insert_List_Before_And_Analyze
1656                     (First (Statements (P)), Post_Call);
1657                else
1658                   Set_Statements (P, Post_Call);
1659                end if;
1660             end;
1661
1662          --  Otherwise, normal case where N is in a statement sequence,
1663          --  just put the post-call stuff after the call statement.
1664
1665          else
1666             Insert_Actions_After (N, Post_Call);
1667          end if;
1668       end if;
1669
1670       --  The call node itself is re-analyzed in Expand_Call
1671
1672    end Expand_Actuals;
1673
1674    -----------------
1675    -- Expand_Call --
1676    -----------------
1677
1678    --  This procedure handles expansion of function calls and procedure call
1679    --  statements (i.e. it serves as the body for Expand_N_Function_Call and
1680    --  Expand_N_Procedure_Call_Statement). Processing for calls includes:
1681
1682    --    Replace call to Raise_Exception by Raise_Exception_Always if possible
1683    --    Provide values of actuals for all formals in Extra_Formals list
1684    --    Replace "call" to enumeration literal function by literal itself
1685    --    Rewrite call to predefined operator as operator
1686    --    Replace actuals to in-out parameters that are numeric conversions,
1687    --     with explicit assignment to temporaries before and after the call.
1688    --    Remove optional actuals if First_Optional_Parameter specified.
1689
1690    --   Note that the list of actuals has been filled with default expressions
1691    --   during semantic analysis of the call. Only the extra actuals required
1692    --   for the 'Constrained attribute and for accessibility checks are added
1693    --   at this point.
1694
1695    procedure Expand_Call (N : Node_Id) is
1696       Loc           : constant Source_Ptr := Sloc (N);
1697       Extra_Actuals : List_Id := No_List;
1698       Prev          : Node_Id := Empty;
1699
1700       procedure Add_Actual_Parameter (Insert_Param : Node_Id);
1701       --  Adds one entry to the end of the actual parameter list. Used for
1702       --  default parameters and for extra actuals (for Extra_Formals). The
1703       --  argument is an N_Parameter_Association node.
1704
1705       procedure Add_Extra_Actual (Expr : Node_Id; EF : Entity_Id);
1706       --  Adds an extra actual to the list of extra actuals. Expr is the
1707       --  expression for the value of the actual, EF is the entity for the
1708       --  extra formal.
1709
1710       function Inherited_From_Formal (S : Entity_Id) return Entity_Id;
1711       --  Within an instance, a type derived from a non-tagged formal derived
1712       --  type inherits from the original parent, not from the actual. The
1713       --  current derivation mechanism has the derived type inherit from the
1714       --  actual, which is only correct outside of the instance. If the
1715       --  subprogram is inherited, we test for this particular case through a
1716       --  convoluted tree traversal before setting the proper subprogram to be
1717       --  called.
1718
1719       --------------------------
1720       -- Add_Actual_Parameter --
1721       --------------------------
1722
1723       procedure Add_Actual_Parameter (Insert_Param : Node_Id) is
1724          Actual_Expr : constant Node_Id :=
1725                          Explicit_Actual_Parameter (Insert_Param);
1726
1727       begin
1728          --  Case of insertion is first named actual
1729
1730          if No (Prev) or else
1731             Nkind (Parent (Prev)) /= N_Parameter_Association
1732          then
1733             Set_Next_Named_Actual (Insert_Param, First_Named_Actual (N));
1734             Set_First_Named_Actual (N, Actual_Expr);
1735
1736             if No (Prev) then
1737                if No (Parameter_Associations (N)) then
1738                   Set_Parameter_Associations (N, New_List);
1739                   Append (Insert_Param, Parameter_Associations (N));
1740                end if;
1741             else
1742                Insert_After (Prev, Insert_Param);
1743             end if;
1744
1745          --  Case of insertion is not first named actual
1746
1747          else
1748             Set_Next_Named_Actual
1749               (Insert_Param, Next_Named_Actual (Parent (Prev)));
1750             Set_Next_Named_Actual (Parent (Prev), Actual_Expr);
1751             Append (Insert_Param, Parameter_Associations (N));
1752          end if;
1753
1754          Prev := Actual_Expr;
1755       end Add_Actual_Parameter;
1756
1757       ----------------------
1758       -- Add_Extra_Actual --
1759       ----------------------
1760
1761       procedure Add_Extra_Actual (Expr : Node_Id; EF : Entity_Id) is
1762          Loc : constant Source_Ptr := Sloc (Expr);
1763
1764       begin
1765          if Extra_Actuals = No_List then
1766             Extra_Actuals := New_List;
1767             Set_Parent (Extra_Actuals, N);
1768          end if;
1769
1770          Append_To (Extra_Actuals,
1771            Make_Parameter_Association (Loc,
1772              Explicit_Actual_Parameter => Expr,
1773              Selector_Name =>
1774                Make_Identifier (Loc, Chars (EF))));
1775
1776          Analyze_And_Resolve (Expr, Etype (EF));
1777       end Add_Extra_Actual;
1778
1779       ---------------------------
1780       -- Inherited_From_Formal --
1781       ---------------------------
1782
1783       function Inherited_From_Formal (S : Entity_Id) return Entity_Id is
1784          Par      : Entity_Id;
1785          Gen_Par  : Entity_Id;
1786          Gen_Prim : Elist_Id;
1787          Elmt     : Elmt_Id;
1788          Indic    : Node_Id;
1789
1790       begin
1791          --  If the operation is inherited, it is attached to the corresponding
1792          --  type derivation. If the parent in the derivation is a generic
1793          --  actual, it is a subtype of the actual, and we have to recover the
1794          --  original derived type declaration to find the proper parent.
1795
1796          if Nkind (Parent (S)) /= N_Full_Type_Declaration
1797            or else not Is_Derived_Type (Defining_Identifier (Parent (S)))
1798            or else Nkind (Type_Definition (Original_Node (Parent (S)))) /=
1799                                                    N_Derived_Type_Definition
1800            or else not In_Instance
1801          then
1802             return Empty;
1803
1804          else
1805             Indic :=
1806               (Subtype_Indication
1807                 (Type_Definition (Original_Node (Parent (S)))));
1808
1809             if Nkind (Indic) = N_Subtype_Indication then
1810                Par := Entity (Subtype_Mark (Indic));
1811             else
1812                Par := Entity (Indic);
1813             end if;
1814          end if;
1815
1816          if not Is_Generic_Actual_Type (Par)
1817            or else Is_Tagged_Type (Par)
1818            or else Nkind (Parent (Par)) /= N_Subtype_Declaration
1819            or else not In_Open_Scopes (Scope (Par))
1820          then
1821             return Empty;
1822
1823          else
1824             Gen_Par := Generic_Parent_Type (Parent (Par));
1825          end if;
1826
1827          --  If the actual has no generic parent type, the formal is not
1828          --  a formal derived type, so nothing to inherit.
1829
1830          if No (Gen_Par) then
1831             return Empty;
1832          end if;
1833
1834          --  If the generic parent type is still the generic type, this is a
1835          --  private formal, not a derived formal, and there are no operations
1836          --  inherited from the formal.
1837
1838          if Nkind (Parent (Gen_Par)) = N_Formal_Type_Declaration then
1839             return Empty;
1840          end if;
1841
1842          Gen_Prim := Collect_Primitive_Operations (Gen_Par);
1843
1844          Elmt := First_Elmt (Gen_Prim);
1845          while Present (Elmt) loop
1846             if Chars (Node (Elmt)) = Chars (S) then
1847                declare
1848                   F1 : Entity_Id;
1849                   F2 : Entity_Id;
1850
1851                begin
1852                   F1 := First_Formal (S);
1853                   F2 := First_Formal (Node (Elmt));
1854                   while Present (F1)
1855                     and then Present (F2)
1856                   loop
1857                      if Etype (F1) = Etype (F2)
1858                        or else Etype (F2) = Gen_Par
1859                      then
1860                         Next_Formal (F1);
1861                         Next_Formal (F2);
1862                      else
1863                         Next_Elmt (Elmt);
1864                         exit;   --  not the right subprogram
1865                      end if;
1866
1867                      return Node (Elmt);
1868                   end loop;
1869                end;
1870
1871             else
1872                Next_Elmt (Elmt);
1873             end if;
1874          end loop;
1875
1876          raise Program_Error;
1877       end Inherited_From_Formal;
1878
1879       --  Local variables
1880
1881       Remote        : constant Boolean := Is_Remote_Call (N);
1882       Actual        : Node_Id;
1883       Formal        : Entity_Id;
1884       Orig_Subp     : Entity_Id := Empty;
1885       Param_Count   : Natural := 0;
1886       Parent_Formal : Entity_Id;
1887       Parent_Subp   : Entity_Id;
1888       Scop          : Entity_Id;
1889       Subp          : Entity_Id;
1890
1891       Prev_Orig     : Node_Id;
1892       --  Original node for an actual, which may have been rewritten. If the
1893       --  actual is a function call that has been transformed from a selected
1894       --  component, the original node is unanalyzed. Otherwise, it carries
1895       --  semantic information used to generate additional actuals.
1896
1897       CW_Interface_Formals_Present : Boolean := False;
1898
1899    --  Start of processing for Expand_Call
1900
1901    begin
1902       --  Ignore if previous error
1903
1904       if Nkind (N) in N_Has_Etype and then Etype (N) = Any_Type then
1905          return;
1906       end if;
1907
1908       --  Call using access to subprogram with explicit dereference
1909
1910       if Nkind (Name (N)) = N_Explicit_Dereference then
1911          Subp        := Etype (Name (N));
1912          Parent_Subp := Empty;
1913
1914       --  Case of call to simple entry, where the Name is a selected component
1915       --  whose prefix is the task, and whose selector name is the entry name
1916
1917       elsif Nkind (Name (N)) = N_Selected_Component then
1918          Subp        := Entity (Selector_Name (Name (N)));
1919          Parent_Subp := Empty;
1920
1921       --  Case of call to member of entry family, where Name is an indexed
1922       --  component, with the prefix being a selected component giving the
1923       --  task and entry family name, and the index being the entry index.
1924
1925       elsif Nkind (Name (N)) = N_Indexed_Component then
1926          Subp        := Entity (Selector_Name (Prefix (Name (N))));
1927          Parent_Subp := Empty;
1928
1929       --  Normal case
1930
1931       else
1932          Subp        := Entity (Name (N));
1933          Parent_Subp := Alias (Subp);
1934
1935          --  Replace call to Raise_Exception by call to Raise_Exception_Always
1936          --  if we can tell that the first parameter cannot possibly be null.
1937          --  This improves efficiency by avoiding a run-time test.
1938
1939          --  We do not do this if Raise_Exception_Always does not exist, which
1940          --  can happen in configurable run time profiles which provide only a
1941          --  Raise_Exception.
1942
1943          if Is_RTE (Subp, RE_Raise_Exception)
1944            and then RTE_Available (RE_Raise_Exception_Always)
1945          then
1946             declare
1947                FA : constant Node_Id := Original_Node (First_Actual (N));
1948
1949             begin
1950                --  The case we catch is where the first argument is obtained
1951                --  using the Identity attribute (which must always be
1952                --  non-null).
1953
1954                if Nkind (FA) = N_Attribute_Reference
1955                  and then Attribute_Name (FA) = Name_Identity
1956                then
1957                   Subp := RTE (RE_Raise_Exception_Always);
1958                   Set_Name (N, New_Occurrence_Of (Subp, Loc));
1959                end if;
1960             end;
1961          end if;
1962
1963          if Ekind (Subp) = E_Entry then
1964             Parent_Subp := Empty;
1965          end if;
1966       end if;
1967
1968       --  Ada 2005 (AI-345): We have a procedure call as a triggering
1969       --  alternative in an asynchronous select or as an entry call in
1970       --  a conditional or timed select. Check whether the procedure call
1971       --  is a renaming of an entry and rewrite it as an entry call.
1972
1973       if Ada_Version >= Ada_05
1974         and then Nkind (N) = N_Procedure_Call_Statement
1975         and then
1976            ((Nkind (Parent (N)) = N_Triggering_Alternative
1977                and then Triggering_Statement (Parent (N)) = N)
1978           or else
1979             (Nkind (Parent (N)) = N_Entry_Call_Alternative
1980                and then Entry_Call_Statement (Parent (N)) = N))
1981       then
1982          declare
1983             Ren_Decl : Node_Id;
1984             Ren_Root : Entity_Id := Subp;
1985
1986          begin
1987             --  This may be a chain of renamings, find the root
1988
1989             if Present (Alias (Ren_Root)) then
1990                Ren_Root := Alias (Ren_Root);
1991             end if;
1992
1993             if Present (Original_Node (Parent (Parent (Ren_Root)))) then
1994                Ren_Decl := Original_Node (Parent (Parent (Ren_Root)));
1995
1996                if Nkind (Ren_Decl) = N_Subprogram_Renaming_Declaration then
1997                   Rewrite (N,
1998                     Make_Entry_Call_Statement (Loc,
1999                       Name =>
2000                         New_Copy_Tree (Name (Ren_Decl)),
2001                       Parameter_Associations =>
2002                         New_Copy_List_Tree (Parameter_Associations (N))));
2003
2004                   return;
2005                end if;
2006             end if;
2007          end;
2008       end if;
2009
2010       --  First step, compute extra actuals, corresponding to any
2011       --  Extra_Formals present. Note that we do not access Extra_Formals
2012       --  directly, instead we simply note the presence of the extra
2013       --  formals as we process the regular formals and collect the
2014       --  corresponding actuals in Extra_Actuals.
2015
2016       --  We also generate any required range checks for actuals as we go
2017       --  through the loop, since this is a convenient place to do this.
2018
2019       Formal      := First_Formal (Subp);
2020       Actual      := First_Actual (N);
2021       Param_Count := 1;
2022       while Present (Formal) loop
2023
2024          --  Generate range check if required (not activated yet ???)
2025
2026 --         if Do_Range_Check (Actual) then
2027 --            Set_Do_Range_Check (Actual, False);
2028 --            Generate_Range_Check
2029 --              (Actual, Etype (Formal), CE_Range_Check_Failed);
2030 --         end if;
2031
2032          --  Prepare to examine current entry
2033
2034          Prev := Actual;
2035          Prev_Orig := Original_Node (Prev);
2036
2037          --  Ada 2005 (AI-251): Check if any formal is a class-wide interface
2038          --  to expand it in a further round.
2039
2040          CW_Interface_Formals_Present :=
2041            CW_Interface_Formals_Present
2042              or else
2043                (Ekind (Etype (Formal)) = E_Class_Wide_Type
2044                   and then Is_Interface (Etype (Etype (Formal))))
2045              or else
2046                (Ekind (Etype (Formal)) = E_Anonymous_Access_Type
2047                  and then Is_Interface (Directly_Designated_Type
2048                                          (Etype (Etype (Formal)))));
2049
2050          --  Create possible extra actual for constrained case. Usually, the
2051          --  extra actual is of the form actual'constrained, but since this
2052          --  attribute is only available for unconstrained records, TRUE is
2053          --  expanded if the type of the formal happens to be constrained (for
2054          --  instance when this procedure is inherited from an unconstrained
2055          --  record to a constrained one) or if the actual has no discriminant
2056          --  (its type is constrained). An exception to this is the case of a
2057          --  private type without discriminants. In this case we pass FALSE
2058          --  because the object has underlying discriminants with defaults.
2059
2060          if Present (Extra_Constrained (Formal)) then
2061             if Ekind (Etype (Prev)) in Private_Kind
2062               and then not Has_Discriminants (Base_Type (Etype (Prev)))
2063             then
2064                Add_Extra_Actual
2065                  (New_Occurrence_Of (Standard_False, Loc),
2066                   Extra_Constrained (Formal));
2067
2068             elsif Is_Constrained (Etype (Formal))
2069               or else not Has_Discriminants (Etype (Prev))
2070             then
2071                Add_Extra_Actual
2072                  (New_Occurrence_Of (Standard_True, Loc),
2073                   Extra_Constrained (Formal));
2074
2075             --  Do not produce extra actuals for Unchecked_Union parameters.
2076             --  Jump directly to the end of the loop.
2077
2078             elsif Is_Unchecked_Union (Base_Type (Etype (Actual))) then
2079                goto Skip_Extra_Actual_Generation;
2080
2081             else
2082                --  If the actual is a type conversion, then the constrained
2083                --  test applies to the actual, not the target type.
2084
2085                declare
2086                   Act_Prev : Node_Id;
2087
2088                begin
2089                   --  Test for unchecked conversions as well, which can occur
2090                   --  as out parameter actuals on calls to stream procedures.
2091
2092                   Act_Prev := Prev;
2093                   while Nkind_In (Act_Prev, N_Type_Conversion,
2094                                             N_Unchecked_Type_Conversion)
2095                   loop
2096                      Act_Prev := Expression (Act_Prev);
2097                   end loop;
2098
2099                   --  If the expression is a conversion of a dereference,
2100                   --  this is internally generated code that manipulates
2101                   --  addresses, e.g. when building interface tables. No
2102                   --  check should occur in this case, and the discriminated
2103                   --  object is not directly a hand.
2104
2105                   if not Comes_From_Source (Actual)
2106                     and then Nkind (Actual) = N_Unchecked_Type_Conversion
2107                     and then Nkind (Act_Prev) = N_Explicit_Dereference
2108                   then
2109                      Add_Extra_Actual
2110                        (New_Occurrence_Of (Standard_False, Loc),
2111                         Extra_Constrained (Formal));
2112
2113                   else
2114                      Add_Extra_Actual
2115                        (Make_Attribute_Reference (Sloc (Prev),
2116                         Prefix =>
2117                           Duplicate_Subexpr_No_Checks
2118                             (Act_Prev, Name_Req => True),
2119                         Attribute_Name => Name_Constrained),
2120                         Extra_Constrained (Formal));
2121                   end if;
2122                end;
2123             end if;
2124          end if;
2125
2126          --  Create possible extra actual for accessibility level
2127
2128          if Present (Extra_Accessibility (Formal)) then
2129
2130             --  Ada 2005 (AI-252): If the actual was rewritten as an Access
2131             --  attribute, then the original actual may be an aliased object
2132             --  occurring as the prefix in a call using "Object.Operation"
2133             --  notation. In that case we must pass the level of the object,
2134             --  so Prev_Orig is reset to Prev and the attribute will be
2135             --  processed by the code for Access attributes further below.
2136
2137             if Prev_Orig /= Prev
2138               and then Nkind (Prev) = N_Attribute_Reference
2139               and then
2140                 Get_Attribute_Id (Attribute_Name (Prev)) = Attribute_Access
2141               and then Is_Aliased_View (Prev_Orig)
2142             then
2143                Prev_Orig := Prev;
2144             end if;
2145
2146             --  Ada 2005 (AI-251): Thunks must propagate the extra actuals
2147             --  of accessibility levels.
2148
2149             if Ekind (Current_Scope) in Subprogram_Kind
2150               and then Is_Thunk (Current_Scope)
2151             then
2152                declare
2153                   Parm_Ent : Entity_Id;
2154
2155                begin
2156                   if Is_Controlling_Actual (Actual) then
2157
2158                      --  Find the corresponding actual of the thunk
2159
2160                      Parm_Ent := First_Entity (Current_Scope);
2161                      for J in 2 .. Param_Count loop
2162                         Next_Entity (Parm_Ent);
2163                      end loop;
2164
2165                   else pragma Assert (Is_Entity_Name (Actual));
2166                      Parm_Ent := Entity (Actual);
2167                   end if;
2168
2169                   Add_Extra_Actual
2170                     (New_Occurrence_Of (Extra_Accessibility (Parm_Ent), Loc),
2171                      Extra_Accessibility (Formal));
2172                end;
2173
2174             elsif Is_Entity_Name (Prev_Orig) then
2175
2176                --  When passing an access parameter, or a renaming of an access
2177                --  parameter, as the actual to another access parameter we need
2178                --  to pass along the actual's own access level parameter. This
2179                --  is done if we are within the scope of the formal access
2180                --  parameter (if this is an inlined body the extra formal is
2181                --  irrelevant).
2182
2183                if (Is_Formal (Entity (Prev_Orig))
2184                     or else
2185                       (Present (Renamed_Object (Entity (Prev_Orig)))
2186                         and then
2187                           Is_Entity_Name (Renamed_Object (Entity (Prev_Orig)))
2188                         and then
2189                           Is_Formal
2190                             (Entity (Renamed_Object (Entity (Prev_Orig))))))
2191                  and then Ekind (Etype (Prev_Orig)) = E_Anonymous_Access_Type
2192                  and then In_Open_Scopes (Scope (Entity (Prev_Orig)))
2193                then
2194                   declare
2195                      Parm_Ent : constant Entity_Id := Param_Entity (Prev_Orig);
2196
2197                   begin
2198                      pragma Assert (Present (Parm_Ent));
2199
2200                      if Present (Extra_Accessibility (Parm_Ent)) then
2201                         Add_Extra_Actual
2202                           (New_Occurrence_Of
2203                              (Extra_Accessibility (Parm_Ent), Loc),
2204                            Extra_Accessibility (Formal));
2205
2206                      --  If the actual access parameter does not have an
2207                      --  associated extra formal providing its scope level,
2208                      --  then treat the actual as having library-level
2209                      --  accessibility.
2210
2211                      else
2212                         Add_Extra_Actual
2213                           (Make_Integer_Literal (Loc,
2214                              Intval => Scope_Depth (Standard_Standard)),
2215                            Extra_Accessibility (Formal));
2216                      end if;
2217                   end;
2218
2219                --  The actual is a normal access value, so just pass the level
2220                --  of the actual's access type.
2221
2222                else
2223                   Add_Extra_Actual
2224                     (Make_Integer_Literal (Loc,
2225                        Intval => Type_Access_Level (Etype (Prev_Orig))),
2226                      Extra_Accessibility (Formal));
2227                end if;
2228
2229             --  If the actual is an access discriminant, then pass the level
2230             --  of the enclosing object (RM05-3.10.2(12.4/2)).
2231
2232             elsif Nkind (Prev_Orig) = N_Selected_Component
2233               and then Ekind (Entity (Selector_Name (Prev_Orig))) =
2234                                                        E_Discriminant
2235               and then Ekind (Etype (Entity (Selector_Name (Prev_Orig)))) =
2236                                                        E_Anonymous_Access_Type
2237             then
2238                Add_Extra_Actual
2239                  (Make_Integer_Literal (Loc,
2240                     Intval => Object_Access_Level (Prefix (Prev_Orig))),
2241                   Extra_Accessibility (Formal));
2242
2243             --  All other cases
2244
2245             else
2246                case Nkind (Prev_Orig) is
2247
2248                   when N_Attribute_Reference =>
2249                      case Get_Attribute_Id (Attribute_Name (Prev_Orig)) is
2250
2251                         --  For X'Access, pass on the level of the prefix X
2252
2253                         when Attribute_Access =>
2254                            Add_Extra_Actual
2255                              (Make_Integer_Literal (Loc,
2256                                 Intval =>
2257                                   Object_Access_Level (Prefix (Prev_Orig))),
2258                               Extra_Accessibility (Formal));
2259
2260                         --  Treat the unchecked attributes as library-level
2261
2262                         when Attribute_Unchecked_Access |
2263                            Attribute_Unrestricted_Access =>
2264                            Add_Extra_Actual
2265                              (Make_Integer_Literal (Loc,
2266                                 Intval => Scope_Depth (Standard_Standard)),
2267                               Extra_Accessibility (Formal));
2268
2269                         --  No other cases of attributes returning access
2270                         --  values that can be passed to access parameters
2271
2272                         when others =>
2273                            raise Program_Error;
2274
2275                      end case;
2276
2277                   --  For allocators we pass the level of the execution of
2278                   --  the called subprogram, which is one greater than the
2279                   --  current scope level.
2280
2281                   when N_Allocator =>
2282                      Add_Extra_Actual
2283                        (Make_Integer_Literal (Loc,
2284                           Intval => Scope_Depth (Current_Scope) + 1),
2285                         Extra_Accessibility (Formal));
2286
2287                   --  For other cases we simply pass the level of the actual's
2288                   --  access type. The type is retrieved from Prev rather than
2289                   --  Prev_Orig, because in some cases Prev_Orig denotes an
2290                   --  original expression that has not been analyzed.
2291
2292                   when others =>
2293                      Add_Extra_Actual
2294                        (Make_Integer_Literal (Loc,
2295                           Intval => Type_Access_Level (Etype (Prev))),
2296                         Extra_Accessibility (Formal));
2297
2298                end case;
2299             end if;
2300          end if;
2301
2302          --  Perform the check of 4.6(49) that prevents a null value from being
2303          --  passed as an actual to an access parameter. Note that the check is
2304          --  elided in the common cases of passing an access attribute or
2305          --  access parameter as an actual. Also, we currently don't enforce
2306          --  this check for expander-generated actuals and when -gnatdj is set.
2307
2308          if Ada_Version >= Ada_05 then
2309
2310             --  Ada 2005 (AI-231): Check null-excluding access types
2311
2312             if Is_Access_Type (Etype (Formal))
2313               and then Can_Never_Be_Null (Etype (Formal))
2314               and then Nkind (Prev) /= N_Raise_Constraint_Error
2315               and then (Known_Null (Prev)
2316                           or else not Can_Never_Be_Null (Etype (Prev)))
2317             then
2318                Install_Null_Excluding_Check (Prev);
2319             end if;
2320
2321          --  Ada_Version < Ada_05
2322
2323          else
2324             if Ekind (Etype (Formal)) /= E_Anonymous_Access_Type
2325               or else Access_Checks_Suppressed (Subp)
2326             then
2327                null;
2328
2329             elsif Debug_Flag_J then
2330                null;
2331
2332             elsif not Comes_From_Source (Prev) then
2333                null;
2334
2335             elsif Is_Entity_Name (Prev)
2336               and then Ekind (Etype (Prev)) = E_Anonymous_Access_Type
2337             then
2338                null;
2339
2340             elsif Nkind_In (Prev, N_Allocator, N_Attribute_Reference) then
2341                null;
2342
2343             --  Suppress null checks when passing to access parameters of Java
2344             --  and CIL subprograms. (Should this be done for other foreign
2345             --  conventions as well ???)
2346
2347             elsif Convention (Subp) = Convention_Java
2348               or else Convention (Subp) = Convention_CIL
2349             then
2350                null;
2351
2352             else
2353                Install_Null_Excluding_Check (Prev);
2354             end if;
2355          end if;
2356
2357          --  Perform appropriate validity checks on parameters that
2358          --  are entities.
2359
2360          if Validity_Checks_On then
2361             if  (Ekind (Formal) = E_In_Parameter
2362                    and then Validity_Check_In_Params)
2363               or else
2364                 (Ekind (Formal) = E_In_Out_Parameter
2365                    and then Validity_Check_In_Out_Params)
2366             then
2367                --  If the actual is an indexed component of a packed type (or
2368                --  is an indexed or selected component whose prefix recursively
2369                --  meets this condition), it has not been expanded yet. It will
2370                --  be copied in the validity code that follows, and has to be
2371                --  expanded appropriately, so reanalyze it.
2372
2373                --  What we do is just to unset analyzed bits on prefixes till
2374                --  we reach something that does not have a prefix.
2375
2376                declare
2377                   Nod : Node_Id;
2378
2379                begin
2380                   Nod := Actual;
2381                   while Nkind_In (Nod, N_Indexed_Component,
2382                                        N_Selected_Component)
2383                   loop
2384                      Set_Analyzed (Nod, False);
2385                      Nod := Prefix (Nod);
2386                   end loop;
2387                end;
2388
2389                Ensure_Valid (Actual);
2390             end if;
2391          end if;
2392
2393          --  For IN OUT and OUT parameters, ensure that subscripts are valid
2394          --  since this is a left side reference. We only do this for calls
2395          --  from the source program since we assume that compiler generated
2396          --  calls explicitly generate any required checks. We also need it
2397          --  only if we are doing standard validity checks, since clearly it
2398          --  is not needed if validity checks are off, and in subscript
2399          --  validity checking mode, all indexed components are checked with
2400          --  a call directly from Expand_N_Indexed_Component.
2401
2402          if Comes_From_Source (N)
2403            and then Ekind (Formal) /= E_In_Parameter
2404            and then Validity_Checks_On
2405            and then Validity_Check_Default
2406            and then not Validity_Check_Subscripts
2407          then
2408             Check_Valid_Lvalue_Subscripts (Actual);
2409          end if;
2410
2411          --  Mark any scalar OUT parameter that is a simple variable as no
2412          --  longer known to be valid (unless the type is always valid). This
2413          --  reflects the fact that if an OUT parameter is never set in a
2414          --  procedure, then it can become invalid on the procedure return.
2415
2416          if Ekind (Formal) = E_Out_Parameter
2417            and then Is_Entity_Name (Actual)
2418            and then Ekind (Entity (Actual)) = E_Variable
2419            and then not Is_Known_Valid (Etype (Actual))
2420          then
2421             Set_Is_Known_Valid (Entity (Actual), False);
2422          end if;
2423
2424          --  For an OUT or IN OUT parameter, if the actual is an entity, then
2425          --  clear current values, since they can be clobbered. We are probably
2426          --  doing this in more places than we need to, but better safe than
2427          --  sorry when it comes to retaining bad current values!
2428
2429          if Ekind (Formal) /= E_In_Parameter
2430            and then Is_Entity_Name (Actual)
2431            and then Present (Entity (Actual))
2432          then
2433             declare
2434                Ent : constant Entity_Id := Entity (Actual);
2435                Sav : Node_Id;
2436
2437             begin
2438                --  For an OUT or IN OUT parameter that is an assignable entity,
2439                --  we do not want to clobber the Last_Assignment field, since
2440                --  if it is set, it was precisely because it is indeed an OUT
2441                --  or IN OUT parameter!
2442
2443                if (Ekind (Formal) = E_Out_Parameter
2444                      or else
2445                    Ekind (Formal) = E_In_Out_Parameter)
2446                  and then Is_Assignable (Ent)
2447                then
2448                   Sav := Last_Assignment (Ent);
2449                   Kill_Current_Values (Ent);
2450                   Set_Last_Assignment (Ent, Sav);
2451
2452                   --  For all other cases, just kill the current values
2453
2454                else
2455                   Kill_Current_Values (Ent);
2456                end if;
2457             end;
2458          end if;
2459
2460          --  If the formal is class wide and the actual is an aggregate, force
2461          --  evaluation so that the back end who does not know about class-wide
2462          --  type, does not generate a temporary of the wrong size.
2463
2464          if not Is_Class_Wide_Type (Etype (Formal)) then
2465             null;
2466
2467          elsif Nkind (Actual) = N_Aggregate
2468            or else (Nkind (Actual) = N_Qualified_Expression
2469                      and then Nkind (Expression (Actual)) = N_Aggregate)
2470          then
2471             Force_Evaluation (Actual);
2472          end if;
2473
2474          --  In a remote call, if the formal is of a class-wide type, check
2475          --  that the actual meets the requirements described in E.4(18).
2476
2477          if Remote and then Is_Class_Wide_Type (Etype (Formal)) then
2478             Insert_Action (Actual,
2479               Make_Transportable_Check (Loc,
2480                 Duplicate_Subexpr_Move_Checks (Actual)));
2481          end if;
2482
2483          --  This label is required when skipping extra actual generation for
2484          --  Unchecked_Union parameters.
2485
2486          <<Skip_Extra_Actual_Generation>>
2487
2488          Param_Count := Param_Count + 1;
2489          Next_Actual (Actual);
2490          Next_Formal (Formal);
2491       end loop;
2492
2493       --  If we are expanding a rhs of an assignment we need to check if tag
2494       --  propagation is needed. You might expect this processing to be in
2495       --  Analyze_Assignment but has to be done earlier (bottom-up) because the
2496       --  assignment might be transformed to a declaration for an unconstrained
2497       --  value if the expression is classwide.
2498
2499       if Nkind (N) = N_Function_Call
2500         and then Is_Tag_Indeterminate (N)
2501         and then Is_Entity_Name (Name (N))
2502       then
2503          declare
2504             Ass : Node_Id := Empty;
2505
2506          begin
2507             if Nkind (Parent (N)) = N_Assignment_Statement then
2508                Ass := Parent (N);
2509
2510             elsif Nkind (Parent (N)) = N_Qualified_Expression
2511               and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
2512             then
2513                Ass := Parent (Parent (N));
2514
2515             elsif Nkind (Parent (N)) = N_Explicit_Dereference
2516               and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
2517             then
2518                Ass := Parent (Parent (N));
2519             end if;
2520
2521             if Present (Ass)
2522               and then Is_Class_Wide_Type (Etype (Name (Ass)))
2523             then
2524                if Is_Access_Type (Etype (N)) then
2525                   if Designated_Type (Etype (N)) /=
2526                     Root_Type (Etype (Name (Ass)))
2527                   then
2528                      Error_Msg_NE
2529                        ("tag-indeterminate expression "
2530                          & " must have designated type& (RM 5.2 (6))",
2531                            N, Root_Type (Etype (Name (Ass))));
2532                   else
2533                      Propagate_Tag (Name (Ass), N);
2534                   end if;
2535
2536                elsif Etype (N) /= Root_Type (Etype (Name (Ass))) then
2537                   Error_Msg_NE
2538                     ("tag-indeterminate expression must have type&"
2539                      & "(RM 5.2 (6))", N, Root_Type (Etype (Name (Ass))));
2540
2541                else
2542                   Propagate_Tag (Name (Ass), N);
2543                end if;
2544
2545                --  The call will be rewritten as a dispatching call, and
2546                --  expanded as such.
2547
2548                return;
2549             end if;
2550          end;
2551       end if;
2552
2553       --  Ada 2005 (AI-251): If some formal is a class-wide interface, expand
2554       --  it to point to the correct secondary virtual table
2555
2556       if Nkind_In (N, N_Function_Call, N_Procedure_Call_Statement)
2557         and then CW_Interface_Formals_Present
2558       then
2559          Expand_Interface_Actuals (N);
2560       end if;
2561
2562       --  Deals with Dispatch_Call if we still have a call, before expanding
2563       --  extra actuals since this will be done on the re-analysis of the
2564       --  dispatching call. Note that we do not try to shorten the actual
2565       --  list for a dispatching call, it would not make sense to do so.
2566       --  Expansion of dispatching calls is suppressed when VM_Target, because
2567       --  the VM back-ends directly handle the generation of dispatching
2568       --  calls and would have to undo any expansion to an indirect call.
2569
2570       if Nkind_In (N, N_Function_Call, N_Procedure_Call_Statement)
2571         and then Present (Controlling_Argument (N))
2572       then
2573          if VM_Target = No_VM then
2574             Expand_Dispatching_Call (N);
2575
2576             --  The following return is worrisome. Is it really OK to
2577             --  skip all remaining processing in this procedure ???
2578
2579             return;
2580
2581          --  Expansion of a dispatching call results in an indirect call, which
2582          --  in turn causes current values to be killed (see Resolve_Call), so
2583          --  on VM targets we do the call here to ensure consistent warnings
2584          --  between VM and non-VM targets.
2585
2586          else
2587             Kill_Current_Values;
2588          end if;
2589       end if;
2590
2591       --  Similarly, expand calls to RCI subprograms on which pragma
2592       --  All_Calls_Remote applies. The rewriting will be reanalyzed
2593       --  later. Do this only when the call comes from source since we do
2594       --  not want such a rewriting to occur in expanded code.
2595
2596       if Is_All_Remote_Call (N) then
2597          Expand_All_Calls_Remote_Subprogram_Call (N);
2598
2599       --  Similarly, do not add extra actuals for an entry call whose entity
2600       --  is a protected procedure, or for an internal protected subprogram
2601       --  call, because it will be rewritten as a protected subprogram call
2602       --  and reanalyzed (see Expand_Protected_Subprogram_Call).
2603
2604       elsif Is_Protected_Type (Scope (Subp))
2605          and then (Ekind (Subp) = E_Procedure
2606                     or else Ekind (Subp) = E_Function)
2607       then
2608          null;
2609
2610       --  During that loop we gathered the extra actuals (the ones that
2611       --  correspond to Extra_Formals), so now they can be appended.
2612
2613       else
2614          while Is_Non_Empty_List (Extra_Actuals) loop
2615             Add_Actual_Parameter (Remove_Head (Extra_Actuals));
2616          end loop;
2617       end if;
2618
2619       --  At this point we have all the actuals, so this is the point at
2620       --  which the various expansion activities for actuals is carried out.
2621
2622       Expand_Actuals (N, Subp);
2623
2624       --  If the subprogram is a renaming, or if it is inherited, replace it
2625       --  in the call with the name of the actual subprogram being called.
2626       --  If this is a dispatching call, the run-time decides what to call.
2627       --  The Alias attribute does not apply to entries.
2628
2629       if Nkind (N) /= N_Entry_Call_Statement
2630         and then No (Controlling_Argument (N))
2631         and then Present (Parent_Subp)
2632       then
2633          if Present (Inherited_From_Formal (Subp)) then
2634             Parent_Subp := Inherited_From_Formal (Subp);
2635          else
2636             while Present (Alias (Parent_Subp)) loop
2637                Parent_Subp := Alias (Parent_Subp);
2638             end loop;
2639          end if;
2640
2641          --  The below setting of Entity is suspect, see F109-018 discussion???
2642
2643          Set_Entity (Name (N), Parent_Subp);
2644
2645          if Is_Abstract_Subprogram (Parent_Subp)
2646            and then not In_Instance
2647          then
2648             Error_Msg_NE
2649               ("cannot call abstract subprogram &!", Name (N), Parent_Subp);
2650          end if;
2651
2652          --  Inspect all formals of derived subprogram Subp. Compare parameter
2653          --  types with the parent subprogram and check whether an actual may
2654          --  need a type conversion to the corresponding formal of the parent
2655          --  subprogram.
2656
2657          --  Not clear whether intrinsic subprograms need such conversions. ???
2658
2659          if not Is_Intrinsic_Subprogram (Parent_Subp)
2660            or else Is_Generic_Instance (Parent_Subp)
2661          then
2662             declare
2663                procedure Convert (Act : Node_Id; Typ : Entity_Id);
2664                --  Rewrite node Act as a type conversion of Act to Typ. Analyze
2665                --  and resolve the newly generated construct.
2666
2667                -------------
2668                -- Convert --
2669                -------------
2670
2671                procedure Convert (Act : Node_Id; Typ : Entity_Id) is
2672                begin
2673                   Rewrite (Act, OK_Convert_To (Typ, Relocate_Node (Act)));
2674                   Analyze (Act);
2675                   Resolve (Act, Typ);
2676                end Convert;
2677
2678                --  Local variables
2679
2680                Actual_Typ : Entity_Id;
2681                Formal_Typ : Entity_Id;
2682                Parent_Typ : Entity_Id;
2683
2684             begin
2685                Actual := First_Actual (N);
2686                Formal := First_Formal (Subp);
2687                Parent_Formal := First_Formal (Parent_Subp);
2688                while Present (Formal) loop
2689                   Actual_Typ := Etype (Actual);
2690                   Formal_Typ := Etype (Formal);
2691                   Parent_Typ := Etype (Parent_Formal);
2692
2693                   --  For an IN parameter of a scalar type, the parent formal
2694                   --  type and derived formal type differ or the parent formal
2695                   --  type and actual type do not match statically.
2696
2697                   if Is_Scalar_Type (Formal_Typ)
2698                     and then Ekind (Formal) = E_In_Parameter
2699                     and then Formal_Typ /= Parent_Typ
2700                     and then
2701                       not Subtypes_Statically_Match (Parent_Typ, Actual_Typ)
2702                     and then not Raises_Constraint_Error (Actual)
2703                   then
2704                      Convert (Actual, Parent_Typ);
2705                      Enable_Range_Check (Actual);
2706
2707                   --  For access types, the parent formal type and actual type
2708                   --  differ.
2709
2710                   elsif Is_Access_Type (Formal_Typ)
2711                     and then Base_Type (Parent_Typ) /= Base_Type (Actual_Typ)
2712                   then
2713                      if Ekind (Formal) /= E_In_Parameter then
2714                         Convert (Actual, Parent_Typ);
2715
2716                      elsif Ekind (Parent_Typ) = E_Anonymous_Access_Type
2717                        and then Designated_Type (Parent_Typ) /=
2718                                 Designated_Type (Actual_Typ)
2719                        and then not Is_Controlling_Formal (Formal)
2720                      then
2721                         --  This unchecked conversion is not necessary unless
2722                         --  inlining is enabled, because in that case the type
2723                         --  mismatch may become visible in the body about to be
2724                         --  inlined.
2725
2726                         Rewrite (Actual,
2727                           Unchecked_Convert_To (Parent_Typ,
2728                             Relocate_Node (Actual)));
2729
2730                         Analyze (Actual);
2731                         Resolve (Actual, Parent_Typ);
2732                      end if;
2733
2734                   --  For array and record types, the parent formal type and
2735                   --  derived formal type have different sizes or pragma Pack
2736                   --  status.
2737
2738                   elsif ((Is_Array_Type (Formal_Typ)
2739                             and then Is_Array_Type (Parent_Typ))
2740                        or else
2741                          (Is_Record_Type (Formal_Typ)
2742                             and then Is_Record_Type (Parent_Typ)))
2743                     and then
2744                       (Esize (Formal_Typ) /= Esize (Parent_Typ)
2745                          or else Has_Pragma_Pack (Formal_Typ) /=
2746                                  Has_Pragma_Pack (Parent_Typ))
2747                   then
2748                      Convert (Actual, Parent_Typ);
2749                   end if;
2750
2751                   Next_Actual (Actual);
2752                   Next_Formal (Formal);
2753                   Next_Formal (Parent_Formal);
2754                end loop;
2755             end;
2756          end if;
2757
2758          Orig_Subp := Subp;
2759          Subp := Parent_Subp;
2760       end if;
2761
2762       --  Check for violation of No_Abort_Statements
2763
2764       if Is_RTE (Subp, RE_Abort_Task) then
2765          Check_Restriction (No_Abort_Statements, N);
2766
2767       --  Check for violation of No_Dynamic_Attachment
2768
2769       elsif RTU_Loaded (Ada_Interrupts)
2770         and then (Is_RTE (Subp, RE_Is_Reserved)      or else
2771                   Is_RTE (Subp, RE_Is_Attached)      or else
2772                   Is_RTE (Subp, RE_Current_Handler)  or else
2773                   Is_RTE (Subp, RE_Attach_Handler)   or else
2774                   Is_RTE (Subp, RE_Exchange_Handler) or else
2775                   Is_RTE (Subp, RE_Detach_Handler)   or else
2776                   Is_RTE (Subp, RE_Reference))
2777       then
2778          Check_Restriction (No_Dynamic_Attachment, N);
2779       end if;
2780
2781       --  Deal with case where call is an explicit dereference
2782
2783       if Nkind (Name (N)) = N_Explicit_Dereference then
2784
2785       --  Handle case of access to protected subprogram type
2786
2787          if Is_Access_Protected_Subprogram_Type
2788               (Base_Type (Etype (Prefix (Name (N)))))
2789          then
2790             --  If this is a call through an access to protected operation,
2791             --  the prefix has the form (object'address, operation'access).
2792             --  Rewrite as a for other protected calls: the object is the
2793             --  first parameter of the list of actuals.
2794
2795             declare
2796                Call : Node_Id;
2797                Parm : List_Id;
2798                Nam  : Node_Id;
2799                Obj  : Node_Id;
2800                Ptr  : constant Node_Id := Prefix (Name (N));
2801
2802                T : constant Entity_Id :=
2803                      Equivalent_Type (Base_Type (Etype (Ptr)));
2804
2805                D_T : constant Entity_Id :=
2806                        Designated_Type (Base_Type (Etype (Ptr)));
2807
2808             begin
2809                Obj :=
2810                  Make_Selected_Component (Loc,
2811                    Prefix        => Unchecked_Convert_To (T, Ptr),
2812                    Selector_Name =>
2813                      New_Occurrence_Of (First_Entity (T), Loc));
2814
2815                Nam :=
2816                  Make_Selected_Component (Loc,
2817                    Prefix        => Unchecked_Convert_To (T, Ptr),
2818                    Selector_Name =>
2819                      New_Occurrence_Of (Next_Entity (First_Entity (T)), Loc));
2820
2821                Nam :=
2822                  Make_Explicit_Dereference (Loc,
2823                    Prefix => Nam);
2824
2825                if Present (Parameter_Associations (N))  then
2826                   Parm := Parameter_Associations (N);
2827                else
2828                   Parm := New_List;
2829                end if;
2830
2831                Prepend (Obj, Parm);
2832
2833                if Etype (D_T) = Standard_Void_Type then
2834                   Call :=
2835                     Make_Procedure_Call_Statement (Loc,
2836                       Name                   => Nam,
2837                       Parameter_Associations => Parm);
2838                else
2839                   Call :=
2840                     Make_Function_Call (Loc,
2841                       Name                   => Nam,
2842                       Parameter_Associations => Parm);
2843                end if;
2844
2845                Set_First_Named_Actual (Call, First_Named_Actual (N));
2846                Set_Etype (Call, Etype (D_T));
2847
2848                --  We do not re-analyze the call to avoid infinite recursion.
2849                --  We analyze separately the prefix and the object, and set
2850                --  the checks on the prefix that would otherwise be emitted
2851                --  when resolving a call.
2852
2853                Rewrite (N, Call);
2854                Analyze (Nam);
2855                Apply_Access_Check (Nam);
2856                Analyze (Obj);
2857                return;
2858             end;
2859          end if;
2860       end if;
2861
2862       --  If this is a call to an intrinsic subprogram, then perform the
2863       --  appropriate expansion to the corresponding tree node and we
2864       --  are all done (since after that the call is gone!)
2865
2866       --  In the case where the intrinsic is to be processed by the back end,
2867       --  the call to Expand_Intrinsic_Call will do nothing, which is fine,
2868       --  since the idea in this case is to pass the call unchanged.
2869       --  If the intrinsic is an inherited unchecked conversion, and the
2870       --  derived type is the target type of the conversion, we must retain
2871       --  it as the return type of the expression. Otherwise the expansion
2872       --  below, which uses the parent operation, will yield the wrong type.
2873
2874       if Is_Intrinsic_Subprogram (Subp) then
2875          Expand_Intrinsic_Call (N, Subp);
2876
2877          if Nkind (N) = N_Unchecked_Type_Conversion
2878            and then Parent_Subp /= Orig_Subp
2879            and then Etype (Parent_Subp) /= Etype (Orig_Subp)
2880          then
2881             Set_Etype (N, Etype (Orig_Subp));
2882          end if;
2883
2884          return;
2885       end if;
2886
2887       if Ekind (Subp) = E_Function
2888         or else Ekind (Subp) = E_Procedure
2889       then
2890          if Is_Inlined (Subp) then
2891
2892             Inlined_Subprogram : declare
2893                Bod         : Node_Id;
2894                Must_Inline : Boolean := False;
2895                Spec        : constant Node_Id := Unit_Declaration_Node (Subp);
2896                Scop        : constant Entity_Id := Scope (Subp);
2897
2898                function In_Unfrozen_Instance return Boolean;
2899                --  If the subprogram comes from an instance in the same
2900                --  unit, and the instance is not yet frozen, inlining might
2901                --  trigger order-of-elaboration problems in gigi.
2902
2903                --------------------------
2904                -- In_Unfrozen_Instance --
2905                --------------------------
2906
2907                function In_Unfrozen_Instance return Boolean is
2908                   S : Entity_Id;
2909
2910                begin
2911                   S := Scop;
2912                   while Present (S)
2913                     and then S /= Standard_Standard
2914                   loop
2915                      if Is_Generic_Instance (S)
2916                        and then Present (Freeze_Node (S))
2917                        and then not Analyzed (Freeze_Node (S))
2918                      then
2919                         return True;
2920                      end if;
2921
2922                      S := Scope (S);
2923                   end loop;
2924
2925                   return False;
2926                end In_Unfrozen_Instance;
2927
2928             --  Start of processing for Inlined_Subprogram
2929
2930             begin
2931                --  Verify that the body to inline has already been seen, and
2932                --  that if the body is in the current unit the inlining does
2933                --  not occur earlier. This avoids order-of-elaboration problems
2934                --  in the back end.
2935
2936                --  This should be documented in sinfo/einfo ???
2937
2938                if No (Spec)
2939                  or else Nkind (Spec) /= N_Subprogram_Declaration
2940                  or else No (Body_To_Inline (Spec))
2941                then
2942                   Must_Inline := False;
2943
2944                --  If this an inherited function that returns a private
2945                --  type, do not inline if the full view is an unconstrained
2946                --  array, because such calls cannot be inlined.
2947
2948                elsif Present (Orig_Subp)
2949                  and then Is_Array_Type (Etype (Orig_Subp))
2950                  and then not Is_Constrained (Etype (Orig_Subp))
2951                then
2952                   Must_Inline := False;
2953
2954                elsif In_Unfrozen_Instance then
2955                   Must_Inline := False;
2956
2957                else
2958                   Bod := Body_To_Inline (Spec);
2959
2960                   if (In_Extended_Main_Code_Unit (N)
2961                         or else In_Extended_Main_Code_Unit (Parent (N))
2962                         or else Has_Pragma_Inline_Always (Subp))
2963                     and then (not In_Same_Extended_Unit (Sloc (Bod), Loc)
2964                                or else
2965                                  Earlier_In_Extended_Unit (Sloc (Bod), Loc))
2966                   then
2967                      Must_Inline := True;
2968
2969                   --  If we are compiling a package body that is not the main
2970                   --  unit, it must be for inlining/instantiation purposes,
2971                   --  in which case we inline the call to insure that the same
2972                   --  temporaries are generated when compiling the body by
2973                   --  itself. Otherwise link errors can occur.
2974
2975                   --  If the function being called is itself in the main unit,
2976                   --  we cannot inline, because there is a risk of double
2977                   --  elaboration and/or circularity: the inlining can make
2978                   --  visible a private entity in the body of the main unit,
2979                   --  that gigi will see before its sees its proper definition.
2980
2981                   elsif not (In_Extended_Main_Code_Unit (N))
2982                     and then In_Package_Body
2983                   then
2984                      Must_Inline := not In_Extended_Main_Source_Unit (Subp);
2985                   end if;
2986                end if;
2987
2988                if Must_Inline then
2989                   Expand_Inlined_Call (N, Subp, Orig_Subp);
2990
2991                else
2992                   --  Let the back end handle it
2993
2994                   Add_Inlined_Body (Subp);
2995
2996                   if Front_End_Inlining
2997                     and then Nkind (Spec) = N_Subprogram_Declaration
2998                     and then (In_Extended_Main_Code_Unit (N))
2999                     and then No (Body_To_Inline (Spec))
3000                     and then not Has_Completion (Subp)
3001                     and then In_Same_Extended_Unit (Sloc (Spec), Loc)
3002                   then
3003                      Cannot_Inline
3004                       ("cannot inline& (body not seen yet)?",
3005                        N, Subp);
3006                   end if;
3007                end if;
3008             end Inlined_Subprogram;
3009          end if;
3010       end if;
3011
3012       --  Check for a protected subprogram. This is either an intra-object
3013       --  call, or a protected function call. Protected procedure calls are
3014       --  rewritten as entry calls and handled accordingly.
3015
3016       --  In Ada 2005, this may be an indirect call to an access parameter
3017       --  that is an access_to_subprogram. In that case the anonymous type
3018       --  has a scope that is a protected operation, but the call is a
3019       --  regular one.
3020
3021       Scop := Scope (Subp);
3022
3023       if Nkind (N) /= N_Entry_Call_Statement
3024         and then Is_Protected_Type (Scop)
3025         and then Ekind (Subp) /= E_Subprogram_Type
3026       then
3027          --  If the call is an internal one, it is rewritten as a call to
3028          --  to the corresponding unprotected subprogram.
3029
3030          Expand_Protected_Subprogram_Call (N, Subp, Scop);
3031       end if;
3032
3033       --  Functions returning controlled objects need special attention
3034       --  If the return type is limited the context is an initialization
3035       --  and different processing applies.
3036
3037       if Needs_Finalization (Etype (Subp))
3038         and then not Is_Inherently_Limited_Type (Etype (Subp))
3039         and then not Is_Limited_Interface (Etype (Subp))
3040       then
3041          Expand_Ctrl_Function_Call (N);
3042       end if;
3043
3044       --  Test for First_Optional_Parameter, and if so, truncate parameter
3045       --  list if there are optional parameters at the trailing end.
3046       --  Note we never delete procedures for call via a pointer.
3047
3048       if (Ekind (Subp) = E_Procedure or else Ekind (Subp) = E_Function)
3049         and then Present (First_Optional_Parameter (Subp))
3050       then
3051          declare
3052             Last_Keep_Arg : Node_Id;
3053
3054          begin
3055             --  Last_Keep_Arg will hold the last actual that should be
3056             --  retained. If it remains empty at the end, it means that
3057             --  all parameters are optional.
3058
3059             Last_Keep_Arg := Empty;
3060
3061             --  Find first optional parameter, must be present since we
3062             --  checked the validity of the parameter before setting it.
3063
3064             Formal := First_Formal (Subp);
3065             Actual := First_Actual (N);
3066             while Formal /= First_Optional_Parameter (Subp) loop
3067                Last_Keep_Arg := Actual;
3068                Next_Formal (Formal);
3069                Next_Actual (Actual);
3070             end loop;
3071
3072             --  We have Formal and Actual pointing to the first potentially
3073             --  droppable argument. We can drop all the trailing arguments
3074             --  whose actual matches the default. Note that we know that all
3075             --  remaining formals have defaults, because we checked that this
3076             --  requirement was met before setting First_Optional_Parameter.
3077
3078             --  We use Fully_Conformant_Expressions to check for identity
3079             --  between formals and actuals, which may miss some cases, but
3080             --  on the other hand, this is only an optimization (if we fail
3081             --  to truncate a parameter it does not affect functionality).
3082             --  So if the default is 3 and the actual is 1+2, we consider
3083             --  them unequal, which hardly seems worrisome.
3084
3085             while Present (Formal) loop
3086                if not Fully_Conformant_Expressions
3087                     (Actual, Default_Value (Formal))
3088                then
3089                   Last_Keep_Arg := Actual;
3090                end if;
3091
3092                Next_Formal (Formal);
3093                Next_Actual (Actual);
3094             end loop;
3095
3096             --  If no arguments, delete entire list, this is the easy case
3097
3098             if No (Last_Keep_Arg) then
3099                Set_Parameter_Associations (N, No_List);
3100                Set_First_Named_Actual (N, Empty);
3101
3102             --  Case where at the last retained argument is positional. This
3103             --  is also an easy case, since the retained arguments are already
3104             --  in the right form, and we don't need to worry about the order
3105             --  of arguments that get eliminated.
3106
3107             elsif Is_List_Member (Last_Keep_Arg) then
3108                while Present (Next (Last_Keep_Arg)) loop
3109                   Discard_Node (Remove_Next (Last_Keep_Arg));
3110                end loop;
3111
3112                Set_First_Named_Actual (N, Empty);
3113
3114             --  This is the annoying case where the last retained argument
3115             --  is a named parameter. Since the original arguments are not
3116             --  in declaration order, we may have to delete some fairly
3117             --  random collection of arguments.
3118
3119             else
3120                declare
3121                   Temp   : Node_Id;
3122                   Passoc : Node_Id;
3123
3124                begin
3125                   --  First step, remove all the named parameters from the
3126                   --  list (they are still chained using First_Named_Actual
3127                   --  and Next_Named_Actual, so we have not lost them!)
3128
3129                   Temp := First (Parameter_Associations (N));
3130
3131                   --  Case of all parameters named, remove them all
3132
3133                   if Nkind (Temp) = N_Parameter_Association then
3134                      while Is_Non_Empty_List (Parameter_Associations (N)) loop
3135                         Temp := Remove_Head (Parameter_Associations (N));
3136                      end loop;
3137
3138                   --  Case of mixed positional/named, remove named parameters
3139
3140                   else
3141                      while Nkind (Next (Temp)) /= N_Parameter_Association loop
3142                         Next (Temp);
3143                      end loop;
3144
3145                      while Present (Next (Temp)) loop
3146                         Remove (Next (Temp));
3147                      end loop;
3148                   end if;
3149
3150                   --  Now we loop through the named parameters, till we get
3151                   --  to the last one to be retained, adding them to the list.
3152                   --  Note that the Next_Named_Actual list does not need to be
3153                   --  touched since we are only reordering them on the actual
3154                   --  parameter association list.
3155
3156                   Passoc := Parent (First_Named_Actual (N));
3157                   loop
3158                      Temp := Relocate_Node (Passoc);
3159                      Append_To
3160                        (Parameter_Associations (N), Temp);
3161                      exit when
3162                        Last_Keep_Arg = Explicit_Actual_Parameter (Passoc);
3163                      Passoc := Parent (Next_Named_Actual (Passoc));
3164                   end loop;
3165
3166                   Set_Next_Named_Actual (Temp, Empty);
3167
3168                   loop
3169                      Temp := Next_Named_Actual (Passoc);
3170                      exit when No (Temp);
3171                      Set_Next_Named_Actual
3172                        (Passoc, Next_Named_Actual (Parent (Temp)));
3173                   end loop;
3174                end;
3175             end if;
3176          end;
3177       end if;
3178    end Expand_Call;
3179
3180    --------------------------
3181    -- Expand_Inlined_Call --
3182    --------------------------
3183
3184    procedure Expand_Inlined_Call
3185     (N         : Node_Id;
3186      Subp      : Entity_Id;
3187      Orig_Subp : Entity_Id)
3188    is
3189       Loc       : constant Source_Ptr := Sloc (N);
3190       Is_Predef : constant Boolean :=
3191                    Is_Predefined_File_Name
3192                      (Unit_File_Name (Get_Source_Unit (Subp)));
3193       Orig_Bod  : constant Node_Id :=
3194                     Body_To_Inline (Unit_Declaration_Node (Subp));
3195
3196       Blk      : Node_Id;
3197       Bod      : Node_Id;
3198       Decl     : Node_Id;
3199       Decls    : constant List_Id := New_List;
3200       Exit_Lab : Entity_Id := Empty;
3201       F        : Entity_Id;
3202       A        : Node_Id;
3203       Lab_Decl : Node_Id;
3204       Lab_Id   : Node_Id;
3205       New_A    : Node_Id;
3206       Num_Ret  : Int := 0;
3207       Ret_Type : Entity_Id;
3208       Targ     : Node_Id;
3209       Targ1    : Node_Id;
3210       Temp     : Entity_Id;
3211       Temp_Typ : Entity_Id;
3212
3213       Is_Unc : constant Boolean :=
3214                     Is_Array_Type (Etype (Subp))
3215                       and then not Is_Constrained (Etype (Subp));
3216       --  If the type returned by the function is unconstrained and the
3217       --  call can be inlined, special processing is required.
3218
3219       function Is_Null_Procedure return Boolean;
3220       --  Predicate to recognize stubbed procedures and null procedures, for
3221       --  which there is no need for the full inlining mechanism.
3222
3223       procedure Make_Exit_Label;
3224       --  Build declaration for exit label to be used in Return statements
3225
3226       function Process_Formals (N : Node_Id) return Traverse_Result;
3227       --  Replace occurrence of a formal with the corresponding actual, or
3228       --  the thunk generated for it.
3229
3230       function Process_Sloc (Nod : Node_Id) return Traverse_Result;
3231       --  If the call being expanded is that of an internal subprogram,
3232       --  set the sloc of the generated block to that of the call itself,
3233       --  so that the expansion is skipped by the -next- command in gdb.
3234       --  Same processing for a subprogram in a predefined file, e.g.
3235       --  Ada.Tags. If Debug_Generated_Code is true, suppress this change
3236       --  to simplify our own development.
3237
3238       procedure Rewrite_Function_Call (N : Node_Id; Blk : Node_Id);
3239       --  If the function body is a single expression, replace call with
3240       --  expression, else insert block appropriately.
3241
3242       procedure Rewrite_Procedure_Call (N : Node_Id; Blk : Node_Id);
3243       --  If procedure body has no local variables, inline body without
3244       --  creating block, otherwise rewrite call with block.
3245
3246       function Formal_Is_Used_Once (Formal : Entity_Id) return Boolean;
3247       --  Determine whether a formal parameter is used only once in Orig_Bod
3248
3249       -----------------------
3250       -- Is_Null_Procedure --
3251       -----------------------
3252
3253       function Is_Null_Procedure return Boolean is
3254          Decl : constant Node_Id := Unit_Declaration_Node (Subp);
3255
3256       begin
3257          if Ekind (Subp) /= E_Procedure then
3258             return False;
3259
3260          elsif Nkind (Orig_Bod) /= N_Subprogram_Body then
3261             return False;
3262
3263          --  Check if this is an Ada 2005 null procedure
3264
3265          elsif Nkind (Decl) = N_Subprogram_Declaration
3266            and then Null_Present (Specification (Decl))
3267          then
3268             return True;
3269
3270          --  Check if the body contains only a null statement, followed by the
3271          --  return statement added during expansion.
3272
3273          else
3274             declare
3275                Stat : constant Node_Id :=
3276                         First
3277                           (Statements (Handled_Statement_Sequence (Orig_Bod)));
3278
3279                Stat2 : constant Node_Id := Next (Stat);
3280
3281             begin
3282                return
3283                  Nkind (Stat) = N_Null_Statement
3284                    and then
3285                      (No (Stat2)
3286                        or else
3287                          (Nkind (Stat2) = N_Simple_Return_Statement
3288                            and then No (Next (Stat2))));
3289             end;
3290          end if;
3291       end Is_Null_Procedure;
3292
3293       ---------------------
3294       -- Make_Exit_Label --
3295       ---------------------
3296
3297       procedure Make_Exit_Label is
3298       begin
3299          --  Create exit label for subprogram if one does not exist yet
3300
3301          if No (Exit_Lab) then
3302             Lab_Id :=
3303               Make_Identifier (Loc,
3304                 Chars => New_Internal_Name ('L'));
3305             Set_Entity (Lab_Id,
3306               Make_Defining_Identifier (Loc, Chars (Lab_Id)));
3307             Exit_Lab := Make_Label (Loc, Lab_Id);
3308
3309             Lab_Decl :=
3310               Make_Implicit_Label_Declaration (Loc,
3311                 Defining_Identifier  => Entity (Lab_Id),
3312                 Label_Construct      => Exit_Lab);
3313          end if;
3314       end Make_Exit_Label;
3315
3316       ---------------------
3317       -- Process_Formals --
3318       ---------------------
3319
3320       function Process_Formals (N : Node_Id) return Traverse_Result is
3321          A   : Entity_Id;
3322          E   : Entity_Id;
3323          Ret : Node_Id;
3324
3325       begin
3326          if Is_Entity_Name (N)
3327            and then Present (Entity (N))
3328          then
3329             E := Entity (N);
3330
3331             if Is_Formal (E)
3332               and then Scope (E) = Subp
3333             then
3334                A := Renamed_Object (E);
3335
3336                --  Rewrite the occurrence of the formal into an occurrence of
3337                --  the actual. Also establish visibility on the proper view of
3338                --  the actual's subtype for the body's context (if the actual's
3339                --  subtype is private at the call point but its full view is
3340                --  visible to the body, then the inlined tree here must be
3341                --  analyzed with the full view).
3342
3343                if Is_Entity_Name (A) then
3344                   Rewrite (N, New_Occurrence_Of (Entity (A), Loc));
3345                   Check_Private_View (N);
3346
3347                elsif Nkind (A) = N_Defining_Identifier then
3348                   Rewrite (N, New_Occurrence_Of (A, Loc));
3349                   Check_Private_View (N);
3350
3351                --  Numeric literal
3352
3353                else
3354                   Rewrite (N, New_Copy (A));
3355                end if;
3356             end if;
3357
3358             return Skip;
3359
3360          elsif Nkind (N) = N_Simple_Return_Statement then
3361             if No (Expression (N)) then
3362                Make_Exit_Label;
3363                Rewrite (N,
3364                  Make_Goto_Statement (Loc,
3365                    Name => New_Copy (Lab_Id)));
3366
3367             else
3368                if Nkind (Parent (N)) = N_Handled_Sequence_Of_Statements
3369                  and then Nkind (Parent (Parent (N))) = N_Subprogram_Body
3370                then
3371                   --  Function body is a single expression. No need for
3372                   --  exit label.
3373
3374                   null;
3375
3376                else
3377                   Num_Ret := Num_Ret + 1;
3378                   Make_Exit_Label;
3379                end if;
3380
3381                --  Because of the presence of private types, the views of the
3382                --  expression and the context may be different, so place an
3383                --  unchecked conversion to the context type to avoid spurious
3384                --  errors, e.g. when the expression is a numeric literal and
3385                --  the context is private. If the expression is an aggregate,
3386                --  use a qualified expression, because an aggregate is not a
3387                --  legal argument of a conversion.
3388
3389                if Nkind_In (Expression (N), N_Aggregate, N_Null) then
3390                   Ret :=
3391                     Make_Qualified_Expression (Sloc (N),
3392                        Subtype_Mark => New_Occurrence_Of (Ret_Type, Sloc (N)),
3393                        Expression => Relocate_Node (Expression (N)));
3394                else
3395                   Ret :=
3396                     Unchecked_Convert_To
3397                       (Ret_Type, Relocate_Node (Expression (N)));
3398                end if;
3399
3400                if Nkind (Targ) = N_Defining_Identifier then
3401                   Rewrite (N,
3402                     Make_Assignment_Statement (Loc,
3403                       Name => New_Occurrence_Of (Targ, Loc),
3404                       Expression => Ret));
3405                else
3406                   Rewrite (N,
3407                     Make_Assignment_Statement (Loc,
3408                       Name => New_Copy (Targ),
3409                       Expression => Ret));
3410                end if;
3411
3412                Set_Assignment_OK (Name (N));
3413
3414                if Present (Exit_Lab) then
3415                   Insert_After (N,
3416                     Make_Goto_Statement (Loc,
3417                       Name => New_Copy (Lab_Id)));
3418                end if;
3419             end if;
3420
3421             return OK;
3422
3423          --  Remove pragma Unreferenced since it may refer to formals that
3424          --  are not visible in the inlined body, and in any case we will
3425          --  not be posting warnings on the inlined body so it is unneeded.
3426
3427          elsif Nkind (N) = N_Pragma
3428            and then Pragma_Name (N) = Name_Unreferenced
3429          then
3430             Rewrite (N, Make_Null_Statement (Sloc (N)));
3431             return OK;
3432
3433          else
3434             return OK;
3435          end if;
3436       end Process_Formals;
3437
3438       procedure Replace_Formals is new Traverse_Proc (Process_Formals);
3439
3440       ------------------
3441       -- Process_Sloc --
3442       ------------------
3443
3444       function Process_Sloc (Nod : Node_Id) return Traverse_Result is
3445       begin
3446          if not Debug_Generated_Code then
3447             Set_Sloc (Nod, Sloc (N));
3448             Set_Comes_From_Source (Nod, False);
3449          end if;
3450
3451          return OK;
3452       end Process_Sloc;
3453
3454       procedure Reset_Slocs is new Traverse_Proc (Process_Sloc);
3455
3456       ---------------------------
3457       -- Rewrite_Function_Call --
3458       ---------------------------
3459
3460       procedure Rewrite_Function_Call (N : Node_Id; Blk : Node_Id) is
3461          HSS : constant Node_Id := Handled_Statement_Sequence (Blk);
3462          Fst : constant Node_Id := First (Statements (HSS));
3463
3464       begin
3465          --  Optimize simple case: function body is a single return statement,
3466          --  which has been expanded into an assignment.
3467
3468          if Is_Empty_List (Declarations (Blk))
3469            and then Nkind (Fst) = N_Assignment_Statement
3470            and then No (Next (Fst))
3471          then
3472
3473             --  The function call may have been rewritten as the temporary
3474             --  that holds the result of the call, in which case remove the
3475             --  now useless declaration.
3476
3477             if Nkind (N) = N_Identifier
3478               and then Nkind (Parent (Entity (N))) = N_Object_Declaration
3479             then
3480                Rewrite (Parent (Entity (N)), Make_Null_Statement (Loc));
3481             end if;
3482
3483             Rewrite (N, Expression (Fst));
3484
3485          elsif Nkind (N) = N_Identifier
3486            and then Nkind (Parent (Entity (N))) = N_Object_Declaration
3487          then
3488             --  The block assigns the result of the call to the temporary
3489
3490             Insert_After (Parent (Entity (N)), Blk);
3491
3492          elsif Nkind (Parent (N)) = N_Assignment_Statement
3493            and then
3494             (Is_Entity_Name (Name (Parent (N)))
3495                or else
3496                   (Nkind (Name (Parent (N))) = N_Explicit_Dereference
3497                     and then Is_Entity_Name (Prefix (Name (Parent (N))))))
3498          then
3499             --  Replace assignment with the block
3500
3501             declare
3502                Original_Assignment : constant Node_Id := Parent (N);
3503
3504             begin
3505                --  Preserve the original assignment node to keep the complete
3506                --  assignment subtree consistent enough for Analyze_Assignment
3507                --  to proceed (specifically, the original Lhs node must still
3508                --  have an assignment statement as its parent).
3509
3510                --  We cannot rely on Original_Node to go back from the block
3511                --  node to the assignment node, because the assignment might
3512                --  already be a rewrite substitution.
3513
3514                Discard_Node (Relocate_Node (Original_Assignment));
3515                Rewrite (Original_Assignment, Blk);
3516             end;
3517
3518          elsif Nkind (Parent (N)) = N_Object_Declaration then
3519             Set_Expression (Parent (N), Empty);
3520             Insert_After (Parent (N), Blk);
3521
3522          elsif Is_Unc then
3523             Insert_Before (Parent (N), Blk);
3524          end if;
3525       end Rewrite_Function_Call;
3526
3527       ----------------------------
3528       -- Rewrite_Procedure_Call --
3529       ----------------------------
3530
3531       procedure Rewrite_Procedure_Call (N : Node_Id; Blk : Node_Id) is
3532          HSS  : constant Node_Id := Handled_Statement_Sequence (Blk);
3533       begin
3534          --  If there is a transient scope for N, this will be the scope of the
3535          --  actions for N, and the statements in Blk need to be within this
3536          --  scope. For example, they need to have visibility on the constant
3537          --  declarations created for the formals.
3538
3539          --  If N needs no transient scope, and if there are no declarations in
3540          --  the inlined body, we can do a little optimization and insert the
3541          --  statements for the body directly after N, and rewrite N to a
3542          --  null statement, instead of rewriting N into a full-blown block
3543          --  statement.
3544
3545          if not Scope_Is_Transient
3546            and then Is_Empty_List (Declarations (Blk))
3547          then
3548             Insert_List_After (N, Statements (HSS));
3549             Rewrite (N, Make_Null_Statement (Loc));
3550          else
3551             Rewrite (N, Blk);
3552          end if;
3553       end Rewrite_Procedure_Call;
3554
3555       -------------------------
3556       -- Formal_Is_Used_Once --
3557       -------------------------
3558
3559       function Formal_Is_Used_Once (Formal : Entity_Id) return Boolean is
3560          Use_Counter : Int := 0;
3561
3562          function Count_Uses (N : Node_Id) return Traverse_Result;
3563          --  Traverse the tree and count the uses of the formal parameter.
3564          --  In this case, for optimization purposes, we do not need to
3565          --  continue the traversal once more than one use is encountered.
3566
3567          ----------------
3568          -- Count_Uses --
3569          ----------------
3570
3571          function Count_Uses (N : Node_Id) return Traverse_Result is
3572          begin
3573             --  The original node is an identifier
3574
3575             if Nkind (N) = N_Identifier
3576               and then Present (Entity (N))
3577
3578                --  Original node's entity points to the one in the copied body
3579
3580               and then Nkind (Entity (N)) = N_Identifier
3581               and then Present (Entity (Entity (N)))
3582
3583                --  The entity of the copied node is the formal parameter
3584
3585               and then Entity (Entity (N)) = Formal
3586             then
3587                Use_Counter := Use_Counter + 1;
3588
3589                if Use_Counter > 1 then
3590
3591                   --  Denote more than one use and abandon the traversal
3592
3593                   Use_Counter := 2;
3594                   return Abandon;
3595
3596                end if;
3597             end if;
3598
3599             return OK;
3600          end Count_Uses;
3601
3602          procedure Count_Formal_Uses is new Traverse_Proc (Count_Uses);
3603
3604       --  Start of processing for Formal_Is_Used_Once
3605
3606       begin
3607          Count_Formal_Uses (Orig_Bod);
3608          return Use_Counter = 1;
3609       end Formal_Is_Used_Once;
3610
3611    --  Start of processing for Expand_Inlined_Call
3612
3613    begin
3614       --  Check for special case of To_Address call, and if so, just do an
3615       --  unchecked conversion instead of expanding the call. Not only is this
3616       --  more efficient, but it also avoids problem with order of elaboration
3617       --  when address clauses are inlined (address expression elaborated at
3618       --  wrong point).
3619
3620       if Subp = RTE (RE_To_Address) then
3621          Rewrite (N,
3622            Unchecked_Convert_To
3623             (RTE (RE_Address),
3624              Relocate_Node (First_Actual (N))));
3625          return;
3626
3627       elsif Is_Null_Procedure  then
3628          Rewrite (N, Make_Null_Statement (Loc));
3629          return;
3630       end if;
3631
3632       --  Check for an illegal attempt to inline a recursive procedure. If the
3633       --  subprogram has parameters this is detected when trying to supply a
3634       --  binding for parameters that already have one. For parameterless
3635       --  subprograms this must be done explicitly.
3636
3637       if In_Open_Scopes (Subp) then
3638          Error_Msg_N ("call to recursive subprogram cannot be inlined?", N);
3639          Set_Is_Inlined (Subp, False);
3640          return;
3641       end if;
3642
3643       if Nkind (Orig_Bod) = N_Defining_Identifier
3644         or else Nkind (Orig_Bod) = N_Defining_Operator_Symbol
3645       then
3646          --  Subprogram is a renaming_as_body. Calls appearing after the
3647          --  renaming can be replaced with calls to the renamed entity
3648          --  directly, because the subprograms are subtype conformant. If
3649          --  the renamed subprogram is an inherited operation, we must redo
3650          --  the expansion because implicit conversions may be needed.
3651
3652          Set_Name (N, New_Occurrence_Of (Orig_Bod, Loc));
3653
3654          if Present (Alias (Orig_Bod)) then
3655             Expand_Call (N);
3656          end if;
3657
3658          return;
3659       end if;
3660
3661       --  Use generic machinery to copy body of inlined subprogram, as if it
3662       --  were an instantiation, resetting source locations appropriately, so
3663       --  that nested inlined calls appear in the main unit.
3664
3665       Save_Env (Subp, Empty);
3666       Set_Copied_Sloc_For_Inlined_Body (N, Defining_Entity (Orig_Bod));
3667
3668       Bod := Copy_Generic_Node (Orig_Bod, Empty, Instantiating => True);
3669       Blk :=
3670         Make_Block_Statement (Loc,
3671           Declarations => Declarations (Bod),
3672           Handled_Statement_Sequence => Handled_Statement_Sequence (Bod));
3673
3674       if No (Declarations (Bod)) then
3675          Set_Declarations (Blk, New_List);
3676       end if;
3677
3678       --  For the unconstrained case, capture the name of the local
3679       --  variable that holds the result. This must be the first declaration
3680       --  in the block, because its bounds cannot depend on local variables.
3681       --  Otherwise there is no way to declare the result outside of the
3682       --  block. Needless to say, in general the bounds will depend on the
3683       --  actuals in the call.
3684
3685       if Is_Unc then
3686          Targ1 := Defining_Identifier (First (Declarations (Blk)));
3687       end if;
3688
3689       --  If this is a derived function, establish the proper return type
3690
3691       if Present (Orig_Subp)
3692         and then Orig_Subp /= Subp
3693       then
3694          Ret_Type := Etype (Orig_Subp);
3695       else
3696          Ret_Type := Etype (Subp);
3697       end if;
3698
3699       --  Create temporaries for the actuals that are expressions, or that
3700       --  are scalars and require copying to preserve semantics.
3701
3702       F := First_Formal (Subp);
3703       A := First_Actual (N);
3704       while Present (F) loop
3705          if Present (Renamed_Object (F)) then
3706             Error_Msg_N ("cannot inline call to recursive subprogram", N);
3707             return;
3708          end if;
3709
3710          --  If the argument may be a controlling argument in a call within
3711          --  the inlined body, we must preserve its classwide nature to insure
3712          --  that dynamic dispatching take place subsequently. If the formal
3713          --  has a constraint it must be preserved to retain the semantics of
3714          --  the body.
3715
3716          if Is_Class_Wide_Type (Etype (F))
3717            or else (Is_Access_Type (Etype (F))
3718                       and then
3719                     Is_Class_Wide_Type (Designated_Type (Etype (F))))
3720          then
3721             Temp_Typ := Etype (F);
3722
3723          elsif Base_Type (Etype (F)) = Base_Type (Etype (A))
3724            and then Etype (F) /= Base_Type (Etype (F))
3725          then
3726             Temp_Typ := Etype (F);
3727
3728          else
3729             Temp_Typ := Etype (A);
3730          end if;
3731
3732          --  If the actual is a simple name or a literal, no need to
3733          --  create a temporary, object can be used directly.
3734
3735          --  If the actual is a literal and the formal has its address taken,
3736          --  we cannot pass the literal itself as an argument, so its value
3737          --  must be captured in a temporary.
3738
3739          if (Is_Entity_Name (A)
3740               and then
3741                (not Is_Scalar_Type (Etype (A))
3742                  or else Ekind (Entity (A)) = E_Enumeration_Literal))
3743
3744          --  When the actual is an identifier and the corresponding formal
3745          --  is used only once in the original body, the formal can be
3746          --  substituted directly with the actual parameter.
3747
3748            or else (Nkind (A) = N_Identifier
3749              and then Formal_Is_Used_Once (F))
3750
3751            or else
3752              (Nkind_In (A, N_Real_Literal,
3753                             N_Integer_Literal,
3754                             N_Character_Literal)
3755                 and then not Address_Taken (F))
3756          then
3757             if Etype (F) /= Etype (A) then
3758                Set_Renamed_Object
3759                 (F, Unchecked_Convert_To (Etype (F), Relocate_Node (A)));
3760             else
3761                Set_Renamed_Object (F, A);
3762             end if;
3763
3764          else
3765             Temp :=
3766               Make_Defining_Identifier (Loc,
3767                 Chars => New_Internal_Name ('C'));
3768
3769             --  If the actual for an in/in-out parameter is a view conversion,
3770             --  make it into an unchecked conversion, given that an untagged
3771             --  type conversion is not a proper object for a renaming.
3772
3773             --  In-out conversions that involve real conversions have already
3774             --  been transformed in Expand_Actuals.
3775
3776             if Nkind (A) = N_Type_Conversion
3777               and then Ekind (F) /= E_In_Parameter
3778             then
3779                New_A :=
3780                  Make_Unchecked_Type_Conversion (Loc,
3781                    Subtype_Mark => New_Occurrence_Of (Etype (F), Loc),
3782                    Expression   => Relocate_Node (Expression (A)));
3783
3784             elsif Etype (F) /= Etype (A) then
3785                New_A := Unchecked_Convert_To (Etype (F), Relocate_Node (A));
3786                Temp_Typ := Etype (F);
3787
3788             else
3789                New_A := Relocate_Node (A);
3790             end if;
3791
3792             Set_Sloc (New_A, Sloc (N));
3793
3794             --  If the actual has a by-reference type, it cannot be copied, so
3795             --  its value is captured in a renaming declaration. Otherwise
3796             --  declare a local constant initialized with the actual.
3797
3798             --  We also use a renaming declaration for expressions of an array
3799             --  type that is not bit-packed, both for efficiency reasons and to
3800             --  respect the semantics of the call: in most cases the original
3801             --  call will pass the parameter by reference, and thus the inlined
3802             --  code will have the same semantics.
3803
3804             if Ekind (F) = E_In_Parameter
3805               and then not Is_Limited_Type (Etype (A))
3806               and then not Is_Tagged_Type  (Etype (A))
3807               and then
3808                (not Is_Array_Type (Etype (A))
3809                  or else not Is_Object_Reference (A)
3810                  or else Is_Bit_Packed_Array (Etype (A)))
3811             then
3812                Decl :=
3813                  Make_Object_Declaration (Loc,
3814                    Defining_Identifier => Temp,
3815                    Constant_Present => True,
3816                    Object_Definition => New_Occurrence_Of (Temp_Typ, Loc),
3817                    Expression => New_A);
3818             else
3819                Decl :=
3820                  Make_Object_Renaming_Declaration (Loc,
3821                    Defining_Identifier => Temp,
3822                    Subtype_Mark        => New_Occurrence_Of (Temp_Typ, Loc),
3823                    Name                => New_A);
3824             end if;
3825
3826             Append (Decl, Decls);
3827             Set_Renamed_Object (F, Temp);
3828          end if;
3829
3830          Next_Formal (F);
3831          Next_Actual (A);
3832       end loop;
3833
3834       --  Establish target of function call. If context is not assignment or
3835       --  declaration, create a temporary as a target. The declaration for
3836       --  the temporary may be subsequently optimized away if the body is a
3837       --  single expression, or if the left-hand side of the assignment is
3838       --  simple enough, i.e. an entity or an explicit dereference of one.
3839
3840       if Ekind (Subp) = E_Function then
3841          if Nkind (Parent (N)) = N_Assignment_Statement
3842            and then Is_Entity_Name (Name (Parent (N)))
3843          then
3844             Targ := Name (Parent (N));
3845
3846          elsif Nkind (Parent (N)) = N_Assignment_Statement
3847            and then Nkind (Name (Parent (N))) = N_Explicit_Dereference
3848            and then Is_Entity_Name (Prefix (Name (Parent (N))))
3849          then
3850             Targ := Name (Parent (N));
3851
3852          else
3853             --  Replace call with temporary and create its declaration
3854
3855             Temp :=
3856               Make_Defining_Identifier (Loc, New_Internal_Name ('C'));
3857             Set_Is_Internal (Temp);
3858
3859             --  For the unconstrained case, the generated temporary has the
3860             --  same constrained declaration as the result variable. It may
3861             --  eventually be possible to remove that temporary and use the
3862             --  result variable directly.
3863
3864             if Is_Unc then
3865                Decl :=
3866                  Make_Object_Declaration (Loc,
3867                    Defining_Identifier => Temp,
3868                    Object_Definition =>
3869                      New_Copy_Tree (Object_Definition (Parent (Targ1))));
3870
3871                Replace_Formals (Decl);
3872
3873             else
3874                Decl :=
3875                  Make_Object_Declaration (Loc,
3876                    Defining_Identifier => Temp,
3877                    Object_Definition =>
3878                      New_Occurrence_Of (Ret_Type, Loc));
3879
3880                Set_Etype (Temp, Ret_Type);
3881             end if;
3882
3883             Set_No_Initialization (Decl);
3884             Append (Decl, Decls);
3885             Rewrite (N, New_Occurrence_Of (Temp, Loc));
3886             Targ := Temp;
3887          end if;
3888       end if;
3889
3890       Insert_Actions (N, Decls);
3891
3892       --  Traverse the tree and replace formals with actuals or their thunks.
3893       --  Attach block to tree before analysis and rewriting.
3894
3895       Replace_Formals (Blk);
3896       Set_Parent (Blk, N);
3897
3898       if not Comes_From_Source (Subp)
3899         or else Is_Predef
3900       then
3901          Reset_Slocs (Blk);
3902       end if;
3903
3904       if Present (Exit_Lab) then
3905
3906          --  If the body was a single expression, the single return statement
3907          --  and the corresponding label are useless.
3908
3909          if Num_Ret = 1
3910            and then
3911              Nkind (Last (Statements (Handled_Statement_Sequence (Blk)))) =
3912                N_Goto_Statement
3913          then
3914             Remove (Last (Statements (Handled_Statement_Sequence (Blk))));
3915          else
3916             Append (Lab_Decl, (Declarations (Blk)));
3917             Append (Exit_Lab, Statements (Handled_Statement_Sequence (Blk)));
3918          end if;
3919       end if;
3920
3921       --  Analyze Blk with In_Inlined_Body set, to avoid spurious errors on
3922       --  conflicting private views that Gigi would ignore. If this is a
3923       --  predefined unit, analyze with checks off, as is done in the non-
3924       --  inlined run-time units.
3925
3926       declare
3927          I_Flag : constant Boolean := In_Inlined_Body;
3928
3929       begin
3930          In_Inlined_Body := True;
3931
3932          if Is_Predef then
3933             declare
3934                Style : constant Boolean := Style_Check;
3935             begin
3936                Style_Check := False;
3937                Analyze (Blk, Suppress => All_Checks);
3938                Style_Check := Style;
3939             end;
3940
3941          else
3942             Analyze (Blk);
3943          end if;
3944
3945          In_Inlined_Body := I_Flag;
3946       end;
3947
3948       if Ekind (Subp) = E_Procedure then
3949          Rewrite_Procedure_Call (N, Blk);
3950       else
3951          Rewrite_Function_Call (N, Blk);
3952
3953          --  For the unconstrained case, the replacement of the call has been
3954          --  made prior to the complete analysis of the generated declarations.
3955          --  Propagate the proper type now.
3956
3957          if Is_Unc then
3958             if Nkind (N) = N_Identifier then
3959                Set_Etype (N, Etype (Entity (N)));
3960             else
3961                Set_Etype (N, Etype (Targ1));
3962             end if;
3963          end if;
3964       end if;
3965
3966       Restore_Env;
3967
3968       --  Cleanup mapping between formals and actuals for other expansions
3969
3970       F := First_Formal (Subp);
3971       while Present (F) loop
3972          Set_Renamed_Object (F, Empty);
3973          Next_Formal (F);
3974       end loop;
3975    end Expand_Inlined_Call;
3976
3977    ----------------------------
3978    -- Expand_N_Function_Call --
3979    ----------------------------
3980
3981    procedure Expand_N_Function_Call (N : Node_Id) is
3982    begin
3983       Expand_Call (N);
3984
3985       --  If the return value of a foreign compiled function is VAX Float, then
3986       --  expand the return (adjusts the location of the return value on
3987       --  Alpha/VMS, no-op everywhere else).
3988       --  Comes_From_Source intercepts recursive expansion.
3989
3990       if Vax_Float (Etype (N))
3991         and then Nkind (N) = N_Function_Call
3992         and then Present (Name (N))
3993         and then Present (Entity (Name (N)))
3994         and then Has_Foreign_Convention (Entity (Name (N)))
3995         and then Comes_From_Source (Parent (N))
3996       then
3997          Expand_Vax_Foreign_Return (N);
3998       end if;
3999    end Expand_N_Function_Call;
4000
4001    ---------------------------------------
4002    -- Expand_N_Procedure_Call_Statement --
4003    ---------------------------------------
4004
4005    procedure Expand_N_Procedure_Call_Statement (N : Node_Id) is
4006    begin
4007       Expand_Call (N);
4008    end Expand_N_Procedure_Call_Statement;
4009
4010    ------------------------------
4011    -- Expand_N_Subprogram_Body --
4012    ------------------------------
4013
4014    --  Add poll call if ATC polling is enabled, unless the body will be inlined
4015    --  by the back-end.
4016
4017    --  Add dummy push/pop label nodes at start and end to clear any local
4018    --  exception indications if local-exception-to-goto optimization is active.
4019
4020    --  Add return statement if last statement in body is not a return statement
4021    --  (this makes things easier on Gigi which does not want to have to handle
4022    --  a missing return).
4023
4024    --  Add call to Activate_Tasks if body is a task activator
4025
4026    --  Deal with possible detection of infinite recursion
4027
4028    --  Eliminate body completely if convention stubbed
4029
4030    --  Encode entity names within body, since we will not need to reference
4031    --  these entities any longer in the front end.
4032
4033    --  Initialize scalar out parameters if Initialize/Normalize_Scalars
4034
4035    --  Reset Pure indication if any parameter has root type System.Address
4036
4037    --  Wrap thread body
4038
4039    procedure Expand_N_Subprogram_Body (N : Node_Id) is
4040       Loc      : constant Source_Ptr := Sloc (N);
4041       H        : constant Node_Id    := Handled_Statement_Sequence (N);
4042       Body_Id  : Entity_Id;
4043       Except_H : Node_Id;
4044       L        : List_Id;
4045       Spec_Id  : Entity_Id;
4046
4047       procedure Add_Return (S : List_Id);
4048       --  Append a return statement to the statement sequence S if the last
4049       --  statement is not already a return or a goto statement. Note that
4050       --  the latter test is not critical, it does not matter if we add a few
4051       --  extra returns, since they get eliminated anyway later on.
4052
4053       ----------------
4054       -- Add_Return --
4055       ----------------
4056
4057       procedure Add_Return (S : List_Id) is
4058          Last_Stm : Node_Id;
4059          Loc      : Source_Ptr;
4060
4061       begin
4062          --  Get last statement, ignoring any Pop_xxx_Label nodes, which are
4063          --  not relevant in this context since they are not executable.
4064
4065          Last_Stm := Last (S);
4066          while Nkind (Last_Stm) in N_Pop_xxx_Label loop
4067             Prev (Last_Stm);
4068          end loop;
4069
4070          --  Now insert return unless last statement is a transfer
4071
4072          if not Is_Transfer (Last_Stm) then
4073
4074             --  The source location for the return is the end label of the
4075             --  procedure if present. Otherwise use the sloc of the last
4076             --  statement in the list. If the list comes from a generated
4077             --  exception handler and we are not debugging generated code,
4078             --  all the statements within the handler are made invisible
4079             --  to the debugger.
4080
4081             if Nkind (Parent (S)) = N_Exception_Handler
4082               and then not Comes_From_Source (Parent (S))
4083             then
4084                Loc := Sloc (Last_Stm);
4085
4086             elsif Present (End_Label (H)) then
4087                Loc := Sloc (End_Label (H));
4088
4089             else
4090                Loc := Sloc (Last_Stm);
4091             end if;
4092
4093             declare
4094                Rtn : constant Node_Id := Make_Simple_Return_Statement (Loc);
4095
4096             begin
4097                --  Append return statement, and set analyzed manually. We can't
4098                --  call Analyze on this return since the scope is wrong.
4099
4100                --  Note: it almost works to push the scope and then do the
4101                --  Analyze call, but something goes wrong in some weird cases
4102                --  and it is not worth worrying about ???
4103
4104                Append_To (S, Rtn);
4105                Set_Analyzed (Rtn);
4106
4107                --  Call _Postconditions procedure if appropriate. We need to
4108                --  do this explicitly because we did not analyze the generated
4109                --  return statement above, so the call did not get inserted.
4110
4111                if Ekind (Spec_Id) = E_Procedure
4112                  and then Has_Postconditions (Spec_Id)
4113                then
4114                   pragma Assert (Present (Postcondition_Proc (Spec_Id)));
4115                   Insert_Action (Rtn,
4116                     Make_Procedure_Call_Statement (Loc,
4117                       Name =>
4118                         New_Reference_To (Postcondition_Proc (Spec_Id), Loc)));
4119                end if;
4120             end;
4121          end if;
4122       end Add_Return;
4123
4124    --  Start of processing for Expand_N_Subprogram_Body
4125
4126    begin
4127       --  Set L to either the list of declarations if present, or to the list
4128       --  of statements if no declarations are present. This is used to insert
4129       --  new stuff at the start.
4130
4131       if Is_Non_Empty_List (Declarations (N)) then
4132          L := Declarations (N);
4133       else
4134          L := Statements (H);
4135       end if;
4136
4137       --  If local-exception-to-goto optimization active, insert dummy push
4138       --  statements at start, and dummy pop statements at end.
4139
4140       if (Debug_Flag_Dot_G
4141            or else Restriction_Active (No_Exception_Propagation))
4142         and then Is_Non_Empty_List (L)
4143       then
4144          declare
4145             FS  : constant Node_Id    := First (L);
4146             FL  : constant Source_Ptr := Sloc (FS);
4147             LS  : Node_Id;
4148             LL  : Source_Ptr;
4149
4150          begin
4151             --  LS points to either last statement, if statements are present
4152             --  or to the last declaration if there are no statements present.
4153             --  It is the node after which the pop's are generated.
4154
4155             if Is_Non_Empty_List (Statements (H)) then
4156                LS := Last (Statements (H));
4157             else
4158                LS := Last (L);
4159             end if;
4160
4161             LL := Sloc (LS);
4162
4163             Insert_List_Before_And_Analyze (FS, New_List (
4164               Make_Push_Constraint_Error_Label (FL),
4165               Make_Push_Program_Error_Label    (FL),
4166               Make_Push_Storage_Error_Label    (FL)));
4167
4168             Insert_List_After_And_Analyze (LS, New_List (
4169               Make_Pop_Constraint_Error_Label  (LL),
4170               Make_Pop_Program_Error_Label     (LL),
4171               Make_Pop_Storage_Error_Label     (LL)));
4172          end;
4173       end if;
4174
4175       --  Find entity for subprogram
4176
4177       Body_Id := Defining_Entity (N);
4178
4179       if Present (Corresponding_Spec (N)) then
4180          Spec_Id := Corresponding_Spec (N);
4181       else
4182          Spec_Id := Body_Id;
4183       end if;
4184
4185       --  Need poll on entry to subprogram if polling enabled. We only do this
4186       --  for non-empty subprograms, since it does not seem necessary to poll
4187       --  for a dummy null subprogram.
4188
4189       if Is_Non_Empty_List (L) then
4190
4191          --  Do not add a polling call if the subprogram is to be inlined by
4192          --  the back-end, to avoid repeated calls with multiple inlinings.
4193
4194          if Is_Inlined (Spec_Id)
4195            and then Front_End_Inlining
4196            and then Optimization_Level > 1
4197          then
4198             null;
4199          else
4200             Generate_Poll_Call (First (L));
4201          end if;
4202       end if;
4203
4204       --  If this is a Pure function which has any parameters whose root type
4205       --  is System.Address, reset the Pure indication, since it will likely
4206       --  cause incorrect code to be generated as the parameter is probably
4207       --  a pointer, and the fact that the same pointer is passed does not mean
4208       --  that the same value is being referenced.
4209
4210       --  Note that if the programmer gave an explicit Pure_Function pragma,
4211       --  then we believe the programmer, and leave the subprogram Pure.
4212
4213       --  This code should probably be at the freeze point, so that it happens
4214       --  even on a -gnatc (or more importantly -gnatt) compile, so that the
4215       --  semantic tree has Is_Pure set properly ???
4216
4217       if Is_Pure (Spec_Id)
4218         and then Is_Subprogram (Spec_Id)
4219         and then not Has_Pragma_Pure_Function (Spec_Id)
4220       then
4221          declare
4222             F : Entity_Id;
4223
4224          begin
4225             F := First_Formal (Spec_Id);
4226             while Present (F) loop
4227                if Is_Descendent_Of_Address (Etype (F)) then
4228                   Set_Is_Pure (Spec_Id, False);
4229
4230                   if Spec_Id /= Body_Id then
4231                      Set_Is_Pure (Body_Id, False);
4232                   end if;
4233
4234                   exit;
4235                end if;
4236
4237                Next_Formal (F);
4238             end loop;
4239          end;
4240       end if;
4241
4242       --  Initialize any scalar OUT args if Initialize/Normalize_Scalars
4243
4244       if Init_Or_Norm_Scalars and then Is_Subprogram (Spec_Id) then
4245          declare
4246             F : Entity_Id;
4247
4248          begin
4249             --  Loop through formals
4250
4251             F := First_Formal (Spec_Id);
4252             while Present (F) loop
4253                if Is_Scalar_Type (Etype (F))
4254                  and then Ekind (F) = E_Out_Parameter
4255                then
4256                   Check_Restriction (No_Default_Initialization, F);
4257
4258                   --  Insert the initialization. We turn off validity checks
4259                   --  for this assignment, since we do not want any check on
4260                   --  the initial value itself (which may well be invalid).
4261
4262                   Insert_Before_And_Analyze (First (L),
4263                     Make_Assignment_Statement (Loc,
4264                       Name       => New_Occurrence_Of (F, Loc),
4265                       Expression => Get_Simple_Init_Val (Etype (F), N)),
4266                     Suppress => Validity_Check);
4267                end if;
4268
4269                Next_Formal (F);
4270             end loop;
4271          end;
4272       end if;
4273
4274       --  Clear out statement list for stubbed procedure
4275
4276       if Present (Corresponding_Spec (N)) then
4277          Set_Elaboration_Flag (N, Spec_Id);
4278
4279          if Convention (Spec_Id) = Convention_Stubbed
4280            or else Is_Eliminated (Spec_Id)
4281          then
4282             Set_Declarations (N, Empty_List);
4283             Set_Handled_Statement_Sequence (N,
4284               Make_Handled_Sequence_Of_Statements (Loc,
4285                 Statements => New_List (
4286                   Make_Null_Statement (Loc))));
4287             return;
4288          end if;
4289       end if;
4290
4291       --  Create a set of discriminals for the next protected subprogram body
4292
4293       if Is_List_Member (N)
4294         and then Present (Parent (List_Containing (N)))
4295         and then Nkind (Parent (List_Containing (N))) = N_Protected_Body
4296         and then Present (Next_Protected_Operation (N))
4297       then
4298          Set_Discriminals (Parent (Base_Type (Scope (Spec_Id))));
4299       end if;
4300
4301       --  Returns_By_Ref flag is normally set when the subprogram is frozen but
4302       --  subprograms with no specs are not frozen.
4303
4304       declare
4305          Typ  : constant Entity_Id := Etype (Spec_Id);
4306          Utyp : constant Entity_Id := Underlying_Type (Typ);
4307
4308       begin
4309          if not Acts_As_Spec (N)
4310            and then Nkind (Parent (Parent (Spec_Id))) /=
4311              N_Subprogram_Body_Stub
4312          then
4313             null;
4314
4315          elsif Is_Inherently_Limited_Type (Typ) then
4316             Set_Returns_By_Ref (Spec_Id);
4317
4318          elsif Present (Utyp) and then CW_Or_Has_Controlled_Part (Utyp) then
4319             Set_Returns_By_Ref (Spec_Id);
4320          end if;
4321       end;
4322
4323       --  For a procedure, we add a return for all possible syntactic ends of
4324       --  the subprogram.
4325
4326       if Ekind (Spec_Id) = E_Procedure
4327         or else Ekind (Spec_Id) = E_Generic_Procedure
4328       then
4329          Add_Return (Statements (H));
4330
4331          if Present (Exception_Handlers (H)) then
4332             Except_H := First_Non_Pragma (Exception_Handlers (H));
4333             while Present (Except_H) loop
4334                Add_Return (Statements (Except_H));
4335                Next_Non_Pragma (Except_H);
4336             end loop;
4337          end if;
4338
4339       --  For a function, we must deal with the case where there is at least
4340       --  one missing return. What we do is to wrap the entire body of the
4341       --  function in a block:
4342
4343       --    begin
4344       --      ...
4345       --    end;
4346
4347       --  becomes
4348
4349       --    begin
4350       --       begin
4351       --          ...
4352       --       end;
4353
4354       --       raise Program_Error;
4355       --    end;
4356
4357       --  This approach is necessary because the raise must be signalled to the
4358       --  caller, not handled by any local handler (RM 6.4(11)).
4359
4360       --  Note: we do not need to analyze the constructed sequence here, since
4361       --  it has no handler, and an attempt to analyze the handled statement
4362       --  sequence twice is risky in various ways (e.g. the issue of expanding
4363       --  cleanup actions twice).
4364
4365       elsif Has_Missing_Return (Spec_Id) then
4366          declare
4367             Hloc : constant Source_Ptr := Sloc (H);
4368             Blok : constant Node_Id    :=
4369                      Make_Block_Statement (Hloc,
4370                        Handled_Statement_Sequence => H);
4371             Rais : constant Node_Id    :=
4372                      Make_Raise_Program_Error (Hloc,
4373                        Reason => PE_Missing_Return);
4374
4375          begin
4376             Set_Handled_Statement_Sequence (N,
4377               Make_Handled_Sequence_Of_Statements (Hloc,
4378                 Statements => New_List (Blok, Rais)));
4379
4380             Push_Scope (Spec_Id);
4381             Analyze (Blok);
4382             Analyze (Rais);
4383             Pop_Scope;
4384          end;
4385       end if;
4386
4387       --  If subprogram contains a parameterless recursive call, then we may
4388       --  have an infinite recursion, so see if we can generate code to check
4389       --  for this possibility if storage checks are not suppressed.
4390
4391       if Ekind (Spec_Id) = E_Procedure
4392         and then Has_Recursive_Call (Spec_Id)
4393         and then not Storage_Checks_Suppressed (Spec_Id)
4394       then
4395          Detect_Infinite_Recursion (N, Spec_Id);
4396       end if;
4397
4398       --  Set to encode entity names in package body before gigi is called
4399
4400       Qualify_Entity_Names (N);
4401    end Expand_N_Subprogram_Body;
4402
4403    -----------------------------------
4404    -- Expand_N_Subprogram_Body_Stub --
4405    -----------------------------------
4406
4407    procedure Expand_N_Subprogram_Body_Stub (N : Node_Id) is
4408    begin
4409       if Present (Corresponding_Body (N)) then
4410          Expand_N_Subprogram_Body (
4411            Unit_Declaration_Node (Corresponding_Body (N)));
4412       end if;
4413    end Expand_N_Subprogram_Body_Stub;
4414
4415    -------------------------------------
4416    -- Expand_N_Subprogram_Declaration --
4417    -------------------------------------
4418
4419    --  If the declaration appears within a protected body, it is a private
4420    --  operation of the protected type. We must create the corresponding
4421    --  protected subprogram an associated formals. For a normal protected
4422    --  operation, this is done when expanding the protected type declaration.
4423
4424    --  If the declaration is for a null procedure, emit null body
4425
4426    procedure Expand_N_Subprogram_Declaration (N : Node_Id) is
4427       Loc       : constant Source_Ptr := Sloc (N);
4428       Subp      : constant Entity_Id  := Defining_Entity (N);
4429       Scop      : constant Entity_Id  := Scope (Subp);
4430       Prot_Decl : Node_Id;
4431       Prot_Bod  : Node_Id;
4432       Prot_Id   : Entity_Id;
4433
4434    begin
4435       --  Deal with case of protected subprogram. Do not generate protected
4436       --  operation if operation is flagged as eliminated.
4437
4438       if Is_List_Member (N)
4439         and then Present (Parent (List_Containing (N)))
4440         and then Nkind (Parent (List_Containing (N))) = N_Protected_Body
4441         and then Is_Protected_Type (Scop)
4442       then
4443          if No (Protected_Body_Subprogram (Subp))
4444            and then not Is_Eliminated (Subp)
4445          then
4446             Prot_Decl :=
4447               Make_Subprogram_Declaration (Loc,
4448                 Specification =>
4449                   Build_Protected_Sub_Specification
4450                     (N, Scop, Unprotected_Mode));
4451
4452             --  The protected subprogram is declared outside of the protected
4453             --  body. Given that the body has frozen all entities so far, we
4454             --  analyze the subprogram and perform freezing actions explicitly.
4455             --  including the generation of an explicit freeze node, to ensure
4456             --  that gigi has the proper order of elaboration.
4457             --  If the body is a subunit, the insertion point is before the
4458             --  stub in the parent.
4459
4460             Prot_Bod := Parent (List_Containing (N));
4461
4462             if Nkind (Parent (Prot_Bod)) = N_Subunit then
4463                Prot_Bod := Corresponding_Stub (Parent (Prot_Bod));
4464             end if;
4465
4466             Insert_Before (Prot_Bod, Prot_Decl);
4467             Prot_Id := Defining_Unit_Name (Specification (Prot_Decl));
4468             Set_Has_Delayed_Freeze (Prot_Id);
4469
4470             Push_Scope (Scope (Scop));
4471             Analyze (Prot_Decl);
4472             Insert_Actions (N, Freeze_Entity (Prot_Id, Loc));
4473             Set_Protected_Body_Subprogram (Subp, Prot_Id);
4474             Pop_Scope;
4475          end if;
4476
4477       --  Ada 2005 (AI-348): Generation of the null body
4478
4479       elsif Nkind (Specification (N)) = N_Procedure_Specification
4480         and then Null_Present (Specification (N))
4481       then
4482          declare
4483             Bod : constant Node_Id :=
4484                     Make_Subprogram_Body (Loc,
4485                       Specification =>
4486                         New_Copy_Tree (Specification (N)),
4487                       Declarations => New_List,
4488                      Handled_Statement_Sequence =>
4489                         Make_Handled_Sequence_Of_Statements (Loc,
4490                           Statements => New_List (Make_Null_Statement (Loc))));
4491          begin
4492             Set_Body_To_Inline (N, Bod);
4493             Insert_After (N, Bod);
4494             Analyze (Bod);
4495
4496             --  Corresponding_Spec isn't being set by Analyze_Subprogram_Body,
4497             --  evidently because Set_Has_Completion is called earlier for null
4498             --  procedures in Analyze_Subprogram_Declaration, so we force its
4499             --  setting here. If the setting of Has_Completion is not set
4500             --  earlier, then it can result in missing body errors if other
4501             --  errors were already reported (since expansion is turned off).
4502
4503             --  Should creation of the empty body be moved to the analyzer???
4504
4505             Set_Corresponding_Spec (Bod, Defining_Entity (Specification (N)));
4506          end;
4507       end if;
4508    end Expand_N_Subprogram_Declaration;
4509
4510    ---------------------------------------
4511    -- Expand_Protected_Object_Reference --
4512    ---------------------------------------
4513
4514    function Expand_Protected_Object_Reference
4515      (N    : Node_Id;
4516       Scop : Entity_Id) return Node_Id
4517    is
4518       Loc   : constant Source_Ptr := Sloc (N);
4519       Corr  : Entity_Id;
4520       Rec   : Node_Id;
4521       Param : Entity_Id;
4522       Proc  : Entity_Id;
4523
4524    begin
4525       Rec :=
4526         Make_Identifier (Loc,
4527           Chars => Name_uObject);
4528       Set_Etype (Rec, Corresponding_Record_Type (Scop));
4529
4530       --  Find enclosing protected operation, and retrieve its first parameter,
4531       --  which denotes the enclosing protected object. If the enclosing
4532       --  operation is an entry, we are immediately within the protected body,
4533       --  and we can retrieve the object from the service entries procedure. A
4534       --  barrier function has the same signature as an entry. A barrier
4535       --  function is compiled within the protected object, but unlike
4536       --  protected operations its never needs locks, so that its protected
4537       --  body subprogram points to itself.
4538
4539       Proc := Current_Scope;
4540       while Present (Proc)
4541         and then Scope (Proc) /= Scop
4542       loop
4543          Proc := Scope (Proc);
4544       end loop;
4545
4546       Corr := Protected_Body_Subprogram (Proc);
4547
4548       if No (Corr) then
4549
4550          --  Previous error left expansion incomplete.
4551          --  Nothing to do on this call.
4552
4553          return Empty;
4554       end if;
4555
4556       Param :=
4557         Defining_Identifier
4558           (First (Parameter_Specifications (Parent (Corr))));
4559
4560       if Is_Subprogram (Proc)
4561         and then Proc /= Corr
4562       then
4563          --  Protected function or procedure
4564
4565          Set_Entity (Rec, Param);
4566
4567          --  Rec is a reference to an entity which will not be in scope when
4568          --  the call is reanalyzed, and needs no further analysis.
4569
4570          Set_Analyzed (Rec);
4571
4572       else
4573          --  Entry or barrier function for entry body. The first parameter of
4574          --  the entry body procedure is pointer to the object. We create a
4575          --  local variable of the proper type, duplicating what is done to
4576          --  define _object later on.
4577
4578          declare
4579             Decls : List_Id;
4580             Obj_Ptr : constant Entity_Id :=  Make_Defining_Identifier (Loc,
4581                                                Chars =>
4582                                                  New_Internal_Name ('T'));
4583
4584          begin
4585             Decls := New_List (
4586               Make_Full_Type_Declaration (Loc,
4587                 Defining_Identifier => Obj_Ptr,
4588                   Type_Definition =>
4589                      Make_Access_To_Object_Definition (Loc,
4590                        Subtype_Indication =>
4591                          New_Reference_To
4592                       (Corresponding_Record_Type (Scop), Loc))));
4593
4594             Insert_Actions (N, Decls);
4595             Insert_Actions (N, Freeze_Entity (Obj_Ptr, Sloc (N)));
4596
4597             Rec :=
4598               Make_Explicit_Dereference (Loc,
4599                 Unchecked_Convert_To (Obj_Ptr,
4600                   New_Occurrence_Of (Param, Loc)));
4601
4602             --  Analyze new actual. Other actuals in calls are already analyzed
4603             --  and the list of actuals is not reanalyzed after rewriting.
4604
4605             Set_Parent (Rec, N);
4606             Analyze (Rec);
4607          end;
4608       end if;
4609
4610       return Rec;
4611    end Expand_Protected_Object_Reference;
4612
4613    --------------------------------------
4614    -- Expand_Protected_Subprogram_Call --
4615    --------------------------------------
4616
4617    procedure Expand_Protected_Subprogram_Call
4618      (N    : Node_Id;
4619       Subp : Entity_Id;
4620       Scop : Entity_Id)
4621    is
4622       Rec   : Node_Id;
4623
4624    begin
4625       --  If the protected object is not an enclosing scope, this is
4626       --  an inter-object function call. Inter-object procedure
4627       --  calls are expanded by Exp_Ch9.Build_Simple_Entry_Call.
4628       --  The call is intra-object only if the subprogram being
4629       --  called is in the protected body being compiled, and if the
4630       --  protected object in the call is statically the enclosing type.
4631       --  The object may be an component of some other data structure,
4632       --  in which case this must be handled as an inter-object call.
4633
4634       if not In_Open_Scopes (Scop)
4635         or else not Is_Entity_Name (Name (N))
4636       then
4637          if Nkind (Name (N)) = N_Selected_Component then
4638             Rec := Prefix (Name (N));
4639
4640          else
4641             pragma Assert (Nkind (Name (N)) = N_Indexed_Component);
4642             Rec := Prefix (Prefix (Name (N)));
4643          end if;
4644
4645          Build_Protected_Subprogram_Call (N,
4646            Name => New_Occurrence_Of (Subp, Sloc (N)),
4647            Rec =>  Convert_Concurrent (Rec, Etype (Rec)),
4648            External => True);
4649
4650       else
4651          Rec := Expand_Protected_Object_Reference (N, Scop);
4652
4653          if No (Rec) then
4654             return;
4655          end if;
4656
4657          Build_Protected_Subprogram_Call (N,
4658            Name     => Name (N),
4659            Rec      => Rec,
4660            External => False);
4661
4662       end if;
4663
4664       Analyze (N);
4665
4666       --  If it is a function call it can appear in elaboration code and
4667       --  the called entity must be frozen here.
4668
4669       if Ekind (Subp) = E_Function then
4670          Freeze_Expression (Name (N));
4671       end if;
4672    end Expand_Protected_Subprogram_Call;
4673
4674    --------------------------------
4675    -- Is_Build_In_Place_Function --
4676    --------------------------------
4677
4678    function Is_Build_In_Place_Function (E : Entity_Id) return Boolean is
4679    begin
4680       --  For now we test whether E denotes a function or access-to-function
4681       --  type whose result subtype is inherently limited. Later this test may
4682       --  be revised to allow composite nonlimited types. Functions with a
4683       --  foreign convention or whose result type has a foreign convention
4684       --  never qualify.
4685
4686       if Ekind (E) = E_Function
4687         or else Ekind (E) = E_Generic_Function
4688         or else (Ekind (E) = E_Subprogram_Type
4689                   and then Etype (E) /= Standard_Void_Type)
4690       then
4691          --  Note: If you have Convention (C) on an inherently limited type,
4692          --  you're on your own. That is, the C code will have to be carefully
4693          --  written to know about the Ada conventions.
4694
4695          if Has_Foreign_Convention (E)
4696            or else Has_Foreign_Convention (Etype (E))
4697          then
4698             return False;
4699
4700          --  If the return type is a limited interface it has to be treated
4701          --  as a return in place, even if the actual object is some non-
4702          --  limited descendant.
4703
4704          elsif Is_Limited_Interface (Etype (E)) then
4705             return True;
4706
4707          else
4708             return Is_Inherently_Limited_Type (Etype (E))
4709               and then Ada_Version >= Ada_05
4710               and then not Debug_Flag_Dot_L;
4711          end if;
4712
4713       else
4714          return False;
4715       end if;
4716    end Is_Build_In_Place_Function;
4717
4718    -------------------------------------
4719    -- Is_Build_In_Place_Function_Call --
4720    -------------------------------------
4721
4722    function Is_Build_In_Place_Function_Call (N : Node_Id) return Boolean is
4723       Exp_Node    : Node_Id := N;
4724       Function_Id : Entity_Id;
4725
4726    begin
4727       --  Step past qualification or unchecked conversion (the latter can occur
4728       --  in cases of calls to 'Input).
4729
4730       if Nkind_In
4731            (Exp_Node, N_Qualified_Expression, N_Unchecked_Type_Conversion)
4732       then
4733          Exp_Node := Expression (N);
4734       end if;
4735
4736       if Nkind (Exp_Node) /= N_Function_Call then
4737          return False;
4738
4739       else
4740          if Is_Entity_Name (Name (Exp_Node)) then
4741             Function_Id := Entity (Name (Exp_Node));
4742
4743          elsif Nkind (Name (Exp_Node)) = N_Explicit_Dereference then
4744             Function_Id := Etype (Name (Exp_Node));
4745          end if;
4746
4747          return Is_Build_In_Place_Function (Function_Id);
4748       end if;
4749    end Is_Build_In_Place_Function_Call;
4750
4751    ---------------------------------------
4752    -- Is_Build_In_Place_Function_Return --
4753    ---------------------------------------
4754
4755    function Is_Build_In_Place_Function_Return (N : Node_Id) return Boolean is
4756    begin
4757       if Nkind_In (N, N_Simple_Return_Statement,
4758                       N_Extended_Return_Statement)
4759       then
4760          return Is_Build_In_Place_Function
4761                   (Return_Applies_To (Return_Statement_Entity (N)));
4762       else
4763          return False;
4764       end if;
4765    end Is_Build_In_Place_Function_Return;
4766
4767    -----------------------
4768    -- Freeze_Subprogram --
4769    -----------------------
4770
4771    procedure Freeze_Subprogram (N : Node_Id) is
4772       Loc : constant Source_Ptr := Sloc (N);
4773
4774       procedure Register_Predefined_DT_Entry (Prim : Entity_Id);
4775       --  (Ada 2005): Register a predefined primitive in all the secondary
4776       --  dispatch tables of its primitive type.
4777
4778       ----------------------------------
4779       -- Register_Predefined_DT_Entry --
4780       ----------------------------------
4781
4782       procedure Register_Predefined_DT_Entry (Prim : Entity_Id) is
4783          Iface_DT_Ptr : Elmt_Id;
4784          Tagged_Typ   : Entity_Id;
4785          Thunk_Id     : Entity_Id;
4786          Thunk_Code   : Node_Id;
4787
4788       begin
4789          Tagged_Typ := Find_Dispatching_Type (Prim);
4790
4791          if No (Access_Disp_Table (Tagged_Typ))
4792            or else not Has_Interfaces (Tagged_Typ)
4793            or else not RTE_Available (RE_Interface_Tag)
4794            or else Restriction_Active (No_Dispatching_Calls)
4795          then
4796             return;
4797          end if;
4798
4799          --  Skip the first two access-to-dispatch-table pointers since they
4800          --  leads to the primary dispatch table (predefined DT and user
4801          --  defined DT). We are only concerned with the secondary dispatch
4802          --  table pointers. Note that the access-to- dispatch-table pointer
4803          --  corresponds to the first implemented interface retrieved below.
4804
4805          Iface_DT_Ptr :=
4806            Next_Elmt (Next_Elmt (First_Elmt (Access_Disp_Table (Tagged_Typ))));
4807
4808          while Present (Iface_DT_Ptr)
4809             and then Ekind (Node (Iface_DT_Ptr)) = E_Constant
4810          loop
4811             pragma Assert (Has_Thunks (Node (Iface_DT_Ptr)));
4812             Expand_Interface_Thunk (Prim, Thunk_Id, Thunk_Code);
4813
4814             if Present (Thunk_Code) then
4815                Insert_Actions_After (N, New_List (
4816                  Thunk_Code,
4817
4818                  Build_Set_Predefined_Prim_Op_Address (Loc,
4819                    Tag_Node =>
4820                      New_Reference_To (Node (Next_Elmt (Iface_DT_Ptr)), Loc),
4821                    Position => DT_Position (Prim),
4822                    Address_Node =>
4823                      Unchecked_Convert_To (RTE (RE_Prim_Ptr),
4824                        Make_Attribute_Reference (Loc,
4825                          Prefix         => New_Reference_To (Thunk_Id, Loc),
4826                          Attribute_Name => Name_Unrestricted_Access))),
4827
4828                  Build_Set_Predefined_Prim_Op_Address (Loc,
4829                    Tag_Node =>
4830                      New_Reference_To
4831                       (Node (Next_Elmt (Next_Elmt (Next_Elmt (Iface_DT_Ptr)))),
4832                        Loc),
4833                    Position => DT_Position (Prim),
4834                    Address_Node =>
4835                      Unchecked_Convert_To (RTE (RE_Prim_Ptr),
4836                        Make_Attribute_Reference (Loc,
4837                          Prefix         => New_Reference_To (Prim, Loc),
4838                          Attribute_Name => Name_Unrestricted_Access)))));
4839             end if;
4840
4841             --  Skip the tag of the predefined primitives dispatch table
4842
4843             Next_Elmt (Iface_DT_Ptr);
4844             pragma Assert (Has_Thunks (Node (Iface_DT_Ptr)));
4845
4846             --  Skip the tag of the no-thunks dispatch table
4847
4848             Next_Elmt (Iface_DT_Ptr);
4849             pragma Assert (not Has_Thunks (Node (Iface_DT_Ptr)));
4850
4851             --  Skip the tag of the predefined primitives no-thunks dispatch
4852             --  table
4853
4854             Next_Elmt (Iface_DT_Ptr);
4855             pragma Assert (not Has_Thunks (Node (Iface_DT_Ptr)));
4856
4857             Next_Elmt (Iface_DT_Ptr);
4858          end loop;
4859       end Register_Predefined_DT_Entry;
4860
4861       --  Local variables
4862
4863       Subp : constant Entity_Id := Entity (N);
4864
4865    --  Start of processing for Freeze_Subprogram
4866
4867    begin
4868       --  We suppress the initialization of the dispatch table entry when
4869       --  VM_Target because the dispatching mechanism is handled internally
4870       --  by the VM.
4871
4872       if Is_Dispatching_Operation (Subp)
4873         and then not Is_Abstract_Subprogram (Subp)
4874         and then Present (DTC_Entity (Subp))
4875         and then Present (Scope (DTC_Entity (Subp)))
4876         and then VM_Target = No_VM
4877         and then not Restriction_Active (No_Dispatching_Calls)
4878         and then RTE_Available (RE_Tag)
4879       then
4880          declare
4881             Typ : constant Entity_Id := Scope (DTC_Entity (Subp));
4882
4883          begin
4884             --  Handle private overridden primitives
4885
4886             if not Is_CPP_Class (Typ) then
4887                Check_Overriding_Operation (Subp);
4888             end if;
4889
4890             --  We assume that imported CPP primitives correspond with objects
4891             --  whose constructor is in the CPP side; therefore we don't need
4892             --  to generate code to register them in the dispatch table.
4893
4894             if Is_CPP_Class (Typ) then
4895                null;
4896
4897             --  Handle CPP primitives found in derivations of CPP_Class types.
4898             --  These primitives must have been inherited from some parent, and
4899             --  there is no need to register them in the dispatch table because
4900             --  Build_Inherit_Prims takes care of the initialization of these
4901             --  slots.
4902
4903             elsif Is_Imported (Subp)
4904                     and then (Convention (Subp) = Convention_CPP
4905                                 or else Convention (Subp) = Convention_C)
4906             then
4907                null;
4908
4909             --  Generate code to register the primitive in non statically
4910             --  allocated dispatch tables
4911
4912             elsif not Static_Dispatch_Tables
4913               or else not
4914                 Is_Library_Level_Tagged_Type (Scope (DTC_Entity (Subp)))
4915             then
4916                --  When a primitive is frozen, enter its name in its dispatch
4917                --  table slot.
4918
4919                if not Is_Interface (Typ)
4920                  or else Present (Interface_Alias (Subp))
4921                then
4922                   if Is_Predefined_Dispatching_Operation (Subp) then
4923                      Register_Predefined_DT_Entry (Subp);
4924                   end if;
4925
4926                   Insert_Actions_After (N,
4927                     Register_Primitive (Loc, Prim => Subp));
4928                end if;
4929             end if;
4930          end;
4931       end if;
4932
4933       --  Mark functions that return by reference. Note that it cannot be part
4934       --  of the normal semantic analysis of the spec since the underlying
4935       --  returned type may not be known yet (for private types).
4936
4937       declare
4938          Typ  : constant Entity_Id := Etype (Subp);
4939          Utyp : constant Entity_Id := Underlying_Type (Typ);
4940       begin
4941          if Is_Inherently_Limited_Type (Typ) then
4942             Set_Returns_By_Ref (Subp);
4943          elsif Present (Utyp) and then CW_Or_Has_Controlled_Part (Utyp) then
4944             Set_Returns_By_Ref (Subp);
4945          end if;
4946       end;
4947    end Freeze_Subprogram;
4948
4949    -------------------------------------------
4950    -- Make_Build_In_Place_Call_In_Allocator --
4951    -------------------------------------------
4952
4953    procedure Make_Build_In_Place_Call_In_Allocator
4954      (Allocator     : Node_Id;
4955       Function_Call : Node_Id)
4956    is
4957       Loc               : Source_Ptr;
4958       Func_Call         : Node_Id := Function_Call;
4959       Function_Id       : Entity_Id;
4960       Result_Subt       : Entity_Id;
4961       Acc_Type          : constant Entity_Id := Etype (Allocator);
4962       New_Allocator     : Node_Id;
4963       Return_Obj_Access : Entity_Id;
4964
4965    begin
4966       --  Step past qualification or unchecked conversion (the latter can occur
4967       --  in cases of calls to 'Input).
4968
4969       if Nkind_In (Func_Call,
4970                    N_Qualified_Expression,
4971                    N_Unchecked_Type_Conversion)
4972       then
4973          Func_Call := Expression (Func_Call);
4974       end if;
4975
4976       --  If the call has already been processed to add build-in-place actuals
4977       --  then return. This should not normally occur in an allocator context,
4978       --  but we add the protection as a defensive measure.
4979
4980       if Is_Expanded_Build_In_Place_Call (Func_Call) then
4981          return;
4982       end if;
4983
4984       --  Mark the call as processed as a build-in-place call
4985
4986       Set_Is_Expanded_Build_In_Place_Call (Func_Call);
4987
4988       Loc := Sloc (Function_Call);
4989
4990       if Is_Entity_Name (Name (Func_Call)) then
4991          Function_Id := Entity (Name (Func_Call));
4992
4993       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
4994          Function_Id := Etype (Name (Func_Call));
4995
4996       else
4997          raise Program_Error;
4998       end if;
4999
5000       Result_Subt := Etype (Function_Id);
5001
5002       --  When the result subtype is constrained, the return object must be
5003       --  allocated on the caller side, and access to it is passed to the
5004       --  function.
5005
5006       --  Here and in related routines, we must examine the full view of the
5007       --  type, because the view at the point of call may differ from that
5008       --  that in the function body, and the expansion mechanism depends on
5009       --  the characteristics of the full view.
5010
5011       if Is_Constrained (Underlying_Type (Result_Subt)) then
5012
5013          --  Replace the initialized allocator of form "new T'(Func (...))"
5014          --  with an uninitialized allocator of form "new T", where T is the
5015          --  result subtype of the called function. The call to the function
5016          --  is handled separately further below.
5017
5018          New_Allocator :=
5019            Make_Allocator (Loc,
5020              Expression => New_Reference_To (Result_Subt, Loc));
5021          Set_No_Initialization (New_Allocator);
5022
5023          --  Copy attributes to new allocator. Note that the new allocator
5024          --  logically comes from source if the original one did, so copy the
5025          --  relevant flag. This ensures proper treatment of the restriction
5026          --  No_Implicit_Heap_Allocations in this case.
5027
5028          Set_Storage_Pool      (New_Allocator, Storage_Pool      (Allocator));
5029          Set_Procedure_To_Call (New_Allocator, Procedure_To_Call (Allocator));
5030          Set_Comes_From_Source (New_Allocator, Comes_From_Source (Allocator));
5031
5032          Rewrite (Allocator, New_Allocator);
5033
5034          --  Create a new access object and initialize it to the result of the
5035          --  new uninitialized allocator.
5036
5037          Return_Obj_Access :=
5038            Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
5039          Set_Etype (Return_Obj_Access, Acc_Type);
5040
5041          Insert_Action (Allocator,
5042            Make_Object_Declaration (Loc,
5043              Defining_Identifier => Return_Obj_Access,
5044              Object_Definition   => New_Reference_To (Acc_Type, Loc),
5045              Expression          => Relocate_Node (Allocator)));
5046
5047          --  When the function has a controlling result, an allocation-form
5048          --  parameter must be passed indicating that the caller is allocating
5049          --  the result object. This is needed because such a function can be
5050          --  called as a dispatching operation and must be treated similarly
5051          --  to functions with unconstrained result subtypes.
5052
5053          Add_Alloc_Form_Actual_To_Build_In_Place_Call
5054            (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
5055
5056          Add_Final_List_Actual_To_Build_In_Place_Call
5057            (Func_Call, Function_Id, Acc_Type);
5058
5059          Add_Task_Actuals_To_Build_In_Place_Call
5060            (Func_Call, Function_Id, Master_Actual => Master_Id (Acc_Type));
5061
5062          --  Add an implicit actual to the function call that provides access
5063          --  to the allocated object. An unchecked conversion to the (specific)
5064          --  result subtype of the function is inserted to handle cases where
5065          --  the access type of the allocator has a class-wide designated type.
5066
5067          Add_Access_Actual_To_Build_In_Place_Call
5068            (Func_Call,
5069             Function_Id,
5070             Make_Unchecked_Type_Conversion (Loc,
5071               Subtype_Mark => New_Reference_To (Result_Subt, Loc),
5072               Expression   =>
5073                 Make_Explicit_Dereference (Loc,
5074                   Prefix => New_Reference_To (Return_Obj_Access, Loc))));
5075
5076       --  When the result subtype is unconstrained, the function itself must
5077       --  perform the allocation of the return object, so we pass parameters
5078       --  indicating that. We don't yet handle the case where the allocation
5079       --  must be done in a user-defined storage pool, which will require
5080       --  passing another actual or two to provide allocation/deallocation
5081       --  operations. ???
5082
5083       else
5084
5085          --  Pass an allocation parameter indicating that the function should
5086          --  allocate its result on the heap.
5087
5088          Add_Alloc_Form_Actual_To_Build_In_Place_Call
5089            (Func_Call, Function_Id, Alloc_Form => Global_Heap);
5090
5091          Add_Final_List_Actual_To_Build_In_Place_Call
5092            (Func_Call, Function_Id, Acc_Type);
5093
5094          Add_Task_Actuals_To_Build_In_Place_Call
5095            (Func_Call, Function_Id, Master_Actual => Master_Id (Acc_Type));
5096
5097          --  The caller does not provide the return object in this case, so we
5098          --  have to pass null for the object access actual.
5099
5100          Add_Access_Actual_To_Build_In_Place_Call
5101            (Func_Call, Function_Id, Return_Object => Empty);
5102       end if;
5103
5104       --  Finally, replace the allocator node with a reference to the result
5105       --  of the function call itself (which will effectively be an access
5106       --  to the object created by the allocator).
5107
5108       Rewrite (Allocator, Make_Reference (Loc, Relocate_Node (Function_Call)));
5109       Analyze_And_Resolve (Allocator, Acc_Type);
5110    end Make_Build_In_Place_Call_In_Allocator;
5111
5112    ---------------------------------------------------
5113    -- Make_Build_In_Place_Call_In_Anonymous_Context --
5114    ---------------------------------------------------
5115
5116    procedure Make_Build_In_Place_Call_In_Anonymous_Context
5117      (Function_Call : Node_Id)
5118    is
5119       Loc             : Source_Ptr;
5120       Func_Call       : Node_Id := Function_Call;
5121       Function_Id     : Entity_Id;
5122       Result_Subt     : Entity_Id;
5123       Return_Obj_Id   : Entity_Id;
5124       Return_Obj_Decl : Entity_Id;
5125
5126    begin
5127       --  Step past qualification or unchecked conversion (the latter can occur
5128       --  in cases of calls to 'Input).
5129
5130       if Nkind_In (Func_Call, N_Qualified_Expression,
5131                               N_Unchecked_Type_Conversion)
5132       then
5133          Func_Call := Expression (Func_Call);
5134       end if;
5135
5136       --  If the call has already been processed to add build-in-place actuals
5137       --  then return. One place this can occur is for calls to build-in-place
5138       --  functions that occur within a call to a protected operation, where
5139       --  due to rewriting and expansion of the protected call there can be
5140       --  more than one call to Expand_Actuals for the same set of actuals.
5141
5142       if Is_Expanded_Build_In_Place_Call (Func_Call) then
5143          return;
5144       end if;
5145
5146       --  Mark the call as processed as a build-in-place call
5147
5148       Set_Is_Expanded_Build_In_Place_Call (Func_Call);
5149
5150       Loc := Sloc (Function_Call);
5151
5152       if Is_Entity_Name (Name (Func_Call)) then
5153          Function_Id := Entity (Name (Func_Call));
5154
5155       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
5156          Function_Id := Etype (Name (Func_Call));
5157
5158       else
5159          raise Program_Error;
5160       end if;
5161
5162       Result_Subt := Etype (Function_Id);
5163
5164       --  When the result subtype is constrained, an object of the subtype is
5165       --  declared and an access value designating it is passed as an actual.
5166
5167       if Is_Constrained (Underlying_Type (Result_Subt)) then
5168
5169          --  Create a temporary object to hold the function result
5170
5171          Return_Obj_Id :=
5172            Make_Defining_Identifier (Loc,
5173              Chars => New_Internal_Name ('R'));
5174          Set_Etype (Return_Obj_Id, Result_Subt);
5175
5176          Return_Obj_Decl :=
5177            Make_Object_Declaration (Loc,
5178              Defining_Identifier => Return_Obj_Id,
5179              Aliased_Present     => True,
5180              Object_Definition   => New_Reference_To (Result_Subt, Loc));
5181
5182          Set_No_Initialization (Return_Obj_Decl);
5183
5184          Insert_Action (Func_Call, Return_Obj_Decl);
5185
5186          --  When the function has a controlling result, an allocation-form
5187          --  parameter must be passed indicating that the caller is allocating
5188          --  the result object. This is needed because such a function can be
5189          --  called as a dispatching operation and must be treated similarly
5190          --  to functions with unconstrained result subtypes.
5191
5192          Add_Alloc_Form_Actual_To_Build_In_Place_Call
5193            (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
5194
5195          Add_Final_List_Actual_To_Build_In_Place_Call
5196            (Func_Call, Function_Id, Acc_Type => Empty);
5197
5198          Add_Task_Actuals_To_Build_In_Place_Call
5199            (Func_Call, Function_Id, Make_Identifier (Loc, Name_uMaster));
5200
5201          --  Add an implicit actual to the function call that provides access
5202          --  to the caller's return object.
5203
5204          Add_Access_Actual_To_Build_In_Place_Call
5205            (Func_Call, Function_Id, New_Reference_To (Return_Obj_Id, Loc));
5206
5207       --  When the result subtype is unconstrained, the function must allocate
5208       --  the return object in the secondary stack, so appropriate implicit
5209       --  parameters are added to the call to indicate that. A transient
5210       --  scope is established to ensure eventual cleanup of the result.
5211
5212       else
5213
5214          --  Pass an allocation parameter indicating that the function should
5215          --  allocate its result on the secondary stack.
5216
5217          Add_Alloc_Form_Actual_To_Build_In_Place_Call
5218            (Func_Call, Function_Id, Alloc_Form => Secondary_Stack);
5219
5220          Add_Final_List_Actual_To_Build_In_Place_Call
5221            (Func_Call, Function_Id, Acc_Type => Empty);
5222
5223          Add_Task_Actuals_To_Build_In_Place_Call
5224            (Func_Call, Function_Id, Make_Identifier (Loc, Name_uMaster));
5225
5226          --  Pass a null value to the function since no return object is
5227          --  available on the caller side.
5228
5229          Add_Access_Actual_To_Build_In_Place_Call
5230            (Func_Call, Function_Id, Empty);
5231
5232          Establish_Transient_Scope (Func_Call, Sec_Stack => True);
5233       end if;
5234    end Make_Build_In_Place_Call_In_Anonymous_Context;
5235
5236    --------------------------------------------
5237    -- Make_Build_In_Place_Call_In_Assignment --
5238    --------------------------------------------
5239
5240    procedure Make_Build_In_Place_Call_In_Assignment
5241      (Assign        : Node_Id;
5242       Function_Call : Node_Id)
5243    is
5244       Lhs             : constant Node_Id := Name (Assign);
5245       Loc             : Source_Ptr;
5246       Func_Call       : Node_Id := Function_Call;
5247       Function_Id     : Entity_Id;
5248       Result_Subt     : Entity_Id;
5249       Ref_Type        : Entity_Id;
5250       Ptr_Typ_Decl    : Node_Id;
5251       Def_Id          : Entity_Id;
5252       New_Expr        : Node_Id;
5253
5254    begin
5255       --  Step past qualification or unchecked conversion (the latter can occur
5256       --  in cases of calls to 'Input).
5257
5258       if Nkind_In (Func_Call, N_Qualified_Expression,
5259                               N_Unchecked_Type_Conversion)
5260       then
5261          Func_Call := Expression (Func_Call);
5262       end if;
5263
5264       --  If the call has already been processed to add build-in-place actuals
5265       --  then return. This should not normally occur in an assignment context,
5266       --  but we add the protection as a defensive measure.
5267
5268       if Is_Expanded_Build_In_Place_Call (Func_Call) then
5269          return;
5270       end if;
5271
5272       --  Mark the call as processed as a build-in-place call
5273
5274       Set_Is_Expanded_Build_In_Place_Call (Func_Call);
5275
5276       Loc := Sloc (Function_Call);
5277
5278       if Is_Entity_Name (Name (Func_Call)) then
5279          Function_Id := Entity (Name (Func_Call));
5280
5281       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
5282          Function_Id := Etype (Name (Func_Call));
5283
5284       else
5285          raise Program_Error;
5286       end if;
5287
5288       Result_Subt := Etype (Function_Id);
5289
5290       --  When the result subtype is unconstrained, an additional actual must
5291       --  be passed to indicate that the caller is providing the return object.
5292       --  This parameter must also be passed when the called function has a
5293       --  controlling result, because dispatching calls to the function needs
5294       --  to be treated effectively the same as calls to class-wide functions.
5295
5296       Add_Alloc_Form_Actual_To_Build_In_Place_Call
5297         (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
5298
5299       --  If Lhs is a selected component, then pass it along so that its prefix
5300       --  object will be used as the source of the finalization list.
5301
5302       if Nkind (Lhs) = N_Selected_Component then
5303          Add_Final_List_Actual_To_Build_In_Place_Call
5304            (Func_Call, Function_Id, Acc_Type => Empty, Sel_Comp => Lhs);
5305       else
5306          Add_Final_List_Actual_To_Build_In_Place_Call
5307            (Func_Call, Function_Id, Acc_Type => Empty);
5308       end if;
5309
5310       Add_Task_Actuals_To_Build_In_Place_Call
5311         (Func_Call, Function_Id, Make_Identifier (Loc, Name_uMaster));
5312
5313       --  Add an implicit actual to the function call that provides access to
5314       --  the caller's return object.
5315
5316       Add_Access_Actual_To_Build_In_Place_Call
5317         (Func_Call,
5318          Function_Id,
5319          Make_Unchecked_Type_Conversion (Loc,
5320            Subtype_Mark => New_Reference_To (Result_Subt, Loc),
5321            Expression   => Relocate_Node (Lhs)));
5322
5323       --  Create an access type designating the function's result subtype
5324
5325       Ref_Type :=
5326         Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
5327
5328       Ptr_Typ_Decl :=
5329         Make_Full_Type_Declaration (Loc,
5330           Defining_Identifier => Ref_Type,
5331           Type_Definition =>
5332             Make_Access_To_Object_Definition (Loc,
5333               All_Present => True,
5334               Subtype_Indication =>
5335                 New_Reference_To (Result_Subt, Loc)));
5336
5337       Insert_After_And_Analyze (Assign, Ptr_Typ_Decl);
5338
5339       --  Finally, create an access object initialized to a reference to the
5340       --  function call.
5341
5342       Def_Id :=
5343         Make_Defining_Identifier (Loc,
5344           Chars => New_Internal_Name ('R'));
5345       Set_Etype (Def_Id, Ref_Type);
5346
5347       New_Expr :=
5348         Make_Reference (Loc,
5349           Prefix => Relocate_Node (Func_Call));
5350
5351       Insert_After_And_Analyze (Ptr_Typ_Decl,
5352         Make_Object_Declaration (Loc,
5353           Defining_Identifier => Def_Id,
5354           Object_Definition   => New_Reference_To (Ref_Type, Loc),
5355           Expression          => New_Expr));
5356
5357       Rewrite (Assign, Make_Null_Statement (Loc));
5358    end Make_Build_In_Place_Call_In_Assignment;
5359
5360    ----------------------------------------------------
5361    -- Make_Build_In_Place_Call_In_Object_Declaration --
5362    ----------------------------------------------------
5363
5364    procedure Make_Build_In_Place_Call_In_Object_Declaration
5365      (Object_Decl   : Node_Id;
5366       Function_Call : Node_Id)
5367    is
5368       Loc             : Source_Ptr;
5369       Obj_Def_Id      : constant Entity_Id :=
5370                           Defining_Identifier (Object_Decl);
5371
5372       Func_Call       : Node_Id := Function_Call;
5373       Function_Id     : Entity_Id;
5374       Result_Subt     : Entity_Id;
5375       Caller_Object   : Node_Id;
5376       Call_Deref      : Node_Id;
5377       Ref_Type        : Entity_Id;
5378       Ptr_Typ_Decl    : Node_Id;
5379       Def_Id          : Entity_Id;
5380       New_Expr        : Node_Id;
5381       Enclosing_Func  : Entity_Id;
5382       Pass_Caller_Acc : Boolean := False;
5383
5384    begin
5385       --  Step past qualification or unchecked conversion (the latter can occur
5386       --  in cases of calls to 'Input).
5387
5388       if Nkind_In (Func_Call, N_Qualified_Expression,
5389                               N_Unchecked_Type_Conversion)
5390       then
5391          Func_Call := Expression (Func_Call);
5392       end if;
5393
5394       --  If the call has already been processed to add build-in-place actuals
5395       --  then return. This should not normally occur in an object declaration,
5396       --  but we add the protection as a defensive measure.
5397
5398       if Is_Expanded_Build_In_Place_Call (Func_Call) then
5399          return;
5400       end if;
5401
5402       --  Mark the call as processed as a build-in-place call
5403
5404       Set_Is_Expanded_Build_In_Place_Call (Func_Call);
5405
5406       Loc := Sloc (Function_Call);
5407
5408       if Is_Entity_Name (Name (Func_Call)) then
5409          Function_Id := Entity (Name (Func_Call));
5410
5411       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
5412          Function_Id := Etype (Name (Func_Call));
5413
5414       else
5415          raise Program_Error;
5416       end if;
5417
5418       Result_Subt := Etype (Function_Id);
5419
5420       --  In the constrained case, add an implicit actual to the function call
5421       --  that provides access to the declared object. An unchecked conversion
5422       --  to the (specific) result type of the function is inserted to handle
5423       --  the case where the object is declared with a class-wide type.
5424
5425       if Is_Constrained (Underlying_Type (Result_Subt)) then
5426          Caller_Object :=
5427             Make_Unchecked_Type_Conversion (Loc,
5428               Subtype_Mark => New_Reference_To (Result_Subt, Loc),
5429               Expression   => New_Reference_To (Obj_Def_Id, Loc));
5430
5431          --  When the function has a controlling result, an allocation-form
5432          --  parameter must be passed indicating that the caller is allocating
5433          --  the result object. This is needed because such a function can be
5434          --  called as a dispatching operation and must be treated similarly
5435          --  to functions with unconstrained result subtypes.
5436
5437          Add_Alloc_Form_Actual_To_Build_In_Place_Call
5438            (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
5439
5440       --  If the function's result subtype is unconstrained and the object is
5441       --  a return object of an enclosing build-in-place function, then the
5442       --  implicit build-in-place parameters of the enclosing function must be
5443       --  passed along to the called function.
5444
5445       elsif Nkind (Parent (Object_Decl)) = N_Extended_Return_Statement then
5446          Pass_Caller_Acc := True;
5447
5448          Enclosing_Func := Enclosing_Subprogram (Obj_Def_Id);
5449
5450          --  If the enclosing function has a constrained result type, then
5451          --  caller allocation will be used.
5452
5453          if Is_Constrained (Etype (Enclosing_Func)) then
5454             Add_Alloc_Form_Actual_To_Build_In_Place_Call
5455               (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
5456
5457          --  Otherwise, when the enclosing function has an unconstrained result
5458          --  type, the BIP_Alloc_Form formal of the enclosing function must be
5459          --  passed along to the callee.
5460
5461          else
5462             Add_Alloc_Form_Actual_To_Build_In_Place_Call
5463               (Func_Call,
5464                Function_Id,
5465                Alloc_Form_Exp =>
5466                  New_Reference_To
5467                    (Build_In_Place_Formal (Enclosing_Func, BIP_Alloc_Form),
5468                     Loc));
5469          end if;
5470
5471          --  Retrieve the BIPacc formal from the enclosing function and convert
5472          --  it to the access type of the callee's BIP_Object_Access formal.
5473
5474          Caller_Object :=
5475             Make_Unchecked_Type_Conversion (Loc,
5476               Subtype_Mark =>
5477                 New_Reference_To
5478                   (Etype
5479                      (Build_In_Place_Formal (Function_Id, BIP_Object_Access)),
5480                    Loc),
5481               Expression   =>
5482                 New_Reference_To
5483                   (Build_In_Place_Formal (Enclosing_Func, BIP_Object_Access),
5484                    Loc));
5485
5486       --  In other unconstrained cases, pass an indication to do the allocation
5487       --  on the secondary stack and set Caller_Object to Empty so that a null
5488       --  value will be passed for the caller's object address. A transient
5489       --  scope is established to ensure eventual cleanup of the result.
5490
5491       else
5492          Add_Alloc_Form_Actual_To_Build_In_Place_Call
5493            (Func_Call,
5494             Function_Id,
5495             Alloc_Form => Secondary_Stack);
5496          Caller_Object := Empty;
5497
5498          Establish_Transient_Scope (Object_Decl, Sec_Stack => True);
5499       end if;
5500
5501       Add_Final_List_Actual_To_Build_In_Place_Call
5502         (Func_Call, Function_Id, Acc_Type => Empty);
5503
5504       if Nkind (Parent (Object_Decl)) = N_Extended_Return_Statement
5505         and then Has_Task (Result_Subt)
5506       then
5507          Enclosing_Func := Enclosing_Subprogram (Obj_Def_Id);
5508
5509          --  Here we're passing along the master that was passed in to this
5510          --  function.
5511
5512          Add_Task_Actuals_To_Build_In_Place_Call
5513            (Func_Call, Function_Id,
5514             Master_Actual =>
5515               New_Reference_To
5516                 (Build_In_Place_Formal (Enclosing_Func, BIP_Master), Loc));
5517
5518       else
5519          Add_Task_Actuals_To_Build_In_Place_Call
5520            (Func_Call, Function_Id, Make_Identifier (Loc, Name_uMaster));
5521       end if;
5522
5523       Add_Access_Actual_To_Build_In_Place_Call
5524         (Func_Call, Function_Id, Caller_Object, Is_Access => Pass_Caller_Acc);
5525
5526       --  Create an access type designating the function's result subtype
5527
5528       Ref_Type :=
5529         Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
5530
5531       Ptr_Typ_Decl :=
5532         Make_Full_Type_Declaration (Loc,
5533           Defining_Identifier => Ref_Type,
5534           Type_Definition =>
5535             Make_Access_To_Object_Definition (Loc,
5536               All_Present => True,
5537               Subtype_Indication =>
5538                 New_Reference_To (Result_Subt, Loc)));
5539
5540       --  The access type and its accompanying object must be inserted after
5541       --  the object declaration in the constrained case, so that the function
5542       --  call can be passed access to the object. In the unconstrained case,
5543       --  the access type and object must be inserted before the object, since
5544       --  the object declaration is rewritten to be a renaming of a dereference
5545       --  of the access object.
5546
5547       if Is_Constrained (Underlying_Type (Result_Subt)) then
5548          Insert_After_And_Analyze (Object_Decl, Ptr_Typ_Decl);
5549       else
5550          Insert_Action (Object_Decl, Ptr_Typ_Decl);
5551       end if;
5552
5553       --  Finally, create an access object initialized to a reference to the
5554       --  function call.
5555
5556       Def_Id :=
5557         Make_Defining_Identifier (Loc,
5558           Chars => New_Internal_Name ('R'));
5559       Set_Etype (Def_Id, Ref_Type);
5560
5561       New_Expr :=
5562         Make_Reference (Loc,
5563           Prefix => Relocate_Node (Func_Call));
5564
5565       Insert_After_And_Analyze (Ptr_Typ_Decl,
5566         Make_Object_Declaration (Loc,
5567           Defining_Identifier => Def_Id,
5568           Object_Definition   => New_Reference_To (Ref_Type, Loc),
5569           Expression          => New_Expr));
5570
5571       if Is_Constrained (Underlying_Type (Result_Subt)) then
5572          Set_Expression (Object_Decl, Empty);
5573          Set_No_Initialization (Object_Decl);
5574
5575       --  In case of an unconstrained result subtype, rewrite the object
5576       --  declaration as an object renaming where the renamed object is a
5577       --  dereference of <function_Call>'reference:
5578       --
5579       --      Obj : Subt renames <function_call>'Ref.all;
5580
5581       else
5582          Call_Deref :=
5583            Make_Explicit_Dereference (Loc,
5584              Prefix => New_Reference_To (Def_Id, Loc));
5585
5586          Rewrite (Object_Decl,
5587            Make_Object_Renaming_Declaration (Loc,
5588              Defining_Identifier => Make_Defining_Identifier (Loc,
5589                                       New_Internal_Name ('D')),
5590              Access_Definition   => Empty,
5591              Subtype_Mark        => New_Occurrence_Of (Result_Subt, Loc),
5592              Name                => Call_Deref));
5593
5594          Set_Renamed_Object (Defining_Identifier (Object_Decl), Call_Deref);
5595
5596          Analyze (Object_Decl);
5597
5598          --  Replace the internal identifier of the renaming declaration's
5599          --  entity with identifier of the original object entity. We also have
5600          --  to exchange the entities containing their defining identifiers to
5601          --  ensure the correct replacement of the object declaration by the
5602          --  object renaming declaration to avoid homograph conflicts (since
5603          --  the object declaration's defining identifier was already entered
5604          --  in current scope). The Next_Entity links of the two entities also
5605          --  have to be swapped since the entities are part of the return
5606          --  scope's entity list and the list structure would otherwise be
5607          --  corrupted.
5608
5609          declare
5610             Renaming_Def_Id  : constant Entity_Id :=
5611                                  Defining_Identifier (Object_Decl);
5612             Next_Entity_Temp : constant Entity_Id :=
5613                                  Next_Entity (Renaming_Def_Id);
5614          begin
5615             Set_Chars (Renaming_Def_Id, Chars (Obj_Def_Id));
5616
5617             --  Swap next entity links in preparation for exchanging entities
5618
5619             Set_Next_Entity (Renaming_Def_Id, Next_Entity (Obj_Def_Id));
5620             Set_Next_Entity (Obj_Def_Id, Next_Entity_Temp);
5621
5622             Exchange_Entities (Renaming_Def_Id, Obj_Def_Id);
5623          end;
5624       end if;
5625
5626       --  If the object entity has a class-wide Etype, then we need to change
5627       --  it to the result subtype of the function call, because otherwise the
5628       --  object will be class-wide without an explicit initialization and
5629       --  won't be allocated properly by the back end. It seems unclean to make
5630       --  such a revision to the type at this point, and we should try to
5631       --  improve this treatment when build-in-place functions with class-wide
5632       --  results are implemented. ???
5633
5634       if Is_Class_Wide_Type (Etype (Defining_Identifier (Object_Decl))) then
5635          Set_Etype (Defining_Identifier (Object_Decl), Result_Subt);
5636       end if;
5637    end Make_Build_In_Place_Call_In_Object_Declaration;
5638
5639    --------------------------
5640    -- Needs_BIP_Final_List --
5641    --------------------------
5642
5643    function Needs_BIP_Final_List (E : Entity_Id) return Boolean is
5644       pragma Assert (Is_Build_In_Place_Function (E));
5645       Result_Subt : constant Entity_Id := Underlying_Type (Etype (E));
5646
5647    begin
5648       --  We need the BIP_Final_List if the result type needs finalization. We
5649       --  also need it for tagged types, even if not class-wide, because some
5650       --  type extension might need finalization, and all overriding functions
5651       --  must have the same calling conventions. However, if there is a
5652       --  pragma Restrictions (No_Finalization), we never need this parameter.
5653
5654       return (Needs_Finalization (Result_Subt)
5655                or else Is_Tagged_Type (Underlying_Type (Result_Subt)))
5656         and then not Restriction_Active (No_Finalization);
5657    end Needs_BIP_Final_List;
5658
5659 end Exp_Ch6;