OSDN Git Service

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