OSDN Git Service

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