OSDN Git Service

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