OSDN Git Service

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