OSDN Git Service

2011-08-29 Tristan Gingold <gingold@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-2011, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Checks;   use Checks;
28 with Debug;    use Debug;
29 with Einfo;    use Einfo;
30 with Errout;   use Errout;
31 with Elists;   use Elists;
32 with Exp_Atag; use Exp_Atag;
33 with Exp_Ch2;  use Exp_Ch2;
34 with Exp_Ch3;  use Exp_Ch3;
35 with Exp_Ch7;  use Exp_Ch7;
36 with Exp_Ch9;  use Exp_Ch9;
37 with Exp_Dbug; use Exp_Dbug;
38 with Exp_Disp; use Exp_Disp;
39 with Exp_Dist; use Exp_Dist;
40 with Exp_Intr; use Exp_Intr;
41 with Exp_Pakd; use Exp_Pakd;
42 with Exp_Tss;  use Exp_Tss;
43 with Exp_Util; use Exp_Util;
44 with Exp_VFpt; use Exp_VFpt;
45 with Fname;    use Fname;
46 with Freeze;   use Freeze;
47 with Inline;   use Inline;
48 with Lib;      use Lib;
49 with Namet;    use Namet;
50 with Nlists;   use Nlists;
51 with Nmake;    use Nmake;
52 with Opt;      use Opt;
53 with Restrict; use Restrict;
54 with Rident;   use Rident;
55 with Rtsfind;  use Rtsfind;
56 with Sem;      use Sem;
57 with Sem_Aux;  use Sem_Aux;
58 with Sem_Ch6;  use Sem_Ch6;
59 with Sem_Ch8;  use Sem_Ch8;
60 with Sem_Ch12; use Sem_Ch12;
61 with Sem_Ch13; use Sem_Ch13;
62 with Sem_Eval; use Sem_Eval;
63 with Sem_Disp; use Sem_Disp;
64 with Sem_Dist; use Sem_Dist;
65 with Sem_Mech; use Sem_Mech;
66 with Sem_Res;  use Sem_Res;
67 with Sem_SCIL; use Sem_SCIL;
68 with Sem_Util; use Sem_Util;
69 with Sinfo;    use Sinfo;
70 with Snames;   use Snames;
71 with Stand;    use Stand;
72 with Targparm; use Targparm;
73 with Tbuild;   use Tbuild;
74 with Uintp;    use Uintp;
75 with Validsw;  use Validsw;
76
77 package body Exp_Ch6 is
78
79    -----------------------
80    -- Local Subprograms --
81    -----------------------
82
83    procedure Add_Access_Actual_To_Build_In_Place_Call
84      (Function_Call : Node_Id;
85       Function_Id   : Entity_Id;
86       Return_Object : Node_Id;
87       Is_Access     : Boolean := False);
88    --  Ada 2005 (AI-318-02): Apply the Unrestricted_Access attribute to the
89    --  object name given by Return_Object and add the attribute to the end of
90    --  the actual parameter list associated with the build-in-place function
91    --  call denoted by Function_Call. However, if Is_Access is True, then
92    --  Return_Object is already an access expression, in which case it's passed
93    --  along directly to the build-in-place function. Finally, if Return_Object
94    --  is empty, then pass a null literal as the actual.
95
96    procedure Add_Alloc_Form_Actual_To_Build_In_Place_Call
97      (Function_Call  : Node_Id;
98       Function_Id    : Entity_Id;
99       Alloc_Form     : BIP_Allocation_Form := Unspecified;
100       Alloc_Form_Exp : Node_Id             := Empty);
101    --  Ada 2005 (AI-318-02): Add an actual indicating the form of allocation,
102    --  if any, to be done by a build-in-place function. If Alloc_Form_Exp is
103    --  present, then use it, otherwise pass a literal corresponding to the
104    --  Alloc_Form parameter (which must not be Unspecified in that case).
105
106    procedure Add_Extra_Actual_To_Call
107      (Subprogram_Call : Node_Id;
108       Extra_Formal    : Entity_Id;
109       Extra_Actual    : Node_Id);
110    --  Adds Extra_Actual as a named parameter association for the formal
111    --  Extra_Formal in Subprogram_Call.
112
113    procedure Add_Finalization_Master_Actual_To_Build_In_Place_Call
114      (Func_Call : Node_Id;
115       Func_Id   : Entity_Id;
116       Ptr_Typ   : Entity_Id := Empty);
117    --  Ada 2005 (AI-318-02): If the result type of a build-in-place call needs
118    --  finalization actions, add an actual parameter which is a pointer to the
119    --  finalization master of the caller. If Ptr_Typ is left Empty, this will
120    --  result in an automatic "null" value for the actual.
121
122    procedure Add_Task_Actuals_To_Build_In_Place_Call
123      (Function_Call : Node_Id;
124       Function_Id   : Entity_Id;
125       Master_Actual : Node_Id);
126    --  Ada 2005 (AI-318-02): For a build-in-place call, if the result type
127    --  contains tasks, add two actual parameters: the master, and a pointer to
128    --  the caller's activation chain. Master_Actual is the actual parameter
129    --  expression to pass for the master. In most cases, this is the current
130    --  master (_master). The two exceptions are: If the function call is the
131    --  initialization expression for an allocator, we pass the master of the
132    --  access type. If the function call is the initialization expression for a
133    --  return object, we pass along the master passed in by the caller. The
134    --  activation chain to pass is always the local one. Note: Master_Actual
135    --  can be Empty, but only if there are no tasks.
136
137    procedure Check_Overriding_Operation (Subp : Entity_Id);
138    --  Subp is a dispatching operation. Check whether it may override an
139    --  inherited private operation, in which case its DT entry is that of
140    --  the hidden operation, not the one it may have received earlier.
141    --  This must be done before emitting the code to set the corresponding
142    --  DT to the address of the subprogram. The actual placement of Subp in
143    --  the proper place in the list of primitive operations is done in
144    --  Declare_Inherited_Private_Subprograms, which also has to deal with
145    --  implicit operations. This duplication is unavoidable for now???
146
147    procedure Detect_Infinite_Recursion (N : Node_Id; Spec : Entity_Id);
148    --  This procedure is called only if the subprogram body N, whose spec
149    --  has the given entity Spec, contains a parameterless recursive call.
150    --  It attempts to generate runtime code to detect if this a case of
151    --  infinite recursion.
152    --
153    --  The body is scanned to determine dependencies. If the only external
154    --  dependencies are on a small set of scalar variables, then the values
155    --  of these variables are captured on entry to the subprogram, and if
156    --  the values are not changed for the call, we know immediately that
157    --  we have an infinite recursion.
158
159    procedure Expand_Actuals (N : Node_Id; Subp : Entity_Id);
160    --  For each actual of an in-out or out parameter which is a numeric
161    --  (view) conversion of the form T (A), where A denotes a variable,
162    --  we insert the declaration:
163    --
164    --    Temp : T[ := T (A)];
165    --
166    --  prior to the call. Then we replace the actual with a reference to Temp,
167    --  and append the assignment:
168    --
169    --    A := TypeA (Temp);
170    --
171    --  after the call. Here TypeA is the actual type of variable A. For out
172    --  parameters, the initial declaration has no expression. If A is not an
173    --  entity name, we generate instead:
174    --
175    --    Var  : TypeA renames A;
176    --    Temp : T := Var;       --  omitting expression for out parameter.
177    --    ...
178    --    Var := TypeA (Temp);
179    --
180    --  For other in-out parameters, we emit the required constraint checks
181    --  before and/or after the call.
182    --
183    --  For all parameter modes, actuals that denote components and slices of
184    --  packed arrays are expanded into suitable temporaries.
185    --
186    --  For non-scalar objects that are possibly unaligned, add call by copy
187    --  code (copy in for IN and IN OUT, copy out for OUT and IN OUT).
188
189    procedure Expand_Ctrl_Function_Call (N : Node_Id);
190    --  N is a function call which returns a controlled object. Transform the
191    --  call into a temporary which retrieves the returned object from the
192    --  secondary stack using 'reference.
193
194    procedure Expand_Inlined_Call
195     (N         : Node_Id;
196      Subp      : Entity_Id;
197      Orig_Subp : Entity_Id);
198    --  If called subprogram can be inlined by the front-end, retrieve the
199    --  analyzed body, replace formals with actuals and expand call in place.
200    --  Generate thunks for actuals that are expressions, and insert the
201    --  corresponding constant declarations before the call. If the original
202    --  call is to a derived operation, the return type is the one of the
203    --  derived operation, but the body is that of the original, so return
204    --  expressions in the body must be converted to the desired type (which
205    --  is simply not noted in the tree without inline expansion).
206
207    procedure Expand_Non_Function_Return (N : Node_Id);
208    --  Called by Expand_N_Simple_Return_Statement in case we're returning from
209    --  a procedure body, entry body, accept statement, or extended return
210    --  statement.  Note that all non-function returns are simple return
211    --  statements.
212
213    function Expand_Protected_Object_Reference
214      (N    : Node_Id;
215       Scop : Entity_Id) return Node_Id;
216
217    procedure Expand_Protected_Subprogram_Call
218      (N    : Node_Id;
219       Subp : Entity_Id;
220       Scop : Entity_Id);
221    --  A call to a protected subprogram within the protected object may appear
222    --  as a regular call. The list of actuals must be expanded to contain a
223    --  reference to the object itself, and the call becomes a call to the
224    --  corresponding protected subprogram.
225
226    procedure Expand_Simple_Function_Return (N : Node_Id);
227    --  Expand simple return from function. In the case where we are returning
228    --  from a function body this is called by Expand_N_Simple_Return_Statement.
229
230    ----------------------------------------------
231    -- Add_Access_Actual_To_Build_In_Place_Call --
232    ----------------------------------------------
233
234    procedure Add_Access_Actual_To_Build_In_Place_Call
235      (Function_Call : Node_Id;
236       Function_Id   : Entity_Id;
237       Return_Object : Node_Id;
238       Is_Access     : Boolean := False)
239    is
240       Loc            : constant Source_Ptr := Sloc (Function_Call);
241       Obj_Address    : Node_Id;
242       Obj_Acc_Formal : Entity_Id;
243
244    begin
245       --  Locate the implicit access parameter in the called function
246
247       Obj_Acc_Formal := Build_In_Place_Formal (Function_Id, BIP_Object_Access);
248
249       --  If no return object is provided, then pass null
250
251       if not Present (Return_Object) then
252          Obj_Address := Make_Null (Loc);
253          Set_Parent (Obj_Address, Function_Call);
254
255       --  If Return_Object is already an expression of an access type, then use
256       --  it directly, since it must be an access value denoting the return
257       --  object, and couldn't possibly be the return object itself.
258
259       elsif Is_Access then
260          Obj_Address := Return_Object;
261          Set_Parent (Obj_Address, Function_Call);
262
263       --  Apply Unrestricted_Access to caller's return object
264
265       else
266          Obj_Address :=
267             Make_Attribute_Reference (Loc,
268               Prefix         => Return_Object,
269               Attribute_Name => Name_Unrestricted_Access);
270
271          Set_Parent (Return_Object, Obj_Address);
272          Set_Parent (Obj_Address, Function_Call);
273       end if;
274
275       Analyze_And_Resolve (Obj_Address, Etype (Obj_Acc_Formal));
276
277       --  Build the parameter association for the new actual and add it to the
278       --  end of the function's actuals.
279
280       Add_Extra_Actual_To_Call (Function_Call, Obj_Acc_Formal, Obj_Address);
281    end Add_Access_Actual_To_Build_In_Place_Call;
282
283    --------------------------------------------------
284    -- Add_Alloc_Form_Actual_To_Build_In_Place_Call --
285    --------------------------------------------------
286
287    procedure Add_Alloc_Form_Actual_To_Build_In_Place_Call
288      (Function_Call  : Node_Id;
289       Function_Id    : Entity_Id;
290       Alloc_Form     : BIP_Allocation_Form := Unspecified;
291       Alloc_Form_Exp : Node_Id             := Empty)
292    is
293       Loc               : constant Source_Ptr := Sloc (Function_Call);
294       Alloc_Form_Actual : Node_Id;
295       Alloc_Form_Formal : Node_Id;
296
297    begin
298       --  The allocation form generally doesn't need to be passed in the case
299       --  of a constrained result subtype, since normally the caller performs
300       --  the allocation in that case. However this formal is still needed in
301       --  the case where the function has a tagged result, because generally
302       --  such functions can be called in a dispatching context and such calls
303       --  must be handled like calls to class-wide functions.
304
305       if Is_Constrained (Underlying_Type (Etype (Function_Id)))
306         and then not Is_Tagged_Type (Underlying_Type (Etype (Function_Id)))
307       then
308          return;
309       end if;
310
311       --  Locate the implicit allocation form parameter in the called function.
312       --  Maybe it would be better for each implicit formal of a build-in-place
313       --  function to have a flag or a Uint attribute to identify it. ???
314
315       Alloc_Form_Formal := Build_In_Place_Formal (Function_Id, BIP_Alloc_Form);
316
317       if Present (Alloc_Form_Exp) then
318          pragma Assert (Alloc_Form = Unspecified);
319
320          Alloc_Form_Actual := Alloc_Form_Exp;
321
322       else
323          pragma Assert (Alloc_Form /= Unspecified);
324
325          Alloc_Form_Actual :=
326            Make_Integer_Literal (Loc,
327              Intval => UI_From_Int (BIP_Allocation_Form'Pos (Alloc_Form)));
328       end if;
329
330       Analyze_And_Resolve (Alloc_Form_Actual, Etype (Alloc_Form_Formal));
331
332       --  Build the parameter association for the new actual and add it to the
333       --  end of the function's actuals.
334
335       Add_Extra_Actual_To_Call
336         (Function_Call, Alloc_Form_Formal, Alloc_Form_Actual);
337    end Add_Alloc_Form_Actual_To_Build_In_Place_Call;
338
339    -----------------------------------------------------------
340    -- Add_Finalization_Master_Actual_To_Build_In_Place_Call --
341    -----------------------------------------------------------
342
343    procedure Add_Finalization_Master_Actual_To_Build_In_Place_Call
344      (Func_Call : Node_Id;
345       Func_Id   : Entity_Id;
346       Ptr_Typ   : Entity_Id := Empty)
347    is
348    begin
349       if not Needs_BIP_Finalization_Master (Func_Id) then
350          return;
351       end if;
352
353       declare
354          Formal : constant Entity_Id :=
355                     Build_In_Place_Formal (Func_Id, BIP_Finalization_Master);
356          Loc    : constant Source_Ptr := Sloc (Func_Call);
357
358          Actual    : Node_Id;
359          Desig_Typ : Entity_Id;
360
361       begin
362          --  Case where the context does not require an actual master
363
364          if No (Ptr_Typ) then
365             Actual := Make_Null (Loc);
366
367          else
368             Desig_Typ := Directly_Designated_Type (Ptr_Typ);
369
370             --  Check for a library-level access type whose designated type has
371             --  supressed finalization. Such an access types lack a master.
372             --  Pass a null actual to the callee in order to signal a missing
373             --  master.
374
375             if Is_Library_Level_Entity (Ptr_Typ)
376               and then Finalize_Storage_Only (Desig_Typ)
377             then
378                Actual := Make_Null (Loc);
379
380             --  Types in need of finalization actions
381
382             elsif Needs_Finalization (Desig_Typ) then
383
384                --  The general mechanism of creating finalization masters for
385                --  anonymous access types is disabled by default, otherwise
386                --  finalization masters will pop all over the place. Such types
387                --  use context-specific masters.
388
389                if Ekind (Ptr_Typ) = E_Anonymous_Access_Type
390                  and then No (Finalization_Master (Ptr_Typ))
391                then
392                   Build_Finalization_Master
393                     (Typ        => Ptr_Typ,
394                      Ins_Node   => Associated_Node_For_Itype (Ptr_Typ),
395                      Encl_Scope => Scope (Ptr_Typ));
396                end if;
397
398                --  Access-to-controlled types should always have a master
399
400                pragma Assert (Present (Finalization_Master (Ptr_Typ)));
401
402                Actual :=
403                  Make_Attribute_Reference (Loc,
404                    Prefix =>
405                      New_Reference_To (Finalization_Master (Ptr_Typ), Loc),
406                    Attribute_Name => Name_Unrestricted_Access);
407
408             --  Tagged types
409
410             else
411                Actual := Make_Null (Loc);
412             end if;
413          end if;
414
415          Analyze_And_Resolve (Actual, Etype (Formal));
416
417          --  Build the parameter association for the new actual and add it to
418          --  the end of the function's actuals.
419
420          Add_Extra_Actual_To_Call (Func_Call, Formal, Actual);
421       end;
422    end Add_Finalization_Master_Actual_To_Build_In_Place_Call;
423
424    ------------------------------
425    -- Add_Extra_Actual_To_Call --
426    ------------------------------
427
428    procedure Add_Extra_Actual_To_Call
429      (Subprogram_Call : Node_Id;
430       Extra_Formal    : Entity_Id;
431       Extra_Actual    : Node_Id)
432    is
433       Loc         : constant Source_Ptr := Sloc (Subprogram_Call);
434       Param_Assoc : Node_Id;
435
436    begin
437       Param_Assoc :=
438         Make_Parameter_Association (Loc,
439           Selector_Name             => New_Occurrence_Of (Extra_Formal, Loc),
440           Explicit_Actual_Parameter => Extra_Actual);
441
442       Set_Parent (Param_Assoc, Subprogram_Call);
443       Set_Parent (Extra_Actual, Param_Assoc);
444
445       if Present (Parameter_Associations (Subprogram_Call)) then
446          if Nkind (Last (Parameter_Associations (Subprogram_Call))) =
447               N_Parameter_Association
448          then
449
450             --  Find last named actual, and append
451
452             declare
453                L : Node_Id;
454             begin
455                L := First_Actual (Subprogram_Call);
456                while Present (L) loop
457                   if No (Next_Actual (L)) then
458                      Set_Next_Named_Actual (Parent (L), Extra_Actual);
459                      exit;
460                   end if;
461                   Next_Actual (L);
462                end loop;
463             end;
464
465          else
466             Set_First_Named_Actual (Subprogram_Call, Extra_Actual);
467          end if;
468
469          Append (Param_Assoc, To => Parameter_Associations (Subprogram_Call));
470
471       else
472          Set_Parameter_Associations (Subprogram_Call, New_List (Param_Assoc));
473          Set_First_Named_Actual (Subprogram_Call, Extra_Actual);
474       end if;
475    end Add_Extra_Actual_To_Call;
476
477    ---------------------------------------------
478    -- Add_Task_Actuals_To_Build_In_Place_Call --
479    ---------------------------------------------
480
481    procedure Add_Task_Actuals_To_Build_In_Place_Call
482      (Function_Call : Node_Id;
483       Function_Id   : Entity_Id;
484       Master_Actual : Node_Id)
485    is
486       Loc    : constant Source_Ptr := Sloc (Function_Call);
487       Actual : Node_Id := Master_Actual;
488
489    begin
490       --  No such extra parameters are needed if there are no tasks
491
492       if not Has_Task (Etype (Function_Id)) then
493          return;
494       end if;
495
496       --  Use a dummy _master actual in case of No_Task_Hierarchy
497
498       if Restriction_Active (No_Task_Hierarchy) then
499          Actual := New_Occurrence_Of (RTE (RE_Library_Task_Level), Loc);
500       end if;
501
502       --  The master
503
504       declare
505          Master_Formal : Node_Id;
506       begin
507          --  Locate implicit master parameter in the called function
508
509          Master_Formal := Build_In_Place_Formal (Function_Id, BIP_Master);
510
511          Analyze_And_Resolve (Actual, Etype (Master_Formal));
512
513          --  Build the parameter association for the new actual and add it to
514          --  the end of the function's actuals.
515
516          Add_Extra_Actual_To_Call
517            (Function_Call, Master_Formal, Actual);
518       end;
519
520       --  The activation chain
521
522       declare
523          Activation_Chain_Actual : Node_Id;
524          Activation_Chain_Formal : Node_Id;
525
526       begin
527          --  Locate implicit activation chain parameter in the called function
528
529          Activation_Chain_Formal := Build_In_Place_Formal
530            (Function_Id, BIP_Activation_Chain);
531
532          --  Create the actual which is a pointer to the current activation
533          --  chain
534
535          Activation_Chain_Actual :=
536            Make_Attribute_Reference (Loc,
537              Prefix         => Make_Identifier (Loc, Name_uChain),
538              Attribute_Name => Name_Unrestricted_Access);
539
540          Analyze_And_Resolve
541            (Activation_Chain_Actual, Etype (Activation_Chain_Formal));
542
543          --  Build the parameter association for the new actual and add it to
544          --  the end of the function's actuals.
545
546          Add_Extra_Actual_To_Call
547            (Function_Call, Activation_Chain_Formal, Activation_Chain_Actual);
548       end;
549    end Add_Task_Actuals_To_Build_In_Place_Call;
550
551    -----------------------
552    -- BIP_Formal_Suffix --
553    -----------------------
554
555    function BIP_Formal_Suffix (Kind : BIP_Formal_Kind) return String is
556    begin
557       case Kind is
558          when BIP_Alloc_Form          =>
559             return "BIPalloc";
560          when BIP_Finalization_Master =>
561             return "BIPfinalizationmaster";
562          when BIP_Master              =>
563             return "BIPmaster";
564          when BIP_Activation_Chain    =>
565             return "BIPactivationchain";
566          when BIP_Object_Access       =>
567             return "BIPaccess";
568       end case;
569    end BIP_Formal_Suffix;
570
571    ---------------------------
572    -- Build_In_Place_Formal --
573    ---------------------------
574
575    function Build_In_Place_Formal
576      (Func : Entity_Id;
577       Kind : BIP_Formal_Kind) return Entity_Id
578    is
579       Extra_Formal : Entity_Id := Extra_Formals (Func);
580
581    begin
582       --  Maybe it would be better for each implicit formal of a build-in-place
583       --  function to have a flag or a Uint attribute to identify it. ???
584
585       loop
586          pragma Assert (Present (Extra_Formal));
587          exit when
588            Chars (Extra_Formal) =
589              New_External_Name (Chars (Func), BIP_Formal_Suffix (Kind));
590          Next_Formal_With_Extras (Extra_Formal);
591       end loop;
592
593       return Extra_Formal;
594    end Build_In_Place_Formal;
595
596    --------------------------------
597    -- Check_Overriding_Operation --
598    --------------------------------
599
600    procedure Check_Overriding_Operation (Subp : Entity_Id) is
601       Typ     : constant Entity_Id := Find_Dispatching_Type (Subp);
602       Op_List : constant Elist_Id  := Primitive_Operations (Typ);
603       Op_Elmt : Elmt_Id;
604       Prim_Op : Entity_Id;
605       Par_Op  : Entity_Id;
606
607    begin
608       if Is_Derived_Type (Typ)
609         and then not Is_Private_Type (Typ)
610         and then In_Open_Scopes (Scope (Etype (Typ)))
611         and then Is_Base_Type (Typ)
612       then
613          --  Subp overrides an inherited private operation if there is an
614          --  inherited operation with a different name than Subp (see
615          --  Derive_Subprogram) whose Alias is a hidden subprogram with the
616          --  same name as Subp.
617
618          Op_Elmt := First_Elmt (Op_List);
619          while Present (Op_Elmt) loop
620             Prim_Op := Node (Op_Elmt);
621             Par_Op  := Alias (Prim_Op);
622
623             if Present (Par_Op)
624               and then not Comes_From_Source (Prim_Op)
625               and then Chars (Prim_Op) /= Chars (Par_Op)
626               and then Chars (Par_Op) = Chars (Subp)
627               and then Is_Hidden (Par_Op)
628               and then Type_Conformant (Prim_Op, Subp)
629             then
630                Set_DT_Position (Subp, DT_Position (Prim_Op));
631             end if;
632
633             Next_Elmt (Op_Elmt);
634          end loop;
635       end if;
636    end Check_Overriding_Operation;
637
638    -------------------------------
639    -- Detect_Infinite_Recursion --
640    -------------------------------
641
642    procedure Detect_Infinite_Recursion (N : Node_Id; Spec : Entity_Id) is
643       Loc : constant Source_Ptr := Sloc (N);
644
645       Var_List : constant Elist_Id := New_Elmt_List;
646       --  List of globals referenced by body of procedure
647
648       Call_List : constant Elist_Id := New_Elmt_List;
649       --  List of recursive calls in body of procedure
650
651       Shad_List : constant Elist_Id := New_Elmt_List;
652       --  List of entity id's for entities created to capture the value of
653       --  referenced globals on entry to the procedure.
654
655       Scop : constant Uint := Scope_Depth (Spec);
656       --  This is used to record the scope depth of the current procedure, so
657       --  that we can identify global references.
658
659       Max_Vars : constant := 4;
660       --  Do not test more than four global variables
661
662       Count_Vars : Natural := 0;
663       --  Count variables found so far
664
665       Var  : Entity_Id;
666       Elm  : Elmt_Id;
667       Ent  : Entity_Id;
668       Call : Elmt_Id;
669       Decl : Node_Id;
670       Test : Node_Id;
671       Elm1 : Elmt_Id;
672       Elm2 : Elmt_Id;
673       Last : Node_Id;
674
675       function Process (Nod : Node_Id) return Traverse_Result;
676       --  Function to traverse the subprogram body (using Traverse_Func)
677
678       -------------
679       -- Process --
680       -------------
681
682       function Process (Nod : Node_Id) return Traverse_Result is
683       begin
684          --  Procedure call
685
686          if Nkind (Nod) = N_Procedure_Call_Statement then
687
688             --  Case of one of the detected recursive calls
689
690             if Is_Entity_Name (Name (Nod))
691               and then Has_Recursive_Call (Entity (Name (Nod)))
692               and then Entity (Name (Nod)) = Spec
693             then
694                Append_Elmt (Nod, Call_List);
695                return Skip;
696
697             --  Any other procedure call may have side effects
698
699             else
700                return Abandon;
701             end if;
702
703          --  A call to a pure function can always be ignored
704
705          elsif Nkind (Nod) = N_Function_Call
706            and then Is_Entity_Name (Name (Nod))
707            and then Is_Pure (Entity (Name (Nod)))
708          then
709             return Skip;
710
711          --  Case of an identifier reference
712
713          elsif Nkind (Nod) = N_Identifier then
714             Ent := Entity (Nod);
715
716             --  If no entity, then ignore the reference
717
718             --  Not clear why this can happen. To investigate, remove this
719             --  test and look at the crash that occurs here in 3401-004 ???
720
721             if No (Ent) then
722                return Skip;
723
724             --  Ignore entities with no Scope, again not clear how this
725             --  can happen, to investigate, look at 4108-008 ???
726
727             elsif No (Scope (Ent)) then
728                return Skip;
729
730             --  Ignore the reference if not to a more global object
731
732             elsif Scope_Depth (Scope (Ent)) >= Scop then
733                return Skip;
734
735             --  References to types, exceptions and constants are always OK
736
737             elsif Is_Type (Ent)
738               or else Ekind (Ent) = E_Exception
739               or else Ekind (Ent) = E_Constant
740             then
741                return Skip;
742
743             --  If other than a non-volatile scalar variable, we have some
744             --  kind of global reference (e.g. to a function) that we cannot
745             --  deal with so we forget the attempt.
746
747             elsif Ekind (Ent) /= E_Variable
748               or else not Is_Scalar_Type (Etype (Ent))
749               or else Treat_As_Volatile (Ent)
750             then
751                return Abandon;
752
753             --  Otherwise we have a reference to a global scalar
754
755             else
756                --  Loop through global entities already detected
757
758                Elm := First_Elmt (Var_List);
759                loop
760                   --  If not detected before, record this new global reference
761
762                   if No (Elm) then
763                      Count_Vars := Count_Vars + 1;
764
765                      if Count_Vars <= Max_Vars then
766                         Append_Elmt (Entity (Nod), Var_List);
767                      else
768                         return Abandon;
769                      end if;
770
771                      exit;
772
773                   --  If recorded before, ignore
774
775                   elsif Node (Elm) = Entity (Nod) then
776                      return Skip;
777
778                   --  Otherwise keep looking
779
780                   else
781                      Next_Elmt (Elm);
782                   end if;
783                end loop;
784
785                return Skip;
786             end if;
787
788          --  For all other node kinds, recursively visit syntactic children
789
790          else
791             return OK;
792          end if;
793       end Process;
794
795       function Traverse_Body is new Traverse_Func (Process);
796
797    --  Start of processing for Detect_Infinite_Recursion
798
799    begin
800       --  Do not attempt detection in No_Implicit_Conditional mode, since we
801       --  won't be able to generate the code to handle the recursion in any
802       --  case.
803
804       if Restriction_Active (No_Implicit_Conditionals) then
805          return;
806       end if;
807
808       --  Otherwise do traversal and quit if we get abandon signal
809
810       if Traverse_Body (N) = Abandon then
811          return;
812
813       --  We must have a call, since Has_Recursive_Call was set. If not just
814       --  ignore (this is only an error check, so if we have a funny situation,
815       --  due to bugs or errors, we do not want to bomb!)
816
817       elsif Is_Empty_Elmt_List (Call_List) then
818          return;
819       end if;
820
821       --  Here is the case where we detect recursion at compile time
822
823       --  Push our current scope for analyzing the declarations and code that
824       --  we will insert for the checking.
825
826       Push_Scope (Spec);
827
828       --  This loop builds temporary variables for each of the referenced
829       --  globals, so that at the end of the loop the list Shad_List contains
830       --  these temporaries in one-to-one correspondence with the elements in
831       --  Var_List.
832
833       Last := Empty;
834       Elm := First_Elmt (Var_List);
835       while Present (Elm) loop
836          Var := Node (Elm);
837          Ent := Make_Temporary (Loc, 'S');
838          Append_Elmt (Ent, Shad_List);
839
840          --  Insert a declaration for this temporary at the start of the
841          --  declarations for the procedure. The temporaries are declared as
842          --  constant objects initialized to the current values of the
843          --  corresponding temporaries.
844
845          Decl :=
846            Make_Object_Declaration (Loc,
847              Defining_Identifier => Ent,
848              Object_Definition   => New_Occurrence_Of (Etype (Var), Loc),
849              Constant_Present    => True,
850              Expression          => New_Occurrence_Of (Var, Loc));
851
852          if No (Last) then
853             Prepend (Decl, Declarations (N));
854          else
855             Insert_After (Last, Decl);
856          end if;
857
858          Last := Decl;
859          Analyze (Decl);
860          Next_Elmt (Elm);
861       end loop;
862
863       --  Loop through calls
864
865       Call := First_Elmt (Call_List);
866       while Present (Call) loop
867
868          --  Build a predicate expression of the form
869
870          --    True
871          --      and then global1 = temp1
872          --      and then global2 = temp2
873          --      ...
874
875          --  This predicate determines if any of the global values
876          --  referenced by the procedure have changed since the
877          --  current call, if not an infinite recursion is assured.
878
879          Test := New_Occurrence_Of (Standard_True, Loc);
880
881          Elm1 := First_Elmt (Var_List);
882          Elm2 := First_Elmt (Shad_List);
883          while Present (Elm1) loop
884             Test :=
885               Make_And_Then (Loc,
886                 Left_Opnd  => Test,
887                 Right_Opnd =>
888                   Make_Op_Eq (Loc,
889                     Left_Opnd  => New_Occurrence_Of (Node (Elm1), Loc),
890                     Right_Opnd => New_Occurrence_Of (Node (Elm2), Loc)));
891
892             Next_Elmt (Elm1);
893             Next_Elmt (Elm2);
894          end loop;
895
896          --  Now we replace the call with the sequence
897
898          --    if no-changes (see above) then
899          --       raise Storage_Error;
900          --    else
901          --       original-call
902          --    end if;
903
904          Rewrite (Node (Call),
905            Make_If_Statement (Loc,
906              Condition       => Test,
907              Then_Statements => New_List (
908                Make_Raise_Storage_Error (Loc,
909                  Reason => SE_Infinite_Recursion)),
910
911              Else_Statements => New_List (
912                Relocate_Node (Node (Call)))));
913
914          Analyze (Node (Call));
915
916          Next_Elmt (Call);
917       end loop;
918
919       --  Remove temporary scope stack entry used for analysis
920
921       Pop_Scope;
922    end Detect_Infinite_Recursion;
923
924    --------------------
925    -- Expand_Actuals --
926    --------------------
927
928    procedure Expand_Actuals (N : Node_Id; Subp : Entity_Id) is
929       Loc       : constant Source_Ptr := Sloc (N);
930       Actual    : Node_Id;
931       Formal    : Entity_Id;
932       N_Node    : Node_Id;
933       Post_Call : List_Id;
934       E_Formal  : Entity_Id;
935
936       procedure Add_Call_By_Copy_Code;
937       --  For cases where the parameter must be passed by copy, this routine
938       --  generates a temporary variable into which the actual is copied and
939       --  then passes this as the parameter. For an OUT or IN OUT parameter,
940       --  an assignment is also generated to copy the result back. The call
941       --  also takes care of any constraint checks required for the type
942       --  conversion case (on both the way in and the way out).
943
944       procedure Add_Simple_Call_By_Copy_Code;
945       --  This is similar to the above, but is used in cases where we know
946       --  that all that is needed is to simply create a temporary and copy
947       --  the value in and out of the temporary.
948
949       procedure Check_Fortran_Logical;
950       --  A value of type Logical that is passed through a formal parameter
951       --  must be normalized because .TRUE. usually does not have the same
952       --  representation as True. We assume that .FALSE. = False = 0.
953       --  What about functions that return a logical type ???
954
955       function Is_Legal_Copy return Boolean;
956       --  Check that an actual can be copied before generating the temporary
957       --  to be used in the call. If the actual is of a by_reference type then
958       --  the program is illegal (this can only happen in the presence of
959       --  rep. clauses that force an incorrect alignment). If the formal is
960       --  a by_reference parameter imposed by a DEC pragma, emit a warning to
961       --  the effect that this might lead to unaligned arguments.
962
963       function Make_Var (Actual : Node_Id) return Entity_Id;
964       --  Returns an entity that refers to the given actual parameter,
965       --  Actual (not including any type conversion). If Actual is an
966       --  entity name, then this entity is returned unchanged, otherwise
967       --  a renaming is created to provide an entity for the actual.
968
969       procedure Reset_Packed_Prefix;
970       --  The expansion of a packed array component reference is delayed in
971       --  the context of a call. Now we need to complete the expansion, so we
972       --  unmark the analyzed bits in all prefixes.
973
974       ---------------------------
975       -- Add_Call_By_Copy_Code --
976       ---------------------------
977
978       procedure Add_Call_By_Copy_Code is
979          Expr  : Node_Id;
980          Init  : Node_Id;
981          Temp  : Entity_Id;
982          Indic : Node_Id;
983          Var   : Entity_Id;
984          F_Typ : constant Entity_Id := Etype (Formal);
985          V_Typ : Entity_Id;
986          Crep  : Boolean;
987
988       begin
989          if not Is_Legal_Copy then
990             return;
991          end if;
992
993          Temp := Make_Temporary (Loc, 'T', Actual);
994
995          --  Use formal type for temp, unless formal type is an unconstrained
996          --  array, in which case we don't have to worry about bounds checks,
997          --  and we use the actual type, since that has appropriate bounds.
998
999          if Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ) then
1000             Indic := New_Occurrence_Of (Etype (Actual), Loc);
1001          else
1002             Indic := New_Occurrence_Of (Etype (Formal), Loc);
1003          end if;
1004
1005          if Nkind (Actual) = N_Type_Conversion then
1006             V_Typ := Etype (Expression (Actual));
1007
1008             --  If the formal is an (in-)out parameter, capture the name
1009             --  of the variable in order to build the post-call assignment.
1010
1011             Var := Make_Var (Expression (Actual));
1012
1013             Crep := not Same_Representation
1014                           (F_Typ, Etype (Expression (Actual)));
1015
1016          else
1017             V_Typ := Etype (Actual);
1018             Var   := Make_Var (Actual);
1019             Crep  := False;
1020          end if;
1021
1022          --  Setup initialization for case of in out parameter, or an out
1023          --  parameter where the formal is an unconstrained array (in the
1024          --  latter case, we have to pass in an object with bounds).
1025
1026          --  If this is an out parameter, the initial copy is wasteful, so as
1027          --  an optimization for the one-dimensional case we extract the
1028          --  bounds of the actual and build an uninitialized temporary of the
1029          --  right size.
1030
1031          if Ekind (Formal) = E_In_Out_Parameter
1032            or else (Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ))
1033          then
1034             if Nkind (Actual) = N_Type_Conversion then
1035                if Conversion_OK (Actual) then
1036                   Init := OK_Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1037                else
1038                   Init := Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1039                end if;
1040
1041             elsif Ekind (Formal) = E_Out_Parameter
1042               and then Is_Array_Type (F_Typ)
1043               and then Number_Dimensions (F_Typ) = 1
1044               and then not Has_Non_Null_Base_Init_Proc (F_Typ)
1045             then
1046                --  Actual is a one-dimensional array or slice, and the type
1047                --  requires no initialization. Create a temporary of the
1048                --  right size, but do not copy actual into it (optimization).
1049
1050                Init := Empty;
1051                Indic :=
1052                  Make_Subtype_Indication (Loc,
1053                    Subtype_Mark =>
1054                      New_Occurrence_Of (F_Typ, Loc),
1055                    Constraint   =>
1056                      Make_Index_Or_Discriminant_Constraint (Loc,
1057                        Constraints => New_List (
1058                          Make_Range (Loc,
1059                            Low_Bound  =>
1060                              Make_Attribute_Reference (Loc,
1061                                Prefix => New_Occurrence_Of (Var, Loc),
1062                                Attribute_Name => Name_First),
1063                            High_Bound =>
1064                              Make_Attribute_Reference (Loc,
1065                                Prefix => New_Occurrence_Of (Var, Loc),
1066                                Attribute_Name => Name_Last)))));
1067
1068             else
1069                Init := New_Occurrence_Of (Var, Loc);
1070             end if;
1071
1072          --  An initialization is created for packed conversions as
1073          --  actuals for out parameters to enable Make_Object_Declaration
1074          --  to determine the proper subtype for N_Node. Note that this
1075          --  is wasteful because the extra copying on the call side is
1076          --  not required for such out parameters. ???
1077
1078          elsif Ekind (Formal) = E_Out_Parameter
1079            and then Nkind (Actual) = N_Type_Conversion
1080            and then (Is_Bit_Packed_Array (F_Typ)
1081                        or else
1082                      Is_Bit_Packed_Array (Etype (Expression (Actual))))
1083          then
1084             if Conversion_OK (Actual) then
1085                Init := OK_Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1086             else
1087                Init := Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1088             end if;
1089
1090          elsif Ekind (Formal) = E_In_Parameter then
1091
1092             --  Handle the case in which the actual is a type conversion
1093
1094             if Nkind (Actual) = N_Type_Conversion then
1095                if Conversion_OK (Actual) then
1096                   Init := OK_Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1097                else
1098                   Init := Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1099                end if;
1100             else
1101                Init := New_Occurrence_Of (Var, Loc);
1102             end if;
1103
1104          else
1105             Init := Empty;
1106          end if;
1107
1108          N_Node :=
1109            Make_Object_Declaration (Loc,
1110              Defining_Identifier => Temp,
1111              Object_Definition   => Indic,
1112              Expression          => Init);
1113          Set_Assignment_OK (N_Node);
1114          Insert_Action (N, N_Node);
1115
1116          --  Now, normally the deal here is that we use the defining
1117          --  identifier created by that object declaration. There is
1118          --  one exception to this. In the change of representation case
1119          --  the above declaration will end up looking like:
1120
1121          --    temp : type := identifier;
1122
1123          --  And in this case we might as well use the identifier directly
1124          --  and eliminate the temporary. Note that the analysis of the
1125          --  declaration was not a waste of time in that case, since it is
1126          --  what generated the necessary change of representation code. If
1127          --  the change of representation introduced additional code, as in
1128          --  a fixed-integer conversion, the expression is not an identifier
1129          --  and must be kept.
1130
1131          if Crep
1132            and then Present (Expression (N_Node))
1133            and then Is_Entity_Name (Expression (N_Node))
1134          then
1135             Temp := Entity (Expression (N_Node));
1136             Rewrite (N_Node, Make_Null_Statement (Loc));
1137          end if;
1138
1139          --  For IN parameter, all we do is to replace the actual
1140
1141          if Ekind (Formal) = E_In_Parameter then
1142             Rewrite (Actual, New_Reference_To (Temp, Loc));
1143             Analyze (Actual);
1144
1145          --  Processing for OUT or IN OUT parameter
1146
1147          else
1148             --  Kill current value indications for the temporary variable we
1149             --  created, since we just passed it as an OUT parameter.
1150
1151             Kill_Current_Values (Temp);
1152             Set_Is_Known_Valid (Temp, False);
1153
1154             --  If type conversion, use reverse conversion on exit
1155
1156             if Nkind (Actual) = N_Type_Conversion then
1157                if Conversion_OK (Actual) then
1158                   Expr := OK_Convert_To (V_Typ, New_Occurrence_Of (Temp, Loc));
1159                else
1160                   Expr := Convert_To (V_Typ, New_Occurrence_Of (Temp, Loc));
1161                end if;
1162             else
1163                Expr := New_Occurrence_Of (Temp, Loc);
1164             end if;
1165
1166             Rewrite (Actual, New_Reference_To (Temp, Loc));
1167             Analyze (Actual);
1168
1169             --  If the actual is a conversion of a packed reference, it may
1170             --  already have been expanded by Remove_Side_Effects, and the
1171             --  resulting variable is a temporary which does not designate
1172             --  the proper out-parameter, which may not be addressable. In
1173             --  that case, generate an assignment to the original expression
1174             --  (before expansion of the packed reference) so that the proper
1175             --  expansion of assignment to a packed component can take place.
1176
1177             declare
1178                Obj : Node_Id;
1179                Lhs : Node_Id;
1180
1181             begin
1182                if Is_Renaming_Of_Object (Var)
1183                  and then Nkind (Renamed_Object (Var)) = N_Selected_Component
1184                  and then Is_Entity_Name (Prefix (Renamed_Object (Var)))
1185                  and then Nkind (Original_Node (Prefix (Renamed_Object (Var))))
1186                    = N_Indexed_Component
1187                  and then
1188                    Has_Non_Standard_Rep (Etype (Prefix (Renamed_Object (Var))))
1189                then
1190                   Obj := Renamed_Object (Var);
1191                   Lhs :=
1192                     Make_Selected_Component (Loc,
1193                       Prefix        =>
1194                         New_Copy_Tree (Original_Node (Prefix (Obj))),
1195                       Selector_Name => New_Copy (Selector_Name (Obj)));
1196                   Reset_Analyzed_Flags (Lhs);
1197
1198                else
1199                   Lhs :=  New_Occurrence_Of (Var, Loc);
1200                end if;
1201
1202                Set_Assignment_OK (Lhs);
1203
1204                Append_To (Post_Call,
1205                  Make_Assignment_Statement (Loc,
1206                    Name       => Lhs,
1207                    Expression => Expr));
1208             end;
1209          end if;
1210       end Add_Call_By_Copy_Code;
1211
1212       ----------------------------------
1213       -- Add_Simple_Call_By_Copy_Code --
1214       ----------------------------------
1215
1216       procedure Add_Simple_Call_By_Copy_Code is
1217          Temp   : Entity_Id;
1218          Decl   : Node_Id;
1219          Incod  : Node_Id;
1220          Outcod : Node_Id;
1221          Lhs    : Node_Id;
1222          Rhs    : Node_Id;
1223          Indic  : Node_Id;
1224          F_Typ  : constant Entity_Id := Etype (Formal);
1225
1226       begin
1227          if not Is_Legal_Copy then
1228             return;
1229          end if;
1230
1231          --  Use formal type for temp, unless formal type is an unconstrained
1232          --  array, in which case we don't have to worry about bounds checks,
1233          --  and we use the actual type, since that has appropriate bounds.
1234
1235          if Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ) then
1236             Indic := New_Occurrence_Of (Etype (Actual), Loc);
1237          else
1238             Indic := New_Occurrence_Of (Etype (Formal), Loc);
1239          end if;
1240
1241          --  Prepare to generate code
1242
1243          Reset_Packed_Prefix;
1244
1245          Temp := Make_Temporary (Loc, 'T', Actual);
1246          Incod  := Relocate_Node (Actual);
1247          Outcod := New_Copy_Tree (Incod);
1248
1249          --  Generate declaration of temporary variable, initializing it
1250          --  with the input parameter unless we have an OUT formal or
1251          --  this is an initialization call.
1252
1253          --  If the formal is an out parameter with discriminants, the
1254          --  discriminants must be captured even if the rest of the object
1255          --  is in principle uninitialized, because the discriminants may
1256          --  be read by the called subprogram.
1257
1258          if Ekind (Formal) = E_Out_Parameter then
1259             Incod := Empty;
1260
1261             if Has_Discriminants (Etype (Formal)) then
1262                Indic := New_Occurrence_Of (Etype (Actual), Loc);
1263             end if;
1264
1265          elsif Inside_Init_Proc then
1266
1267             --  Could use a comment here to match comment below ???
1268
1269             if Nkind (Actual) /= N_Selected_Component
1270               or else
1271                 not Has_Discriminant_Dependent_Constraint
1272                   (Entity (Selector_Name (Actual)))
1273             then
1274                Incod := Empty;
1275
1276             --  Otherwise, keep the component in order to generate the proper
1277             --  actual subtype, that depends on enclosing discriminants.
1278
1279             else
1280                null;
1281             end if;
1282          end if;
1283
1284          Decl :=
1285            Make_Object_Declaration (Loc,
1286              Defining_Identifier => Temp,
1287              Object_Definition   => Indic,
1288              Expression          => Incod);
1289
1290          if Inside_Init_Proc
1291            and then No (Incod)
1292          then
1293             --  If the call is to initialize a component of a composite type,
1294             --  and the component does not depend on discriminants, use the
1295             --  actual type of the component. This is required in case the
1296             --  component is constrained, because in general the formal of the
1297             --  initialization procedure will be unconstrained. Note that if
1298             --  the component being initialized is constrained by an enclosing
1299             --  discriminant, the presence of the initialization in the
1300             --  declaration will generate an expression for the actual subtype.
1301
1302             Set_No_Initialization (Decl);
1303             Set_Object_Definition (Decl,
1304               New_Occurrence_Of (Etype (Actual), Loc));
1305          end if;
1306
1307          Insert_Action (N, Decl);
1308
1309          --  The actual is simply a reference to the temporary
1310
1311          Rewrite (Actual, New_Occurrence_Of (Temp, Loc));
1312
1313          --  Generate copy out if OUT or IN OUT parameter
1314
1315          if Ekind (Formal) /= E_In_Parameter then
1316             Lhs := Outcod;
1317             Rhs := New_Occurrence_Of (Temp, Loc);
1318
1319             --  Deal with conversion
1320
1321             if Nkind (Lhs) = N_Type_Conversion then
1322                Lhs := Expression (Lhs);
1323                Rhs := Convert_To (Etype (Actual), Rhs);
1324             end if;
1325
1326             Append_To (Post_Call,
1327               Make_Assignment_Statement (Loc,
1328                 Name       => Lhs,
1329                 Expression => Rhs));
1330             Set_Assignment_OK (Name (Last (Post_Call)));
1331          end if;
1332       end Add_Simple_Call_By_Copy_Code;
1333
1334       ---------------------------
1335       -- Check_Fortran_Logical --
1336       ---------------------------
1337
1338       procedure Check_Fortran_Logical is
1339          Logical : constant Entity_Id := Etype (Formal);
1340          Var     : Entity_Id;
1341
1342       --  Note: this is very incomplete, e.g. it does not handle arrays
1343       --  of logical values. This is really not the right approach at all???)
1344
1345       begin
1346          if Convention (Subp) = Convention_Fortran
1347            and then Root_Type (Etype (Formal)) = Standard_Boolean
1348            and then Ekind (Formal) /= E_In_Parameter
1349          then
1350             Var := Make_Var (Actual);
1351             Append_To (Post_Call,
1352               Make_Assignment_Statement (Loc,
1353                 Name => New_Occurrence_Of (Var, Loc),
1354                 Expression =>
1355                   Unchecked_Convert_To (
1356                     Logical,
1357                     Make_Op_Ne (Loc,
1358                       Left_Opnd  => New_Occurrence_Of (Var, Loc),
1359                       Right_Opnd =>
1360                         Unchecked_Convert_To (
1361                           Logical,
1362                           New_Occurrence_Of (Standard_False, Loc))))));
1363          end if;
1364       end Check_Fortran_Logical;
1365
1366       -------------------
1367       -- Is_Legal_Copy --
1368       -------------------
1369
1370       function Is_Legal_Copy return Boolean is
1371       begin
1372          --  An attempt to copy a value of such a type can only occur if
1373          --  representation clauses give the actual a misaligned address.
1374
1375          if Is_By_Reference_Type (Etype (Formal)) then
1376             Error_Msg_N
1377               ("misaligned actual cannot be passed by reference", Actual);
1378             return False;
1379
1380          --  For users of Starlet, we assume that the specification of by-
1381          --  reference mechanism is mandatory. This may lead to unaligned
1382          --  objects but at least for DEC legacy code it is known to work.
1383          --  The warning will alert users of this code that a problem may
1384          --  be lurking.
1385
1386          elsif Mechanism (Formal) = By_Reference
1387            and then Is_Valued_Procedure (Scope (Formal))
1388          then
1389             Error_Msg_N
1390               ("by_reference actual may be misaligned?", Actual);
1391             return False;
1392
1393          else
1394             return True;
1395          end if;
1396       end Is_Legal_Copy;
1397
1398       --------------
1399       -- Make_Var --
1400       --------------
1401
1402       function Make_Var (Actual : Node_Id) return Entity_Id is
1403          Var : Entity_Id;
1404
1405       begin
1406          if Is_Entity_Name (Actual) then
1407             return Entity (Actual);
1408
1409          else
1410             Var := Make_Temporary (Loc, 'T', Actual);
1411
1412             N_Node :=
1413               Make_Object_Renaming_Declaration (Loc,
1414                 Defining_Identifier => Var,
1415                 Subtype_Mark        =>
1416                   New_Occurrence_Of (Etype (Actual), Loc),
1417                 Name                => Relocate_Node (Actual));
1418
1419             Insert_Action (N, N_Node);
1420             return Var;
1421          end if;
1422       end Make_Var;
1423
1424       -------------------------
1425       -- Reset_Packed_Prefix --
1426       -------------------------
1427
1428       procedure Reset_Packed_Prefix is
1429          Pfx : Node_Id := Actual;
1430       begin
1431          loop
1432             Set_Analyzed (Pfx, False);
1433             exit when
1434               not Nkind_In (Pfx, N_Selected_Component, N_Indexed_Component);
1435             Pfx := Prefix (Pfx);
1436          end loop;
1437       end Reset_Packed_Prefix;
1438
1439    --  Start of processing for Expand_Actuals
1440
1441    begin
1442       Post_Call := New_List;
1443
1444       Formal := First_Formal (Subp);
1445       Actual := First_Actual (N);
1446       while Present (Formal) loop
1447          E_Formal := Etype (Formal);
1448
1449          if Is_Scalar_Type (E_Formal)
1450            or else Nkind (Actual) = N_Slice
1451          then
1452             Check_Fortran_Logical;
1453
1454          --  RM 6.4.1 (11)
1455
1456          elsif Ekind (Formal) /= E_Out_Parameter then
1457
1458             --  The unusual case of the current instance of a protected type
1459             --  requires special handling. This can only occur in the context
1460             --  of a call within the body of a protected operation.
1461
1462             if Is_Entity_Name (Actual)
1463               and then Ekind (Entity (Actual)) = E_Protected_Type
1464               and then In_Open_Scopes (Entity (Actual))
1465             then
1466                if Scope (Subp) /= Entity (Actual) then
1467                   Error_Msg_N ("operation outside protected type may not "
1468                     & "call back its protected operations?", Actual);
1469                end if;
1470
1471                Rewrite (Actual,
1472                  Expand_Protected_Object_Reference (N, Entity (Actual)));
1473             end if;
1474
1475             --  Ada 2005 (AI-318-02): If the actual parameter is a call to a
1476             --  build-in-place function, then a temporary return object needs
1477             --  to be created and access to it must be passed to the function.
1478             --  Currently we limit such functions to those with inherently
1479             --  limited result subtypes, but eventually we plan to expand the
1480             --  functions that are treated as build-in-place to include other
1481             --  composite result types.
1482
1483             if Is_Build_In_Place_Function_Call (Actual) then
1484                Make_Build_In_Place_Call_In_Anonymous_Context (Actual);
1485             end if;
1486
1487             Apply_Constraint_Check (Actual, E_Formal);
1488
1489          --  Out parameter case. No constraint checks on access type
1490          --  RM 6.4.1 (13)
1491
1492          elsif Is_Access_Type (E_Formal) then
1493             null;
1494
1495          --  RM 6.4.1 (14)
1496
1497          elsif Has_Discriminants (Base_Type (E_Formal))
1498            or else Has_Non_Null_Base_Init_Proc (E_Formal)
1499          then
1500             Apply_Constraint_Check (Actual, E_Formal);
1501
1502          --  RM 6.4.1 (15)
1503
1504          else
1505             Apply_Constraint_Check (Actual, Base_Type (E_Formal));
1506          end if;
1507
1508          --  Processing for IN-OUT and OUT parameters
1509
1510          if Ekind (Formal) /= E_In_Parameter then
1511
1512             --  For type conversions of arrays, apply length/range checks
1513
1514             if Is_Array_Type (E_Formal)
1515               and then Nkind (Actual) = N_Type_Conversion
1516             then
1517                if Is_Constrained (E_Formal) then
1518                   Apply_Length_Check (Expression (Actual), E_Formal);
1519                else
1520                   Apply_Range_Check (Expression (Actual), E_Formal);
1521                end if;
1522             end if;
1523
1524             --  If argument is a type conversion for a type that is passed
1525             --  by copy, then we must pass the parameter by copy.
1526
1527             if Nkind (Actual) = N_Type_Conversion
1528               and then
1529                 (Is_Numeric_Type (E_Formal)
1530                   or else Is_Access_Type (E_Formal)
1531                   or else Is_Enumeration_Type (E_Formal)
1532                   or else Is_Bit_Packed_Array (Etype (Formal))
1533                   or else Is_Bit_Packed_Array (Etype (Expression (Actual)))
1534
1535                   --  Also pass by copy if change of representation
1536
1537                   or else not Same_Representation
1538                                (Etype (Formal),
1539                                 Etype (Expression (Actual))))
1540             then
1541                Add_Call_By_Copy_Code;
1542
1543             --  References to components of bit packed arrays are expanded
1544             --  at this point, rather than at the point of analysis of the
1545             --  actuals, to handle the expansion of the assignment to
1546             --  [in] out parameters.
1547
1548             elsif Is_Ref_To_Bit_Packed_Array (Actual) then
1549                Add_Simple_Call_By_Copy_Code;
1550
1551             --  If a non-scalar actual is possibly bit-aligned, we need a copy
1552             --  because the back-end cannot cope with such objects. In other
1553             --  cases where alignment forces a copy, the back-end generates
1554             --  it properly. It should not be generated unconditionally in the
1555             --  front-end because it does not know precisely the alignment
1556             --  requirements of the target, and makes too conservative an
1557             --  estimate, leading to superfluous copies or spurious errors
1558             --  on by-reference parameters.
1559
1560             elsif Nkind (Actual) = N_Selected_Component
1561               and then
1562                 Component_May_Be_Bit_Aligned (Entity (Selector_Name (Actual)))
1563               and then not Represented_As_Scalar (Etype (Formal))
1564             then
1565                Add_Simple_Call_By_Copy_Code;
1566
1567             --  References to slices of bit packed arrays are expanded
1568
1569             elsif Is_Ref_To_Bit_Packed_Slice (Actual) then
1570                Add_Call_By_Copy_Code;
1571
1572             --  References to possibly unaligned slices of arrays are expanded
1573
1574             elsif Is_Possibly_Unaligned_Slice (Actual) then
1575                Add_Call_By_Copy_Code;
1576
1577             --  Deal with access types where the actual subtype and the
1578             --  formal subtype are not the same, requiring a check.
1579
1580             --  It is necessary to exclude tagged types because of "downward
1581             --  conversion" errors.
1582
1583             elsif Is_Access_Type (E_Formal)
1584               and then not Same_Type (E_Formal, Etype (Actual))
1585               and then not Is_Tagged_Type (Designated_Type (E_Formal))
1586             then
1587                Add_Call_By_Copy_Code;
1588
1589             --  If the actual is not a scalar and is marked for volatile
1590             --  treatment, whereas the formal is not volatile, then pass
1591             --  by copy unless it is a by-reference type.
1592
1593             --  Note: we use Is_Volatile here rather than Treat_As_Volatile,
1594             --  because this is the enforcement of a language rule that applies
1595             --  only to "real" volatile variables, not e.g. to the address
1596             --  clause overlay case.
1597
1598             elsif Is_Entity_Name (Actual)
1599               and then Is_Volatile (Entity (Actual))
1600               and then not Is_By_Reference_Type (Etype (Actual))
1601               and then not Is_Scalar_Type (Etype (Entity (Actual)))
1602               and then not Is_Volatile (E_Formal)
1603             then
1604                Add_Call_By_Copy_Code;
1605
1606             elsif Nkind (Actual) = N_Indexed_Component
1607               and then Is_Entity_Name (Prefix (Actual))
1608               and then Has_Volatile_Components (Entity (Prefix (Actual)))
1609             then
1610                Add_Call_By_Copy_Code;
1611
1612             --  Add call-by-copy code for the case of scalar out parameters
1613             --  when it is not known at compile time that the subtype of the
1614             --  formal is a subrange of the subtype of the actual (or vice
1615             --  versa for in out parameters), in order to get range checks
1616             --  on such actuals. (Maybe this case should be handled earlier
1617             --  in the if statement???)
1618
1619             elsif Is_Scalar_Type (E_Formal)
1620               and then
1621                 (not In_Subrange_Of (E_Formal, Etype (Actual))
1622                   or else
1623                     (Ekind (Formal) = E_In_Out_Parameter
1624                       and then not In_Subrange_Of (Etype (Actual), E_Formal)))
1625             then
1626                --  Perhaps the setting back to False should be done within
1627                --  Add_Call_By_Copy_Code, since it could get set on other
1628                --  cases occurring above???
1629
1630                if Do_Range_Check (Actual) then
1631                   Set_Do_Range_Check (Actual, False);
1632                end if;
1633
1634                Add_Call_By_Copy_Code;
1635             end if;
1636
1637          --  Processing for IN parameters
1638
1639          else
1640             --  For IN parameters is in the packed array case, we expand an
1641             --  indexed component (the circuit in Exp_Ch4 deliberately left
1642             --  indexed components appearing as actuals untouched, so that
1643             --  the special processing above for the OUT and IN OUT cases
1644             --  could be performed. We could make the test in Exp_Ch4 more
1645             --  complex and have it detect the parameter mode, but it is
1646             --  easier simply to handle all cases here.)
1647
1648             if Nkind (Actual) = N_Indexed_Component
1649               and then Is_Packed (Etype (Prefix (Actual)))
1650             then
1651                Reset_Packed_Prefix;
1652                Expand_Packed_Element_Reference (Actual);
1653
1654             --  If we have a reference to a bit packed array, we copy it, since
1655             --  the actual must be byte aligned.
1656
1657             --  Is this really necessary in all cases???
1658
1659             elsif Is_Ref_To_Bit_Packed_Array (Actual) then
1660                Add_Simple_Call_By_Copy_Code;
1661
1662             --  If a non-scalar actual is possibly unaligned, we need a copy
1663
1664             elsif Is_Possibly_Unaligned_Object (Actual)
1665               and then not Represented_As_Scalar (Etype (Formal))
1666             then
1667                Add_Simple_Call_By_Copy_Code;
1668
1669             --  Similarly, we have to expand slices of packed arrays here
1670             --  because the result must be byte aligned.
1671
1672             elsif Is_Ref_To_Bit_Packed_Slice (Actual) then
1673                Add_Call_By_Copy_Code;
1674
1675             --  Only processing remaining is to pass by copy if this is a
1676             --  reference to a possibly unaligned slice, since the caller
1677             --  expects an appropriately aligned argument.
1678
1679             elsif Is_Possibly_Unaligned_Slice (Actual) then
1680                Add_Call_By_Copy_Code;
1681
1682             --  An unusual case: a current instance of an enclosing task can be
1683             --  an actual, and must be replaced by a reference to self.
1684
1685             elsif Is_Entity_Name (Actual)
1686               and then Is_Task_Type (Entity (Actual))
1687             then
1688                if In_Open_Scopes (Entity (Actual)) then
1689                   Rewrite (Actual,
1690                     (Make_Function_Call (Loc,
1691                      Name => New_Reference_To (RTE (RE_Self), Loc))));
1692                   Analyze (Actual);
1693
1694                --  A task type cannot otherwise appear as an actual
1695
1696                else
1697                   raise Program_Error;
1698                end if;
1699             end if;
1700          end if;
1701
1702          Next_Formal (Formal);
1703          Next_Actual (Actual);
1704       end loop;
1705
1706       --  Find right place to put post call stuff if it is present
1707
1708       if not Is_Empty_List (Post_Call) then
1709
1710          --  If call is not a list member, it must be the triggering statement
1711          --  of a triggering alternative or an entry call alternative, and we
1712          --  can add the post call stuff to the corresponding statement list.
1713
1714          if not Is_List_Member (N) then
1715             declare
1716                P : constant Node_Id := Parent (N);
1717
1718             begin
1719                pragma Assert (Nkind_In (P, N_Triggering_Alternative,
1720                                            N_Entry_Call_Alternative));
1721
1722                if Is_Non_Empty_List (Statements (P)) then
1723                   Insert_List_Before_And_Analyze
1724                     (First (Statements (P)), Post_Call);
1725                else
1726                   Set_Statements (P, Post_Call);
1727                end if;
1728             end;
1729
1730          --  Otherwise, normal case where N is in a statement sequence,
1731          --  just put the post-call stuff after the call statement.
1732
1733          else
1734             Insert_Actions_After (N, Post_Call);
1735          end if;
1736       end if;
1737
1738       --  The call node itself is re-analyzed in Expand_Call
1739
1740    end Expand_Actuals;
1741
1742    -----------------
1743    -- Expand_Call --
1744    -----------------
1745
1746    --  This procedure handles expansion of function calls and procedure call
1747    --  statements (i.e. it serves as the body for Expand_N_Function_Call and
1748    --  Expand_N_Procedure_Call_Statement). Processing for calls includes:
1749
1750    --    Replace call to Raise_Exception by Raise_Exception_Always if possible
1751    --    Provide values of actuals for all formals in Extra_Formals list
1752    --    Replace "call" to enumeration literal function by literal itself
1753    --    Rewrite call to predefined operator as operator
1754    --    Replace actuals to in-out parameters that are numeric conversions,
1755    --     with explicit assignment to temporaries before and after the call.
1756    --    Remove optional actuals if First_Optional_Parameter specified.
1757
1758    --   Note that the list of actuals has been filled with default expressions
1759    --   during semantic analysis of the call. Only the extra actuals required
1760    --   for the 'Constrained attribute and for accessibility checks are added
1761    --   at this point.
1762
1763    procedure Expand_Call (N : Node_Id) is
1764       Loc           : constant Source_Ptr := Sloc (N);
1765       Call_Node     : Node_Id := N;
1766       Extra_Actuals : List_Id := No_List;
1767       Prev          : Node_Id := Empty;
1768
1769       procedure Add_Actual_Parameter (Insert_Param : Node_Id);
1770       --  Adds one entry to the end of the actual parameter list. Used for
1771       --  default parameters and for extra actuals (for Extra_Formals). The
1772       --  argument is an N_Parameter_Association node.
1773
1774       procedure Add_Extra_Actual (Expr : Node_Id; EF : Entity_Id);
1775       --  Adds an extra actual to the list of extra actuals. Expr is the
1776       --  expression for the value of the actual, EF is the entity for the
1777       --  extra formal.
1778
1779       function Inherited_From_Formal (S : Entity_Id) return Entity_Id;
1780       --  Within an instance, a type derived from a non-tagged formal derived
1781       --  type inherits from the original parent, not from the actual. The
1782       --  current derivation mechanism has the derived type inherit from the
1783       --  actual, which is only correct outside of the instance. If the
1784       --  subprogram is inherited, we test for this particular case through a
1785       --  convoluted tree traversal before setting the proper subprogram to be
1786       --  called.
1787
1788       function Is_Direct_Deep_Call (Subp : Entity_Id) return Boolean;
1789       --  Determine if Subp denotes a non-dispatching call to a Deep routine
1790
1791       function New_Value (From : Node_Id) return Node_Id;
1792       --  From is the original Expression. New_Value is equivalent to a call
1793       --  to Duplicate_Subexpr with an explicit dereference when From is an
1794       --  access parameter.
1795
1796       --------------------------
1797       -- Add_Actual_Parameter --
1798       --------------------------
1799
1800       procedure Add_Actual_Parameter (Insert_Param : Node_Id) is
1801          Actual_Expr : constant Node_Id :=
1802                          Explicit_Actual_Parameter (Insert_Param);
1803
1804       begin
1805          --  Case of insertion is first named actual
1806
1807          if No (Prev) or else
1808             Nkind (Parent (Prev)) /= N_Parameter_Association
1809          then
1810             Set_Next_Named_Actual
1811               (Insert_Param, First_Named_Actual (Call_Node));
1812             Set_First_Named_Actual (Call_Node, Actual_Expr);
1813
1814             if No (Prev) then
1815                if No (Parameter_Associations (Call_Node)) then
1816                   Set_Parameter_Associations (Call_Node, New_List);
1817                   Append (Insert_Param, Parameter_Associations (Call_Node));
1818                end if;
1819             else
1820                Insert_After (Prev, Insert_Param);
1821             end if;
1822
1823          --  Case of insertion is not first named actual
1824
1825          else
1826             Set_Next_Named_Actual
1827               (Insert_Param, Next_Named_Actual (Parent (Prev)));
1828             Set_Next_Named_Actual (Parent (Prev), Actual_Expr);
1829             Append (Insert_Param, Parameter_Associations (Call_Node));
1830          end if;
1831
1832          Prev := Actual_Expr;
1833       end Add_Actual_Parameter;
1834
1835       ----------------------
1836       -- Add_Extra_Actual --
1837       ----------------------
1838
1839       procedure Add_Extra_Actual (Expr : Node_Id; EF : Entity_Id) is
1840          Loc : constant Source_Ptr := Sloc (Expr);
1841
1842       begin
1843          if Extra_Actuals = No_List then
1844             Extra_Actuals := New_List;
1845             Set_Parent (Extra_Actuals, Call_Node);
1846          end if;
1847
1848          Append_To (Extra_Actuals,
1849            Make_Parameter_Association (Loc,
1850              Selector_Name             => Make_Identifier (Loc, Chars (EF)),
1851              Explicit_Actual_Parameter => Expr));
1852
1853          Analyze_And_Resolve (Expr, Etype (EF));
1854
1855          if Nkind (Call_Node) = N_Function_Call then
1856             Set_Is_Accessibility_Actual (Parent (Expr));
1857          end if;
1858       end Add_Extra_Actual;
1859
1860       ---------------------------
1861       -- Inherited_From_Formal --
1862       ---------------------------
1863
1864       function Inherited_From_Formal (S : Entity_Id) return Entity_Id is
1865          Par      : Entity_Id;
1866          Gen_Par  : Entity_Id;
1867          Gen_Prim : Elist_Id;
1868          Elmt     : Elmt_Id;
1869          Indic    : Node_Id;
1870
1871       begin
1872          --  If the operation is inherited, it is attached to the corresponding
1873          --  type derivation. If the parent in the derivation is a generic
1874          --  actual, it is a subtype of the actual, and we have to recover the
1875          --  original derived type declaration to find the proper parent.
1876
1877          if Nkind (Parent (S)) /= N_Full_Type_Declaration
1878            or else not Is_Derived_Type (Defining_Identifier (Parent (S)))
1879            or else Nkind (Type_Definition (Original_Node (Parent (S)))) /=
1880                                                    N_Derived_Type_Definition
1881            or else not In_Instance
1882          then
1883             return Empty;
1884
1885          else
1886             Indic :=
1887               Subtype_Indication
1888                 (Type_Definition (Original_Node (Parent (S))));
1889
1890             if Nkind (Indic) = N_Subtype_Indication then
1891                Par := Entity (Subtype_Mark (Indic));
1892             else
1893                Par := Entity (Indic);
1894             end if;
1895          end if;
1896
1897          if not Is_Generic_Actual_Type (Par)
1898            or else Is_Tagged_Type (Par)
1899            or else Nkind (Parent (Par)) /= N_Subtype_Declaration
1900            or else not In_Open_Scopes (Scope (Par))
1901          then
1902             return Empty;
1903          else
1904             Gen_Par := Generic_Parent_Type (Parent (Par));
1905          end if;
1906
1907          --  If the actual has no generic parent type, the formal is not
1908          --  a formal derived type, so nothing to inherit.
1909
1910          if No (Gen_Par) then
1911             return Empty;
1912          end if;
1913
1914          --  If the generic parent type is still the generic type, this is a
1915          --  private formal, not a derived formal, and there are no operations
1916          --  inherited from the formal.
1917
1918          if Nkind (Parent (Gen_Par)) = N_Formal_Type_Declaration then
1919             return Empty;
1920          end if;
1921
1922          Gen_Prim := Collect_Primitive_Operations (Gen_Par);
1923
1924          Elmt := First_Elmt (Gen_Prim);
1925          while Present (Elmt) loop
1926             if Chars (Node (Elmt)) = Chars (S) then
1927                declare
1928                   F1 : Entity_Id;
1929                   F2 : Entity_Id;
1930
1931                begin
1932                   F1 := First_Formal (S);
1933                   F2 := First_Formal (Node (Elmt));
1934                   while Present (F1)
1935                     and then Present (F2)
1936                   loop
1937                      if Etype (F1) = Etype (F2)
1938                        or else Etype (F2) = Gen_Par
1939                      then
1940                         Next_Formal (F1);
1941                         Next_Formal (F2);
1942                      else
1943                         Next_Elmt (Elmt);
1944                         exit;   --  not the right subprogram
1945                      end if;
1946
1947                      return Node (Elmt);
1948                   end loop;
1949                end;
1950
1951             else
1952                Next_Elmt (Elmt);
1953             end if;
1954          end loop;
1955
1956          raise Program_Error;
1957       end Inherited_From_Formal;
1958
1959       -------------------------
1960       -- Is_Direct_Deep_Call --
1961       -------------------------
1962
1963       function Is_Direct_Deep_Call (Subp : Entity_Id) return Boolean is
1964       begin
1965          if Is_TSS (Subp, TSS_Deep_Adjust)
1966            or else Is_TSS (Subp, TSS_Deep_Finalize)
1967            or else Is_TSS (Subp, TSS_Deep_Initialize)
1968          then
1969             declare
1970                Actual : Node_Id;
1971                Formal : Node_Id;
1972
1973             begin
1974                Actual := First (Parameter_Associations (N));
1975                Formal := First_Formal (Subp);
1976                while Present (Actual)
1977                  and then Present (Formal)
1978                loop
1979                   if Nkind (Actual) = N_Identifier
1980                     and then Is_Controlling_Actual (Actual)
1981                     and then Etype (Actual) = Etype (Formal)
1982                   then
1983                      return True;
1984                   end if;
1985
1986                   Next (Actual);
1987                   Next_Formal (Formal);
1988                end loop;
1989             end;
1990          end if;
1991
1992          return False;
1993       end Is_Direct_Deep_Call;
1994
1995       ---------------
1996       -- New_Value --
1997       ---------------
1998
1999       function New_Value (From : Node_Id) return Node_Id is
2000          Res : constant Node_Id := Duplicate_Subexpr (From);
2001       begin
2002          if Is_Access_Type (Etype (From)) then
2003             return
2004               Make_Explicit_Dereference (Sloc (From),
2005                 Prefix => Res);
2006          else
2007             return Res;
2008          end if;
2009       end New_Value;
2010
2011       --  Local variables
2012
2013       Curr_S        : constant Entity_Id := Current_Scope;
2014       Remote        : constant Boolean   := Is_Remote_Call (Call_Node);
2015       Actual        : Node_Id;
2016       Formal        : Entity_Id;
2017       Orig_Subp     : Entity_Id := Empty;
2018       Param_Count   : Natural := 0;
2019       Parent_Formal : Entity_Id;
2020       Parent_Subp   : Entity_Id;
2021       Scop          : Entity_Id;
2022       Subp          : Entity_Id;
2023
2024       Prev_Orig : Node_Id;
2025       --  Original node for an actual, which may have been rewritten. If the
2026       --  actual is a function call that has been transformed from a selected
2027       --  component, the original node is unanalyzed. Otherwise, it carries
2028       --  semantic information used to generate additional actuals.
2029
2030       CW_Interface_Formals_Present : Boolean := False;
2031
2032    --  Start of processing for Expand_Call
2033
2034    begin
2035       --  Ignore if previous error
2036
2037       if Nkind (Call_Node) in N_Has_Etype
2038         and then Etype (Call_Node) = Any_Type
2039       then
2040          return;
2041       end if;
2042
2043       --  Call using access to subprogram with explicit dereference
2044
2045       if Nkind (Name (Call_Node)) = N_Explicit_Dereference then
2046          Subp        := Etype (Name (Call_Node));
2047          Parent_Subp := Empty;
2048
2049       --  Case of call to simple entry, where the Name is a selected component
2050       --  whose prefix is the task, and whose selector name is the entry name
2051
2052       elsif Nkind (Name (Call_Node)) = N_Selected_Component then
2053          Subp        := Entity (Selector_Name (Name (Call_Node)));
2054          Parent_Subp := Empty;
2055
2056       --  Case of call to member of entry family, where Name is an indexed
2057       --  component, with the prefix being a selected component giving the
2058       --  task and entry family name, and the index being the entry index.
2059
2060       elsif Nkind (Name (Call_Node)) = N_Indexed_Component then
2061          Subp        := Entity (Selector_Name (Prefix (Name (Call_Node))));
2062          Parent_Subp := Empty;
2063
2064       --  Normal case
2065
2066       else
2067          Subp        := Entity (Name (Call_Node));
2068          Parent_Subp := Alias (Subp);
2069
2070          --  Replace call to Raise_Exception by call to Raise_Exception_Always
2071          --  if we can tell that the first parameter cannot possibly be null.
2072          --  This improves efficiency by avoiding a run-time test.
2073
2074          --  We do not do this if Raise_Exception_Always does not exist, which
2075          --  can happen in configurable run time profiles which provide only a
2076          --  Raise_Exception.
2077
2078          if Is_RTE (Subp, RE_Raise_Exception)
2079            and then RTE_Available (RE_Raise_Exception_Always)
2080          then
2081             declare
2082                FA : constant Node_Id :=
2083                       Original_Node (First_Actual (Call_Node));
2084
2085             begin
2086                --  The case we catch is where the first argument is obtained
2087                --  using the Identity attribute (which must always be
2088                --  non-null).
2089
2090                if Nkind (FA) = N_Attribute_Reference
2091                  and then Attribute_Name (FA) = Name_Identity
2092                then
2093                   Subp := RTE (RE_Raise_Exception_Always);
2094                   Set_Name (Call_Node, New_Occurrence_Of (Subp, Loc));
2095                end if;
2096             end;
2097          end if;
2098
2099          if Ekind (Subp) = E_Entry then
2100             Parent_Subp := Empty;
2101          end if;
2102       end if;
2103
2104       --  Detect the following code in System.Finalization_Masters only on
2105       --  .NET/JVM targets:
2106       --
2107       --    procedure Finalize (Master : in out Finalization_Master) is
2108       --    begin
2109       --       . . .
2110       --       begin
2111       --          Finalize (Curr_Ptr.all);
2112       --
2113       --  Since .NET/JVM compilers lack address arithmetic and Deep_Finalize
2114       --  cannot be named in library or user code, the compiler has to install
2115       --  a kludge and transform the call to Finalize into Deep_Finalize.
2116
2117       if VM_Target /= No_VM
2118         and then Chars (Subp) = Name_Finalize
2119         and then Ekind (Curr_S) = E_Block
2120         and then Ekind (Scope (Curr_S)) = E_Procedure
2121         and then Chars (Scope (Curr_S)) = Name_Finalize
2122         and then Etype (First_Formal (Scope (Curr_S))) =
2123                    RTE (RE_Finalization_Master)
2124       then
2125          declare
2126             Deep_Fin : constant Entity_Id :=
2127                          Find_Prim_Op (RTE (RE_Root_Controlled),
2128                                        TSS_Deep_Finalize);
2129          begin
2130             --  Since Root_Controlled is a tagged type, the compiler should
2131             --  always generate Deep_Finalize for it.
2132
2133             pragma Assert (Present (Deep_Fin));
2134
2135             --  Generate:
2136             --    Deep_Finalize (Curr_Ptr.all);
2137
2138             Rewrite (N,
2139               Make_Procedure_Call_Statement (Loc,
2140                 Name =>
2141                   New_Reference_To (Deep_Fin, Loc),
2142                 Parameter_Associations =>
2143                   New_Copy_List_Tree (Parameter_Associations (N))));
2144
2145             Analyze (N);
2146             return;
2147          end;
2148       end if;
2149
2150       --  Ada 2005 (AI-345): We have a procedure call as a triggering
2151       --  alternative in an asynchronous select or as an entry call in
2152       --  a conditional or timed select. Check whether the procedure call
2153       --  is a renaming of an entry and rewrite it as an entry call.
2154
2155       if Ada_Version >= Ada_2005
2156         and then Nkind (Call_Node) = N_Procedure_Call_Statement
2157         and then
2158            ((Nkind (Parent (Call_Node)) = N_Triggering_Alternative
2159               and then Triggering_Statement (Parent (Call_Node)) = Call_Node)
2160           or else
2161             (Nkind (Parent (Call_Node)) = N_Entry_Call_Alternative
2162               and then Entry_Call_Statement (Parent (Call_Node)) = Call_Node))
2163       then
2164          declare
2165             Ren_Decl : Node_Id;
2166             Ren_Root : Entity_Id := Subp;
2167
2168          begin
2169             --  This may be a chain of renamings, find the root
2170
2171             if Present (Alias (Ren_Root)) then
2172                Ren_Root := Alias (Ren_Root);
2173             end if;
2174
2175             if Present (Original_Node (Parent (Parent (Ren_Root)))) then
2176                Ren_Decl := Original_Node (Parent (Parent (Ren_Root)));
2177
2178                if Nkind (Ren_Decl) = N_Subprogram_Renaming_Declaration then
2179                   Rewrite (Call_Node,
2180                     Make_Entry_Call_Statement (Loc,
2181                       Name =>
2182                         New_Copy_Tree (Name (Ren_Decl)),
2183                       Parameter_Associations =>
2184                         New_Copy_List_Tree
2185                           (Parameter_Associations (Call_Node))));
2186
2187                   return;
2188                end if;
2189             end if;
2190          end;
2191       end if;
2192
2193       --  First step, compute extra actuals, corresponding to any Extra_Formals
2194       --  present. Note that we do not access Extra_Formals directly, instead
2195       --  we simply note the presence of the extra formals as we process the
2196       --  regular formals collecting corresponding actuals in Extra_Actuals.
2197
2198       --  We also generate any required range checks for actuals for in formals
2199       --  as we go through the loop, since this is a convenient place to do it.
2200       --  (Though it seems that this would be better done in Expand_Actuals???)
2201
2202       Formal      := First_Formal (Subp);
2203       Actual      := First_Actual (Call_Node);
2204       Param_Count := 1;
2205       while Present (Formal) loop
2206
2207          --  Generate range check if required
2208
2209          if Do_Range_Check (Actual)
2210            and then Ekind (Formal) = E_In_Parameter
2211          then
2212             Set_Do_Range_Check (Actual, False);
2213             Generate_Range_Check
2214               (Actual, Etype (Formal), CE_Range_Check_Failed);
2215          end if;
2216
2217          --  Prepare to examine current entry
2218
2219          Prev := Actual;
2220          Prev_Orig := Original_Node (Prev);
2221
2222          --  Ada 2005 (AI-251): Check if any formal is a class-wide interface
2223          --  to expand it in a further round.
2224
2225          CW_Interface_Formals_Present :=
2226            CW_Interface_Formals_Present
2227              or else
2228                (Ekind (Etype (Formal)) = E_Class_Wide_Type
2229                   and then Is_Interface (Etype (Etype (Formal))))
2230              or else
2231                (Ekind (Etype (Formal)) = E_Anonymous_Access_Type
2232                  and then Is_Interface (Directly_Designated_Type
2233                                          (Etype (Etype (Formal)))));
2234
2235          --  Create possible extra actual for constrained case. Usually, the
2236          --  extra actual is of the form actual'constrained, but since this
2237          --  attribute is only available for unconstrained records, TRUE is
2238          --  expanded if the type of the formal happens to be constrained (for
2239          --  instance when this procedure is inherited from an unconstrained
2240          --  record to a constrained one) or if the actual has no discriminant
2241          --  (its type is constrained). An exception to this is the case of a
2242          --  private type without discriminants. In this case we pass FALSE
2243          --  because the object has underlying discriminants with defaults.
2244
2245          if Present (Extra_Constrained (Formal)) then
2246             if Ekind (Etype (Prev)) in Private_Kind
2247               and then not Has_Discriminants (Base_Type (Etype (Prev)))
2248             then
2249                Add_Extra_Actual
2250                  (New_Occurrence_Of (Standard_False, Loc),
2251                   Extra_Constrained (Formal));
2252
2253             elsif Is_Constrained (Etype (Formal))
2254               or else not Has_Discriminants (Etype (Prev))
2255             then
2256                Add_Extra_Actual
2257                  (New_Occurrence_Of (Standard_True, Loc),
2258                   Extra_Constrained (Formal));
2259
2260             --  Do not produce extra actuals for Unchecked_Union parameters.
2261             --  Jump directly to the end of the loop.
2262
2263             elsif Is_Unchecked_Union (Base_Type (Etype (Actual))) then
2264                goto Skip_Extra_Actual_Generation;
2265
2266             else
2267                --  If the actual is a type conversion, then the constrained
2268                --  test applies to the actual, not the target type.
2269
2270                declare
2271                   Act_Prev : Node_Id;
2272
2273                begin
2274                   --  Test for unchecked conversions as well, which can occur
2275                   --  as out parameter actuals on calls to stream procedures.
2276
2277                   Act_Prev := Prev;
2278                   while Nkind_In (Act_Prev, N_Type_Conversion,
2279                                             N_Unchecked_Type_Conversion)
2280                   loop
2281                      Act_Prev := Expression (Act_Prev);
2282                   end loop;
2283
2284                   --  If the expression is a conversion of a dereference, this
2285                   --  is internally generated code that manipulates addresses,
2286                   --  e.g. when building interface tables. No check should
2287                   --  occur in this case, and the discriminated object is not
2288                   --  directly a hand.
2289
2290                   if not Comes_From_Source (Actual)
2291                     and then Nkind (Actual) = N_Unchecked_Type_Conversion
2292                     and then Nkind (Act_Prev) = N_Explicit_Dereference
2293                   then
2294                      Add_Extra_Actual
2295                        (New_Occurrence_Of (Standard_False, Loc),
2296                         Extra_Constrained (Formal));
2297
2298                   else
2299                      Add_Extra_Actual
2300                        (Make_Attribute_Reference (Sloc (Prev),
2301                         Prefix =>
2302                           Duplicate_Subexpr_No_Checks
2303                             (Act_Prev, Name_Req => True),
2304                         Attribute_Name => Name_Constrained),
2305                         Extra_Constrained (Formal));
2306                   end if;
2307                end;
2308             end if;
2309          end if;
2310
2311          --  Create possible extra actual for accessibility level
2312
2313          if Present (Extra_Accessibility (Formal)) then
2314
2315             --  Ada 2005 (AI-252): If the actual was rewritten as an Access
2316             --  attribute, then the original actual may be an aliased object
2317             --  occurring as the prefix in a call using "Object.Operation"
2318             --  notation. In that case we must pass the level of the object,
2319             --  so Prev_Orig is reset to Prev and the attribute will be
2320             --  processed by the code for Access attributes further below.
2321
2322             if Prev_Orig /= Prev
2323               and then Nkind (Prev) = N_Attribute_Reference
2324               and then
2325                 Get_Attribute_Id (Attribute_Name (Prev)) = Attribute_Access
2326               and then Is_Aliased_View (Prev_Orig)
2327             then
2328                Prev_Orig := Prev;
2329             end if;
2330
2331             --  Ada 2005 (AI-251): Thunks must propagate the extra actuals of
2332             --  accessibility levels.
2333
2334             if Ekind (Current_Scope) in Subprogram_Kind
2335               and then Is_Thunk (Current_Scope)
2336             then
2337                declare
2338                   Parm_Ent : Entity_Id;
2339
2340                begin
2341                   if Is_Controlling_Actual (Actual) then
2342
2343                      --  Find the corresponding actual of the thunk
2344
2345                      Parm_Ent := First_Entity (Current_Scope);
2346                      for J in 2 .. Param_Count loop
2347                         Next_Entity (Parm_Ent);
2348                      end loop;
2349
2350                   else pragma Assert (Is_Entity_Name (Actual));
2351                      Parm_Ent := Entity (Actual);
2352                   end if;
2353
2354                   Add_Extra_Actual
2355                     (New_Occurrence_Of (Extra_Accessibility (Parm_Ent), Loc),
2356                      Extra_Accessibility (Formal));
2357                end;
2358
2359             elsif Is_Entity_Name (Prev_Orig) then
2360
2361                --  When passing an access parameter, or a renaming of an access
2362                --  parameter, as the actual to another access parameter we need
2363                --  to pass along the actual's own access level parameter. This
2364                --  is done if we are within the scope of the formal access
2365                --  parameter (if this is an inlined body the extra formal is
2366                --  irrelevant).
2367
2368                if (Is_Formal (Entity (Prev_Orig))
2369                     or else
2370                       (Present (Renamed_Object (Entity (Prev_Orig)))
2371                         and then
2372                           Is_Entity_Name (Renamed_Object (Entity (Prev_Orig)))
2373                         and then
2374                           Is_Formal
2375                             (Entity (Renamed_Object (Entity (Prev_Orig))))))
2376                  and then Ekind (Etype (Prev_Orig)) = E_Anonymous_Access_Type
2377                  and then In_Open_Scopes (Scope (Entity (Prev_Orig)))
2378                then
2379                   declare
2380                      Parm_Ent : constant Entity_Id := Param_Entity (Prev_Orig);
2381
2382                   begin
2383                      pragma Assert (Present (Parm_Ent));
2384
2385                      if Present (Extra_Accessibility (Parm_Ent)) then
2386                         Add_Extra_Actual
2387                           (New_Occurrence_Of
2388                              (Extra_Accessibility (Parm_Ent), Loc),
2389                            Extra_Accessibility (Formal));
2390
2391                      --  If the actual access parameter does not have an
2392                      --  associated extra formal providing its scope level,
2393                      --  then treat the actual as having library-level
2394                      --  accessibility.
2395
2396                      else
2397                         Add_Extra_Actual
2398                           (Make_Integer_Literal (Loc,
2399                              Intval => Scope_Depth (Standard_Standard)),
2400                            Extra_Accessibility (Formal));
2401                      end if;
2402                   end;
2403
2404                --  The actual is a normal access value, so just pass the level
2405                --  of the actual's access type.
2406
2407                else
2408                   Add_Extra_Actual
2409                     (Make_Integer_Literal (Loc,
2410                        Intval => Type_Access_Level (Etype (Prev_Orig))),
2411                      Extra_Accessibility (Formal));
2412                end if;
2413
2414             --  If the actual is an access discriminant, then pass the level
2415             --  of the enclosing object (RM05-3.10.2(12.4/2)).
2416
2417             elsif Nkind (Prev_Orig) = N_Selected_Component
2418               and then Ekind (Entity (Selector_Name (Prev_Orig))) =
2419                                                        E_Discriminant
2420               and then Ekind (Etype (Entity (Selector_Name (Prev_Orig)))) =
2421                                                        E_Anonymous_Access_Type
2422             then
2423                Add_Extra_Actual
2424                  (Make_Integer_Literal (Loc,
2425                     Intval => Object_Access_Level (Prefix (Prev_Orig))),
2426                   Extra_Accessibility (Formal));
2427
2428             --  All other cases
2429
2430             else
2431                case Nkind (Prev_Orig) is
2432
2433                   when N_Attribute_Reference =>
2434                      case Get_Attribute_Id (Attribute_Name (Prev_Orig)) is
2435
2436                         --  For X'Access, pass on the level of the prefix X
2437
2438                         when Attribute_Access =>
2439                            Add_Extra_Actual
2440                              (Make_Integer_Literal (Loc,
2441                                Intval =>
2442                                  Object_Access_Level
2443                                    (Prefix (Prev_Orig))),
2444                                     Extra_Accessibility (Formal));
2445
2446                         --  Treat the unchecked attributes as library-level
2447
2448                         when Attribute_Unchecked_Access |
2449                            Attribute_Unrestricted_Access =>
2450                            Add_Extra_Actual
2451                              (Make_Integer_Literal (Loc,
2452                                 Intval => Scope_Depth (Standard_Standard)),
2453                               Extra_Accessibility (Formal));
2454
2455                         --  No other cases of attributes returning access
2456                         --  values that can be passed to access parameters.
2457
2458                         when others =>
2459                            raise Program_Error;
2460
2461                      end case;
2462
2463                   --  For allocators we pass the level of the execution of the
2464                   --  called subprogram, which is one greater than the current
2465                   --  scope level.
2466
2467                   when N_Allocator =>
2468                      Add_Extra_Actual
2469                        (Make_Integer_Literal (Loc,
2470                           Intval => Scope_Depth (Current_Scope) + 1),
2471                         Extra_Accessibility (Formal));
2472
2473                   --  For other cases we simply pass the level of the actual's
2474                   --  access type. The type is retrieved from Prev rather than
2475                   --  Prev_Orig, because in some cases Prev_Orig denotes an
2476                   --  original expression that has not been analyzed.
2477
2478                   when others =>
2479                      Add_Extra_Actual
2480                        (Make_Integer_Literal (Loc,
2481                           Intval => Type_Access_Level (Etype (Prev))),
2482                         Extra_Accessibility (Formal));
2483                end case;
2484             end if;
2485          end if;
2486
2487          --  Perform the check of 4.6(49) that prevents a null value from being
2488          --  passed as an actual to an access parameter. Note that the check
2489          --  is elided in the common cases of passing an access attribute or
2490          --  access parameter as an actual. Also, we currently don't enforce
2491          --  this check for expander-generated actuals and when -gnatdj is set.
2492
2493          if Ada_Version >= Ada_2005 then
2494
2495             --  Ada 2005 (AI-231): Check null-excluding access types. Note that
2496             --  the intent of 6.4.1(13) is that null-exclusion checks should
2497             --  not be done for 'out' parameters, even though it refers only
2498             --  to constraint checks, and a null_exclusion is not a constraint.
2499             --  Note that AI05-0196-1 corrects this mistake in the RM.
2500
2501             if Is_Access_Type (Etype (Formal))
2502               and then Can_Never_Be_Null (Etype (Formal))
2503               and then Ekind (Formal) /= E_Out_Parameter
2504               and then Nkind (Prev) /= N_Raise_Constraint_Error
2505               and then (Known_Null (Prev)
2506                           or else not Can_Never_Be_Null (Etype (Prev)))
2507             then
2508                Install_Null_Excluding_Check (Prev);
2509             end if;
2510
2511          --  Ada_Version < Ada_2005
2512
2513          else
2514             if Ekind (Etype (Formal)) /= E_Anonymous_Access_Type
2515               or else Access_Checks_Suppressed (Subp)
2516             then
2517                null;
2518
2519             elsif Debug_Flag_J then
2520                null;
2521
2522             elsif not Comes_From_Source (Prev) then
2523                null;
2524
2525             elsif Is_Entity_Name (Prev)
2526               and then Ekind (Etype (Prev)) = E_Anonymous_Access_Type
2527             then
2528                null;
2529
2530             elsif Nkind_In (Prev, N_Allocator, N_Attribute_Reference) then
2531                null;
2532
2533             --  Suppress null checks when passing to access parameters of Java
2534             --  and CIL subprograms. (Should this be done for other foreign
2535             --  conventions as well ???)
2536
2537             elsif Convention (Subp) = Convention_Java
2538               or else Convention (Subp) = Convention_CIL
2539             then
2540                null;
2541
2542             else
2543                Install_Null_Excluding_Check (Prev);
2544             end if;
2545          end if;
2546
2547          --  Perform appropriate validity checks on parameters that
2548          --  are entities.
2549
2550          if Validity_Checks_On then
2551             if  (Ekind (Formal) = E_In_Parameter
2552                    and then Validity_Check_In_Params)
2553               or else
2554                 (Ekind (Formal) = E_In_Out_Parameter
2555                    and then Validity_Check_In_Out_Params)
2556             then
2557                --  If the actual is an indexed component of a packed type (or
2558                --  is an indexed or selected component whose prefix recursively
2559                --  meets this condition), it has not been expanded yet. It will
2560                --  be copied in the validity code that follows, and has to be
2561                --  expanded appropriately, so reanalyze it.
2562
2563                --  What we do is just to unset analyzed bits on prefixes till
2564                --  we reach something that does not have a prefix.
2565
2566                declare
2567                   Nod : Node_Id;
2568
2569                begin
2570                   Nod := Actual;
2571                   while Nkind_In (Nod, N_Indexed_Component,
2572                                        N_Selected_Component)
2573                   loop
2574                      Set_Analyzed (Nod, False);
2575                      Nod := Prefix (Nod);
2576                   end loop;
2577                end;
2578
2579                Ensure_Valid (Actual);
2580             end if;
2581          end if;
2582
2583          --  For IN OUT and OUT parameters, ensure that subscripts are valid
2584          --  since this is a left side reference. We only do this for calls
2585          --  from the source program since we assume that compiler generated
2586          --  calls explicitly generate any required checks. We also need it
2587          --  only if we are doing standard validity checks, since clearly it is
2588          --  not needed if validity checks are off, and in subscript validity
2589          --  checking mode, all indexed components are checked with a call
2590          --  directly from Expand_N_Indexed_Component.
2591
2592          if Comes_From_Source (Call_Node)
2593            and then Ekind (Formal) /= E_In_Parameter
2594            and then Validity_Checks_On
2595            and then Validity_Check_Default
2596            and then not Validity_Check_Subscripts
2597          then
2598             Check_Valid_Lvalue_Subscripts (Actual);
2599          end if;
2600
2601          --  Mark any scalar OUT parameter that is a simple variable as no
2602          --  longer known to be valid (unless the type is always valid). This
2603          --  reflects the fact that if an OUT parameter is never set in a
2604          --  procedure, then it can become invalid on the procedure return.
2605
2606          if Ekind (Formal) = E_Out_Parameter
2607            and then Is_Entity_Name (Actual)
2608            and then Ekind (Entity (Actual)) = E_Variable
2609            and then not Is_Known_Valid (Etype (Actual))
2610          then
2611             Set_Is_Known_Valid (Entity (Actual), False);
2612          end if;
2613
2614          --  For an OUT or IN OUT parameter, if the actual is an entity, then
2615          --  clear current values, since they can be clobbered. We are probably
2616          --  doing this in more places than we need to, but better safe than
2617          --  sorry when it comes to retaining bad current values!
2618
2619          if Ekind (Formal) /= E_In_Parameter
2620            and then Is_Entity_Name (Actual)
2621            and then Present (Entity (Actual))
2622          then
2623             declare
2624                Ent : constant Entity_Id := Entity (Actual);
2625                Sav : Node_Id;
2626
2627             begin
2628                --  For an OUT or IN OUT parameter that is an assignable entity,
2629                --  we do not want to clobber the Last_Assignment field, since
2630                --  if it is set, it was precisely because it is indeed an OUT
2631                --  or IN OUT parameter! We do reset the Is_Known_Valid flag
2632                --  since the subprogram could have returned in invalid value.
2633
2634                if (Ekind (Formal) = E_Out_Parameter
2635                      or else
2636                    Ekind (Formal) = E_In_Out_Parameter)
2637                  and then Is_Assignable (Ent)
2638                then
2639                   Sav := Last_Assignment (Ent);
2640                   Kill_Current_Values (Ent);
2641                   Set_Last_Assignment (Ent, Sav);
2642                   Set_Is_Known_Valid (Ent, False);
2643
2644                   --  For all other cases, just kill the current values
2645
2646                else
2647                   Kill_Current_Values (Ent);
2648                end if;
2649             end;
2650          end if;
2651
2652          --  If the formal is class wide and the actual is an aggregate, force
2653          --  evaluation so that the back end who does not know about class-wide
2654          --  type, does not generate a temporary of the wrong size.
2655
2656          if not Is_Class_Wide_Type (Etype (Formal)) then
2657             null;
2658
2659          elsif Nkind (Actual) = N_Aggregate
2660            or else (Nkind (Actual) = N_Qualified_Expression
2661                      and then Nkind (Expression (Actual)) = N_Aggregate)
2662          then
2663             Force_Evaluation (Actual);
2664          end if;
2665
2666          --  In a remote call, if the formal is of a class-wide type, check
2667          --  that the actual meets the requirements described in E.4(18).
2668
2669          if Remote and then Is_Class_Wide_Type (Etype (Formal)) then
2670             Insert_Action (Actual,
2671               Make_Transportable_Check (Loc,
2672                 Duplicate_Subexpr_Move_Checks (Actual)));
2673          end if;
2674
2675          --  This label is required when skipping extra actual generation for
2676          --  Unchecked_Union parameters.
2677
2678          <<Skip_Extra_Actual_Generation>>
2679
2680          Param_Count := Param_Count + 1;
2681          Next_Actual (Actual);
2682          Next_Formal (Formal);
2683       end loop;
2684
2685       --  If we are expanding a rhs of an assignment we need to check if tag
2686       --  propagation is needed. You might expect this processing to be in
2687       --  Analyze_Assignment but has to be done earlier (bottom-up) because the
2688       --  assignment might be transformed to a declaration for an unconstrained
2689       --  value if the expression is classwide.
2690
2691       if Nkind (Call_Node) = N_Function_Call
2692         and then Is_Tag_Indeterminate (Call_Node)
2693         and then Is_Entity_Name (Name (Call_Node))
2694       then
2695          declare
2696             Ass : Node_Id := Empty;
2697
2698          begin
2699             if Nkind (Parent (Call_Node)) = N_Assignment_Statement then
2700                Ass := Parent (Call_Node);
2701
2702             elsif Nkind (Parent (Call_Node)) = N_Qualified_Expression
2703               and then Nkind (Parent (Parent (Call_Node))) =
2704                                                   N_Assignment_Statement
2705             then
2706                Ass := Parent (Parent (Call_Node));
2707
2708             elsif Nkind (Parent (Call_Node)) = N_Explicit_Dereference
2709               and then Nkind (Parent (Parent (Call_Node))) =
2710                                                   N_Assignment_Statement
2711             then
2712                Ass := Parent (Parent (Call_Node));
2713             end if;
2714
2715             if Present (Ass)
2716               and then Is_Class_Wide_Type (Etype (Name (Ass)))
2717             then
2718                if Is_Access_Type (Etype (Call_Node)) then
2719                   if Designated_Type (Etype (Call_Node)) /=
2720                     Root_Type (Etype (Name (Ass)))
2721                   then
2722                      Error_Msg_NE
2723                        ("tag-indeterminate expression "
2724                          & " must have designated type& (RM 5.2 (6))",
2725                          Call_Node, Root_Type (Etype (Name (Ass))));
2726                   else
2727                      Propagate_Tag (Name (Ass), Call_Node);
2728                   end if;
2729
2730                elsif Etype (Call_Node) /= Root_Type (Etype (Name (Ass))) then
2731                   Error_Msg_NE
2732                     ("tag-indeterminate expression must have type&"
2733                      & "(RM 5.2 (6))",
2734                      Call_Node, Root_Type (Etype (Name (Ass))));
2735
2736                else
2737                   Propagate_Tag (Name (Ass), Call_Node);
2738                end if;
2739
2740                --  The call will be rewritten as a dispatching call, and
2741                --  expanded as such.
2742
2743                return;
2744             end if;
2745          end;
2746       end if;
2747
2748       --  Ada 2005 (AI-251): If some formal is a class-wide interface, expand
2749       --  it to point to the correct secondary virtual table
2750
2751       if Nkind_In (Call_Node, N_Function_Call, N_Procedure_Call_Statement)
2752         and then CW_Interface_Formals_Present
2753       then
2754          Expand_Interface_Actuals (Call_Node);
2755       end if;
2756
2757       --  Deals with Dispatch_Call if we still have a call, before expanding
2758       --  extra actuals since this will be done on the re-analysis of the
2759       --  dispatching call. Note that we do not try to shorten the actual list
2760       --  for a dispatching call, it would not make sense to do so. Expansion
2761       --  of dispatching calls is suppressed when VM_Target, because the VM
2762       --  back-ends directly handle the generation of dispatching calls and
2763       --  would have to undo any expansion to an indirect call.
2764
2765       if Nkind_In (Call_Node, N_Function_Call, N_Procedure_Call_Statement)
2766         and then Present (Controlling_Argument (Call_Node))
2767       then
2768          declare
2769             Call_Typ   : constant Entity_Id := Etype (Call_Node);
2770             Typ        : constant Entity_Id := Find_Dispatching_Type (Subp);
2771             Eq_Prim_Op : Entity_Id := Empty;
2772             New_Call   : Node_Id;
2773             Param      : Node_Id;
2774             Prev_Call  : Node_Id;
2775
2776          begin
2777             if not Is_Limited_Type (Typ) then
2778                Eq_Prim_Op := Find_Prim_Op (Typ, Name_Op_Eq);
2779             end if;
2780
2781             if Tagged_Type_Expansion then
2782                Expand_Dispatching_Call (Call_Node);
2783
2784                --  The following return is worrisome. Is it really OK to skip
2785                --  all remaining processing in this procedure ???
2786
2787                return;
2788
2789             --  VM targets
2790
2791             else
2792                Apply_Tag_Checks (Call_Node);
2793
2794                --  If this is a dispatching "=", we must first compare the
2795                --  tags so we generate: x.tag = y.tag and then x = y
2796
2797                if Subp = Eq_Prim_Op then
2798
2799                   --  Mark the node as analyzed to avoid reanalizing this
2800                   --  dispatching call (which would cause a never-ending loop)
2801
2802                   Prev_Call := Relocate_Node (Call_Node);
2803                   Set_Analyzed (Prev_Call);
2804
2805                   Param := First_Actual (Call_Node);
2806                   New_Call :=
2807                     Make_And_Then (Loc,
2808                       Left_Opnd =>
2809                            Make_Op_Eq (Loc,
2810                              Left_Opnd =>
2811                                Make_Selected_Component (Loc,
2812                                  Prefix        => New_Value (Param),
2813                                  Selector_Name =>
2814                                    New_Reference_To (First_Tag_Component (Typ),
2815                                                      Loc)),
2816
2817                              Right_Opnd =>
2818                                Make_Selected_Component (Loc,
2819                                  Prefix        =>
2820                                    Unchecked_Convert_To (Typ,
2821                                      New_Value (Next_Actual (Param))),
2822                                  Selector_Name =>
2823                                    New_Reference_To
2824                                      (First_Tag_Component (Typ), Loc))),
2825                       Right_Opnd => Prev_Call);
2826
2827                   Rewrite (Call_Node, New_Call);
2828
2829                   Analyze_And_Resolve
2830                     (Call_Node, Call_Typ, Suppress => All_Checks);
2831                end if;
2832
2833                --  Expansion of a dispatching call results in an indirect call,
2834                --  which in turn causes current values to be killed (see
2835                --  Resolve_Call), so on VM targets we do the call here to
2836                --  ensure consistent warnings between VM and non-VM targets.
2837
2838                Kill_Current_Values;
2839             end if;
2840
2841             --  If this is a dispatching "=" then we must update the reference
2842             --  to the call node because we generated:
2843             --     x.tag = y.tag and then x = y
2844
2845             if Subp = Eq_Prim_Op then
2846                Call_Node := Right_Opnd (Call_Node);
2847             end if;
2848          end;
2849       end if;
2850
2851       --  Similarly, expand calls to RCI subprograms on which pragma
2852       --  All_Calls_Remote applies. The rewriting will be reanalyzed
2853       --  later. Do this only when the call comes from source since we
2854       --  do not want such a rewriting to occur in expanded code.
2855
2856       if Is_All_Remote_Call (Call_Node) then
2857          Expand_All_Calls_Remote_Subprogram_Call (Call_Node);
2858
2859       --  Similarly, do not add extra actuals for an entry call whose entity
2860       --  is a protected procedure, or for an internal protected subprogram
2861       --  call, because it will be rewritten as a protected subprogram call
2862       --  and reanalyzed (see Expand_Protected_Subprogram_Call).
2863
2864       elsif Is_Protected_Type (Scope (Subp))
2865          and then (Ekind (Subp) = E_Procedure
2866                     or else Ekind (Subp) = E_Function)
2867       then
2868          null;
2869
2870       --  During that loop we gathered the extra actuals (the ones that
2871       --  correspond to Extra_Formals), so now they can be appended.
2872
2873       else
2874          while Is_Non_Empty_List (Extra_Actuals) loop
2875             Add_Actual_Parameter (Remove_Head (Extra_Actuals));
2876          end loop;
2877       end if;
2878
2879       --  At this point we have all the actuals, so this is the point at which
2880       --  the various expansion activities for actuals is carried out.
2881
2882       Expand_Actuals (Call_Node, Subp);
2883
2884       --  If the subprogram is a renaming, or if it is inherited, replace it in
2885       --  the call with the name of the actual subprogram being called. If this
2886       --  is a dispatching call, the run-time decides what to call. The Alias
2887       --  attribute does not apply to entries.
2888
2889       if Nkind (Call_Node) /= N_Entry_Call_Statement
2890         and then No (Controlling_Argument (Call_Node))
2891         and then Present (Parent_Subp)
2892         and then not Is_Direct_Deep_Call (Subp)
2893       then
2894          if Present (Inherited_From_Formal (Subp)) then
2895             Parent_Subp := Inherited_From_Formal (Subp);
2896          else
2897             Parent_Subp := Ultimate_Alias (Parent_Subp);
2898          end if;
2899
2900          --  The below setting of Entity is suspect, see F109-018 discussion???
2901
2902          Set_Entity (Name (Call_Node), Parent_Subp);
2903
2904          if Is_Abstract_Subprogram (Parent_Subp)
2905            and then not In_Instance
2906          then
2907             Error_Msg_NE
2908               ("cannot call abstract subprogram &!",
2909                Name (Call_Node), Parent_Subp);
2910          end if;
2911
2912          --  Inspect all formals of derived subprogram Subp. Compare parameter
2913          --  types with the parent subprogram and check whether an actual may
2914          --  need a type conversion to the corresponding formal of the parent
2915          --  subprogram.
2916
2917          --  Not clear whether intrinsic subprograms need such conversions. ???
2918
2919          if not Is_Intrinsic_Subprogram (Parent_Subp)
2920            or else Is_Generic_Instance (Parent_Subp)
2921          then
2922             declare
2923                procedure Convert (Act : Node_Id; Typ : Entity_Id);
2924                --  Rewrite node Act as a type conversion of Act to Typ. Analyze
2925                --  and resolve the newly generated construct.
2926
2927                -------------
2928                -- Convert --
2929                -------------
2930
2931                procedure Convert (Act : Node_Id; Typ : Entity_Id) is
2932                begin
2933                   Rewrite (Act, OK_Convert_To (Typ, Relocate_Node (Act)));
2934                   Analyze (Act);
2935                   Resolve (Act, Typ);
2936                end Convert;
2937
2938                --  Local variables
2939
2940                Actual_Typ : Entity_Id;
2941                Formal_Typ : Entity_Id;
2942                Parent_Typ : Entity_Id;
2943
2944             begin
2945                Actual := First_Actual (Call_Node);
2946                Formal := First_Formal (Subp);
2947                Parent_Formal := First_Formal (Parent_Subp);
2948                while Present (Formal) loop
2949                   Actual_Typ := Etype (Actual);
2950                   Formal_Typ := Etype (Formal);
2951                   Parent_Typ := Etype (Parent_Formal);
2952
2953                   --  For an IN parameter of a scalar type, the parent formal
2954                   --  type and derived formal type differ or the parent formal
2955                   --  type and actual type do not match statically.
2956
2957                   if Is_Scalar_Type (Formal_Typ)
2958                     and then Ekind (Formal) = E_In_Parameter
2959                     and then Formal_Typ /= Parent_Typ
2960                     and then
2961                       not Subtypes_Statically_Match (Parent_Typ, Actual_Typ)
2962                     and then not Raises_Constraint_Error (Actual)
2963                   then
2964                      Convert (Actual, Parent_Typ);
2965                      Enable_Range_Check (Actual);
2966
2967                      --  If the actual has been marked as requiring a range
2968                      --  check, then generate it here.
2969
2970                      if Do_Range_Check (Actual) then
2971                         Set_Do_Range_Check (Actual, False);
2972                         Generate_Range_Check
2973                           (Actual, Etype (Formal), CE_Range_Check_Failed);
2974                      end if;
2975
2976                   --  For access types, the parent formal type and actual type
2977                   --  differ.
2978
2979                   elsif Is_Access_Type (Formal_Typ)
2980                     and then Base_Type (Parent_Typ) /= Base_Type (Actual_Typ)
2981                   then
2982                      if Ekind (Formal) /= E_In_Parameter then
2983                         Convert (Actual, Parent_Typ);
2984
2985                      elsif Ekind (Parent_Typ) = E_Anonymous_Access_Type
2986                        and then Designated_Type (Parent_Typ) /=
2987                                 Designated_Type (Actual_Typ)
2988                        and then not Is_Controlling_Formal (Formal)
2989                      then
2990                         --  This unchecked conversion is not necessary unless
2991                         --  inlining is enabled, because in that case the type
2992                         --  mismatch may become visible in the body about to be
2993                         --  inlined.
2994
2995                         Rewrite (Actual,
2996                           Unchecked_Convert_To (Parent_Typ,
2997                             Relocate_Node (Actual)));
2998                         Analyze (Actual);
2999                         Resolve (Actual, Parent_Typ);
3000                      end if;
3001
3002                   --  For array and record types, the parent formal type and
3003                   --  derived formal type have different sizes or pragma Pack
3004                   --  status.
3005
3006                   elsif ((Is_Array_Type (Formal_Typ)
3007                             and then Is_Array_Type (Parent_Typ))
3008                        or else
3009                          (Is_Record_Type (Formal_Typ)
3010                             and then Is_Record_Type (Parent_Typ)))
3011                     and then
3012                       (Esize (Formal_Typ) /= Esize (Parent_Typ)
3013                          or else Has_Pragma_Pack (Formal_Typ) /=
3014                                  Has_Pragma_Pack (Parent_Typ))
3015                   then
3016                      Convert (Actual, Parent_Typ);
3017                   end if;
3018
3019                   Next_Actual (Actual);
3020                   Next_Formal (Formal);
3021                   Next_Formal (Parent_Formal);
3022                end loop;
3023             end;
3024          end if;
3025
3026          Orig_Subp := Subp;
3027          Subp := Parent_Subp;
3028       end if;
3029
3030       --  Check for violation of No_Abort_Statements
3031
3032       if Restriction_Check_Required (No_Abort_Statements)
3033         and then Is_RTE (Subp, RE_Abort_Task)
3034       then
3035          Check_Restriction (No_Abort_Statements, Call_Node);
3036
3037       --  Check for violation of No_Dynamic_Attachment
3038
3039       elsif Restriction_Check_Required (No_Dynamic_Attachment)
3040         and then RTU_Loaded (Ada_Interrupts)
3041         and then (Is_RTE (Subp, RE_Is_Reserved)      or else
3042                   Is_RTE (Subp, RE_Is_Attached)      or else
3043                   Is_RTE (Subp, RE_Current_Handler)  or else
3044                   Is_RTE (Subp, RE_Attach_Handler)   or else
3045                   Is_RTE (Subp, RE_Exchange_Handler) or else
3046                   Is_RTE (Subp, RE_Detach_Handler)   or else
3047                   Is_RTE (Subp, RE_Reference))
3048       then
3049          Check_Restriction (No_Dynamic_Attachment, Call_Node);
3050       end if;
3051
3052       --  Deal with case where call is an explicit dereference
3053
3054       if Nkind (Name (Call_Node)) = N_Explicit_Dereference then
3055
3056       --  Handle case of access to protected subprogram type
3057
3058          if Is_Access_Protected_Subprogram_Type
3059               (Base_Type (Etype (Prefix (Name (Call_Node)))))
3060          then
3061             --  If this is a call through an access to protected operation, the
3062             --  prefix has the form (object'address, operation'access). Rewrite
3063             --  as a for other protected calls: the object is the 1st parameter
3064             --  of the list of actuals.
3065
3066             declare
3067                Call : Node_Id;
3068                Parm : List_Id;
3069                Nam  : Node_Id;
3070                Obj  : Node_Id;
3071                Ptr  : constant Node_Id := Prefix (Name (Call_Node));
3072
3073                T : constant Entity_Id :=
3074                      Equivalent_Type (Base_Type (Etype (Ptr)));
3075
3076                D_T : constant Entity_Id :=
3077                        Designated_Type (Base_Type (Etype (Ptr)));
3078
3079             begin
3080                Obj :=
3081                  Make_Selected_Component (Loc,
3082                    Prefix        => Unchecked_Convert_To (T, Ptr),
3083                    Selector_Name =>
3084                      New_Occurrence_Of (First_Entity (T), Loc));
3085
3086                Nam :=
3087                  Make_Selected_Component (Loc,
3088                    Prefix        => Unchecked_Convert_To (T, Ptr),
3089                    Selector_Name =>
3090                      New_Occurrence_Of (Next_Entity (First_Entity (T)), Loc));
3091
3092                Nam :=
3093                  Make_Explicit_Dereference (Loc,
3094                    Prefix => Nam);
3095
3096                if Present (Parameter_Associations (Call_Node))  then
3097                   Parm := Parameter_Associations (Call_Node);
3098                else
3099                   Parm := New_List;
3100                end if;
3101
3102                Prepend (Obj, Parm);
3103
3104                if Etype (D_T) = Standard_Void_Type then
3105                   Call :=
3106                     Make_Procedure_Call_Statement (Loc,
3107                       Name                   => Nam,
3108                       Parameter_Associations => Parm);
3109                else
3110                   Call :=
3111                     Make_Function_Call (Loc,
3112                       Name                   => Nam,
3113                       Parameter_Associations => Parm);
3114                end if;
3115
3116                Set_First_Named_Actual (Call, First_Named_Actual (Call_Node));
3117                Set_Etype (Call, Etype (D_T));
3118
3119                --  We do not re-analyze the call to avoid infinite recursion.
3120                --  We analyze separately the prefix and the object, and set
3121                --  the checks on the prefix that would otherwise be emitted
3122                --  when resolving a call.
3123
3124                Rewrite (Call_Node, Call);
3125                Analyze (Nam);
3126                Apply_Access_Check (Nam);
3127                Analyze (Obj);
3128                return;
3129             end;
3130          end if;
3131       end if;
3132
3133       --  If this is a call to an intrinsic subprogram, then perform the
3134       --  appropriate expansion to the corresponding tree node and we
3135       --  are all done (since after that the call is gone!)
3136
3137       --  In the case where the intrinsic is to be processed by the back end,
3138       --  the call to Expand_Intrinsic_Call will do nothing, which is fine,
3139       --  since the idea in this case is to pass the call unchanged. If the
3140       --  intrinsic is an inherited unchecked conversion, and the derived type
3141       --  is the target type of the conversion, we must retain it as the return
3142       --  type of the expression. Otherwise the expansion below, which uses the
3143       --  parent operation, will yield the wrong type.
3144
3145       if Is_Intrinsic_Subprogram (Subp) then
3146          Expand_Intrinsic_Call (Call_Node, Subp);
3147
3148          if Nkind (Call_Node) = N_Unchecked_Type_Conversion
3149            and then Parent_Subp /= Orig_Subp
3150            and then Etype (Parent_Subp) /= Etype (Orig_Subp)
3151          then
3152             Set_Etype (Call_Node, Etype (Orig_Subp));
3153          end if;
3154
3155          return;
3156       end if;
3157
3158       if Ekind_In (Subp, E_Function, E_Procedure) then
3159
3160          --  We perform two simple optimization on calls:
3161
3162          --  a) replace calls to null procedures unconditionally;
3163
3164          --  b) for To_Address, just do an unchecked conversion. Not only is
3165          --  this efficient, but it also avoids order of elaboration problems
3166          --  when address clauses are inlined (address expression elaborated
3167          --  at the wrong point).
3168
3169          --  We perform these optimization regardless of whether we are in the
3170          --  main unit or in a unit in the context of the main unit, to ensure
3171          --  that tree generated is the same in both cases, for Inspector use.
3172
3173          if Is_RTE (Subp, RE_To_Address) then
3174             Rewrite (Call_Node,
3175               Unchecked_Convert_To
3176                 (RTE (RE_Address), Relocate_Node (First_Actual (Call_Node))));
3177             return;
3178
3179          elsif Is_Null_Procedure (Subp)  then
3180             Rewrite (Call_Node, Make_Null_Statement (Loc));
3181             return;
3182          end if;
3183
3184          if Is_Inlined (Subp) then
3185
3186             Inlined_Subprogram : declare
3187                Bod         : Node_Id;
3188                Must_Inline : Boolean := False;
3189                Spec        : constant Node_Id := Unit_Declaration_Node (Subp);
3190                Scop        : constant Entity_Id := Scope (Subp);
3191
3192                function In_Unfrozen_Instance return Boolean;
3193                --  If the subprogram comes from an instance in the same unit,
3194                --  and the instance is not yet frozen, inlining might trigger
3195                --  order-of-elaboration problems in gigi.
3196
3197                --------------------------
3198                -- In_Unfrozen_Instance --
3199                --------------------------
3200
3201                function In_Unfrozen_Instance return Boolean is
3202                   S : Entity_Id;
3203
3204                begin
3205                   S := Scop;
3206                   while Present (S)
3207                     and then S /= Standard_Standard
3208                   loop
3209                      if Is_Generic_Instance (S)
3210                        and then Present (Freeze_Node (S))
3211                        and then not Analyzed (Freeze_Node (S))
3212                      then
3213                         return True;
3214                      end if;
3215
3216                      S := Scope (S);
3217                   end loop;
3218
3219                   return False;
3220                end In_Unfrozen_Instance;
3221
3222             --  Start of processing for Inlined_Subprogram
3223
3224             begin
3225                --  Verify that the body to inline has already been seen, and
3226                --  that if the body is in the current unit the inlining does
3227                --  not occur earlier. This avoids order-of-elaboration problems
3228                --  in the back end.
3229
3230                --  This should be documented in sinfo/einfo ???
3231
3232                if No (Spec)
3233                  or else Nkind (Spec) /= N_Subprogram_Declaration
3234                  or else No (Body_To_Inline (Spec))
3235                then
3236                   Must_Inline := False;
3237
3238                --  If this an inherited function that returns a private type,
3239                --  do not inline if the full view is an unconstrained array,
3240                --  because such calls cannot be inlined.
3241
3242                elsif Present (Orig_Subp)
3243                  and then Is_Array_Type (Etype (Orig_Subp))
3244                  and then not Is_Constrained (Etype (Orig_Subp))
3245                then
3246                   Must_Inline := False;
3247
3248                elsif In_Unfrozen_Instance then
3249                   Must_Inline := False;
3250
3251                else
3252                   Bod := Body_To_Inline (Spec);
3253
3254                   if (In_Extended_Main_Code_Unit (Call_Node)
3255                         or else In_Extended_Main_Code_Unit (Parent (Call_Node))
3256                         or else Has_Pragma_Inline_Always (Subp))
3257                     and then (not In_Same_Extended_Unit (Sloc (Bod), Loc)
3258                                or else
3259                                  Earlier_In_Extended_Unit (Sloc (Bod), Loc))
3260                   then
3261                      Must_Inline := True;
3262
3263                   --  If we are compiling a package body that is not the main
3264                   --  unit, it must be for inlining/instantiation purposes,
3265                   --  in which case we inline the call to insure that the same
3266                   --  temporaries are generated when compiling the body by
3267                   --  itself. Otherwise link errors can occur.
3268
3269                   --  If the function being called is itself in the main unit,
3270                   --  we cannot inline, because there is a risk of double
3271                   --  elaboration and/or circularity: the inlining can make
3272                   --  visible a private entity in the body of the main unit,
3273                   --  that gigi will see before its sees its proper definition.
3274
3275                   elsif not (In_Extended_Main_Code_Unit (Call_Node))
3276                     and then In_Package_Body
3277                   then
3278                      Must_Inline := not In_Extended_Main_Source_Unit (Subp);
3279                   end if;
3280                end if;
3281
3282                if Must_Inline then
3283                   Expand_Inlined_Call (Call_Node, Subp, Orig_Subp);
3284
3285                else
3286                   --  Let the back end handle it
3287
3288                   Add_Inlined_Body (Subp);
3289
3290                   if Front_End_Inlining
3291                     and then Nkind (Spec) = N_Subprogram_Declaration
3292                     and then (In_Extended_Main_Code_Unit (Call_Node))
3293                     and then No (Body_To_Inline (Spec))
3294                     and then not Has_Completion (Subp)
3295                     and then In_Same_Extended_Unit (Sloc (Spec), Loc)
3296                   then
3297                      Cannot_Inline
3298                       ("cannot inline& (body not seen yet)?", Call_Node, Subp);
3299                   end if;
3300                end if;
3301             end Inlined_Subprogram;
3302          end if;
3303       end if;
3304
3305       --  Check for protected subprogram. This is either an intra-object call,
3306       --  or a protected function call. Protected procedure calls are rewritten
3307       --  as entry calls and handled accordingly.
3308
3309       --  In Ada 2005, this may be an indirect call to an access parameter that
3310       --  is an access_to_subprogram. In that case the anonymous type has a
3311       --  scope that is a protected operation, but the call is a regular one.
3312       --  In either case do not expand call if subprogram is eliminated.
3313
3314       Scop := Scope (Subp);
3315
3316       if Nkind (Call_Node) /= N_Entry_Call_Statement
3317         and then Is_Protected_Type (Scop)
3318         and then Ekind (Subp) /= E_Subprogram_Type
3319         and then not Is_Eliminated (Subp)
3320       then
3321          --  If the call is an internal one, it is rewritten as a call to the
3322          --  corresponding unprotected subprogram.
3323
3324          Expand_Protected_Subprogram_Call (Call_Node, Subp, Scop);
3325       end if;
3326
3327       --  Functions returning controlled objects need special attention. If
3328       --  the return type is limited, then the context is initialization and
3329       --  different processing applies. If the call is to a protected function,
3330       --  the expansion above will call Expand_Call recursively. Otherwise the
3331       --  function call is transformed into a temporary which obtains the
3332       --  result from the secondary stack.
3333
3334       if Needs_Finalization (Etype (Subp)) then
3335          if not Is_Immutably_Limited_Type (Etype (Subp))
3336            and then
3337              (No (First_Formal (Subp))
3338                 or else
3339                   not Is_Concurrent_Record_Type (Etype (First_Formal (Subp))))
3340          then
3341             Expand_Ctrl_Function_Call (Call_Node);
3342
3343          --  Build-in-place function calls which appear in anonymous contexts
3344          --  need a transient scope to ensure the proper finalization of the
3345          --  intermediate result after its use.
3346
3347          elsif Is_Build_In_Place_Function_Call (Call_Node)
3348            and then Nkind_In (Parent (Call_Node), N_Attribute_Reference,
3349                                           N_Function_Call,
3350                                           N_Indexed_Component,
3351                                           N_Object_Renaming_Declaration,
3352                                           N_Procedure_Call_Statement,
3353                                           N_Selected_Component,
3354                                           N_Slice)
3355          then
3356             Establish_Transient_Scope (Call_Node, Sec_Stack => True);
3357          end if;
3358       end if;
3359
3360       --  Test for First_Optional_Parameter, and if so, truncate parameter list
3361       --  if there are optional parameters at the trailing end.
3362       --  Note: we never delete procedures for call via a pointer.
3363
3364       if (Ekind (Subp) = E_Procedure or else Ekind (Subp) = E_Function)
3365         and then Present (First_Optional_Parameter (Subp))
3366       then
3367          declare
3368             Last_Keep_Arg : Node_Id;
3369
3370          begin
3371             --  Last_Keep_Arg will hold the last actual that should be kept.
3372             --  If it remains empty at the end, it means that all parameters
3373             --  are optional.
3374
3375             Last_Keep_Arg := Empty;
3376
3377             --  Find first optional parameter, must be present since we checked
3378             --  the validity of the parameter before setting it.
3379
3380             Formal := First_Formal (Subp);
3381             Actual := First_Actual (Call_Node);
3382             while Formal /= First_Optional_Parameter (Subp) loop
3383                Last_Keep_Arg := Actual;
3384                Next_Formal (Formal);
3385                Next_Actual (Actual);
3386             end loop;
3387
3388             --  We have Formal and Actual pointing to the first potentially
3389             --  droppable argument. We can drop all the trailing arguments
3390             --  whose actual matches the default. Note that we know that all
3391             --  remaining formals have defaults, because we checked that this
3392             --  requirement was met before setting First_Optional_Parameter.
3393
3394             --  We use Fully_Conformant_Expressions to check for identity
3395             --  between formals and actuals, which may miss some cases, but
3396             --  on the other hand, this is only an optimization (if we fail
3397             --  to truncate a parameter it does not affect functionality).
3398             --  So if the default is 3 and the actual is 1+2, we consider
3399             --  them unequal, which hardly seems worrisome.
3400
3401             while Present (Formal) loop
3402                if not Fully_Conformant_Expressions
3403                     (Actual, Default_Value (Formal))
3404                then
3405                   Last_Keep_Arg := Actual;
3406                end if;
3407
3408                Next_Formal (Formal);
3409                Next_Actual (Actual);
3410             end loop;
3411
3412             --  If no arguments, delete entire list, this is the easy case
3413
3414             if No (Last_Keep_Arg) then
3415                Set_Parameter_Associations (Call_Node, No_List);
3416                Set_First_Named_Actual (Call_Node, Empty);
3417
3418             --  Case where at the last retained argument is positional. This
3419             --  is also an easy case, since the retained arguments are already
3420             --  in the right form, and we don't need to worry about the order
3421             --  of arguments that get eliminated.
3422
3423             elsif Is_List_Member (Last_Keep_Arg) then
3424                while Present (Next (Last_Keep_Arg)) loop
3425                   Discard_Node (Remove_Next (Last_Keep_Arg));
3426                end loop;
3427
3428                Set_First_Named_Actual (Call_Node, Empty);
3429
3430             --  This is the annoying case where the last retained argument
3431             --  is a named parameter. Since the original arguments are not
3432             --  in declaration order, we may have to delete some fairly
3433             --  random collection of arguments.
3434
3435             else
3436                declare
3437                   Temp   : Node_Id;
3438                   Passoc : Node_Id;
3439
3440                begin
3441                   --  First step, remove all the named parameters from the
3442                   --  list (they are still chained using First_Named_Actual
3443                   --  and Next_Named_Actual, so we have not lost them!)
3444
3445                   Temp := First (Parameter_Associations (Call_Node));
3446
3447                   --  Case of all parameters named, remove them all
3448
3449                   if Nkind (Temp) = N_Parameter_Association then
3450                      --  Suppress warnings to avoid warning on possible
3451                      --  infinite loop (because Call_Node is not modified).
3452
3453                      pragma Warnings (Off);
3454                      while Is_Non_Empty_List
3455                              (Parameter_Associations (Call_Node))
3456                      loop
3457                         Temp :=
3458                           Remove_Head (Parameter_Associations (Call_Node));
3459                      end loop;
3460                      pragma Warnings (On);
3461
3462                   --  Case of mixed positional/named, remove named parameters
3463
3464                   else
3465                      while Nkind (Next (Temp)) /= N_Parameter_Association loop
3466                         Next (Temp);
3467                      end loop;
3468
3469                      while Present (Next (Temp)) loop
3470                         Remove (Next (Temp));
3471                      end loop;
3472                   end if;
3473
3474                   --  Now we loop through the named parameters, till we get
3475                   --  to the last one to be retained, adding them to the list.
3476                   --  Note that the Next_Named_Actual list does not need to be
3477                   --  touched since we are only reordering them on the actual
3478                   --  parameter association list.
3479
3480                   Passoc := Parent (First_Named_Actual (Call_Node));
3481                   loop
3482                      Temp := Relocate_Node (Passoc);
3483                      Append_To
3484                        (Parameter_Associations (Call_Node), Temp);
3485                      exit when
3486                        Last_Keep_Arg = Explicit_Actual_Parameter (Passoc);
3487                      Passoc := Parent (Next_Named_Actual (Passoc));
3488                   end loop;
3489
3490                   Set_Next_Named_Actual (Temp, Empty);
3491
3492                   loop
3493                      Temp := Next_Named_Actual (Passoc);
3494                      exit when No (Temp);
3495                      Set_Next_Named_Actual
3496                        (Passoc, Next_Named_Actual (Parent (Temp)));
3497                   end loop;
3498                end;
3499
3500             end if;
3501          end;
3502       end if;
3503    end Expand_Call;
3504
3505    -------------------------------
3506    -- Expand_Ctrl_Function_Call --
3507    -------------------------------
3508
3509    procedure Expand_Ctrl_Function_Call (N : Node_Id) is
3510    begin
3511       --  Optimization, if the returned value (which is on the sec-stack) is
3512       --  returned again, no need to copy/readjust/finalize, we can just pass
3513       --  the value thru (see Expand_N_Simple_Return_Statement), and thus no
3514       --  attachment is needed
3515
3516       if Nkind (Parent (N)) = N_Simple_Return_Statement then
3517          return;
3518       end if;
3519
3520       --  Resolution is now finished, make sure we don't start analysis again
3521       --  because of the duplication.
3522
3523       Set_Analyzed (N);
3524
3525       --  A function which returns a controlled object uses the secondary
3526       --  stack. Rewrite the call into a temporary which obtains the result of
3527       --  the function using 'reference.
3528
3529       Remove_Side_Effects (N);
3530    end Expand_Ctrl_Function_Call;
3531
3532    --------------------------
3533    -- Expand_Inlined_Call --
3534    --------------------------
3535
3536    procedure Expand_Inlined_Call
3537     (N         : Node_Id;
3538      Subp      : Entity_Id;
3539      Orig_Subp : Entity_Id)
3540    is
3541       Loc       : constant Source_Ptr := Sloc (N);
3542       Is_Predef : constant Boolean :=
3543                    Is_Predefined_File_Name
3544                      (Unit_File_Name (Get_Source_Unit (Subp)));
3545       Orig_Bod  : constant Node_Id :=
3546                     Body_To_Inline (Unit_Declaration_Node (Subp));
3547
3548       Blk      : Node_Id;
3549       Bod      : Node_Id;
3550       Decl     : Node_Id;
3551       Decls    : constant List_Id := New_List;
3552       Exit_Lab : Entity_Id := Empty;
3553       F        : Entity_Id;
3554       A        : Node_Id;
3555       Lab_Decl : Node_Id;
3556       Lab_Id   : Node_Id;
3557       New_A    : Node_Id;
3558       Num_Ret  : Int := 0;
3559       Ret_Type : Entity_Id;
3560       Targ     : Node_Id;
3561       Targ1    : Node_Id;
3562       Temp     : Entity_Id;
3563       Temp_Typ : Entity_Id;
3564
3565       Return_Object : Entity_Id := Empty;
3566       --  Entity in declaration in an extended_return_statement
3567
3568       Is_Unc : constant Boolean :=
3569                     Is_Array_Type (Etype (Subp))
3570                       and then not Is_Constrained (Etype (Subp));
3571       --  If the type returned by the function is unconstrained and the call
3572       --  can be inlined, special processing is required.
3573
3574       procedure Make_Exit_Label;
3575       --  Build declaration for exit label to be used in Return statements,
3576       --  sets Exit_Lab (the label node) and Lab_Decl (corresponding implicit
3577       --  declaration). Does nothing if Exit_Lab already set.
3578
3579       function Process_Formals (N : Node_Id) return Traverse_Result;
3580       --  Replace occurrence of a formal with the corresponding actual, or the
3581       --  thunk generated for it.
3582
3583       function Process_Sloc (Nod : Node_Id) return Traverse_Result;
3584       --  If the call being expanded is that of an internal subprogram, set the
3585       --  sloc of the generated block to that of the call itself, so that the
3586       --  expansion is skipped by the "next" command in gdb.
3587       --  Same processing for a subprogram in a predefined file, e.g.
3588       --  Ada.Tags. If Debug_Generated_Code is true, suppress this change to
3589       --  simplify our own development.
3590
3591       procedure Rewrite_Function_Call (N : Node_Id; Blk : Node_Id);
3592       --  If the function body is a single expression, replace call with
3593       --  expression, else insert block appropriately.
3594
3595       procedure Rewrite_Procedure_Call (N : Node_Id; Blk : Node_Id);
3596       --  If procedure body has no local variables, inline body without
3597       --  creating block, otherwise rewrite call with block.
3598
3599       function Formal_Is_Used_Once (Formal : Entity_Id) return Boolean;
3600       --  Determine whether a formal parameter is used only once in Orig_Bod
3601
3602       ---------------------
3603       -- Make_Exit_Label --
3604       ---------------------
3605
3606       procedure Make_Exit_Label is
3607          Lab_Ent : Entity_Id;
3608       begin
3609          if No (Exit_Lab) then
3610             Lab_Ent := Make_Temporary (Loc, 'L');
3611             Lab_Id  := New_Reference_To (Lab_Ent, Loc);
3612             Exit_Lab := Make_Label (Loc, Lab_Id);
3613             Lab_Decl :=
3614               Make_Implicit_Label_Declaration (Loc,
3615                 Defining_Identifier  => Lab_Ent,
3616                 Label_Construct      => Exit_Lab);
3617          end if;
3618       end Make_Exit_Label;
3619
3620       ---------------------
3621       -- Process_Formals --
3622       ---------------------
3623
3624       function Process_Formals (N : Node_Id) return Traverse_Result is
3625          A   : Entity_Id;
3626          E   : Entity_Id;
3627          Ret : Node_Id;
3628
3629       begin
3630          if Is_Entity_Name (N)
3631            and then Present (Entity (N))
3632          then
3633             E := Entity (N);
3634
3635             if Is_Formal (E)
3636               and then Scope (E) = Subp
3637             then
3638                A := Renamed_Object (E);
3639
3640                --  Rewrite the occurrence of the formal into an occurrence of
3641                --  the actual. Also establish visibility on the proper view of
3642                --  the actual's subtype for the body's context (if the actual's
3643                --  subtype is private at the call point but its full view is
3644                --  visible to the body, then the inlined tree here must be
3645                --  analyzed with the full view).
3646
3647                if Is_Entity_Name (A) then
3648                   Rewrite (N, New_Occurrence_Of (Entity (A), Loc));
3649                   Check_Private_View (N);
3650
3651                elsif Nkind (A) = N_Defining_Identifier then
3652                   Rewrite (N, New_Occurrence_Of (A, Loc));
3653                   Check_Private_View (N);
3654
3655                --  Numeric literal
3656
3657                else
3658                   Rewrite (N, New_Copy (A));
3659                end if;
3660             end if;
3661             return Skip;
3662
3663          elsif Is_Entity_Name (N)
3664            and then Present (Return_Object)
3665            and then Chars (N) = Chars (Return_Object)
3666          then
3667             --  Occurrence within an extended return statement. The return
3668             --  object is local to the body been inlined, and thus the generic
3669             --  copy is not analyzed yet, so we match by name, and replace it
3670             --  with target of call.
3671
3672             if Nkind (Targ) = N_Defining_Identifier then
3673                Rewrite (N, New_Occurrence_Of (Targ, Loc));
3674             else
3675                Rewrite (N, New_Copy_Tree (Targ));
3676             end if;
3677
3678             return Skip;
3679
3680          elsif Nkind (N) = N_Simple_Return_Statement then
3681             if No (Expression (N)) then
3682                Make_Exit_Label;
3683                Rewrite (N,
3684                  Make_Goto_Statement (Loc, Name => New_Copy (Lab_Id)));
3685
3686             else
3687                if Nkind (Parent (N)) = N_Handled_Sequence_Of_Statements
3688                  and then Nkind (Parent (Parent (N))) = N_Subprogram_Body
3689                then
3690                   --  Function body is a single expression. No need for
3691                   --  exit label.
3692
3693                   null;
3694
3695                else
3696                   Num_Ret := Num_Ret + 1;
3697                   Make_Exit_Label;
3698                end if;
3699
3700                --  Because of the presence of private types, the views of the
3701                --  expression and the context may be different, so place an
3702                --  unchecked conversion to the context type to avoid spurious
3703                --  errors, e.g. when the expression is a numeric literal and
3704                --  the context is private. If the expression is an aggregate,
3705                --  use a qualified expression, because an aggregate is not a
3706                --  legal argument of a conversion.
3707
3708                if Nkind_In (Expression (N), N_Aggregate, N_Null) then
3709                   Ret :=
3710                     Make_Qualified_Expression (Sloc (N),
3711                        Subtype_Mark => New_Occurrence_Of (Ret_Type, Sloc (N)),
3712                        Expression => Relocate_Node (Expression (N)));
3713                else
3714                   Ret :=
3715                     Unchecked_Convert_To
3716                       (Ret_Type, Relocate_Node (Expression (N)));
3717                end if;
3718
3719                if Nkind (Targ) = N_Defining_Identifier then
3720                   Rewrite (N,
3721                     Make_Assignment_Statement (Loc,
3722                       Name => New_Occurrence_Of (Targ, Loc),
3723                       Expression => Ret));
3724                else
3725                   Rewrite (N,
3726                     Make_Assignment_Statement (Loc,
3727                       Name => New_Copy (Targ),
3728                       Expression => Ret));
3729                end if;
3730
3731                Set_Assignment_OK (Name (N));
3732
3733                if Present (Exit_Lab) then
3734                   Insert_After (N,
3735                     Make_Goto_Statement (Loc,
3736                       Name => New_Copy (Lab_Id)));
3737                end if;
3738             end if;
3739
3740             return OK;
3741
3742          elsif Nkind (N) = N_Extended_Return_Statement then
3743
3744             --  An extended return becomes a block whose first statement is
3745             --  the assignment of the initial expression of the return object
3746             --  to the target of the call itself.
3747
3748             declare
3749                Return_Decl : constant Entity_Id :=
3750                                First (Return_Object_Declarations (N));
3751                Assign      : Node_Id;
3752
3753             begin
3754                Return_Object := Defining_Identifier (Return_Decl);
3755
3756                if Present (Expression (Return_Decl)) then
3757                   if Nkind (Targ) = N_Defining_Identifier then
3758                      Assign :=
3759                        Make_Assignment_Statement (Loc,
3760                          Name => New_Occurrence_Of (Targ, Loc),
3761                          Expression => Expression (Return_Decl));
3762                   else
3763                      Assign :=
3764                        Make_Assignment_Statement (Loc,
3765                          Name => New_Copy (Targ),
3766                          Expression => Expression (Return_Decl));
3767                   end if;
3768
3769                   Set_Assignment_OK (Name (Assign));
3770                   Prepend (Assign,
3771                     Statements (Handled_Statement_Sequence (N)));
3772                end if;
3773
3774                Rewrite (N,
3775                  Make_Block_Statement (Loc,
3776                     Handled_Statement_Sequence =>
3777                       Handled_Statement_Sequence (N)));
3778
3779                return OK;
3780             end;
3781
3782          --  Remove pragma Unreferenced since it may refer to formals that
3783          --  are not visible in the inlined body, and in any case we will
3784          --  not be posting warnings on the inlined body so it is unneeded.
3785
3786          elsif Nkind (N) = N_Pragma
3787            and then Pragma_Name (N) = Name_Unreferenced
3788          then
3789             Rewrite (N, Make_Null_Statement (Sloc (N)));
3790             return OK;
3791
3792          else
3793             return OK;
3794          end if;
3795       end Process_Formals;
3796
3797       procedure Replace_Formals is new Traverse_Proc (Process_Formals);
3798
3799       ------------------
3800       -- Process_Sloc --
3801       ------------------
3802
3803       function Process_Sloc (Nod : Node_Id) return Traverse_Result is
3804       begin
3805          if not Debug_Generated_Code then
3806             Set_Sloc (Nod, Sloc (N));
3807             Set_Comes_From_Source (Nod, False);
3808          end if;
3809
3810          return OK;
3811       end Process_Sloc;
3812
3813       procedure Reset_Slocs is new Traverse_Proc (Process_Sloc);
3814
3815       ---------------------------
3816       -- Rewrite_Function_Call --
3817       ---------------------------
3818
3819       procedure Rewrite_Function_Call (N : Node_Id; Blk : Node_Id) is
3820          HSS : constant Node_Id := Handled_Statement_Sequence (Blk);
3821          Fst : constant Node_Id := First (Statements (HSS));
3822
3823       begin
3824          --  Optimize simple case: function body is a single return statement,
3825          --  which has been expanded into an assignment.
3826
3827          if Is_Empty_List (Declarations (Blk))
3828            and then Nkind (Fst) = N_Assignment_Statement
3829            and then No (Next (Fst))
3830          then
3831
3832             --  The function call may have been rewritten as the temporary
3833             --  that holds the result of the call, in which case remove the
3834             --  now useless declaration.
3835
3836             if Nkind (N) = N_Identifier
3837               and then Nkind (Parent (Entity (N))) = N_Object_Declaration
3838             then
3839                Rewrite (Parent (Entity (N)), Make_Null_Statement (Loc));
3840             end if;
3841
3842             Rewrite (N, Expression (Fst));
3843
3844          elsif Nkind (N) = N_Identifier
3845            and then Nkind (Parent (Entity (N))) = N_Object_Declaration
3846          then
3847             --  The block assigns the result of the call to the temporary
3848
3849             Insert_After (Parent (Entity (N)), Blk);
3850
3851          elsif Nkind (Parent (N)) = N_Assignment_Statement
3852            and then
3853             (Is_Entity_Name (Name (Parent (N)))
3854                or else
3855                   (Nkind (Name (Parent (N))) = N_Explicit_Dereference
3856                     and then Is_Entity_Name (Prefix (Name (Parent (N))))))
3857          then
3858             --  Replace assignment with the block
3859
3860             declare
3861                Original_Assignment : constant Node_Id := Parent (N);
3862
3863             begin
3864                --  Preserve the original assignment node to keep the complete
3865                --  assignment subtree consistent enough for Analyze_Assignment
3866                --  to proceed (specifically, the original Lhs node must still
3867                --  have an assignment statement as its parent).
3868
3869                --  We cannot rely on Original_Node to go back from the block
3870                --  node to the assignment node, because the assignment might
3871                --  already be a rewrite substitution.
3872
3873                Discard_Node (Relocate_Node (Original_Assignment));
3874                Rewrite (Original_Assignment, Blk);
3875             end;
3876
3877          elsif Nkind (Parent (N)) = N_Object_Declaration then
3878             Set_Expression (Parent (N), Empty);
3879             Insert_After (Parent (N), Blk);
3880
3881          elsif Is_Unc then
3882             Insert_Before (Parent (N), Blk);
3883          end if;
3884       end Rewrite_Function_Call;
3885
3886       ----------------------------
3887       -- Rewrite_Procedure_Call --
3888       ----------------------------
3889
3890       procedure Rewrite_Procedure_Call (N : Node_Id; Blk : Node_Id) is
3891          HSS  : constant Node_Id := Handled_Statement_Sequence (Blk);
3892       begin
3893          --  If there is a transient scope for N, this will be the scope of the
3894          --  actions for N, and the statements in Blk need to be within this
3895          --  scope. For example, they need to have visibility on the constant
3896          --  declarations created for the formals.
3897
3898          --  If N needs no transient scope, and if there are no declarations in
3899          --  the inlined body, we can do a little optimization and insert the
3900          --  statements for the body directly after N, and rewrite N to a
3901          --  null statement, instead of rewriting N into a full-blown block
3902          --  statement.
3903
3904          if not Scope_Is_Transient
3905            and then Is_Empty_List (Declarations (Blk))
3906          then
3907             Insert_List_After (N, Statements (HSS));
3908             Rewrite (N, Make_Null_Statement (Loc));
3909          else
3910             Rewrite (N, Blk);
3911          end if;
3912       end Rewrite_Procedure_Call;
3913
3914       -------------------------
3915       -- Formal_Is_Used_Once --
3916       -------------------------
3917
3918       function Formal_Is_Used_Once (Formal : Entity_Id) return Boolean is
3919          Use_Counter : Int := 0;
3920
3921          function Count_Uses (N : Node_Id) return Traverse_Result;
3922          --  Traverse the tree and count the uses of the formal parameter.
3923          --  In this case, for optimization purposes, we do not need to
3924          --  continue the traversal once more than one use is encountered.
3925
3926          ----------------
3927          -- Count_Uses --
3928          ----------------
3929
3930          function Count_Uses (N : Node_Id) return Traverse_Result is
3931          begin
3932             --  The original node is an identifier
3933
3934             if Nkind (N) = N_Identifier
3935               and then Present (Entity (N))
3936
3937                --  Original node's entity points to the one in the copied body
3938
3939               and then Nkind (Entity (N)) = N_Identifier
3940               and then Present (Entity (Entity (N)))
3941
3942                --  The entity of the copied node is the formal parameter
3943
3944               and then Entity (Entity (N)) = Formal
3945             then
3946                Use_Counter := Use_Counter + 1;
3947
3948                if Use_Counter > 1 then
3949
3950                   --  Denote more than one use and abandon the traversal
3951
3952                   Use_Counter := 2;
3953                   return Abandon;
3954
3955                end if;
3956             end if;
3957
3958             return OK;
3959          end Count_Uses;
3960
3961          procedure Count_Formal_Uses is new Traverse_Proc (Count_Uses);
3962
3963       --  Start of processing for Formal_Is_Used_Once
3964
3965       begin
3966          Count_Formal_Uses (Orig_Bod);
3967          return Use_Counter = 1;
3968       end Formal_Is_Used_Once;
3969
3970    --  Start of processing for Expand_Inlined_Call
3971
3972    begin
3973
3974       --  Check for an illegal attempt to inline a recursive procedure. If the
3975       --  subprogram has parameters this is detected when trying to supply a
3976       --  binding for parameters that already have one. For parameterless
3977       --  subprograms this must be done explicitly.
3978
3979       if In_Open_Scopes (Subp) then
3980          Error_Msg_N ("call to recursive subprogram cannot be inlined?", N);
3981          Set_Is_Inlined (Subp, False);
3982          return;
3983       end if;
3984
3985       if Nkind (Orig_Bod) = N_Defining_Identifier
3986         or else Nkind (Orig_Bod) = N_Defining_Operator_Symbol
3987       then
3988          --  Subprogram is renaming_as_body. Calls occurring after the renaming
3989          --  can be replaced with calls to the renamed entity directly, because
3990          --  the subprograms are subtype conformant. If the renamed subprogram
3991          --  is an inherited operation, we must redo the expansion because
3992          --  implicit conversions may be needed. Similarly, if the renamed
3993          --  entity is inlined, expand the call for further optimizations.
3994
3995          Set_Name (N, New_Occurrence_Of (Orig_Bod, Loc));
3996
3997          if Present (Alias (Orig_Bod)) or else Is_Inlined (Orig_Bod) then
3998             Expand_Call (N);
3999          end if;
4000
4001          return;
4002       end if;
4003
4004       --  Use generic machinery to copy body of inlined subprogram, as if it
4005       --  were an instantiation, resetting source locations appropriately, so
4006       --  that nested inlined calls appear in the main unit.
4007
4008       Save_Env (Subp, Empty);
4009       Set_Copied_Sloc_For_Inlined_Body (N, Defining_Entity (Orig_Bod));
4010
4011       Bod := Copy_Generic_Node (Orig_Bod, Empty, Instantiating => True);
4012       Blk :=
4013         Make_Block_Statement (Loc,
4014           Declarations => Declarations (Bod),
4015           Handled_Statement_Sequence => Handled_Statement_Sequence (Bod));
4016
4017       if No (Declarations (Bod)) then
4018          Set_Declarations (Blk, New_List);
4019       end if;
4020
4021       --  For the unconstrained case, capture the name of the local
4022       --  variable that holds the result. This must be the first declaration
4023       --  in the block, because its bounds cannot depend on local variables.
4024       --  Otherwise there is no way to declare the result outside of the
4025       --  block. Needless to say, in general the bounds will depend on the
4026       --  actuals in the call.
4027
4028       if Is_Unc then
4029          Targ1 := Defining_Identifier (First (Declarations (Blk)));
4030       end if;
4031
4032       --  If this is a derived function, establish the proper return type
4033
4034       if Present (Orig_Subp)
4035         and then Orig_Subp /= Subp
4036       then
4037          Ret_Type := Etype (Orig_Subp);
4038       else
4039          Ret_Type := Etype (Subp);
4040       end if;
4041
4042       --  Create temporaries for the actuals that are expressions, or that
4043       --  are scalars and require copying to preserve semantics.
4044
4045       F := First_Formal (Subp);
4046       A := First_Actual (N);
4047       while Present (F) loop
4048          if Present (Renamed_Object (F)) then
4049             Error_Msg_N ("cannot inline call to recursive subprogram", N);
4050             return;
4051          end if;
4052
4053          --  If the argument may be a controlling argument in a call within
4054          --  the inlined body, we must preserve its classwide nature to insure
4055          --  that dynamic dispatching take place subsequently. If the formal
4056          --  has a constraint it must be preserved to retain the semantics of
4057          --  the body.
4058
4059          if Is_Class_Wide_Type (Etype (F))
4060            or else (Is_Access_Type (Etype (F))
4061                       and then
4062                     Is_Class_Wide_Type (Designated_Type (Etype (F))))
4063          then
4064             Temp_Typ := Etype (F);
4065
4066          elsif Base_Type (Etype (F)) = Base_Type (Etype (A))
4067            and then Etype (F) /= Base_Type (Etype (F))
4068          then
4069             Temp_Typ := Etype (F);
4070
4071          else
4072             Temp_Typ := Etype (A);
4073          end if;
4074
4075          --  If the actual is a simple name or a literal, no need to
4076          --  create a temporary, object can be used directly.
4077
4078          --  If the actual is a literal and the formal has its address taken,
4079          --  we cannot pass the literal itself as an argument, so its value
4080          --  must be captured in a temporary.
4081
4082          if (Is_Entity_Name (A)
4083               and then
4084                (not Is_Scalar_Type (Etype (A))
4085                  or else Ekind (Entity (A)) = E_Enumeration_Literal))
4086
4087          --  When the actual is an identifier and the corresponding formal
4088          --  is used only once in the original body, the formal can be
4089          --  substituted directly with the actual parameter.
4090
4091            or else (Nkind (A) = N_Identifier
4092              and then Formal_Is_Used_Once (F))
4093
4094            or else
4095              (Nkind_In (A, N_Real_Literal,
4096                             N_Integer_Literal,
4097                             N_Character_Literal)
4098                 and then not Address_Taken (F))
4099          then
4100             if Etype (F) /= Etype (A) then
4101                Set_Renamed_Object
4102                 (F, Unchecked_Convert_To (Etype (F), Relocate_Node (A)));
4103             else
4104                Set_Renamed_Object (F, A);
4105             end if;
4106
4107          else
4108             Temp := Make_Temporary (Loc, 'C');
4109
4110             --  If the actual for an in/in-out parameter is a view conversion,
4111             --  make it into an unchecked conversion, given that an untagged
4112             --  type conversion is not a proper object for a renaming.
4113
4114             --  In-out conversions that involve real conversions have already
4115             --  been transformed in Expand_Actuals.
4116
4117             if Nkind (A) = N_Type_Conversion
4118               and then Ekind (F) /= E_In_Parameter
4119             then
4120                New_A :=
4121                  Make_Unchecked_Type_Conversion (Loc,
4122                    Subtype_Mark => New_Occurrence_Of (Etype (F), Loc),
4123                    Expression   => Relocate_Node (Expression (A)));
4124
4125             elsif Etype (F) /= Etype (A) then
4126                New_A := Unchecked_Convert_To (Etype (F), Relocate_Node (A));
4127                Temp_Typ := Etype (F);
4128
4129             else
4130                New_A := Relocate_Node (A);
4131             end if;
4132
4133             Set_Sloc (New_A, Sloc (N));
4134
4135             --  If the actual has a by-reference type, it cannot be copied, so
4136             --  its value is captured in a renaming declaration. Otherwise
4137             --  declare a local constant initialized with the actual.
4138
4139             --  We also use a renaming declaration for expressions of an array
4140             --  type that is not bit-packed, both for efficiency reasons and to
4141             --  respect the semantics of the call: in most cases the original
4142             --  call will pass the parameter by reference, and thus the inlined
4143             --  code will have the same semantics.
4144
4145             if Ekind (F) = E_In_Parameter
4146               and then not Is_Limited_Type (Etype (A))
4147               and then not Is_Tagged_Type  (Etype (A))
4148               and then
4149                (not Is_Array_Type (Etype (A))
4150                  or else not Is_Object_Reference (A)
4151                  or else Is_Bit_Packed_Array (Etype (A)))
4152             then
4153                Decl :=
4154                  Make_Object_Declaration (Loc,
4155                    Defining_Identifier => Temp,
4156                    Constant_Present => True,
4157                    Object_Definition => New_Occurrence_Of (Temp_Typ, Loc),
4158                    Expression => New_A);
4159             else
4160                Decl :=
4161                  Make_Object_Renaming_Declaration (Loc,
4162                    Defining_Identifier => Temp,
4163                    Subtype_Mark        => New_Occurrence_Of (Temp_Typ, Loc),
4164                    Name                => New_A);
4165             end if;
4166
4167             Append (Decl, Decls);
4168             Set_Renamed_Object (F, Temp);
4169          end if;
4170
4171          Next_Formal (F);
4172          Next_Actual (A);
4173       end loop;
4174
4175       --  Establish target of function call. If context is not assignment or
4176       --  declaration, create a temporary as a target. The declaration for
4177       --  the temporary may be subsequently optimized away if the body is a
4178       --  single expression, or if the left-hand side of the assignment is
4179       --  simple enough, i.e. an entity or an explicit dereference of one.
4180
4181       if Ekind (Subp) = E_Function then
4182          if Nkind (Parent (N)) = N_Assignment_Statement
4183            and then Is_Entity_Name (Name (Parent (N)))
4184          then
4185             Targ := Name (Parent (N));
4186
4187          elsif Nkind (Parent (N)) = N_Assignment_Statement
4188            and then Nkind (Name (Parent (N))) = N_Explicit_Dereference
4189            and then Is_Entity_Name (Prefix (Name (Parent (N))))
4190          then
4191             Targ := Name (Parent (N));
4192
4193          elsif Nkind (Parent (N)) = N_Object_Declaration
4194            and then Is_Limited_Type (Etype (Subp))
4195          then
4196             Targ := Defining_Identifier (Parent (N));
4197
4198          else
4199             --  Replace call with temporary and create its declaration
4200
4201             Temp := Make_Temporary (Loc, 'C');
4202             Set_Is_Internal (Temp);
4203
4204             --  For the unconstrained case, the generated temporary has the
4205             --  same constrained declaration as the result variable. It may
4206             --  eventually be possible to remove that temporary and use the
4207             --  result variable directly.
4208
4209             if Is_Unc then
4210                Decl :=
4211                  Make_Object_Declaration (Loc,
4212                    Defining_Identifier => Temp,
4213                    Object_Definition =>
4214                      New_Copy_Tree (Object_Definition (Parent (Targ1))));
4215
4216                Replace_Formals (Decl);
4217
4218             else
4219                Decl :=
4220                  Make_Object_Declaration (Loc,
4221                    Defining_Identifier => Temp,
4222                    Object_Definition =>
4223                      New_Occurrence_Of (Ret_Type, Loc));
4224
4225                Set_Etype (Temp, Ret_Type);
4226             end if;
4227
4228             Set_No_Initialization (Decl);
4229             Append (Decl, Decls);
4230             Rewrite (N, New_Occurrence_Of (Temp, Loc));
4231             Targ := Temp;
4232          end if;
4233       end if;
4234
4235       Insert_Actions (N, Decls);
4236
4237       --  Traverse the tree and replace formals with actuals or their thunks.
4238       --  Attach block to tree before analysis and rewriting.
4239
4240       Replace_Formals (Blk);
4241       Set_Parent (Blk, N);
4242
4243       if not Comes_From_Source (Subp)
4244         or else Is_Predef
4245       then
4246          Reset_Slocs (Blk);
4247       end if;
4248
4249       if Present (Exit_Lab) then
4250
4251          --  If the body was a single expression, the single return statement
4252          --  and the corresponding label are useless.
4253
4254          if Num_Ret = 1
4255            and then
4256              Nkind (Last (Statements (Handled_Statement_Sequence (Blk)))) =
4257                N_Goto_Statement
4258          then
4259             Remove (Last (Statements (Handled_Statement_Sequence (Blk))));
4260          else
4261             Append (Lab_Decl, (Declarations (Blk)));
4262             Append (Exit_Lab, Statements (Handled_Statement_Sequence (Blk)));
4263          end if;
4264       end if;
4265
4266       --  Analyze Blk with In_Inlined_Body set, to avoid spurious errors on
4267       --  conflicting private views that Gigi would ignore. If this is a
4268       --  predefined unit, analyze with checks off, as is done in the non-
4269       --  inlined run-time units.
4270
4271       declare
4272          I_Flag : constant Boolean := In_Inlined_Body;
4273
4274       begin
4275          In_Inlined_Body := True;
4276
4277          if Is_Predef then
4278             declare
4279                Style : constant Boolean := Style_Check;
4280             begin
4281                Style_Check := False;
4282                Analyze (Blk, Suppress => All_Checks);
4283                Style_Check := Style;
4284             end;
4285
4286          else
4287             Analyze (Blk);
4288          end if;
4289
4290          In_Inlined_Body := I_Flag;
4291       end;
4292
4293       if Ekind (Subp) = E_Procedure then
4294          Rewrite_Procedure_Call (N, Blk);
4295       else
4296          Rewrite_Function_Call (N, Blk);
4297
4298          --  For the unconstrained case, the replacement of the call has been
4299          --  made prior to the complete analysis of the generated declarations.
4300          --  Propagate the proper type now.
4301
4302          if Is_Unc then
4303             if Nkind (N) = N_Identifier then
4304                Set_Etype (N, Etype (Entity (N)));
4305             else
4306                Set_Etype (N, Etype (Targ1));
4307             end if;
4308          end if;
4309       end if;
4310
4311       Restore_Env;
4312
4313       --  Cleanup mapping between formals and actuals for other expansions
4314
4315       F := First_Formal (Subp);
4316       while Present (F) loop
4317          Set_Renamed_Object (F, Empty);
4318          Next_Formal (F);
4319       end loop;
4320    end Expand_Inlined_Call;
4321
4322    ----------------------------------------
4323    -- Expand_N_Extended_Return_Statement --
4324    ----------------------------------------
4325
4326    --  If there is a Handled_Statement_Sequence, we rewrite this:
4327
4328    --     return Result : T := <expression> do
4329    --        <handled_seq_of_stms>
4330    --     end return;
4331
4332    --  to be:
4333
4334    --     declare
4335    --        Result : T := <expression>;
4336    --     begin
4337    --        <handled_seq_of_stms>
4338    --        return Result;
4339    --     end;
4340
4341    --  Otherwise (no Handled_Statement_Sequence), we rewrite this:
4342
4343    --     return Result : T := <expression>;
4344
4345    --  to be:
4346
4347    --     return <expression>;
4348
4349    --  unless it's build-in-place or there's no <expression>, in which case
4350    --  we generate:
4351
4352    --     declare
4353    --        Result : T := <expression>;
4354    --     begin
4355    --        return Result;
4356    --     end;
4357
4358    --  Note that this case could have been written by the user as an extended
4359    --  return statement, or could have been transformed to this from a simple
4360    --  return statement.
4361
4362    --  That is, we need to have a reified return object if there are statements
4363    --  (which might refer to it) or if we're doing build-in-place (so we can
4364    --  set its address to the final resting place or if there is no expression
4365    --  (in which case default initial values might need to be set).
4366
4367    procedure Expand_N_Extended_Return_Statement (N : Node_Id) is
4368       Loc : constant Source_Ptr := Sloc (N);
4369
4370       Par_Func     : constant Entity_Id :=
4371                        Return_Applies_To (Return_Statement_Entity (N));
4372       Ret_Obj_Id   : constant Entity_Id :=
4373                        First_Entity (Return_Statement_Entity (N));
4374       Ret_Obj_Decl : constant Node_Id := Parent (Ret_Obj_Id);
4375
4376       Is_Build_In_Place : constant Boolean :=
4377                             Is_Build_In_Place_Function (Par_Func);
4378
4379       Exp         : Node_Id;
4380       HSS         : Node_Id;
4381       Result      : Node_Id;
4382       Return_Stmt : Node_Id;
4383       Stmts       : List_Id;
4384
4385       function Build_Heap_Allocator
4386         (Temp_Id    : Entity_Id;
4387          Temp_Typ   : Entity_Id;
4388          Func_Id    : Entity_Id;
4389          Ret_Typ    : Entity_Id;
4390          Alloc_Expr : Node_Id) return Node_Id;
4391       --  Create the statements necessary to allocate a return object on the
4392       --  caller's master. The master is available through implicit parameter
4393       --  BIPfinalizationmaster.
4394       --
4395       --    if BIPfinalizationmaster /= null then
4396       --       declare
4397       --          type Ptr_Typ is access Ret_Typ;
4398       --          for Ptr_Typ'Storage_Pool use
4399       --                Base_Pool (BIPfinalizationmaster.all).all;
4400       --          Local : Ptr_Typ;
4401       --
4402       --       begin
4403       --          procedure Allocate (...) is
4404       --          begin
4405       --             System.Storage_Pools.Subpools.Allocate_Any (...);
4406       --          end Allocate;
4407       --
4408       --          Local := <Alloc_Expr>;
4409       --          Temp_Id := Temp_Typ (Local);
4410       --       end;
4411       --    end if;
4412       --
4413       --  Temp_Id is the temporary which is used to reference the internally
4414       --  created object in all allocation forms. Temp_Typ is the type of the
4415       --  temporary. Func_Id is the enclosing function. Ret_Typ is the return
4416       --  type of Func_Id. Alloc_Expr is the actual allocator.
4417
4418       function Move_Activation_Chain return Node_Id;
4419       --  Construct a call to System.Tasking.Stages.Move_Activation_Chain
4420       --  with parameters:
4421       --    From         current activation chain
4422       --    To           activation chain passed in by the caller
4423       --    New_Master   master passed in by the caller
4424
4425       --------------------------
4426       -- Build_Heap_Allocator --
4427       --------------------------
4428
4429       function Build_Heap_Allocator
4430         (Temp_Id    : Entity_Id;
4431          Temp_Typ   : Entity_Id;
4432          Func_Id    : Entity_Id;
4433          Ret_Typ    : Entity_Id;
4434          Alloc_Expr : Node_Id) return Node_Id
4435       is
4436       begin
4437          --  Processing for build-in-place object allocation. This is disabled
4438          --  on .NET/JVM because the targets do not support pools.
4439
4440          if VM_Target = No_VM
4441            and then Is_Build_In_Place_Function (Func_Id)
4442            and then Needs_Finalization (Ret_Typ)
4443          then
4444             declare
4445                Decls      : constant List_Id := New_List;
4446                Fin_Mas_Id : constant Entity_Id :=
4447                               Build_In_Place_Formal
4448                                 (Func_Id, BIP_Finalization_Master);
4449                Stmts      : constant List_Id := New_List;
4450
4451                Local_Id : Entity_Id;
4452                Pool_Id  : Entity_Id;
4453                Ptr_Typ  : Entity_Id;
4454
4455             begin
4456                --  Generate:
4457                --    Pool_Id renames Base_Pool (BIPfinalizationmaster.all).all;
4458
4459                Pool_Id := Make_Temporary (Loc, 'P');
4460
4461                Append_To (Decls,
4462                  Make_Object_Renaming_Declaration (Loc,
4463                    Defining_Identifier => Pool_Id,
4464                    Subtype_Mark        =>
4465                      New_Reference_To (RTE (RE_Root_Storage_Pool), Loc),
4466                    Name                =>
4467                      Make_Explicit_Dereference (Loc,
4468                        Prefix =>
4469                          Make_Function_Call (Loc,
4470                            Name                   =>
4471                              New_Reference_To (RTE (RE_Base_Pool), Loc),
4472                            Parameter_Associations => New_List (
4473                              Make_Explicit_Dereference (Loc,
4474                                Prefix =>
4475                                  New_Reference_To (Fin_Mas_Id, Loc)))))));
4476
4477                --  Create an access type which uses the storage pool of the
4478                --  caller's master. This additional type is necessary because
4479                --  the finalization master cannot be associated with the type
4480                --  of the temporary. Otherwise the secondary stack allocation
4481                --  will fail.
4482
4483                --  Generate:
4484                --    type Ptr_Typ is access Ret_Typ;
4485
4486                Ptr_Typ := Make_Temporary (Loc, 'P');
4487
4488                Append_To (Decls,
4489                  Make_Full_Type_Declaration (Loc,
4490                    Defining_Identifier => Ptr_Typ,
4491                    Type_Definition     =>
4492                      Make_Access_To_Object_Definition (Loc,
4493                        Subtype_Indication =>
4494                          New_Reference_To (Ret_Typ, Loc))));
4495
4496                --  Perform minor decoration in order to set the master and the
4497                --  storage pool attributes.
4498
4499                Set_Ekind (Ptr_Typ, E_Access_Type);
4500                Set_Finalization_Master     (Ptr_Typ, Fin_Mas_Id);
4501                Set_Associated_Storage_Pool (Ptr_Typ, Pool_Id);
4502
4503                --  Create the temporary, generate:
4504                --
4505                --    Local_Id : Ptr_Typ;
4506
4507                Local_Id := Make_Temporary (Loc, 'T');
4508
4509                Append_To (Decls,
4510                  Make_Object_Declaration (Loc,
4511                    Defining_Identifier => Local_Id,
4512                    Object_Definition   =>
4513                      New_Reference_To (Ptr_Typ, Loc)));
4514
4515                --  Allocate the object, generate:
4516                --
4517                --    Local_Id := <Alloc_Expr>;
4518
4519                Append_To (Stmts,
4520                  Make_Assignment_Statement (Loc,
4521                    Name       => New_Reference_To (Local_Id, Loc),
4522                    Expression => Alloc_Expr));
4523
4524                --  Generate:
4525                --    Temp_Id := Temp_Typ (Local_Id);
4526
4527                Append_To (Stmts,
4528                  Make_Assignment_Statement (Loc,
4529                    Name       => New_Reference_To (Temp_Id, Loc),
4530                    Expression =>
4531                      Unchecked_Convert_To (Temp_Typ,
4532                        New_Reference_To (Local_Id, Loc))));
4533
4534                --  Wrap the allocation in a block. This is further conditioned
4535                --  by checking the caller finalization master at runtime. A
4536                --  null value indicates a non-existent master, most likely due
4537                --  to a Finalize_Storage_Only allocation.
4538
4539                --  Generate:
4540                --    if BIPfinalizationmaster /= null then
4541                --       declare
4542                --          <Decls>
4543                --       begin
4544                --          <Stmts>
4545                --       end;
4546                --    end if;
4547
4548                return
4549                  Make_If_Statement (Loc,
4550                    Condition       =>
4551                      Make_Op_Ne (Loc,
4552                        Left_Opnd  => New_Reference_To (Fin_Mas_Id, Loc),
4553                        Right_Opnd => Make_Null (Loc)),
4554
4555                    Then_Statements => New_List (
4556                      Make_Block_Statement (Loc,
4557                        Declarations               => Decls,
4558                        Handled_Statement_Sequence =>
4559                          Make_Handled_Sequence_Of_Statements (Loc,
4560                            Statements => Stmts))));
4561             end;
4562
4563          --  For all other cases, generate:
4564          --
4565          --    Temp_Id := <Alloc_Expr>;
4566
4567          else
4568             return
4569               Make_Assignment_Statement (Loc,
4570                 Name       => New_Reference_To (Temp_Id, Loc),
4571                 Expression => Alloc_Expr);
4572          end if;
4573       end Build_Heap_Allocator;
4574
4575       ---------------------------
4576       -- Move_Activation_Chain --
4577       ---------------------------
4578
4579       function Move_Activation_Chain return Node_Id is
4580          Chain_Formal  : constant Entity_Id :=
4581                            Build_In_Place_Formal
4582                             (Par_Func, BIP_Activation_Chain);
4583          To            : constant Node_Id :=
4584                            New_Reference_To (Chain_Formal, Loc);
4585          Master_Formal : constant Entity_Id :=
4586                            Build_In_Place_Formal (Par_Func, BIP_Master);
4587          New_Master    : constant Node_Id :=
4588                            New_Reference_To (Master_Formal, Loc);
4589
4590          Chain_Id : Entity_Id;
4591          From     : Node_Id;
4592
4593       begin
4594          Chain_Id := First_Entity (Return_Statement_Entity (N));
4595          while Chars (Chain_Id) /= Name_uChain loop
4596             Chain_Id := Next_Entity (Chain_Id);
4597          end loop;
4598
4599          From :=
4600            Make_Attribute_Reference (Loc,
4601              Prefix =>
4602                New_Reference_To (Chain_Id, Loc),
4603              Attribute_Name => Name_Unrestricted_Access);
4604          --  ??? Not clear why "Make_Identifier (Loc, Name_uChain)" doesn't
4605          --  work, instead of "New_Reference_To (Chain_Id, Loc)" above.
4606
4607          return
4608            Make_Procedure_Call_Statement (Loc,
4609              Name                   =>
4610                New_Reference_To (RTE (RE_Move_Activation_Chain), Loc),
4611              Parameter_Associations => New_List (From, To, New_Master));
4612       end Move_Activation_Chain;
4613
4614    --  Start of processing for Expand_N_Extended_Return_Statement
4615
4616    begin
4617       if Nkind (Ret_Obj_Decl) = N_Object_Declaration then
4618          Exp := Expression (Ret_Obj_Decl);
4619       else
4620          Exp := Empty;
4621       end if;
4622
4623       HSS := Handled_Statement_Sequence (N);
4624
4625       --  If the returned object needs finalization actions, the function must
4626       --  perform the appropriate cleanup should it fail to return. The state
4627       --  of the function itself is tracked through a flag which is coupled
4628       --  with the scope finalizer. There is one flag per each return object
4629       --  in case of multiple returns.
4630
4631       if Is_Build_In_Place
4632         and then Needs_Finalization (Etype (Ret_Obj_Id))
4633       then
4634          declare
4635             Flag_Decl : Node_Id;
4636             Flag_Id   : Entity_Id;
4637             Func_Bod  : Node_Id;
4638
4639          begin
4640             --  Recover the function body
4641
4642             Func_Bod := Unit_Declaration_Node (Par_Func);
4643             if Nkind (Func_Bod) = N_Subprogram_Declaration then
4644                Func_Bod := Parent (Parent (Corresponding_Body (Func_Bod)));
4645             end if;
4646
4647             --  Create a flag to track the function state
4648
4649             Flag_Id := Make_Temporary (Loc, 'F');
4650             Set_Return_Flag_Or_Transient_Decl (Ret_Obj_Id, Flag_Id);
4651
4652             --  Insert the flag at the beginning of the function declarations,
4653             --  generate:
4654             --    Fnn : Boolean := False;
4655
4656             Flag_Decl :=
4657               Make_Object_Declaration (Loc,
4658                 Defining_Identifier => Flag_Id,
4659                   Object_Definition =>
4660                     New_Reference_To (Standard_Boolean, Loc),
4661                   Expression        => New_Reference_To (Standard_False, Loc));
4662
4663             Prepend_To (Declarations (Func_Bod), Flag_Decl);
4664             Analyze (Flag_Decl);
4665          end;
4666       end if;
4667
4668       --  Build a simple_return_statement that returns the return object when
4669       --  there is a statement sequence, or no expression, or the result will
4670       --  be built in place. Note however that we currently do this for all
4671       --  composite cases, even though nonlimited composite results are not yet
4672       --  built in place (though we plan to do so eventually).
4673
4674       if Present (HSS)
4675         or else Is_Composite_Type (Etype (Par_Func))
4676         or else No (Exp)
4677       then
4678          if No (HSS) then
4679             Stmts := New_List;
4680
4681          --  If the extended return has a handled statement sequence, then wrap
4682          --  it in a block and use the block as the first statement.
4683
4684          else
4685             Stmts := New_List (
4686               Make_Block_Statement (Loc,
4687                 Declarations               => New_List,
4688                 Handled_Statement_Sequence => HSS));
4689          end if;
4690
4691          --  If the result type contains tasks, we call Move_Activation_Chain.
4692          --  Later, the cleanup code will call Complete_Master, which will
4693          --  terminate any unactivated tasks belonging to the return statement
4694          --  master. But Move_Activation_Chain updates their master to be that
4695          --  of the caller, so they will not be terminated unless the return
4696          --  statement completes unsuccessfully due to exception, abort, goto,
4697          --  or exit. As a formality, we test whether the function requires the
4698          --  result to be built in place, though that's necessarily true for
4699          --  the case of result types with task parts.
4700
4701          if Is_Build_In_Place
4702            and then Has_Task (Etype (Par_Func))
4703          then
4704             Append_To (Stmts, Move_Activation_Chain);
4705          end if;
4706
4707          --  Update the state of the function right before the object is
4708          --  returned.
4709
4710          if Is_Build_In_Place
4711            and then Needs_Finalization (Etype (Ret_Obj_Id))
4712          then
4713             declare
4714                Flag_Id : constant Entity_Id :=
4715                            Return_Flag_Or_Transient_Decl (Ret_Obj_Id);
4716
4717             begin
4718                --  Generate:
4719                --    Fnn := True;
4720
4721                Append_To (Stmts,
4722                  Make_Assignment_Statement (Loc,
4723                    Name       => New_Reference_To (Flag_Id, Loc),
4724                    Expression => New_Reference_To (Standard_True, Loc)));
4725             end;
4726          end if;
4727
4728          --  Build a simple_return_statement that returns the return object
4729
4730          Return_Stmt :=
4731            Make_Simple_Return_Statement (Loc,
4732              Expression => New_Occurrence_Of (Ret_Obj_Id, Loc));
4733          Append_To (Stmts, Return_Stmt);
4734
4735          HSS := Make_Handled_Sequence_Of_Statements (Loc, Stmts);
4736       end if;
4737
4738       --  Case where we build a return statement block
4739
4740       if Present (HSS) then
4741          Result :=
4742            Make_Block_Statement (Loc,
4743              Declarations               => Return_Object_Declarations (N),
4744              Handled_Statement_Sequence => HSS);
4745
4746          --  We set the entity of the new block statement to be that of the
4747          --  return statement. This is necessary so that various fields, such
4748          --  as Finalization_Chain_Entity carry over from the return statement
4749          --  to the block. Note that this block is unusual, in that its entity
4750          --  is an E_Return_Statement rather than an E_Block.
4751
4752          Set_Identifier
4753            (Result, New_Occurrence_Of (Return_Statement_Entity (N), Loc));
4754
4755          --  If the object decl was already rewritten as a renaming, then
4756          --  we don't want to do the object allocation and transformation of
4757          --  of the return object declaration to a renaming. This case occurs
4758          --  when the return object is initialized by a call to another
4759          --  build-in-place function, and that function is responsible for the
4760          --  allocation of the return object.
4761
4762          if Is_Build_In_Place
4763            and then Nkind (Ret_Obj_Decl) = N_Object_Renaming_Declaration
4764          then
4765             pragma Assert
4766               (Nkind (Original_Node (Ret_Obj_Decl)) = N_Object_Declaration
4767                 and then Is_Build_In_Place_Function_Call
4768                            (Expression (Original_Node (Ret_Obj_Decl))));
4769
4770             --  Return the build-in-place result by reference
4771
4772             Set_By_Ref (Return_Stmt);
4773
4774          elsif Is_Build_In_Place then
4775
4776             --  Locate the implicit access parameter associated with the
4777             --  caller-supplied return object and convert the return
4778             --  statement's return object declaration to a renaming of a
4779             --  dereference of the access parameter. If the return object's
4780             --  declaration includes an expression that has not already been
4781             --  expanded as separate assignments, then add an assignment
4782             --  statement to ensure the return object gets initialized.
4783
4784             --    declare
4785             --       Result : T [:= <expression>];
4786             --    begin
4787             --       ...
4788
4789             --  is converted to
4790
4791             --    declare
4792             --       Result : T renames FuncRA.all;
4793             --       [Result := <expression;]
4794             --    begin
4795             --       ...
4796
4797             declare
4798                Return_Obj_Id    : constant Entity_Id :=
4799                                     Defining_Identifier (Ret_Obj_Decl);
4800                Return_Obj_Typ   : constant Entity_Id := Etype (Return_Obj_Id);
4801                Return_Obj_Expr  : constant Node_Id :=
4802                                     Expression (Ret_Obj_Decl);
4803                Result_Subt      : constant Entity_Id := Etype (Par_Func);
4804                Constr_Result    : constant Boolean :=
4805                                     Is_Constrained (Result_Subt);
4806                Obj_Alloc_Formal : Entity_Id;
4807                Object_Access    : Entity_Id;
4808                Obj_Acc_Deref    : Node_Id;
4809                Init_Assignment  : Node_Id := Empty;
4810
4811             begin
4812                --  Build-in-place results must be returned by reference
4813
4814                Set_By_Ref (Return_Stmt);
4815
4816                --  Retrieve the implicit access parameter passed by the caller
4817
4818                Object_Access :=
4819                  Build_In_Place_Formal (Par_Func, BIP_Object_Access);
4820
4821                --  If the return object's declaration includes an expression
4822                --  and the declaration isn't marked as No_Initialization, then
4823                --  we need to generate an assignment to the object and insert
4824                --  it after the declaration before rewriting it as a renaming
4825                --  (otherwise we'll lose the initialization). The case where
4826                --  the result type is an interface (or class-wide interface)
4827                --  is also excluded because the context of the function call
4828                --  must be unconstrained, so the initialization will always
4829                --  be done as part of an allocator evaluation (storage pool
4830                --  or secondary stack), never to a constrained target object
4831                --  passed in by the caller. Besides the assignment being
4832                --  unneeded in this case, it avoids problems with trying to
4833                --  generate a dispatching assignment when the return expression
4834                --  is a nonlimited descendant of a limited interface (the
4835                --  interface has no assignment operation).
4836
4837                if Present (Return_Obj_Expr)
4838                  and then not No_Initialization (Ret_Obj_Decl)
4839                  and then not Is_Interface (Return_Obj_Typ)
4840                then
4841                   Init_Assignment :=
4842                     Make_Assignment_Statement (Loc,
4843                       Name       => New_Reference_To (Return_Obj_Id, Loc),
4844                       Expression => Relocate_Node (Return_Obj_Expr));
4845
4846                   Set_Etype (Name (Init_Assignment), Etype (Return_Obj_Id));
4847                   Set_Assignment_OK (Name (Init_Assignment));
4848                   Set_No_Ctrl_Actions (Init_Assignment);
4849
4850                   Set_Parent (Name (Init_Assignment), Init_Assignment);
4851                   Set_Parent (Expression (Init_Assignment), Init_Assignment);
4852
4853                   Set_Expression (Ret_Obj_Decl, Empty);
4854
4855                   if Is_Class_Wide_Type (Etype (Return_Obj_Id))
4856                     and then not Is_Class_Wide_Type
4857                                    (Etype (Expression (Init_Assignment)))
4858                   then
4859                      Rewrite (Expression (Init_Assignment),
4860                        Make_Type_Conversion (Loc,
4861                          Subtype_Mark =>
4862                            New_Occurrence_Of (Etype (Return_Obj_Id), Loc),
4863                          Expression   =>
4864                            Relocate_Node (Expression (Init_Assignment))));
4865                   end if;
4866
4867                   --  In the case of functions where the calling context can
4868                   --  determine the form of allocation needed, initialization
4869                   --  is done with each part of the if statement that handles
4870                   --  the different forms of allocation (this is true for
4871                   --  unconstrained and tagged result subtypes).
4872
4873                   if Constr_Result
4874                     and then not Is_Tagged_Type (Underlying_Type (Result_Subt))
4875                   then
4876                      Insert_After (Ret_Obj_Decl, Init_Assignment);
4877                   end if;
4878                end if;
4879
4880                --  When the function's subtype is unconstrained, a run-time
4881                --  test is needed to determine the form of allocation to use
4882                --  for the return object. The function has an implicit formal
4883                --  parameter indicating this. If the BIP_Alloc_Form formal has
4884                --  the value one, then the caller has passed access to an
4885                --  existing object for use as the return object. If the value
4886                --  is two, then the return object must be allocated on the
4887                --  secondary stack. Otherwise, the object must be allocated in
4888                --  a storage pool (currently only supported for the global
4889                --  heap, user-defined storage pools TBD ???). We generate an
4890                --  if statement to test the implicit allocation formal and
4891                --  initialize a local access value appropriately, creating
4892                --  allocators in the secondary stack and global heap cases.
4893                --  The special formal also exists and must be tested when the
4894                --  function has a tagged result, even when the result subtype
4895                --  is constrained, because in general such functions can be
4896                --  called in dispatching contexts and must be handled similarly
4897                --  to functions with a class-wide result.
4898
4899                if not Constr_Result
4900                  or else Is_Tagged_Type (Underlying_Type (Result_Subt))
4901                then
4902                   Obj_Alloc_Formal :=
4903                     Build_In_Place_Formal (Par_Func, BIP_Alloc_Form);
4904
4905                   declare
4906                      Ref_Type       : Entity_Id;
4907                      Ptr_Type_Decl  : Node_Id;
4908                      Alloc_Obj_Id   : Entity_Id;
4909                      Alloc_Obj_Decl : Node_Id;
4910                      Alloc_If_Stmt  : Node_Id;
4911                      Heap_Allocator : Node_Id;
4912                      SS_Allocator   : Node_Id;
4913
4914                   begin
4915                      --  Reuse the itype created for the function's implicit
4916                      --  access formal. This avoids the need to create a new
4917                      --  access type here, plus it allows assigning the access
4918                      --  formal directly without applying a conversion.
4919
4920                      --    Ref_Type := Etype (Object_Access);
4921
4922                      --  Create an access type designating the function's
4923                      --  result subtype.
4924
4925                      Ref_Type := Make_Temporary (Loc, 'A');
4926
4927                      Ptr_Type_Decl :=
4928                        Make_Full_Type_Declaration (Loc,
4929                          Defining_Identifier => Ref_Type,
4930                          Type_Definition     =>
4931                            Make_Access_To_Object_Definition (Loc,
4932                              All_Present        => True,
4933                              Subtype_Indication =>
4934                                New_Reference_To (Return_Obj_Typ, Loc)));
4935
4936                      Insert_Before (Ret_Obj_Decl, Ptr_Type_Decl);
4937
4938                      --  Create an access object that will be initialized to an
4939                      --  access value denoting the return object, either coming
4940                      --  from an implicit access value passed in by the caller
4941                      --  or from the result of an allocator.
4942
4943                      Alloc_Obj_Id := Make_Temporary (Loc, 'R');
4944                      Set_Etype (Alloc_Obj_Id, Ref_Type);
4945
4946                      Alloc_Obj_Decl :=
4947                        Make_Object_Declaration (Loc,
4948                          Defining_Identifier => Alloc_Obj_Id,
4949                          Object_Definition   =>
4950                            New_Reference_To (Ref_Type, Loc));
4951
4952                      Insert_Before (Ret_Obj_Decl, Alloc_Obj_Decl);
4953
4954                      --  Create allocators for both the secondary stack and
4955                      --  global heap. If there's an initialization expression,
4956                      --  then create these as initialized allocators.
4957
4958                      if Present (Return_Obj_Expr)
4959                        and then not No_Initialization (Ret_Obj_Decl)
4960                      then
4961                         --  Always use the type of the expression for the
4962                         --  qualified expression, rather than the result type.
4963                         --  In general we cannot always use the result type
4964                         --  for the allocator, because the expression might be
4965                         --  of a specific type, such as in the case of an
4966                         --  aggregate or even a nonlimited object when the
4967                         --  result type is a limited class-wide interface type.
4968
4969                         Heap_Allocator :=
4970                           Make_Allocator (Loc,
4971                             Expression =>
4972                               Make_Qualified_Expression (Loc,
4973                                 Subtype_Mark =>
4974                                   New_Reference_To
4975                                     (Etype (Return_Obj_Expr), Loc),
4976                                 Expression   =>
4977                                   New_Copy_Tree (Return_Obj_Expr)));
4978
4979                      else
4980                         --  If the function returns a class-wide type we cannot
4981                         --  use the return type for the allocator. Instead we
4982                         --  use the type of the expression, which must be an
4983                         --  aggregate of a definite type.
4984
4985                         if Is_Class_Wide_Type (Return_Obj_Typ) then
4986                            Heap_Allocator :=
4987                              Make_Allocator (Loc,
4988                                Expression =>
4989                                  New_Reference_To
4990                                    (Etype (Return_Obj_Expr), Loc));
4991                         else
4992                            Heap_Allocator :=
4993                              Make_Allocator (Loc,
4994                                Expression =>
4995                                  New_Reference_To (Return_Obj_Typ, Loc));
4996                         end if;
4997
4998                         --  If the object requires default initialization then
4999                         --  that will happen later following the elaboration of
5000                         --  the object renaming. If we don't turn it off here
5001                         --  then the object will be default initialized twice.
5002
5003                         Set_No_Initialization (Heap_Allocator);
5004                      end if;
5005
5006                      --  If the No_Allocators restriction is active, then only
5007                      --  an allocator for secondary stack allocation is needed.
5008                      --  It's OK for such allocators to have Comes_From_Source
5009                      --  set to False, because gigi knows not to flag them as
5010                      --  being a violation of No_Implicit_Heap_Allocations.
5011
5012                      if Restriction_Active (No_Allocators) then
5013                         SS_Allocator   := Heap_Allocator;
5014                         Heap_Allocator := Make_Null (Loc);
5015
5016                      --  Otherwise the heap allocator may be needed, so we make
5017                      --  another allocator for secondary stack allocation.
5018
5019                      else
5020                         SS_Allocator := New_Copy_Tree (Heap_Allocator);
5021
5022                         --  The heap allocator is marked Comes_From_Source
5023                         --  since it corresponds to an explicit user-written
5024                         --  allocator (that is, it will only be executed on
5025                         --  behalf of callers that call the function as
5026                         --  initialization for such an allocator). This
5027                         --  prevents errors when No_Implicit_Heap_Allocations
5028                         --  is in force.
5029
5030                         Set_Comes_From_Source (Heap_Allocator, True);
5031                      end if;
5032
5033                      --  The allocator is returned on the secondary stack. We
5034                      --  don't do this on VM targets, since the SS is not used.
5035
5036                      if VM_Target = No_VM then
5037                         Set_Storage_Pool (SS_Allocator, RTE (RE_SS_Pool));
5038                         Set_Procedure_To_Call
5039                           (SS_Allocator, RTE (RE_SS_Allocate));
5040
5041                         --  The allocator is returned on the secondary stack,
5042                         --  so indicate that the function return, as well as
5043                         --  the block that encloses the allocator, must not
5044                         --  release it. The flags must be set now because the
5045                         --  decision to use the secondary stack is done very
5046                         --  late in the course of expanding the return
5047                         --  statement, past the point where these flags are
5048                         --  normally set.
5049
5050                         Set_Sec_Stack_Needed_For_Return (Par_Func);
5051                         Set_Sec_Stack_Needed_For_Return
5052                           (Return_Statement_Entity (N));
5053                         Set_Uses_Sec_Stack (Par_Func);
5054                         Set_Uses_Sec_Stack (Return_Statement_Entity (N));
5055                      end if;
5056
5057                      --  Create an if statement to test the BIP_Alloc_Form
5058                      --  formal and initialize the access object to either the
5059                      --  BIP_Object_Access formal (BIP_Alloc_Form = 0), the
5060                      --  result of allocating the object in the secondary stack
5061                      --  (BIP_Alloc_Form = 1), or else an allocator to create
5062                      --  the return object in the heap (BIP_Alloc_Form = 2).
5063
5064                      --  ??? An unchecked type conversion must be made in the
5065                      --  case of assigning the access object formal to the
5066                      --  local access object, because a normal conversion would
5067                      --  be illegal in some cases (such as converting access-
5068                      --  to-unconstrained to access-to-constrained), but the
5069                      --  the unchecked conversion will presumably fail to work
5070                      --  right in just such cases. It's not clear at all how to
5071                      --  handle this. ???
5072
5073                      Alloc_If_Stmt :=
5074                        Make_If_Statement (Loc,
5075                          Condition =>
5076                            Make_Op_Eq (Loc,
5077                              Left_Opnd  =>
5078                                New_Reference_To (Obj_Alloc_Formal, Loc),
5079                              Right_Opnd =>
5080                                Make_Integer_Literal (Loc,
5081                                  UI_From_Int (BIP_Allocation_Form'Pos
5082                                                 (Caller_Allocation)))),
5083
5084                          Then_Statements => New_List (
5085                            Make_Assignment_Statement (Loc,
5086                              Name       =>
5087                                New_Reference_To (Alloc_Obj_Id, Loc),
5088                              Expression =>
5089                                Make_Unchecked_Type_Conversion (Loc,
5090                                  Subtype_Mark =>
5091                                    New_Reference_To (Ref_Type, Loc),
5092                                  Expression   =>
5093                                    New_Reference_To (Object_Access, Loc)))),
5094
5095                          Elsif_Parts => New_List (
5096                            Make_Elsif_Part (Loc,
5097                              Condition =>
5098                                Make_Op_Eq (Loc,
5099                                  Left_Opnd  =>
5100                                    New_Reference_To (Obj_Alloc_Formal, Loc),
5101                                  Right_Opnd =>
5102                                    Make_Integer_Literal (Loc,
5103                                      UI_From_Int (BIP_Allocation_Form'Pos
5104                                                     (Secondary_Stack)))),
5105
5106                              Then_Statements => New_List (
5107                                Make_Assignment_Statement (Loc,
5108                                  Name       =>
5109                                    New_Reference_To (Alloc_Obj_Id, Loc),
5110                                  Expression => SS_Allocator)))),
5111
5112                          Else_Statements => New_List (
5113                            Build_Heap_Allocator
5114                              (Temp_Id    => Alloc_Obj_Id,
5115                               Temp_Typ   => Ref_Type,
5116                               Func_Id    => Par_Func,
5117                               Ret_Typ    => Return_Obj_Typ,
5118                               Alloc_Expr => Heap_Allocator)));
5119
5120                      --  If a separate initialization assignment was created
5121                      --  earlier, append that following the assignment of the
5122                      --  implicit access formal to the access object, to ensure
5123                      --  that the return object is initialized in that case.
5124                      --  In this situation, the target of the assignment must
5125                      --  be rewritten to denote a dereference of the access to
5126                      --  the return object passed in by the caller.
5127
5128                      if Present (Init_Assignment) then
5129                         Rewrite (Name (Init_Assignment),
5130                           Make_Explicit_Dereference (Loc,
5131                             Prefix => New_Reference_To (Alloc_Obj_Id, Loc)));
5132
5133                         Set_Etype
5134                           (Name (Init_Assignment), Etype (Return_Obj_Id));
5135
5136                         Append_To
5137                           (Then_Statements (Alloc_If_Stmt), Init_Assignment);
5138                      end if;
5139
5140                      Insert_Before (Ret_Obj_Decl, Alloc_If_Stmt);
5141
5142                      --  Remember the local access object for use in the
5143                      --  dereference of the renaming created below.
5144
5145                      Object_Access := Alloc_Obj_Id;
5146                   end;
5147                end if;
5148
5149                --  Replace the return object declaration with a renaming of a
5150                --  dereference of the access value designating the return
5151                --  object.
5152
5153                Obj_Acc_Deref :=
5154                  Make_Explicit_Dereference (Loc,
5155                    Prefix => New_Reference_To (Object_Access, Loc));
5156
5157                Rewrite (Ret_Obj_Decl,
5158                  Make_Object_Renaming_Declaration (Loc,
5159                    Defining_Identifier => Return_Obj_Id,
5160                    Access_Definition   => Empty,
5161                    Subtype_Mark        =>
5162                      New_Occurrence_Of (Return_Obj_Typ, Loc),
5163                    Name                => Obj_Acc_Deref));
5164
5165                Set_Renamed_Object (Return_Obj_Id, Obj_Acc_Deref);
5166             end;
5167          end if;
5168
5169       --  Case where we do not build a block
5170
5171       else
5172          --  We're about to drop Return_Object_Declarations on the floor, so
5173          --  we need to insert it, in case it got expanded into useful code.
5174          --  Remove side effects from expression, which may be duplicated in
5175          --  subsequent checks (see Expand_Simple_Function_Return).
5176
5177          Insert_List_Before (N, Return_Object_Declarations (N));
5178          Remove_Side_Effects (Exp);
5179
5180          --  Build simple_return_statement that returns the expression directly
5181
5182          Return_Stmt := Make_Simple_Return_Statement (Loc, Expression => Exp);
5183          Result := Return_Stmt;
5184       end if;
5185
5186       --  Set the flag to prevent infinite recursion
5187
5188       Set_Comes_From_Extended_Return_Statement (Return_Stmt);
5189
5190       Rewrite (N, Result);
5191       Analyze (N);
5192    end Expand_N_Extended_Return_Statement;
5193
5194    ----------------------------
5195    -- Expand_N_Function_Call --
5196    ----------------------------
5197
5198    procedure Expand_N_Function_Call (N : Node_Id) is
5199    begin
5200       Expand_Call (N);
5201
5202       --  If the return value of a foreign compiled function is VAX Float, then
5203       --  expand the return (adjusts the location of the return value on
5204       --  Alpha/VMS, no-op everywhere else).
5205       --  Comes_From_Source intercepts recursive expansion.
5206
5207       if Vax_Float (Etype (N))
5208         and then Nkind (N) = N_Function_Call
5209         and then Present (Name (N))
5210         and then Present (Entity (Name (N)))
5211         and then Has_Foreign_Convention (Entity (Name (N)))
5212         and then Comes_From_Source (Parent (N))
5213       then
5214          Expand_Vax_Foreign_Return (N);
5215       end if;
5216    end Expand_N_Function_Call;
5217
5218    ---------------------------------------
5219    -- Expand_N_Procedure_Call_Statement --
5220    ---------------------------------------
5221
5222    procedure Expand_N_Procedure_Call_Statement (N : Node_Id) is
5223    begin
5224       Expand_Call (N);
5225    end Expand_N_Procedure_Call_Statement;
5226
5227    --------------------------------------
5228    -- Expand_N_Simple_Return_Statement --
5229    --------------------------------------
5230
5231    procedure Expand_N_Simple_Return_Statement (N : Node_Id) is
5232    begin
5233       --  Defend against previous errors (i.e. the return statement calls a
5234       --  function that is not available in configurable runtime).
5235
5236       if Present (Expression (N))
5237         and then Nkind (Expression (N)) = N_Empty
5238       then
5239          return;
5240       end if;
5241
5242       --  Distinguish the function and non-function cases:
5243
5244       case Ekind (Return_Applies_To (Return_Statement_Entity (N))) is
5245
5246          when E_Function          |
5247               E_Generic_Function  =>
5248             Expand_Simple_Function_Return (N);
5249
5250          when E_Procedure         |
5251               E_Generic_Procedure |
5252               E_Entry             |
5253               E_Entry_Family      |
5254               E_Return_Statement =>
5255             Expand_Non_Function_Return (N);
5256
5257          when others =>
5258             raise Program_Error;
5259       end case;
5260
5261    exception
5262       when RE_Not_Available =>
5263          return;
5264    end Expand_N_Simple_Return_Statement;
5265
5266    ------------------------------
5267    -- Expand_N_Subprogram_Body --
5268    ------------------------------
5269
5270    --  Add poll call if ATC polling is enabled, unless the body will be inlined
5271    --  by the back-end.
5272
5273    --  Add dummy push/pop label nodes at start and end to clear any local
5274    --  exception indications if local-exception-to-goto optimization is active.
5275
5276    --  Add return statement if last statement in body is not a return statement
5277    --  (this makes things easier on Gigi which does not want to have to handle
5278    --  a missing return).
5279
5280    --  Add call to Activate_Tasks if body is a task activator
5281
5282    --  Deal with possible detection of infinite recursion
5283
5284    --  Eliminate body completely if convention stubbed
5285
5286    --  Encode entity names within body, since we will not need to reference
5287    --  these entities any longer in the front end.
5288
5289    --  Initialize scalar out parameters if Initialize/Normalize_Scalars
5290
5291    --  Reset Pure indication if any parameter has root type System.Address
5292    --  or has any parameters of limited types, where limited means that the
5293    --  run-time view is limited (i.e. the full type is limited).
5294
5295    --  Wrap thread body
5296
5297    procedure Expand_N_Subprogram_Body (N : Node_Id) is
5298       Loc      : constant Source_Ptr := Sloc (N);
5299       H        : constant Node_Id    := Handled_Statement_Sequence (N);
5300       Body_Id  : Entity_Id;
5301       Except_H : Node_Id;
5302       L        : List_Id;
5303       Spec_Id  : Entity_Id;
5304
5305       procedure Add_Return (S : List_Id);
5306       --  Append a return statement to the statement sequence S if the last
5307       --  statement is not already a return or a goto statement. Note that
5308       --  the latter test is not critical, it does not matter if we add a few
5309       --  extra returns, since they get eliminated anyway later on.
5310
5311       ----------------
5312       -- Add_Return --
5313       ----------------
5314
5315       procedure Add_Return (S : List_Id) is
5316          Last_Stm : Node_Id;
5317          Loc      : Source_Ptr;
5318
5319       begin
5320          --  Get last statement, ignoring any Pop_xxx_Label nodes, which are
5321          --  not relevant in this context since they are not executable.
5322
5323          Last_Stm := Last (S);
5324          while Nkind (Last_Stm) in N_Pop_xxx_Label loop
5325             Prev (Last_Stm);
5326          end loop;
5327
5328          --  Now insert return unless last statement is a transfer
5329
5330          if not Is_Transfer (Last_Stm) then
5331
5332             --  The source location for the return is the end label of the
5333             --  procedure if present. Otherwise use the sloc of the last
5334             --  statement in the list. If the list comes from a generated
5335             --  exception handler and we are not debugging generated code,
5336             --  all the statements within the handler are made invisible
5337             --  to the debugger.
5338
5339             if Nkind (Parent (S)) = N_Exception_Handler
5340               and then not Comes_From_Source (Parent (S))
5341             then
5342                Loc := Sloc (Last_Stm);
5343             elsif Present (End_Label (H)) then
5344                Loc := Sloc (End_Label (H));
5345             else
5346                Loc := Sloc (Last_Stm);
5347             end if;
5348
5349             declare
5350                Rtn : constant Node_Id := Make_Simple_Return_Statement (Loc);
5351
5352             begin
5353                --  Append return statement, and set analyzed manually. We can't
5354                --  call Analyze on this return since the scope is wrong.
5355
5356                --  Note: it almost works to push the scope and then do the
5357                --  Analyze call, but something goes wrong in some weird cases
5358                --  and it is not worth worrying about ???
5359
5360                Append_To (S, Rtn);
5361                Set_Analyzed (Rtn);
5362
5363                --  Call _Postconditions procedure if appropriate. We need to
5364                --  do this explicitly because we did not analyze the generated
5365                --  return statement above, so the call did not get inserted.
5366
5367                if Ekind (Spec_Id) = E_Procedure
5368                  and then Has_Postconditions (Spec_Id)
5369                then
5370                   pragma Assert (Present (Postcondition_Proc (Spec_Id)));
5371                   Insert_Action (Rtn,
5372                     Make_Procedure_Call_Statement (Loc,
5373                       Name =>
5374                         New_Reference_To (Postcondition_Proc (Spec_Id), Loc)));
5375                end if;
5376             end;
5377          end if;
5378       end Add_Return;
5379
5380    --  Start of processing for Expand_N_Subprogram_Body
5381
5382    begin
5383       --  Set L to either the list of declarations if present, or to the list
5384       --  of statements if no declarations are present. This is used to insert
5385       --  new stuff at the start.
5386
5387       if Is_Non_Empty_List (Declarations (N)) then
5388          L := Declarations (N);
5389       else
5390          L := Statements (H);
5391       end if;
5392
5393       --  If local-exception-to-goto optimization active, insert dummy push
5394       --  statements at start, and dummy pop statements at end.
5395
5396       if (Debug_Flag_Dot_G
5397            or else Restriction_Active (No_Exception_Propagation))
5398         and then Is_Non_Empty_List (L)
5399       then
5400          declare
5401             FS  : constant Node_Id    := First (L);
5402             FL  : constant Source_Ptr := Sloc (FS);
5403             LS  : Node_Id;
5404             LL  : Source_Ptr;
5405
5406          begin
5407             --  LS points to either last statement, if statements are present
5408             --  or to the last declaration if there are no statements present.
5409             --  It is the node after which the pop's are generated.
5410
5411             if Is_Non_Empty_List (Statements (H)) then
5412                LS := Last (Statements (H));
5413             else
5414                LS := Last (L);
5415             end if;
5416
5417             LL := Sloc (LS);
5418
5419             Insert_List_Before_And_Analyze (FS, New_List (
5420               Make_Push_Constraint_Error_Label (FL),
5421               Make_Push_Program_Error_Label    (FL),
5422               Make_Push_Storage_Error_Label    (FL)));
5423
5424             Insert_List_After_And_Analyze (LS, New_List (
5425               Make_Pop_Constraint_Error_Label  (LL),
5426               Make_Pop_Program_Error_Label     (LL),
5427               Make_Pop_Storage_Error_Label     (LL)));
5428          end;
5429       end if;
5430
5431       --  Find entity for subprogram
5432
5433       Body_Id := Defining_Entity (N);
5434
5435       if Present (Corresponding_Spec (N)) then
5436          Spec_Id := Corresponding_Spec (N);
5437       else
5438          Spec_Id := Body_Id;
5439       end if;
5440
5441       --  Need poll on entry to subprogram if polling enabled. We only do this
5442       --  for non-empty subprograms, since it does not seem necessary to poll
5443       --  for a dummy null subprogram.
5444
5445       if Is_Non_Empty_List (L) then
5446
5447          --  Do not add a polling call if the subprogram is to be inlined by
5448          --  the back-end, to avoid repeated calls with multiple inlinings.
5449
5450          if Is_Inlined (Spec_Id)
5451            and then Front_End_Inlining
5452            and then Optimization_Level > 1
5453          then
5454             null;
5455          else
5456             Generate_Poll_Call (First (L));
5457          end if;
5458       end if;
5459
5460       --  If this is a Pure function which has any parameters whose root type
5461       --  is System.Address, reset the Pure indication, since it will likely
5462       --  cause incorrect code to be generated as the parameter is probably
5463       --  a pointer, and the fact that the same pointer is passed does not mean
5464       --  that the same value is being referenced.
5465
5466       --  Note that if the programmer gave an explicit Pure_Function pragma,
5467       --  then we believe the programmer, and leave the subprogram Pure.
5468
5469       --  This code should probably be at the freeze point, so that it happens
5470       --  even on a -gnatc (or more importantly -gnatt) compile, so that the
5471       --  semantic tree has Is_Pure set properly ???
5472
5473       if Is_Pure (Spec_Id)
5474         and then Is_Subprogram (Spec_Id)
5475         and then not Has_Pragma_Pure_Function (Spec_Id)
5476       then
5477          declare
5478             F : Entity_Id;
5479
5480          begin
5481             F := First_Formal (Spec_Id);
5482             while Present (F) loop
5483                if Is_Descendent_Of_Address (Etype (F))
5484
5485                  --  Note that this test is being made in the body of the
5486                  --  subprogram, not the spec, so we are testing the full
5487                  --  type for being limited here, as required.
5488
5489                  or else Is_Limited_Type (Etype (F))
5490                then
5491                   Set_Is_Pure (Spec_Id, False);
5492
5493                   if Spec_Id /= Body_Id then
5494                      Set_Is_Pure (Body_Id, False);
5495                   end if;
5496
5497                   exit;
5498                end if;
5499
5500                Next_Formal (F);
5501             end loop;
5502          end;
5503       end if;
5504
5505       --  Initialize any scalar OUT args if Initialize/Normalize_Scalars
5506
5507       if Init_Or_Norm_Scalars and then Is_Subprogram (Spec_Id) then
5508          declare
5509             F : Entity_Id;
5510
5511          begin
5512             --  Loop through formals
5513
5514             F := First_Formal (Spec_Id);
5515             while Present (F) loop
5516                if Is_Scalar_Type (Etype (F))
5517                  and then Ekind (F) = E_Out_Parameter
5518                then
5519                   Check_Restriction (No_Default_Initialization, F);
5520
5521                   --  Insert the initialization. We turn off validity checks
5522                   --  for this assignment, since we do not want any check on
5523                   --  the initial value itself (which may well be invalid).
5524
5525                   Insert_Before_And_Analyze (First (L),
5526                     Make_Assignment_Statement (Loc,
5527                       Name       => New_Occurrence_Of (F, Loc),
5528                       Expression => Get_Simple_Init_Val (Etype (F), N)),
5529                     Suppress => Validity_Check);
5530                end if;
5531
5532                Next_Formal (F);
5533             end loop;
5534          end;
5535       end if;
5536
5537       --  Clear out statement list for stubbed procedure
5538
5539       if Present (Corresponding_Spec (N)) then
5540          Set_Elaboration_Flag (N, Spec_Id);
5541
5542          if Convention (Spec_Id) = Convention_Stubbed
5543            or else Is_Eliminated (Spec_Id)
5544          then
5545             Set_Declarations (N, Empty_List);
5546             Set_Handled_Statement_Sequence (N,
5547               Make_Handled_Sequence_Of_Statements (Loc,
5548                 Statements => New_List (Make_Null_Statement (Loc))));
5549             return;
5550          end if;
5551       end if;
5552
5553       --  Create a set of discriminals for the next protected subprogram body
5554
5555       if Is_List_Member (N)
5556         and then Present (Parent (List_Containing (N)))
5557         and then Nkind (Parent (List_Containing (N))) = N_Protected_Body
5558         and then Present (Next_Protected_Operation (N))
5559       then
5560          Set_Discriminals (Parent (Base_Type (Scope (Spec_Id))));
5561       end if;
5562
5563       --  Returns_By_Ref flag is normally set when the subprogram is frozen but
5564       --  subprograms with no specs are not frozen.
5565
5566       declare
5567          Typ  : constant Entity_Id := Etype (Spec_Id);
5568          Utyp : constant Entity_Id := Underlying_Type (Typ);
5569
5570       begin
5571          if not Acts_As_Spec (N)
5572            and then Nkind (Parent (Parent (Spec_Id))) /=
5573              N_Subprogram_Body_Stub
5574          then
5575             null;
5576
5577          elsif Is_Immutably_Limited_Type (Typ) then
5578             Set_Returns_By_Ref (Spec_Id);
5579
5580          elsif Present (Utyp) and then CW_Or_Has_Controlled_Part (Utyp) then
5581             Set_Returns_By_Ref (Spec_Id);
5582          end if;
5583       end;
5584
5585       --  For a procedure, we add a return for all possible syntactic ends of
5586       --  the subprogram.
5587
5588       if Ekind_In (Spec_Id, E_Procedure, E_Generic_Procedure) then
5589          Add_Return (Statements (H));
5590
5591          if Present (Exception_Handlers (H)) then
5592             Except_H := First_Non_Pragma (Exception_Handlers (H));
5593             while Present (Except_H) loop
5594                Add_Return (Statements (Except_H));
5595                Next_Non_Pragma (Except_H);
5596             end loop;
5597          end if;
5598
5599       --  For a function, we must deal with the case where there is at least
5600       --  one missing return. What we do is to wrap the entire body of the
5601       --  function in a block:
5602
5603       --    begin
5604       --      ...
5605       --    end;
5606
5607       --  becomes
5608
5609       --    begin
5610       --       begin
5611       --          ...
5612       --       end;
5613
5614       --       raise Program_Error;
5615       --    end;
5616
5617       --  This approach is necessary because the raise must be signalled to the
5618       --  caller, not handled by any local handler (RM 6.4(11)).
5619
5620       --  Note: we do not need to analyze the constructed sequence here, since
5621       --  it has no handler, and an attempt to analyze the handled statement
5622       --  sequence twice is risky in various ways (e.g. the issue of expanding
5623       --  cleanup actions twice).
5624
5625       elsif Has_Missing_Return (Spec_Id) then
5626          declare
5627             Hloc : constant Source_Ptr := Sloc (H);
5628             Blok : constant Node_Id    :=
5629                      Make_Block_Statement (Hloc,
5630                        Handled_Statement_Sequence => H);
5631             Rais : constant Node_Id    :=
5632                      Make_Raise_Program_Error (Hloc,
5633                        Reason => PE_Missing_Return);
5634
5635          begin
5636             Set_Handled_Statement_Sequence (N,
5637               Make_Handled_Sequence_Of_Statements (Hloc,
5638                 Statements => New_List (Blok, Rais)));
5639
5640             Push_Scope (Spec_Id);
5641             Analyze (Blok);
5642             Analyze (Rais);
5643             Pop_Scope;
5644          end;
5645       end if;
5646
5647       --  If subprogram contains a parameterless recursive call, then we may
5648       --  have an infinite recursion, so see if we can generate code to check
5649       --  for this possibility if storage checks are not suppressed.
5650
5651       if Ekind (Spec_Id) = E_Procedure
5652         and then Has_Recursive_Call (Spec_Id)
5653         and then not Storage_Checks_Suppressed (Spec_Id)
5654       then
5655          Detect_Infinite_Recursion (N, Spec_Id);
5656       end if;
5657
5658       --  Set to encode entity names in package body before gigi is called
5659
5660       Qualify_Entity_Names (N);
5661    end Expand_N_Subprogram_Body;
5662
5663    -----------------------------------
5664    -- Expand_N_Subprogram_Body_Stub --
5665    -----------------------------------
5666
5667    procedure Expand_N_Subprogram_Body_Stub (N : Node_Id) is
5668    begin
5669       if Present (Corresponding_Body (N)) then
5670          Expand_N_Subprogram_Body (
5671            Unit_Declaration_Node (Corresponding_Body (N)));
5672       end if;
5673    end Expand_N_Subprogram_Body_Stub;
5674
5675    -------------------------------------
5676    -- Expand_N_Subprogram_Declaration --
5677    -------------------------------------
5678
5679    --  If the declaration appears within a protected body, it is a private
5680    --  operation of the protected type. We must create the corresponding
5681    --  protected subprogram an associated formals. For a normal protected
5682    --  operation, this is done when expanding the protected type declaration.
5683
5684    --  If the declaration is for a null procedure, emit null body
5685
5686    procedure Expand_N_Subprogram_Declaration (N : Node_Id) is
5687       Loc       : constant Source_Ptr := Sloc (N);
5688       Subp      : constant Entity_Id  := Defining_Entity (N);
5689       Scop      : constant Entity_Id  := Scope (Subp);
5690       Prot_Decl : Node_Id;
5691       Prot_Bod  : Node_Id;
5692       Prot_Id   : Entity_Id;
5693
5694    begin
5695       --  In SPARK, subprogram declarations are only allowed in package
5696       --  specifications.
5697
5698       if Nkind (Parent (N)) /= N_Package_Specification then
5699          if Nkind (Parent (N)) = N_Compilation_Unit then
5700             Check_SPARK_Restriction
5701               ("subprogram declaration is not a library item", N);
5702
5703          elsif Present (Next (N))
5704            and then Nkind (Next (N)) = N_Pragma
5705            and then Get_Pragma_Id (Pragma_Name (Next (N))) = Pragma_Import
5706          then
5707             --  In SPARK, subprogram declarations are also permitted in
5708             --  declarative parts when immediately followed by a corresponding
5709             --  pragma Import. We only check here that there is some pragma
5710             --  Import.
5711
5712             null;
5713          else
5714             Check_SPARK_Restriction
5715               ("subprogram declaration is not allowed here", N);
5716          end if;
5717       end if;
5718
5719       --  Deal with case of protected subprogram. Do not generate protected
5720       --  operation if operation is flagged as eliminated.
5721
5722       if Is_List_Member (N)
5723         and then Present (Parent (List_Containing (N)))
5724         and then Nkind (Parent (List_Containing (N))) = N_Protected_Body
5725         and then Is_Protected_Type (Scop)
5726       then
5727          if No (Protected_Body_Subprogram (Subp))
5728            and then not Is_Eliminated (Subp)
5729          then
5730             Prot_Decl :=
5731               Make_Subprogram_Declaration (Loc,
5732                 Specification =>
5733                   Build_Protected_Sub_Specification
5734                     (N, Scop, Unprotected_Mode));
5735
5736             --  The protected subprogram is declared outside of the protected
5737             --  body. Given that the body has frozen all entities so far, we
5738             --  analyze the subprogram and perform freezing actions explicitly.
5739             --  including the generation of an explicit freeze node, to ensure
5740             --  that gigi has the proper order of elaboration.
5741             --  If the body is a subunit, the insertion point is before the
5742             --  stub in the parent.
5743
5744             Prot_Bod := Parent (List_Containing (N));
5745
5746             if Nkind (Parent (Prot_Bod)) = N_Subunit then
5747                Prot_Bod := Corresponding_Stub (Parent (Prot_Bod));
5748             end if;
5749
5750             Insert_Before (Prot_Bod, Prot_Decl);
5751             Prot_Id := Defining_Unit_Name (Specification (Prot_Decl));
5752             Set_Has_Delayed_Freeze (Prot_Id);
5753
5754             Push_Scope (Scope (Scop));
5755             Analyze (Prot_Decl);
5756             Freeze_Before (N, Prot_Id);
5757             Set_Protected_Body_Subprogram (Subp, Prot_Id);
5758
5759             --  Create protected operation as well. Even though the operation
5760             --  is only accessible within the body, it is possible to make it
5761             --  available outside of the protected object by using 'Access to
5762             --  provide a callback, so build protected version in all cases.
5763
5764             Prot_Decl :=
5765               Make_Subprogram_Declaration (Loc,
5766                 Specification =>
5767                   Build_Protected_Sub_Specification (N, Scop, Protected_Mode));
5768             Insert_Before (Prot_Bod, Prot_Decl);
5769             Analyze (Prot_Decl);
5770
5771             Pop_Scope;
5772          end if;
5773
5774       --  Ada 2005 (AI-348): Generate body for a null procedure.
5775       --  In most cases this is superfluous because calls to it
5776       --  will be automatically inlined, but we definitely need
5777       --  the body if preconditions for the procedure are present.
5778
5779       elsif Nkind (Specification (N)) = N_Procedure_Specification
5780         and then Null_Present (Specification (N))
5781       then
5782          declare
5783             Bod : constant Node_Id := Body_To_Inline (N);
5784
5785          begin
5786             Set_Has_Completion (Subp, False);
5787             Append_Freeze_Action (Subp, Bod);
5788
5789             --  The body now contains raise statements, so calls to it will
5790             --  not be inlined.
5791
5792             Set_Is_Inlined (Subp, False);
5793          end;
5794       end if;
5795    end Expand_N_Subprogram_Declaration;
5796
5797    --------------------------------
5798    -- Expand_Non_Function_Return --
5799    --------------------------------
5800
5801    procedure Expand_Non_Function_Return (N : Node_Id) is
5802       pragma Assert (No (Expression (N)));
5803
5804       Loc         : constant Source_Ptr := Sloc (N);
5805       Scope_Id    : Entity_Id :=
5806                       Return_Applies_To (Return_Statement_Entity (N));
5807       Kind        : constant Entity_Kind := Ekind (Scope_Id);
5808       Call        : Node_Id;
5809       Acc_Stat    : Node_Id;
5810       Goto_Stat   : Node_Id;
5811       Lab_Node    : Node_Id;
5812
5813    begin
5814       --  Call _Postconditions procedure if procedure with active
5815       --  postconditions. Here, we use the Postcondition_Proc attribute, which
5816       --  is needed for implicitly-generated returns. Functions never
5817       --  have implicitly-generated returns, and there's no room for
5818       --  Postcondition_Proc in E_Function, so we look up the identifier
5819       --  Name_uPostconditions for function returns (see
5820       --  Expand_Simple_Function_Return).
5821
5822       if Ekind (Scope_Id) = E_Procedure
5823         and then Has_Postconditions (Scope_Id)
5824       then
5825          pragma Assert (Present (Postcondition_Proc (Scope_Id)));
5826          Insert_Action (N,
5827            Make_Procedure_Call_Statement (Loc,
5828              Name => New_Reference_To (Postcondition_Proc (Scope_Id), Loc)));
5829       end if;
5830
5831       --  If it is a return from a procedure do no extra steps
5832
5833       if Kind = E_Procedure or else Kind = E_Generic_Procedure then
5834          return;
5835
5836       --  If it is a nested return within an extended one, replace it with a
5837       --  return of the previously declared return object.
5838
5839       elsif Kind = E_Return_Statement then
5840          Rewrite (N,
5841            Make_Simple_Return_Statement (Loc,
5842              Expression =>
5843                New_Occurrence_Of (First_Entity (Scope_Id), Loc)));
5844          Set_Comes_From_Extended_Return_Statement (N);
5845          Set_Return_Statement_Entity (N, Scope_Id);
5846          Expand_Simple_Function_Return (N);
5847          return;
5848       end if;
5849
5850       pragma Assert (Is_Entry (Scope_Id));
5851
5852       --  Look at the enclosing block to see whether the return is from an
5853       --  accept statement or an entry body.
5854
5855       for J in reverse 0 .. Scope_Stack.Last loop
5856          Scope_Id := Scope_Stack.Table (J).Entity;
5857          exit when Is_Concurrent_Type (Scope_Id);
5858       end loop;
5859
5860       --  If it is a return from accept statement it is expanded as call to
5861       --  RTS Complete_Rendezvous and a goto to the end of the accept body.
5862
5863       --  (cf : Expand_N_Accept_Statement, Expand_N_Selective_Accept,
5864       --  Expand_N_Accept_Alternative in exp_ch9.adb)
5865
5866       if Is_Task_Type (Scope_Id) then
5867
5868          Call :=
5869            Make_Procedure_Call_Statement (Loc,
5870              Name => New_Reference_To (RTE (RE_Complete_Rendezvous), Loc));
5871          Insert_Before (N, Call);
5872          --  why not insert actions here???
5873          Analyze (Call);
5874
5875          Acc_Stat := Parent (N);
5876          while Nkind (Acc_Stat) /= N_Accept_Statement loop
5877             Acc_Stat := Parent (Acc_Stat);
5878          end loop;
5879
5880          Lab_Node := Last (Statements
5881            (Handled_Statement_Sequence (Acc_Stat)));
5882
5883          Goto_Stat := Make_Goto_Statement (Loc,
5884            Name => New_Occurrence_Of
5885              (Entity (Identifier (Lab_Node)), Loc));
5886
5887          Set_Analyzed (Goto_Stat);
5888
5889          Rewrite (N, Goto_Stat);
5890          Analyze (N);
5891
5892       --  If it is a return from an entry body, put a Complete_Entry_Body call
5893       --  in front of the return.
5894
5895       elsif Is_Protected_Type (Scope_Id) then
5896          Call :=
5897            Make_Procedure_Call_Statement (Loc,
5898              Name =>
5899                New_Reference_To (RTE (RE_Complete_Entry_Body), Loc),
5900              Parameter_Associations => New_List (
5901                Make_Attribute_Reference (Loc,
5902                  Prefix         =>
5903                    New_Reference_To
5904                      (Find_Protection_Object (Current_Scope), Loc),
5905                  Attribute_Name => Name_Unchecked_Access)));
5906
5907          Insert_Before (N, Call);
5908          Analyze (Call);
5909       end if;
5910    end Expand_Non_Function_Return;
5911
5912    ---------------------------------------
5913    -- Expand_Protected_Object_Reference --
5914    ---------------------------------------
5915
5916    function Expand_Protected_Object_Reference
5917      (N    : Node_Id;
5918       Scop : Entity_Id) return Node_Id
5919    is
5920       Loc   : constant Source_Ptr := Sloc (N);
5921       Corr  : Entity_Id;
5922       Rec   : Node_Id;
5923       Param : Entity_Id;
5924       Proc  : Entity_Id;
5925
5926    begin
5927       Rec := Make_Identifier (Loc, Name_uObject);
5928       Set_Etype (Rec, Corresponding_Record_Type (Scop));
5929
5930       --  Find enclosing protected operation, and retrieve its first parameter,
5931       --  which denotes the enclosing protected object. If the enclosing
5932       --  operation is an entry, we are immediately within the protected body,
5933       --  and we can retrieve the object from the service entries procedure. A
5934       --  barrier function has the same signature as an entry. A barrier
5935       --  function is compiled within the protected object, but unlike
5936       --  protected operations its never needs locks, so that its protected
5937       --  body subprogram points to itself.
5938
5939       Proc := Current_Scope;
5940       while Present (Proc)
5941         and then Scope (Proc) /= Scop
5942       loop
5943          Proc := Scope (Proc);
5944       end loop;
5945
5946       Corr := Protected_Body_Subprogram (Proc);
5947
5948       if No (Corr) then
5949
5950          --  Previous error left expansion incomplete.
5951          --  Nothing to do on this call.
5952
5953          return Empty;
5954       end if;
5955
5956       Param :=
5957         Defining_Identifier
5958           (First (Parameter_Specifications (Parent (Corr))));
5959
5960       if Is_Subprogram (Proc)
5961         and then Proc /= Corr
5962       then
5963          --  Protected function or procedure
5964
5965          Set_Entity (Rec, Param);
5966
5967          --  Rec is a reference to an entity which will not be in scope when
5968          --  the call is reanalyzed, and needs no further analysis.
5969
5970          Set_Analyzed (Rec);
5971
5972       else
5973          --  Entry or barrier function for entry body. The first parameter of
5974          --  the entry body procedure is pointer to the object. We create a
5975          --  local variable of the proper type, duplicating what is done to
5976          --  define _object later on.
5977
5978          declare
5979             Decls   : List_Id;
5980             Obj_Ptr : constant Entity_Id :=  Make_Temporary (Loc, 'T');
5981
5982          begin
5983             Decls := New_List (
5984               Make_Full_Type_Declaration (Loc,
5985                 Defining_Identifier => Obj_Ptr,
5986                   Type_Definition   =>
5987                      Make_Access_To_Object_Definition (Loc,
5988                        Subtype_Indication =>
5989                          New_Reference_To
5990                            (Corresponding_Record_Type (Scop), Loc))));
5991
5992             Insert_Actions (N, Decls);
5993             Freeze_Before (N, Obj_Ptr);
5994
5995             Rec :=
5996               Make_Explicit_Dereference (Loc,
5997                 Prefix =>
5998                   Unchecked_Convert_To (Obj_Ptr,
5999                     New_Occurrence_Of (Param, Loc)));
6000
6001             --  Analyze new actual. Other actuals in calls are already analyzed
6002             --  and the list of actuals is not reanalyzed after rewriting.
6003
6004             Set_Parent (Rec, N);
6005             Analyze (Rec);
6006          end;
6007       end if;
6008
6009       return Rec;
6010    end Expand_Protected_Object_Reference;
6011
6012    --------------------------------------
6013    -- Expand_Protected_Subprogram_Call --
6014    --------------------------------------
6015
6016    procedure Expand_Protected_Subprogram_Call
6017      (N    : Node_Id;
6018       Subp : Entity_Id;
6019       Scop : Entity_Id)
6020    is
6021       Rec   : Node_Id;
6022
6023    begin
6024       --  If the protected object is not an enclosing scope, this is an
6025       --  inter-object function call. Inter-object procedure calls are expanded
6026       --  by Exp_Ch9.Build_Simple_Entry_Call. The call is intra-object only if
6027       --  the subprogram being called is in the protected body being compiled,
6028       --  and if the protected object in the call is statically the enclosing
6029       --  type. The object may be an component of some other data structure, in
6030       --  which case this must be handled as an inter-object call.
6031
6032       if not In_Open_Scopes (Scop)
6033         or else not Is_Entity_Name (Name (N))
6034       then
6035          if Nkind (Name (N)) = N_Selected_Component then
6036             Rec := Prefix (Name (N));
6037
6038          else
6039             pragma Assert (Nkind (Name (N)) = N_Indexed_Component);
6040             Rec := Prefix (Prefix (Name (N)));
6041          end if;
6042
6043          Build_Protected_Subprogram_Call (N,
6044            Name     => New_Occurrence_Of (Subp, Sloc (N)),
6045            Rec      =>  Convert_Concurrent (Rec, Etype (Rec)),
6046            External => True);
6047
6048       else
6049          Rec := Expand_Protected_Object_Reference (N, Scop);
6050
6051          if No (Rec) then
6052             return;
6053          end if;
6054
6055          Build_Protected_Subprogram_Call (N,
6056            Name     => Name (N),
6057            Rec      => Rec,
6058            External => False);
6059
6060       end if;
6061
6062       --  If it is a function call it can appear in elaboration code and
6063       --  the called entity must be frozen here.
6064
6065       if Ekind (Subp) = E_Function then
6066          Freeze_Expression (Name (N));
6067       end if;
6068
6069       --  Analyze and resolve the new call. The actuals have already been
6070       --  resolved, but expansion of a function call will add extra actuals
6071       --  if needed. Analysis of a procedure call already includes resolution.
6072
6073       Analyze (N);
6074
6075       if Ekind (Subp) = E_Function then
6076          Resolve (N, Etype (Subp));
6077       end if;
6078    end Expand_Protected_Subprogram_Call;
6079
6080    -----------------------------------
6081    -- Expand_Simple_Function_Return --
6082    -----------------------------------
6083
6084    --  The "simple" comes from the syntax rule simple_return_statement.
6085    --  The semantics are not at all simple!
6086
6087    procedure Expand_Simple_Function_Return (N : Node_Id) is
6088       Loc : constant Source_Ptr := Sloc (N);
6089
6090       Scope_Id : constant Entity_Id :=
6091                    Return_Applies_To (Return_Statement_Entity (N));
6092       --  The function we are returning from
6093
6094       R_Type : constant Entity_Id := Etype (Scope_Id);
6095       --  The result type of the function
6096
6097       Utyp : constant Entity_Id := Underlying_Type (R_Type);
6098
6099       Exp : constant Node_Id := Expression (N);
6100       pragma Assert (Present (Exp));
6101
6102       Exptyp : constant Entity_Id := Etype (Exp);
6103       --  The type of the expression (not necessarily the same as R_Type)
6104
6105       Subtype_Ind : Node_Id;
6106       --  If the result type of the function is class-wide and the
6107       --  expression has a specific type, then we use the expression's
6108       --  type as the type of the return object. In cases where the
6109       --  expression is an aggregate that is built in place, this avoids
6110       --  the need for an expensive conversion of the return object to
6111       --  the specific type on assignments to the individual components.
6112
6113    begin
6114       if Is_Class_Wide_Type (R_Type)
6115         and then not Is_Class_Wide_Type (Etype (Exp))
6116       then
6117          Subtype_Ind := New_Occurrence_Of (Etype (Exp), Loc);
6118       else
6119          Subtype_Ind := New_Occurrence_Of (R_Type, Loc);
6120       end if;
6121
6122       --  For the case of a simple return that does not come from an extended
6123       --  return, in the case of Ada 2005 where we are returning a limited
6124       --  type, we rewrite "return <expression>;" to be:
6125
6126       --    return _anon_ : <return_subtype> := <expression>
6127
6128       --  The expansion produced by Expand_N_Extended_Return_Statement will
6129       --  contain simple return statements (for example, a block containing
6130       --  simple return of the return object), which brings us back here with
6131       --  Comes_From_Extended_Return_Statement set. The reason for the barrier
6132       --  checking for a simple return that does not come from an extended
6133       --  return is to avoid this infinite recursion.
6134
6135       --  The reason for this design is that for Ada 2005 limited returns, we
6136       --  need to reify the return object, so we can build it "in place", and
6137       --  we need a block statement to hang finalization and tasking stuff.
6138
6139       --  ??? In order to avoid disruption, we avoid translating to extended
6140       --  return except in the cases where we really need to (Ada 2005 for
6141       --  inherently limited). We might prefer to do this translation in all
6142       --  cases (except perhaps for the case of Ada 95 inherently limited),
6143       --  in order to fully exercise the Expand_N_Extended_Return_Statement
6144       --  code. This would also allow us to do the build-in-place optimization
6145       --  for efficiency even in cases where it is semantically not required.
6146
6147       --  As before, we check the type of the return expression rather than the
6148       --  return type of the function, because the latter may be a limited
6149       --  class-wide interface type, which is not a limited type, even though
6150       --  the type of the expression may be.
6151
6152       if not Comes_From_Extended_Return_Statement (N)
6153         and then Is_Immutably_Limited_Type (Etype (Expression (N)))
6154         and then Ada_Version >= Ada_2005
6155         and then not Debug_Flag_Dot_L
6156       then
6157          declare
6158             Return_Object_Entity : constant Entity_Id :=
6159                                      Make_Temporary (Loc, 'R', Exp);
6160             Obj_Decl : constant Node_Id :=
6161                          Make_Object_Declaration (Loc,
6162                            Defining_Identifier => Return_Object_Entity,
6163                            Object_Definition   => Subtype_Ind,
6164                            Expression          => Exp);
6165
6166             Ext : constant Node_Id := Make_Extended_Return_Statement (Loc,
6167                     Return_Object_Declarations => New_List (Obj_Decl));
6168             --  Do not perform this high-level optimization if the result type
6169             --  is an interface because the "this" pointer must be displaced.
6170
6171          begin
6172             Rewrite (N, Ext);
6173             Analyze (N);
6174             return;
6175          end;
6176       end if;
6177
6178       --  Here we have a simple return statement that is part of the expansion
6179       --  of an extended return statement (either written by the user, or
6180       --  generated by the above code).
6181
6182       --  Always normalize C/Fortran boolean result. This is not always needed,
6183       --  but it seems a good idea to minimize the passing around of non-
6184       --  normalized values, and in any case this handles the processing of
6185       --  barrier functions for protected types, which turn the condition into
6186       --  a return statement.
6187
6188       if Is_Boolean_Type (Exptyp)
6189         and then Nonzero_Is_True (Exptyp)
6190       then
6191          Adjust_Condition (Exp);
6192          Adjust_Result_Type (Exp, Exptyp);
6193       end if;
6194
6195       --  Do validity check if enabled for returns
6196
6197       if Validity_Checks_On
6198         and then Validity_Check_Returns
6199       then
6200          Ensure_Valid (Exp);
6201       end if;
6202
6203       --  Check the result expression of a scalar function against the subtype
6204       --  of the function by inserting a conversion. This conversion must
6205       --  eventually be performed for other classes of types, but for now it's
6206       --  only done for scalars.
6207       --  ???
6208
6209       if Is_Scalar_Type (Exptyp) then
6210          Rewrite (Exp, Convert_To (R_Type, Exp));
6211
6212          --  The expression is resolved to ensure that the conversion gets
6213          --  expanded to generate a possible constraint check.
6214
6215          Analyze_And_Resolve (Exp, R_Type);
6216       end if;
6217
6218       --  Deal with returning variable length objects and controlled types
6219
6220       --  Nothing to do if we are returning by reference, or this is not a
6221       --  type that requires special processing (indicated by the fact that
6222       --  it requires a cleanup scope for the secondary stack case).
6223
6224       if Is_Immutably_Limited_Type (Exptyp)
6225         or else Is_Limited_Interface (Exptyp)
6226       then
6227          null;
6228
6229       elsif not Requires_Transient_Scope (R_Type) then
6230
6231          --  Mutable records with no variable length components are not
6232          --  returned on the sec-stack, so we need to make sure that the
6233          --  backend will only copy back the size of the actual value, and not
6234          --  the maximum size. We create an actual subtype for this purpose.
6235
6236          declare
6237             Ubt  : constant Entity_Id := Underlying_Type (Base_Type (Exptyp));
6238             Decl : Node_Id;
6239             Ent  : Entity_Id;
6240          begin
6241             if Has_Discriminants (Ubt)
6242               and then not Is_Constrained (Ubt)
6243               and then not Has_Unchecked_Union (Ubt)
6244             then
6245                Decl := Build_Actual_Subtype (Ubt, Exp);
6246                Ent := Defining_Identifier (Decl);
6247                Insert_Action (Exp, Decl);
6248                Rewrite (Exp, Unchecked_Convert_To (Ent, Exp));
6249                Analyze_And_Resolve (Exp);
6250             end if;
6251          end;
6252
6253       --  Here if secondary stack is used
6254
6255       else
6256          --  Make sure that no surrounding block will reclaim the secondary
6257          --  stack on which we are going to put the result. Not only may this
6258          --  introduce secondary stack leaks but worse, if the reclamation is
6259          --  done too early, then the result we are returning may get
6260          --  clobbered.
6261
6262          declare
6263             S : Entity_Id;
6264          begin
6265             S := Current_Scope;
6266             while Ekind (S) = E_Block or else Ekind (S) = E_Loop loop
6267                Set_Sec_Stack_Needed_For_Return (S, True);
6268                S := Enclosing_Dynamic_Scope (S);
6269             end loop;
6270          end;
6271
6272          --  Optimize the case where the result is a function call. In this
6273          --  case either the result is already on the secondary stack, or is
6274          --  already being returned with the stack pointer depressed and no
6275          --  further processing is required except to set the By_Ref flag to
6276          --  ensure that gigi does not attempt an extra unnecessary copy.
6277          --  (actually not just unnecessary but harmfully wrong in the case
6278          --  of a controlled type, where gigi does not know how to do a copy).
6279          --  To make up for a gcc 2.8.1 deficiency (???), we perform
6280          --  the copy for array types if the constrained status of the
6281          --  target type is different from that of the expression.
6282
6283          if Requires_Transient_Scope (Exptyp)
6284            and then
6285               (not Is_Array_Type (Exptyp)
6286                 or else Is_Constrained (Exptyp) = Is_Constrained (R_Type)
6287                 or else CW_Or_Has_Controlled_Part (Utyp))
6288            and then Nkind (Exp) = N_Function_Call
6289          then
6290             Set_By_Ref (N);
6291
6292             --  Remove side effects from the expression now so that other parts
6293             --  of the expander do not have to reanalyze this node without this
6294             --  optimization
6295
6296             Rewrite (Exp, Duplicate_Subexpr_No_Checks (Exp));
6297
6298          --  For controlled types, do the allocation on the secondary stack
6299          --  manually in order to call adjust at the right time:
6300
6301          --    type Anon1 is access R_Type;
6302          --    for Anon1'Storage_pool use ss_pool;
6303          --    Anon2 : anon1 := new R_Type'(expr);
6304          --    return Anon2.all;
6305
6306          --  We do the same for classwide types that are not potentially
6307          --  controlled (by the virtue of restriction No_Finalization) because
6308          --  gigi is not able to properly allocate class-wide types.
6309
6310          elsif CW_Or_Has_Controlled_Part (Utyp) then
6311             declare
6312                Loc        : constant Source_Ptr := Sloc (N);
6313                Acc_Typ    : constant Entity_Id := Make_Temporary (Loc, 'A');
6314                Alloc_Node : Node_Id;
6315                Temp       : Entity_Id;
6316
6317             begin
6318                Set_Ekind (Acc_Typ, E_Access_Type);
6319
6320                Set_Associated_Storage_Pool (Acc_Typ, RTE (RE_SS_Pool));
6321
6322                --  This is an allocator for the secondary stack, and it's fine
6323                --  to have Comes_From_Source set False on it, as gigi knows not
6324                --  to flag it as a violation of No_Implicit_Heap_Allocations.
6325
6326                Alloc_Node :=
6327                  Make_Allocator (Loc,
6328                    Expression =>
6329                      Make_Qualified_Expression (Loc,
6330                        Subtype_Mark => New_Reference_To (Etype (Exp), Loc),
6331                        Expression   => Relocate_Node (Exp)));
6332
6333                --  We do not want discriminant checks on the declaration,
6334                --  given that it gets its value from the allocator.
6335
6336                Set_No_Initialization (Alloc_Node);
6337
6338                Temp := Make_Temporary (Loc, 'R', Alloc_Node);
6339
6340                Insert_List_Before_And_Analyze (N, New_List (
6341                  Make_Full_Type_Declaration (Loc,
6342                    Defining_Identifier => Acc_Typ,
6343                    Type_Definition     =>
6344                      Make_Access_To_Object_Definition (Loc,
6345                        Subtype_Indication => Subtype_Ind)),
6346
6347                  Make_Object_Declaration (Loc,
6348                    Defining_Identifier => Temp,
6349                    Object_Definition   => New_Reference_To (Acc_Typ, Loc),
6350                    Expression          => Alloc_Node)));
6351
6352                Rewrite (Exp,
6353                  Make_Explicit_Dereference (Loc,
6354                  Prefix => New_Reference_To (Temp, Loc)));
6355
6356                Analyze_And_Resolve (Exp, R_Type);
6357             end;
6358
6359          --  Otherwise use the gigi mechanism to allocate result on the
6360          --  secondary stack.
6361
6362          else
6363             Check_Restriction (No_Secondary_Stack, N);
6364             Set_Storage_Pool (N, RTE (RE_SS_Pool));
6365
6366             --  If we are generating code for the VM do not use
6367             --  SS_Allocate since everything is heap-allocated anyway.
6368
6369             if VM_Target = No_VM then
6370                Set_Procedure_To_Call (N, RTE (RE_SS_Allocate));
6371             end if;
6372          end if;
6373       end if;
6374
6375       --  Implement the rules of 6.5(8-10), which require a tag check in the
6376       --  case of a limited tagged return type, and tag reassignment for
6377       --  nonlimited tagged results. These actions are needed when the return
6378       --  type is a specific tagged type and the result expression is a
6379       --  conversion or a formal parameter, because in that case the tag of the
6380       --  expression might differ from the tag of the specific result type.
6381
6382       if Is_Tagged_Type (Utyp)
6383         and then not Is_Class_Wide_Type (Utyp)
6384         and then (Nkind_In (Exp, N_Type_Conversion,
6385                                  N_Unchecked_Type_Conversion)
6386                     or else (Is_Entity_Name (Exp)
6387                                and then Ekind (Entity (Exp)) in Formal_Kind))
6388       then
6389          --  When the return type is limited, perform a check that the
6390          --  tag of the result is the same as the tag of the return type.
6391
6392          if Is_Limited_Type (R_Type) then
6393             Insert_Action (Exp,
6394               Make_Raise_Constraint_Error (Loc,
6395                 Condition =>
6396                   Make_Op_Ne (Loc,
6397                     Left_Opnd  =>
6398                       Make_Selected_Component (Loc,
6399                         Prefix        => Duplicate_Subexpr (Exp),
6400                         Selector_Name => Make_Identifier (Loc, Name_uTag)),
6401                     Right_Opnd =>
6402                       Make_Attribute_Reference (Loc,
6403                         Prefix         =>
6404                           New_Occurrence_Of (Base_Type (Utyp), Loc),
6405                         Attribute_Name => Name_Tag)),
6406                 Reason    => CE_Tag_Check_Failed));
6407
6408          --  If the result type is a specific nonlimited tagged type, then we
6409          --  have to ensure that the tag of the result is that of the result
6410          --  type. This is handled by making a copy of the expression in the
6411          --  case where it might have a different tag, namely when the
6412          --  expression is a conversion or a formal parameter. We create a new
6413          --  object of the result type and initialize it from the expression,
6414          --  which will implicitly force the tag to be set appropriately.
6415
6416          else
6417             declare
6418                ExpR       : constant Node_Id   := Relocate_Node (Exp);
6419                Result_Id  : constant Entity_Id :=
6420                               Make_Temporary (Loc, 'R', ExpR);
6421                Result_Exp : constant Node_Id   :=
6422                               New_Reference_To (Result_Id, Loc);
6423                Result_Obj : constant Node_Id   :=
6424                               Make_Object_Declaration (Loc,
6425                                 Defining_Identifier => Result_Id,
6426                                 Object_Definition   =>
6427                                   New_Reference_To (R_Type, Loc),
6428                                 Constant_Present    => True,
6429                                 Expression          => ExpR);
6430
6431             begin
6432                Set_Assignment_OK (Result_Obj);
6433                Insert_Action (Exp, Result_Obj);
6434
6435                Rewrite (Exp, Result_Exp);
6436                Analyze_And_Resolve (Exp, R_Type);
6437             end;
6438          end if;
6439
6440       --  Ada 2005 (AI-344): If the result type is class-wide, then insert
6441       --  a check that the level of the return expression's underlying type
6442       --  is not deeper than the level of the master enclosing the function.
6443       --  Always generate the check when the type of the return expression
6444       --  is class-wide, when it's a type conversion, or when it's a formal
6445       --  parameter. Otherwise, suppress the check in the case where the
6446       --  return expression has a specific type whose level is known not to
6447       --  be statically deeper than the function's result type.
6448
6449       --  Note: accessibility check is skipped in the VM case, since there
6450       --  does not seem to be any practical way to implement this check.
6451
6452       elsif Ada_Version >= Ada_2005
6453         and then Tagged_Type_Expansion
6454         and then Is_Class_Wide_Type (R_Type)
6455         and then not Scope_Suppress (Accessibility_Check)
6456         and then
6457           (Is_Class_Wide_Type (Etype (Exp))
6458             or else Nkind_In (Exp, N_Type_Conversion,
6459                                    N_Unchecked_Type_Conversion)
6460             or else (Is_Entity_Name (Exp)
6461                       and then Ekind (Entity (Exp)) in Formal_Kind)
6462             or else Scope_Depth (Enclosing_Dynamic_Scope (Etype (Exp))) >
6463                       Scope_Depth (Enclosing_Dynamic_Scope (Scope_Id)))
6464       then
6465          declare
6466             Tag_Node : Node_Id;
6467
6468          begin
6469             --  Ada 2005 (AI-251): In class-wide interface objects we displace
6470             --  "this" to reference the base of the object --- required to get
6471             --  access to the TSD of the object.
6472
6473             if Is_Class_Wide_Type (Etype (Exp))
6474               and then Is_Interface (Etype (Exp))
6475               and then Nkind (Exp) = N_Explicit_Dereference
6476             then
6477                Tag_Node :=
6478                  Make_Explicit_Dereference (Loc,
6479                    Prefix =>
6480                      Unchecked_Convert_To (RTE (RE_Tag_Ptr),
6481                        Make_Function_Call (Loc,
6482                          Name                   =>
6483                            New_Reference_To (RTE (RE_Base_Address), Loc),
6484                          Parameter_Associations => New_List (
6485                            Unchecked_Convert_To (RTE (RE_Address),
6486                              Duplicate_Subexpr (Prefix (Exp)))))));
6487             else
6488                Tag_Node :=
6489                  Make_Attribute_Reference (Loc,
6490                    Prefix         => Duplicate_Subexpr (Exp),
6491                    Attribute_Name => Name_Tag);
6492             end if;
6493
6494             Insert_Action (Exp,
6495               Make_Raise_Program_Error (Loc,
6496                 Condition =>
6497                   Make_Op_Gt (Loc,
6498                     Left_Opnd  => Build_Get_Access_Level (Loc, Tag_Node),
6499                     Right_Opnd =>
6500                       Make_Integer_Literal (Loc,
6501                         Scope_Depth (Enclosing_Dynamic_Scope (Scope_Id)))),
6502                 Reason => PE_Accessibility_Check_Failed));
6503          end;
6504
6505       --  AI05-0073: If function has a controlling access result, check that
6506       --  the tag of the return value, if it is not null, matches designated
6507       --  type of return type.
6508       --  The return expression is referenced twice in the code below, so
6509       --  it must be made free of side effects. Given that different compilers
6510       --  may evaluate these parameters in different order, both occurrences
6511       --  perform a copy.
6512
6513       elsif Ekind (R_Type) = E_Anonymous_Access_Type
6514         and then Has_Controlling_Result (Scope_Id)
6515       then
6516          Insert_Action (N,
6517            Make_Raise_Constraint_Error (Loc,
6518              Condition =>
6519                Make_And_Then (Loc,
6520                  Left_Opnd  =>
6521                    Make_Op_Ne (Loc,
6522                      Left_Opnd  => Duplicate_Subexpr (Exp),
6523                      Right_Opnd => Make_Null (Loc)),
6524                  Right_Opnd => Make_Op_Ne (Loc,
6525                    Left_Opnd  =>
6526                      Make_Selected_Component (Loc,
6527                        Prefix        => Duplicate_Subexpr (Exp),
6528                        Selector_Name => Make_Identifier (Loc, Name_uTag)),
6529                    Right_Opnd =>
6530                      Make_Attribute_Reference (Loc,
6531                        Prefix         =>
6532                          New_Occurrence_Of (Designated_Type (R_Type), Loc),
6533                        Attribute_Name => Name_Tag))),
6534              Reason    => CE_Tag_Check_Failed),
6535              Suppress  => All_Checks);
6536       end if;
6537
6538       --  If we are returning an object that may not be bit-aligned, then copy
6539       --  the value into a temporary first. This copy may need to expand to a
6540       --  loop of component operations.
6541
6542       if Is_Possibly_Unaligned_Slice (Exp)
6543         or else Is_Possibly_Unaligned_Object (Exp)
6544       then
6545          declare
6546             ExpR : constant Node_Id   := Relocate_Node (Exp);
6547             Tnn  : constant Entity_Id := Make_Temporary (Loc, 'T', ExpR);
6548          begin
6549             Insert_Action (Exp,
6550               Make_Object_Declaration (Loc,
6551                 Defining_Identifier => Tnn,
6552                 Constant_Present    => True,
6553                 Object_Definition   => New_Occurrence_Of (R_Type, Loc),
6554                 Expression          => ExpR),
6555               Suppress => All_Checks);
6556             Rewrite (Exp, New_Occurrence_Of (Tnn, Loc));
6557          end;
6558       end if;
6559
6560       --  Generate call to postcondition checks if they are present
6561
6562       if Ekind (Scope_Id) = E_Function
6563         and then Has_Postconditions (Scope_Id)
6564       then
6565          --  We are going to reference the returned value twice in this case,
6566          --  once in the call to _Postconditions, and once in the actual return
6567          --  statement, but we can't have side effects happening twice, and in
6568          --  any case for efficiency we don't want to do the computation twice.
6569
6570          --  If the returned expression is an entity name, we don't need to
6571          --  worry since it is efficient and safe to reference it twice, that's
6572          --  also true for literals other than string literals, and for the
6573          --  case of X.all where X is an entity name.
6574
6575          if Is_Entity_Name (Exp)
6576            or else Nkind_In (Exp, N_Character_Literal,
6577                                   N_Integer_Literal,
6578                                   N_Real_Literal)
6579            or else (Nkind (Exp) = N_Explicit_Dereference
6580                      and then Is_Entity_Name (Prefix (Exp)))
6581          then
6582             null;
6583
6584          --  Otherwise we are going to need a temporary to capture the value
6585
6586          else
6587             declare
6588                ExpR : constant Node_Id   := Relocate_Node (Exp);
6589                Tnn  : constant Entity_Id := Make_Temporary (Loc, 'T', ExpR);
6590
6591             begin
6592                --  For a complex expression of an elementary type, capture
6593                --  value in the temporary and use it as the reference.
6594
6595                if Is_Elementary_Type (R_Type) then
6596                   Insert_Action (Exp,
6597                     Make_Object_Declaration (Loc,
6598                       Defining_Identifier => Tnn,
6599                       Constant_Present    => True,
6600                       Object_Definition   => New_Occurrence_Of (R_Type, Loc),
6601                       Expression          => ExpR),
6602                     Suppress => All_Checks);
6603
6604                   Rewrite (Exp, New_Occurrence_Of (Tnn, Loc));
6605
6606                --  If we have something we can rename, generate a renaming of
6607                --  the object and replace the expression with a reference
6608
6609                elsif Is_Object_Reference (Exp) then
6610                   Insert_Action (Exp,
6611                     Make_Object_Renaming_Declaration (Loc,
6612                       Defining_Identifier => Tnn,
6613                       Subtype_Mark        => New_Occurrence_Of (R_Type, Loc),
6614                       Name                => ExpR),
6615                     Suppress => All_Checks);
6616
6617                   Rewrite (Exp, New_Occurrence_Of (Tnn, Loc));
6618
6619                --  Otherwise we have something like a string literal or an
6620                --  aggregate. We could copy the value, but that would be
6621                --  inefficient. Instead we make a reference to the value and
6622                --  capture this reference with a renaming, the expression is
6623                --  then replaced by a dereference of this renaming.
6624
6625                else
6626                   --  For now, copy the value, since the code below does not
6627                   --  seem to work correctly ???
6628
6629                   Insert_Action (Exp,
6630                     Make_Object_Declaration (Loc,
6631                       Defining_Identifier => Tnn,
6632                       Constant_Present    => True,
6633                       Object_Definition   => New_Occurrence_Of (R_Type, Loc),
6634                       Expression          => Relocate_Node (Exp)),
6635                     Suppress => All_Checks);
6636
6637                   Rewrite (Exp, New_Occurrence_Of (Tnn, Loc));
6638
6639                   --  Insert_Action (Exp,
6640                   --    Make_Object_Renaming_Declaration (Loc,
6641                   --      Defining_Identifier => Tnn,
6642                   --      Access_Definition =>
6643                   --        Make_Access_Definition (Loc,
6644                   --          All_Present  => True,
6645                   --          Subtype_Mark => New_Occurrence_Of (R_Type, Loc)),
6646                   --      Name =>
6647                   --        Make_Reference (Loc,
6648                   --          Prefix => Relocate_Node (Exp))),
6649                   --    Suppress => All_Checks);
6650
6651                   --  Rewrite (Exp,
6652                   --    Make_Explicit_Dereference (Loc,
6653                   --      Prefix => New_Occurrence_Of (Tnn, Loc)));
6654                end if;
6655             end;
6656          end if;
6657
6658          --  Generate call to _postconditions
6659
6660          Insert_Action (Exp,
6661            Make_Procedure_Call_Statement (Loc,
6662              Name => Make_Identifier (Loc, Name_uPostconditions),
6663              Parameter_Associations => New_List (Duplicate_Subexpr (Exp))));
6664       end if;
6665
6666       --  Ada 2005 (AI-251): If this return statement corresponds with an
6667       --  simple return statement associated with an extended return statement
6668       --  and the type of the returned object is an interface then generate an
6669       --  implicit conversion to force displacement of the "this" pointer.
6670
6671       if Ada_Version >= Ada_2005
6672         and then Comes_From_Extended_Return_Statement (N)
6673         and then Nkind (Expression (N)) = N_Identifier
6674         and then Is_Interface (Utyp)
6675         and then Utyp /= Underlying_Type (Exptyp)
6676       then
6677          Rewrite (Exp, Convert_To (Utyp, Relocate_Node (Exp)));
6678          Analyze_And_Resolve (Exp);
6679       end if;
6680    end Expand_Simple_Function_Return;
6681
6682    --------------------------------
6683    -- Is_Build_In_Place_Function --
6684    --------------------------------
6685
6686    function Is_Build_In_Place_Function (E : Entity_Id) return Boolean is
6687    begin
6688       --  This function is called from Expand_Subtype_From_Expr during
6689       --  semantic analysis, even when expansion is off. In those cases
6690       --  the build_in_place expansion will not take place.
6691
6692       if not Expander_Active then
6693          return False;
6694       end if;
6695
6696       --  For now we test whether E denotes a function or access-to-function
6697       --  type whose result subtype is inherently limited. Later this test may
6698       --  be revised to allow composite nonlimited types. Functions with a
6699       --  foreign convention or whose result type has a foreign convention
6700       --  never qualify.
6701
6702       if Ekind_In (E, E_Function, E_Generic_Function)
6703         or else (Ekind (E) = E_Subprogram_Type
6704                   and then Etype (E) /= Standard_Void_Type)
6705       then
6706          --  Note: If you have Convention (C) on an inherently limited type,
6707          --  you're on your own. That is, the C code will have to be carefully
6708          --  written to know about the Ada conventions.
6709
6710          if Has_Foreign_Convention (E)
6711            or else Has_Foreign_Convention (Etype (E))
6712          then
6713             return False;
6714
6715          --  In Ada 2005 all functions with an inherently limited return type
6716          --  must be handled using a build-in-place profile, including the case
6717          --  of a function with a limited interface result, where the function
6718          --  may return objects of nonlimited descendants.
6719
6720          else
6721             return Is_Immutably_Limited_Type (Etype (E))
6722               and then Ada_Version >= Ada_2005
6723               and then not Debug_Flag_Dot_L;
6724          end if;
6725
6726       else
6727          return False;
6728       end if;
6729    end Is_Build_In_Place_Function;
6730
6731    -------------------------------------
6732    -- Is_Build_In_Place_Function_Call --
6733    -------------------------------------
6734
6735    function Is_Build_In_Place_Function_Call (N : Node_Id) return Boolean is
6736       Exp_Node    : Node_Id := N;
6737       Function_Id : Entity_Id;
6738
6739    begin
6740       --  Step past qualification or unchecked conversion (the latter can occur
6741       --  in cases of calls to 'Input).
6742
6743       if Nkind_In
6744            (Exp_Node, N_Qualified_Expression, N_Unchecked_Type_Conversion)
6745       then
6746          Exp_Node := Expression (N);
6747       end if;
6748
6749       if Nkind (Exp_Node) /= N_Function_Call then
6750          return False;
6751
6752       else
6753          if Is_Entity_Name (Name (Exp_Node)) then
6754             Function_Id := Entity (Name (Exp_Node));
6755
6756          elsif Nkind (Name (Exp_Node)) = N_Explicit_Dereference then
6757             Function_Id := Etype (Name (Exp_Node));
6758          end if;
6759
6760          return Is_Build_In_Place_Function (Function_Id);
6761       end if;
6762    end Is_Build_In_Place_Function_Call;
6763
6764    -----------------------
6765    -- Freeze_Subprogram --
6766    -----------------------
6767
6768    procedure Freeze_Subprogram (N : Node_Id) is
6769       Loc : constant Source_Ptr := Sloc (N);
6770
6771       procedure Register_Predefined_DT_Entry (Prim : Entity_Id);
6772       --  (Ada 2005): Register a predefined primitive in all the secondary
6773       --  dispatch tables of its primitive type.
6774
6775       ----------------------------------
6776       -- Register_Predefined_DT_Entry --
6777       ----------------------------------
6778
6779       procedure Register_Predefined_DT_Entry (Prim : Entity_Id) is
6780          Iface_DT_Ptr : Elmt_Id;
6781          Tagged_Typ   : Entity_Id;
6782          Thunk_Id     : Entity_Id;
6783          Thunk_Code   : Node_Id;
6784
6785       begin
6786          Tagged_Typ := Find_Dispatching_Type (Prim);
6787
6788          if No (Access_Disp_Table (Tagged_Typ))
6789            or else not Has_Interfaces (Tagged_Typ)
6790            or else not RTE_Available (RE_Interface_Tag)
6791            or else Restriction_Active (No_Dispatching_Calls)
6792          then
6793             return;
6794          end if;
6795
6796          --  Skip the first two access-to-dispatch-table pointers since they
6797          --  leads to the primary dispatch table (predefined DT and user
6798          --  defined DT). We are only concerned with the secondary dispatch
6799          --  table pointers. Note that the access-to- dispatch-table pointer
6800          --  corresponds to the first implemented interface retrieved below.
6801
6802          Iface_DT_Ptr :=
6803            Next_Elmt (Next_Elmt (First_Elmt (Access_Disp_Table (Tagged_Typ))));
6804
6805          while Present (Iface_DT_Ptr)
6806            and then Ekind (Node (Iface_DT_Ptr)) = E_Constant
6807          loop
6808             pragma Assert (Has_Thunks (Node (Iface_DT_Ptr)));
6809             Expand_Interface_Thunk (Prim, Thunk_Id, Thunk_Code);
6810
6811             if Present (Thunk_Code) then
6812                Insert_Actions_After (N, New_List (
6813                  Thunk_Code,
6814
6815                  Build_Set_Predefined_Prim_Op_Address (Loc,
6816                    Tag_Node =>
6817                      New_Reference_To (Node (Next_Elmt (Iface_DT_Ptr)), Loc),
6818                    Position => DT_Position (Prim),
6819                    Address_Node =>
6820                      Unchecked_Convert_To (RTE (RE_Prim_Ptr),
6821                        Make_Attribute_Reference (Loc,
6822                          Prefix         => New_Reference_To (Thunk_Id, Loc),
6823                          Attribute_Name => Name_Unrestricted_Access))),
6824
6825                  Build_Set_Predefined_Prim_Op_Address (Loc,
6826                    Tag_Node =>
6827                      New_Reference_To
6828                       (Node (Next_Elmt (Next_Elmt (Next_Elmt (Iface_DT_Ptr)))),
6829                        Loc),
6830                    Position => DT_Position (Prim),
6831                    Address_Node =>
6832                      Unchecked_Convert_To (RTE (RE_Prim_Ptr),
6833                        Make_Attribute_Reference (Loc,
6834                          Prefix         => New_Reference_To (Prim, Loc),
6835                          Attribute_Name => Name_Unrestricted_Access)))));
6836             end if;
6837
6838             --  Skip the tag of the predefined primitives dispatch table
6839
6840             Next_Elmt (Iface_DT_Ptr);
6841             pragma Assert (Has_Thunks (Node (Iface_DT_Ptr)));
6842
6843             --  Skip the tag of the no-thunks dispatch table
6844
6845             Next_Elmt (Iface_DT_Ptr);
6846             pragma Assert (not Has_Thunks (Node (Iface_DT_Ptr)));
6847
6848             --  Skip the tag of the predefined primitives no-thunks dispatch
6849             --  table.
6850
6851             Next_Elmt (Iface_DT_Ptr);
6852             pragma Assert (not Has_Thunks (Node (Iface_DT_Ptr)));
6853
6854             Next_Elmt (Iface_DT_Ptr);
6855          end loop;
6856       end Register_Predefined_DT_Entry;
6857
6858       --  Local variables
6859
6860       Subp : constant Entity_Id  := Entity (N);
6861
6862    --  Start of processing for Freeze_Subprogram
6863
6864    begin
6865       --  We suppress the initialization of the dispatch table entry when
6866       --  VM_Target because the dispatching mechanism is handled internally
6867       --  by the VM.
6868
6869       if Is_Dispatching_Operation (Subp)
6870         and then not Is_Abstract_Subprogram (Subp)
6871         and then Present (DTC_Entity (Subp))
6872         and then Present (Scope (DTC_Entity (Subp)))
6873         and then Tagged_Type_Expansion
6874         and then not Restriction_Active (No_Dispatching_Calls)
6875         and then RTE_Available (RE_Tag)
6876       then
6877          declare
6878             Typ : constant Entity_Id := Scope (DTC_Entity (Subp));
6879
6880          begin
6881             --  Handle private overridden primitives
6882
6883             if not Is_CPP_Class (Typ) then
6884                Check_Overriding_Operation (Subp);
6885             end if;
6886
6887             --  We assume that imported CPP primitives correspond with objects
6888             --  whose constructor is in the CPP side; therefore we don't need
6889             --  to generate code to register them in the dispatch table.
6890
6891             if Is_CPP_Class (Typ) then
6892                null;
6893
6894             --  Handle CPP primitives found in derivations of CPP_Class types.
6895             --  These primitives must have been inherited from some parent, and
6896             --  there is no need to register them in the dispatch table because
6897             --  Build_Inherit_Prims takes care of the initialization of these
6898             --  slots.
6899
6900             elsif Is_Imported (Subp)
6901                     and then (Convention (Subp) = Convention_CPP
6902                                 or else Convention (Subp) = Convention_C)
6903             then
6904                null;
6905
6906             --  Generate code to register the primitive in non statically
6907             --  allocated dispatch tables
6908
6909             elsif not Building_Static_DT (Scope (DTC_Entity (Subp))) then
6910
6911                --  When a primitive is frozen, enter its name in its dispatch
6912                --  table slot.
6913
6914                if not Is_Interface (Typ)
6915                  or else Present (Interface_Alias (Subp))
6916                then
6917                   if Is_Predefined_Dispatching_Operation (Subp) then
6918                      Register_Predefined_DT_Entry (Subp);
6919                   end if;
6920
6921                   Insert_Actions_After (N,
6922                     Register_Primitive (Loc, Prim => Subp));
6923                end if;
6924             end if;
6925          end;
6926       end if;
6927
6928       --  Mark functions that return by reference. Note that it cannot be part
6929       --  of the normal semantic analysis of the spec since the underlying
6930       --  returned type may not be known yet (for private types).
6931
6932       declare
6933          Typ  : constant Entity_Id := Etype (Subp);
6934          Utyp : constant Entity_Id := Underlying_Type (Typ);
6935       begin
6936          if Is_Immutably_Limited_Type (Typ) then
6937             Set_Returns_By_Ref (Subp);
6938          elsif Present (Utyp) and then CW_Or_Has_Controlled_Part (Utyp) then
6939             Set_Returns_By_Ref (Subp);
6940          end if;
6941       end;
6942    end Freeze_Subprogram;
6943
6944    -----------------------
6945    -- Is_Null_Procedure --
6946    -----------------------
6947
6948    function Is_Null_Procedure (Subp : Entity_Id) return Boolean is
6949       Decl : constant Node_Id := Unit_Declaration_Node (Subp);
6950
6951    begin
6952       if Ekind (Subp) /= E_Procedure then
6953          return False;
6954
6955       --  Check if this is a declared null procedure
6956
6957       elsif Nkind (Decl) = N_Subprogram_Declaration then
6958          if not Null_Present (Specification (Decl)) then
6959             return False;
6960
6961          elsif No (Body_To_Inline (Decl)) then
6962             return False;
6963
6964          --  Check if the body contains only a null statement, followed by
6965          --  the return statement added during expansion.
6966
6967          else
6968             declare
6969                Orig_Bod : constant Node_Id := Body_To_Inline (Decl);
6970
6971                Stat  : Node_Id;
6972                Stat2 : Node_Id;
6973
6974             begin
6975                if Nkind (Orig_Bod) /= N_Subprogram_Body then
6976                   return False;
6977                else
6978                   --  We must skip SCIL nodes because they are currently
6979                   --  implemented as special N_Null_Statement nodes.
6980
6981                   Stat :=
6982                      First_Non_SCIL_Node
6983                        (Statements (Handled_Statement_Sequence (Orig_Bod)));
6984                   Stat2 := Next_Non_SCIL_Node (Stat);
6985
6986                   return
6987                      Is_Empty_List (Declarations (Orig_Bod))
6988                        and then Nkind (Stat) = N_Null_Statement
6989                        and then
6990                         (No (Stat2)
6991                           or else
6992                             (Nkind (Stat2) = N_Simple_Return_Statement
6993                               and then No (Next (Stat2))));
6994                end if;
6995             end;
6996          end if;
6997
6998       else
6999          return False;
7000       end if;
7001    end Is_Null_Procedure;
7002
7003    -------------------------------------------
7004    -- Make_Build_In_Place_Call_In_Allocator --
7005    -------------------------------------------
7006
7007    procedure Make_Build_In_Place_Call_In_Allocator
7008      (Allocator     : Node_Id;
7009       Function_Call : Node_Id)
7010    is
7011       Loc               : Source_Ptr;
7012       Func_Call         : Node_Id := Function_Call;
7013       Function_Id       : Entity_Id;
7014       Result_Subt       : Entity_Id;
7015       Acc_Type          : constant Entity_Id := Etype (Allocator);
7016       New_Allocator     : Node_Id;
7017       Return_Obj_Access : Entity_Id;
7018
7019    begin
7020       --  Step past qualification or unchecked conversion (the latter can occur
7021       --  in cases of calls to 'Input).
7022
7023       if Nkind_In (Func_Call,
7024                    N_Qualified_Expression,
7025                    N_Unchecked_Type_Conversion)
7026       then
7027          Func_Call := Expression (Func_Call);
7028       end if;
7029
7030       --  If the call has already been processed to add build-in-place actuals
7031       --  then return. This should not normally occur in an allocator context,
7032       --  but we add the protection as a defensive measure.
7033
7034       if Is_Expanded_Build_In_Place_Call (Func_Call) then
7035          return;
7036       end if;
7037
7038       --  Mark the call as processed as a build-in-place call
7039
7040       Set_Is_Expanded_Build_In_Place_Call (Func_Call);
7041
7042       Loc := Sloc (Function_Call);
7043
7044       if Is_Entity_Name (Name (Func_Call)) then
7045          Function_Id := Entity (Name (Func_Call));
7046
7047       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
7048          Function_Id := Etype (Name (Func_Call));
7049
7050       else
7051          raise Program_Error;
7052       end if;
7053
7054       Result_Subt := Etype (Function_Id);
7055
7056       --  When the result subtype is constrained, the return object must be
7057       --  allocated on the caller side, and access to it is passed to the
7058       --  function.
7059
7060       --  Here and in related routines, we must examine the full view of the
7061       --  type, because the view at the point of call may differ from that
7062       --  that in the function body, and the expansion mechanism depends on
7063       --  the characteristics of the full view.
7064
7065       if Is_Constrained (Underlying_Type (Result_Subt)) then
7066
7067          --  Replace the initialized allocator of form "new T'(Func (...))"
7068          --  with an uninitialized allocator of form "new T", where T is the
7069          --  result subtype of the called function. The call to the function
7070          --  is handled separately further below.
7071
7072          New_Allocator :=
7073            Make_Allocator (Loc,
7074              Expression => New_Reference_To (Result_Subt, Loc));
7075          Set_No_Initialization (New_Allocator);
7076
7077          --  Copy attributes to new allocator. Note that the new allocator
7078          --  logically comes from source if the original one did, so copy the
7079          --  relevant flag. This ensures proper treatment of the restriction
7080          --  No_Implicit_Heap_Allocations in this case.
7081
7082          Set_Storage_Pool      (New_Allocator, Storage_Pool      (Allocator));
7083          Set_Procedure_To_Call (New_Allocator, Procedure_To_Call (Allocator));
7084          Set_Comes_From_Source (New_Allocator, Comes_From_Source (Allocator));
7085
7086          Rewrite (Allocator, New_Allocator);
7087
7088          --  Create a new access object and initialize it to the result of the
7089          --  new uninitialized allocator. Note: we do not use Allocator as the
7090          --  Related_Node of Return_Obj_Access in call to Make_Temporary below
7091          --  as this would create a sort of infinite "recursion".
7092
7093          Return_Obj_Access := Make_Temporary (Loc, 'R');
7094          Set_Etype (Return_Obj_Access, Acc_Type);
7095
7096          Insert_Action (Allocator,
7097            Make_Object_Declaration (Loc,
7098              Defining_Identifier => Return_Obj_Access,
7099              Object_Definition   => New_Reference_To (Acc_Type, Loc),
7100              Expression          => Relocate_Node (Allocator)));
7101
7102          --  When the function has a controlling result, an allocation-form
7103          --  parameter must be passed indicating that the caller is allocating
7104          --  the result object. This is needed because such a function can be
7105          --  called as a dispatching operation and must be treated similarly
7106          --  to functions with unconstrained result subtypes.
7107
7108          Add_Alloc_Form_Actual_To_Build_In_Place_Call
7109            (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
7110
7111          Add_Finalization_Master_Actual_To_Build_In_Place_Call
7112            (Func_Call, Function_Id, Acc_Type);
7113
7114          Add_Task_Actuals_To_Build_In_Place_Call
7115            (Func_Call, Function_Id, Master_Actual => Master_Id (Acc_Type));
7116
7117          --  Add an implicit actual to the function call that provides access
7118          --  to the allocated object. An unchecked conversion to the (specific)
7119          --  result subtype of the function is inserted to handle cases where
7120          --  the access type of the allocator has a class-wide designated type.
7121
7122          Add_Access_Actual_To_Build_In_Place_Call
7123            (Func_Call,
7124             Function_Id,
7125             Make_Unchecked_Type_Conversion (Loc,
7126               Subtype_Mark => New_Reference_To (Result_Subt, Loc),
7127               Expression   =>
7128                 Make_Explicit_Dereference (Loc,
7129                   Prefix => New_Reference_To (Return_Obj_Access, Loc))));
7130
7131       --  When the result subtype is unconstrained, the function itself must
7132       --  perform the allocation of the return object, so we pass parameters
7133       --  indicating that. We don't yet handle the case where the allocation
7134       --  must be done in a user-defined storage pool, which will require
7135       --  passing another actual or two to provide allocation/deallocation
7136       --  operations. ???
7137
7138       else
7139          --  Pass an allocation parameter indicating that the function should
7140          --  allocate its result on the heap.
7141
7142          Add_Alloc_Form_Actual_To_Build_In_Place_Call
7143            (Func_Call, Function_Id, Alloc_Form => Global_Heap);
7144
7145          Add_Finalization_Master_Actual_To_Build_In_Place_Call
7146            (Func_Call, Function_Id, Acc_Type);
7147
7148          Add_Task_Actuals_To_Build_In_Place_Call
7149            (Func_Call, Function_Id, Master_Actual => Master_Id (Acc_Type));
7150
7151          --  The caller does not provide the return object in this case, so we
7152          --  have to pass null for the object access actual.
7153
7154          Add_Access_Actual_To_Build_In_Place_Call
7155            (Func_Call, Function_Id, Return_Object => Empty);
7156       end if;
7157
7158       --  Finally, replace the allocator node with a reference to the result
7159       --  of the function call itself (which will effectively be an access
7160       --  to the object created by the allocator).
7161
7162       Rewrite (Allocator, Make_Reference (Loc, Relocate_Node (Function_Call)));
7163       Analyze_And_Resolve (Allocator, Acc_Type);
7164    end Make_Build_In_Place_Call_In_Allocator;
7165
7166    ---------------------------------------------------
7167    -- Make_Build_In_Place_Call_In_Anonymous_Context --
7168    ---------------------------------------------------
7169
7170    procedure Make_Build_In_Place_Call_In_Anonymous_Context
7171      (Function_Call : Node_Id)
7172    is
7173       Loc             : Source_Ptr;
7174       Func_Call       : Node_Id := Function_Call;
7175       Function_Id     : Entity_Id;
7176       Result_Subt     : Entity_Id;
7177       Return_Obj_Id   : Entity_Id;
7178       Return_Obj_Decl : Entity_Id;
7179
7180    begin
7181       --  Step past qualification or unchecked conversion (the latter can occur
7182       --  in cases of calls to 'Input).
7183
7184       if Nkind_In (Func_Call, N_Qualified_Expression,
7185                               N_Unchecked_Type_Conversion)
7186       then
7187          Func_Call := Expression (Func_Call);
7188       end if;
7189
7190       --  If the call has already been processed to add build-in-place actuals
7191       --  then return. One place this can occur is for calls to build-in-place
7192       --  functions that occur within a call to a protected operation, where
7193       --  due to rewriting and expansion of the protected call there can be
7194       --  more than one call to Expand_Actuals for the same set of actuals.
7195
7196       if Is_Expanded_Build_In_Place_Call (Func_Call) then
7197          return;
7198       end if;
7199
7200       --  Mark the call as processed as a build-in-place call
7201
7202       Set_Is_Expanded_Build_In_Place_Call (Func_Call);
7203
7204       Loc := Sloc (Function_Call);
7205
7206       if Is_Entity_Name (Name (Func_Call)) then
7207          Function_Id := Entity (Name (Func_Call));
7208
7209       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
7210          Function_Id := Etype (Name (Func_Call));
7211
7212       else
7213          raise Program_Error;
7214       end if;
7215
7216       Result_Subt := Etype (Function_Id);
7217
7218       --  If the build-in-place function returns a controlled object, then the
7219       --  object needs to be finalized immediately after the context. Since
7220       --  this case produces a transient scope, the servicing finalizer needs
7221       --  to name the returned object. Create a temporary which is initialized
7222       --  with the function call:
7223       --
7224       --    Temp_Id : Func_Type := BIP_Func_Call;
7225       --
7226       --  The initialization expression of the temporary will be rewritten by
7227       --  the expander using the appropriate mechanism in Make_Build_In_Place_
7228       --  Call_In_Object_Declaration.
7229
7230       if Needs_Finalization (Result_Subt) then
7231          declare
7232             Temp_Id   : constant Entity_Id := Make_Temporary (Loc, 'R');
7233             Temp_Decl : Node_Id;
7234
7235          begin
7236             --  Reset the guard on the function call since the following does
7237             --  not perform actual call expansion.
7238
7239             Set_Is_Expanded_Build_In_Place_Call (Func_Call, False);
7240
7241             Temp_Decl :=
7242               Make_Object_Declaration (Loc,
7243                 Defining_Identifier => Temp_Id,
7244                 Object_Definition =>
7245                   New_Reference_To (Result_Subt, Loc),
7246                 Expression =>
7247                   New_Copy_Tree (Function_Call));
7248
7249             Insert_Action (Function_Call, Temp_Decl);
7250
7251             Rewrite (Function_Call, New_Reference_To (Temp_Id, Loc));
7252             Analyze (Function_Call);
7253          end;
7254
7255       --  When the result subtype is constrained, an object of the subtype is
7256       --  declared and an access value designating it is passed as an actual.
7257
7258       elsif Is_Constrained (Underlying_Type (Result_Subt)) then
7259
7260          --  Create a temporary object to hold the function result
7261
7262          Return_Obj_Id := Make_Temporary (Loc, 'R');
7263          Set_Etype (Return_Obj_Id, Result_Subt);
7264
7265          Return_Obj_Decl :=
7266            Make_Object_Declaration (Loc,
7267              Defining_Identifier => Return_Obj_Id,
7268              Aliased_Present     => True,
7269              Object_Definition   => New_Reference_To (Result_Subt, Loc));
7270
7271          Set_No_Initialization (Return_Obj_Decl);
7272
7273          Insert_Action (Func_Call, Return_Obj_Decl);
7274
7275          --  When the function has a controlling result, an allocation-form
7276          --  parameter must be passed indicating that the caller is allocating
7277          --  the result object. This is needed because such a function can be
7278          --  called as a dispatching operation and must be treated similarly
7279          --  to functions with unconstrained result subtypes.
7280
7281          Add_Alloc_Form_Actual_To_Build_In_Place_Call
7282            (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
7283
7284          Add_Finalization_Master_Actual_To_Build_In_Place_Call
7285            (Func_Call, Function_Id);
7286
7287          Add_Task_Actuals_To_Build_In_Place_Call
7288            (Func_Call, Function_Id, Make_Identifier (Loc, Name_uMaster));
7289
7290          --  Add an implicit actual to the function call that provides access
7291          --  to the caller's return object.
7292
7293          Add_Access_Actual_To_Build_In_Place_Call
7294            (Func_Call, Function_Id, New_Reference_To (Return_Obj_Id, Loc));
7295
7296       --  When the result subtype is unconstrained, the function must allocate
7297       --  the return object in the secondary stack, so appropriate implicit
7298       --  parameters are added to the call to indicate that. A transient
7299       --  scope is established to ensure eventual cleanup of the result.
7300
7301       else
7302          --  Pass an allocation parameter indicating that the function should
7303          --  allocate its result on the secondary stack.
7304
7305          Add_Alloc_Form_Actual_To_Build_In_Place_Call
7306            (Func_Call, Function_Id, Alloc_Form => Secondary_Stack);
7307
7308          Add_Finalization_Master_Actual_To_Build_In_Place_Call
7309            (Func_Call, Function_Id);
7310
7311          Add_Task_Actuals_To_Build_In_Place_Call
7312            (Func_Call, Function_Id, Make_Identifier (Loc, Name_uMaster));
7313
7314          --  Pass a null value to the function since no return object is
7315          --  available on the caller side.
7316
7317          Add_Access_Actual_To_Build_In_Place_Call
7318            (Func_Call, Function_Id, Empty);
7319       end if;
7320    end Make_Build_In_Place_Call_In_Anonymous_Context;
7321
7322    --------------------------------------------
7323    -- Make_Build_In_Place_Call_In_Assignment --
7324    --------------------------------------------
7325
7326    procedure Make_Build_In_Place_Call_In_Assignment
7327      (Assign        : Node_Id;
7328       Function_Call : Node_Id)
7329    is
7330       Lhs          : constant Node_Id := Name (Assign);
7331       Func_Call    : Node_Id := Function_Call;
7332       Func_Id      : Entity_Id;
7333       Loc          : Source_Ptr;
7334       Obj_Decl     : Node_Id;
7335       Obj_Id       : Entity_Id;
7336       Ptr_Typ      : Entity_Id;
7337       Ptr_Typ_Decl : Node_Id;
7338       Result_Subt  : Entity_Id;
7339       Target       : Node_Id;
7340
7341    begin
7342       --  Step past qualification or unchecked conversion (the latter can occur
7343       --  in cases of calls to 'Input).
7344
7345       if Nkind_In (Func_Call, N_Qualified_Expression,
7346                               N_Unchecked_Type_Conversion)
7347       then
7348          Func_Call := Expression (Func_Call);
7349       end if;
7350
7351       --  If the call has already been processed to add build-in-place actuals
7352       --  then return. This should not normally occur in an assignment context,
7353       --  but we add the protection as a defensive measure.
7354
7355       if Is_Expanded_Build_In_Place_Call (Func_Call) then
7356          return;
7357       end if;
7358
7359       --  Mark the call as processed as a build-in-place call
7360
7361       Set_Is_Expanded_Build_In_Place_Call (Func_Call);
7362
7363       Loc := Sloc (Function_Call);
7364
7365       if Is_Entity_Name (Name (Func_Call)) then
7366          Func_Id := Entity (Name (Func_Call));
7367
7368       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
7369          Func_Id := Etype (Name (Func_Call));
7370
7371       else
7372          raise Program_Error;
7373       end if;
7374
7375       Result_Subt := Etype (Func_Id);
7376
7377       --  When the result subtype is unconstrained, an additional actual must
7378       --  be passed to indicate that the caller is providing the return object.
7379       --  This parameter must also be passed when the called function has a
7380       --  controlling result, because dispatching calls to the function needs
7381       --  to be treated effectively the same as calls to class-wide functions.
7382
7383       Add_Alloc_Form_Actual_To_Build_In_Place_Call
7384         (Func_Call, Func_Id, Alloc_Form => Caller_Allocation);
7385
7386       Add_Finalization_Master_Actual_To_Build_In_Place_Call
7387         (Func_Call, Func_Id);
7388
7389       Add_Task_Actuals_To_Build_In_Place_Call
7390         (Func_Call, Func_Id, Make_Identifier (Loc, Name_uMaster));
7391
7392       --  Add an implicit actual to the function call that provides access to
7393       --  the caller's return object.
7394
7395       Add_Access_Actual_To_Build_In_Place_Call
7396         (Func_Call,
7397          Func_Id,
7398          Make_Unchecked_Type_Conversion (Loc,
7399            Subtype_Mark => New_Reference_To (Result_Subt, Loc),
7400            Expression   => Relocate_Node (Lhs)));
7401
7402       --  Create an access type designating the function's result subtype
7403
7404       Ptr_Typ := Make_Temporary (Loc, 'A');
7405
7406       Ptr_Typ_Decl :=
7407         Make_Full_Type_Declaration (Loc,
7408           Defining_Identifier => Ptr_Typ,
7409           Type_Definition     =>
7410             Make_Access_To_Object_Definition (Loc,
7411               All_Present        => True,
7412               Subtype_Indication =>
7413                 New_Reference_To (Result_Subt, Loc)));
7414       Insert_After_And_Analyze (Assign, Ptr_Typ_Decl);
7415
7416       --  Finally, create an access object initialized to a reference to the
7417       --  function call.
7418
7419       Obj_Id := Make_Temporary (Loc, 'R');
7420       Set_Etype (Obj_Id, Ptr_Typ);
7421
7422       Obj_Decl :=
7423         Make_Object_Declaration (Loc,
7424           Defining_Identifier => Obj_Id,
7425           Object_Definition   => New_Reference_To (Ptr_Typ, Loc),
7426           Expression => Make_Reference (Loc, Relocate_Node (Func_Call)));
7427       Insert_After_And_Analyze (Ptr_Typ_Decl, Obj_Decl);
7428
7429       Rewrite (Assign, Make_Null_Statement (Loc));
7430
7431       --  Retrieve the target of the assignment
7432
7433       if Nkind (Lhs) = N_Selected_Component then
7434          Target := Selector_Name (Lhs);
7435       elsif Nkind (Lhs) = N_Type_Conversion then
7436          Target := Expression (Lhs);
7437       else
7438          Target := Lhs;
7439       end if;
7440
7441       --  If we are assigning to a return object or this is an expression of
7442       --  an extension aggregate, the target should either be an identifier
7443       --  or a simple expression. All other cases imply a different scenario.
7444
7445       if Nkind (Target) in N_Has_Entity then
7446          Target := Entity (Target);
7447       else
7448          return;
7449       end if;
7450    end Make_Build_In_Place_Call_In_Assignment;
7451
7452    ----------------------------------------------------
7453    -- Make_Build_In_Place_Call_In_Object_Declaration --
7454    ----------------------------------------------------
7455
7456    procedure Make_Build_In_Place_Call_In_Object_Declaration
7457      (Object_Decl   : Node_Id;
7458       Function_Call : Node_Id)
7459    is
7460       Loc             : Source_Ptr;
7461       Obj_Def_Id      : constant Entity_Id :=
7462                           Defining_Identifier (Object_Decl);
7463
7464       Func_Call       : Node_Id := Function_Call;
7465       Function_Id     : Entity_Id;
7466       Result_Subt     : Entity_Id;
7467       Caller_Object   : Node_Id;
7468       Call_Deref      : Node_Id;
7469       Ref_Type        : Entity_Id;
7470       Ptr_Typ_Decl    : Node_Id;
7471       Def_Id          : Entity_Id;
7472       New_Expr        : Node_Id;
7473       Enclosing_Func  : Entity_Id;
7474       Pass_Caller_Acc : Boolean := False;
7475
7476    begin
7477       --  Step past qualification or unchecked conversion (the latter can occur
7478       --  in cases of calls to 'Input).
7479
7480       if Nkind_In (Func_Call, N_Qualified_Expression,
7481                               N_Unchecked_Type_Conversion)
7482       then
7483          Func_Call := Expression (Func_Call);
7484       end if;
7485
7486       --  If the call has already been processed to add build-in-place actuals
7487       --  then return. This should not normally occur in an object declaration,
7488       --  but we add the protection as a defensive measure.
7489
7490       if Is_Expanded_Build_In_Place_Call (Func_Call) then
7491          return;
7492       end if;
7493
7494       --  Mark the call as processed as a build-in-place call
7495
7496       Set_Is_Expanded_Build_In_Place_Call (Func_Call);
7497
7498       Loc := Sloc (Function_Call);
7499
7500       if Is_Entity_Name (Name (Func_Call)) then
7501          Function_Id := Entity (Name (Func_Call));
7502
7503       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
7504          Function_Id := Etype (Name (Func_Call));
7505
7506       else
7507          raise Program_Error;
7508       end if;
7509
7510       Result_Subt := Etype (Function_Id);
7511
7512       --  In the constrained case, add an implicit actual to the function call
7513       --  that provides access to the declared object. An unchecked conversion
7514       --  to the (specific) result type of the function is inserted to handle
7515       --  the case where the object is declared with a class-wide type.
7516
7517       if Is_Constrained (Underlying_Type (Result_Subt)) then
7518          Caller_Object :=
7519             Make_Unchecked_Type_Conversion (Loc,
7520               Subtype_Mark => New_Reference_To (Result_Subt, Loc),
7521               Expression   => New_Reference_To (Obj_Def_Id, Loc));
7522
7523          --  When the function has a controlling result, an allocation-form
7524          --  parameter must be passed indicating that the caller is allocating
7525          --  the result object. This is needed because such a function can be
7526          --  called as a dispatching operation and must be treated similarly
7527          --  to functions with unconstrained result subtypes.
7528
7529          Add_Alloc_Form_Actual_To_Build_In_Place_Call
7530            (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
7531
7532       --  If the function's result subtype is unconstrained and the object is
7533       --  a return object of an enclosing build-in-place function, then the
7534       --  implicit build-in-place parameters of the enclosing function must be
7535       --  passed along to the called function. (Unfortunately, this won't cover
7536       --  the case of extension aggregates where the ancestor part is a build-
7537       --  in-place unconstrained function call that should be passed along the
7538       --  caller's parameters. Currently those get mishandled by reassigning
7539       --  the result of the call to the aggregate return object, when the call
7540       --  result should really be directly built in place in the aggregate and
7541       --  not built in a temporary. ???)
7542
7543       elsif Is_Return_Object (Defining_Identifier (Object_Decl)) then
7544          Pass_Caller_Acc := True;
7545
7546          Enclosing_Func := Enclosing_Subprogram (Obj_Def_Id);
7547
7548          --  If the enclosing function has a constrained result type, then
7549          --  caller allocation will be used.
7550
7551          if Is_Constrained (Etype (Enclosing_Func)) then
7552             Add_Alloc_Form_Actual_To_Build_In_Place_Call
7553               (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
7554
7555          --  Otherwise, when the enclosing function has an unconstrained result
7556          --  type, the BIP_Alloc_Form formal of the enclosing function must be
7557          --  passed along to the callee.
7558
7559          else
7560             Add_Alloc_Form_Actual_To_Build_In_Place_Call
7561               (Func_Call,
7562                Function_Id,
7563                Alloc_Form_Exp =>
7564                  New_Reference_To
7565                    (Build_In_Place_Formal (Enclosing_Func, BIP_Alloc_Form),
7566                     Loc));
7567          end if;
7568
7569          --  Retrieve the BIPacc formal from the enclosing function and convert
7570          --  it to the access type of the callee's BIP_Object_Access formal.
7571
7572          Caller_Object :=
7573             Make_Unchecked_Type_Conversion (Loc,
7574               Subtype_Mark =>
7575                 New_Reference_To
7576                   (Etype
7577                      (Build_In_Place_Formal (Function_Id, BIP_Object_Access)),
7578                    Loc),
7579               Expression   =>
7580                 New_Reference_To
7581                   (Build_In_Place_Formal (Enclosing_Func, BIP_Object_Access),
7582                    Loc));
7583
7584       --  In other unconstrained cases, pass an indication to do the allocation
7585       --  on the secondary stack and set Caller_Object to Empty so that a null
7586       --  value will be passed for the caller's object address. A transient
7587       --  scope is established to ensure eventual cleanup of the result.
7588
7589       else
7590          Add_Alloc_Form_Actual_To_Build_In_Place_Call
7591            (Func_Call,
7592             Function_Id,
7593             Alloc_Form => Secondary_Stack);
7594          Caller_Object := Empty;
7595
7596          Establish_Transient_Scope (Object_Decl, Sec_Stack => True);
7597       end if;
7598
7599       Add_Finalization_Master_Actual_To_Build_In_Place_Call
7600         (Func_Call, Function_Id);
7601
7602       if Nkind (Parent (Object_Decl)) = N_Extended_Return_Statement
7603         and then Has_Task (Result_Subt)
7604       then
7605          Enclosing_Func := Enclosing_Subprogram (Obj_Def_Id);
7606
7607          --  Here we're passing along the master that was passed in to this
7608          --  function.
7609
7610          Add_Task_Actuals_To_Build_In_Place_Call
7611            (Func_Call, Function_Id,
7612             Master_Actual =>
7613               New_Reference_To
7614                 (Build_In_Place_Formal (Enclosing_Func, BIP_Master), Loc));
7615
7616       else
7617          Add_Task_Actuals_To_Build_In_Place_Call
7618            (Func_Call, Function_Id, Make_Identifier (Loc, Name_uMaster));
7619       end if;
7620
7621       Add_Access_Actual_To_Build_In_Place_Call
7622         (Func_Call, Function_Id, Caller_Object, Is_Access => Pass_Caller_Acc);
7623
7624       --  Create an access type designating the function's result subtype. We
7625       --  use the type of the original expression because it may be a call to
7626       --  an inherited operation, which the expansion has replaced with the
7627       --  parent operation that yields the parent type.
7628
7629       Ref_Type := Make_Temporary (Loc, 'A');
7630
7631       Ptr_Typ_Decl :=
7632         Make_Full_Type_Declaration (Loc,
7633           Defining_Identifier => Ref_Type,
7634           Type_Definition     =>
7635             Make_Access_To_Object_Definition (Loc,
7636               All_Present        => True,
7637               Subtype_Indication =>
7638                 New_Reference_To (Etype (Function_Call), Loc)));
7639
7640       --  The access type and its accompanying object must be inserted after
7641       --  the object declaration in the constrained case, so that the function
7642       --  call can be passed access to the object. In the unconstrained case,
7643       --  the access type and object must be inserted before the object, since
7644       --  the object declaration is rewritten to be a renaming of a dereference
7645       --  of the access object.
7646
7647       if Is_Constrained (Underlying_Type (Result_Subt)) then
7648          Insert_After_And_Analyze (Object_Decl, Ptr_Typ_Decl);
7649       else
7650          Insert_Action (Object_Decl, Ptr_Typ_Decl);
7651       end if;
7652
7653       --  Finally, create an access object initialized to a reference to the
7654       --  function call.
7655
7656       New_Expr := Make_Reference (Loc, Relocate_Node (Func_Call));
7657
7658       Def_Id := Make_Temporary (Loc, 'R', New_Expr);
7659       Set_Etype (Def_Id, Ref_Type);
7660
7661       Insert_After_And_Analyze (Ptr_Typ_Decl,
7662         Make_Object_Declaration (Loc,
7663           Defining_Identifier => Def_Id,
7664           Object_Definition   => New_Reference_To (Ref_Type, Loc),
7665           Expression          => New_Expr));
7666
7667       if Is_Constrained (Underlying_Type (Result_Subt)) then
7668          Set_Expression (Object_Decl, Empty);
7669          Set_No_Initialization (Object_Decl);
7670
7671       --  In case of an unconstrained result subtype, rewrite the object
7672       --  declaration as an object renaming where the renamed object is a
7673       --  dereference of <function_Call>'reference:
7674       --
7675       --      Obj : Subt renames <function_call>'Ref.all;
7676
7677       else
7678          Call_Deref :=
7679            Make_Explicit_Dereference (Loc,
7680              Prefix => New_Reference_To (Def_Id, Loc));
7681
7682          Loc := Sloc (Object_Decl);
7683          Rewrite (Object_Decl,
7684            Make_Object_Renaming_Declaration (Loc,
7685              Defining_Identifier => Make_Temporary (Loc, 'D'),
7686              Access_Definition   => Empty,
7687              Subtype_Mark        => New_Occurrence_Of (Result_Subt, Loc),
7688              Name                => Call_Deref));
7689
7690          Set_Renamed_Object (Defining_Identifier (Object_Decl), Call_Deref);
7691
7692          Analyze (Object_Decl);
7693
7694          --  Replace the internal identifier of the renaming declaration's
7695          --  entity with identifier of the original object entity. We also have
7696          --  to exchange the entities containing their defining identifiers to
7697          --  ensure the correct replacement of the object declaration by the
7698          --  object renaming declaration to avoid homograph conflicts (since
7699          --  the object declaration's defining identifier was already entered
7700          --  in current scope). The Next_Entity links of the two entities also
7701          --  have to be swapped since the entities are part of the return
7702          --  scope's entity list and the list structure would otherwise be
7703          --  corrupted. Finally, the homonym chain must be preserved as well.
7704
7705          declare
7706             Renaming_Def_Id  : constant Entity_Id :=
7707                                  Defining_Identifier (Object_Decl);
7708             Next_Entity_Temp : constant Entity_Id :=
7709                                  Next_Entity (Renaming_Def_Id);
7710          begin
7711             Set_Chars (Renaming_Def_Id, Chars (Obj_Def_Id));
7712
7713             --  Swap next entity links in preparation for exchanging entities
7714
7715             Set_Next_Entity (Renaming_Def_Id, Next_Entity (Obj_Def_Id));
7716             Set_Next_Entity (Obj_Def_Id, Next_Entity_Temp);
7717             Set_Homonym     (Renaming_Def_Id, Homonym (Obj_Def_Id));
7718
7719             Exchange_Entities (Renaming_Def_Id, Obj_Def_Id);
7720
7721             --  Preserve source indication of original declaration, so that
7722             --  xref information is properly generated for the right entity.
7723
7724             Preserve_Comes_From_Source
7725               (Object_Decl, Original_Node (Object_Decl));
7726
7727             Preserve_Comes_From_Source
7728               (Obj_Def_Id, Original_Node (Object_Decl));
7729
7730             Set_Comes_From_Source (Renaming_Def_Id, False);
7731          end;
7732       end if;
7733
7734       --  If the object entity has a class-wide Etype, then we need to change
7735       --  it to the result subtype of the function call, because otherwise the
7736       --  object will be class-wide without an explicit initialization and
7737       --  won't be allocated properly by the back end. It seems unclean to make
7738       --  such a revision to the type at this point, and we should try to
7739       --  improve this treatment when build-in-place functions with class-wide
7740       --  results are implemented. ???
7741
7742       if Is_Class_Wide_Type (Etype (Defining_Identifier (Object_Decl))) then
7743          Set_Etype (Defining_Identifier (Object_Decl), Result_Subt);
7744       end if;
7745    end Make_Build_In_Place_Call_In_Object_Declaration;
7746
7747    -----------------------------------
7748    -- Needs_BIP_Finalization_Master --
7749    -----------------------------------
7750
7751    function Needs_BIP_Finalization_Master
7752      (Func_Id : Entity_Id) return Boolean
7753    is
7754       pragma Assert (Is_Build_In_Place_Function (Func_Id));
7755       Func_Typ : constant Entity_Id := Underlying_Type (Etype (Func_Id));
7756
7757    begin
7758       return
7759         not Restriction_Active (No_Finalization)
7760           and then Needs_Finalization (Func_Typ);
7761    end Needs_BIP_Finalization_Master;
7762
7763 end Exp_Ch6;