OSDN Git Service

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