OSDN Git Service

2007-08-16 Gary Dismukes <dismukes@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-2007, 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 2,  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 COPYING.  If not, write --
19 -- to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, --
20 -- Boston, MA 02110-1301, USA.                                              --
21 --                                                                          --
22 -- GNAT was originally developed  by the GNAT team at  New York University. --
23 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
24 --                                                                          --
25 ------------------------------------------------------------------------------
26
27 with Atree;    use Atree;
28 with Checks;   use Checks;
29 with Debug;    use Debug;
30 with Einfo;    use Einfo;
31 with Errout;   use Errout;
32 with Elists;   use Elists;
33 with Exp_Atag; use Exp_Atag;
34 with Exp_Ch2;  use Exp_Ch2;
35 with Exp_Ch3;  use Exp_Ch3;
36 with Exp_Ch7;  use Exp_Ch7;
37 with Exp_Ch9;  use Exp_Ch9;
38 with Exp_Dbug; use Exp_Dbug;
39 with Exp_Disp; use Exp_Disp;
40 with Exp_Dist; use Exp_Dist;
41 with Exp_Intr; use Exp_Intr;
42 with Exp_Pakd; use Exp_Pakd;
43 with Exp_Tss;  use Exp_Tss;
44 with Exp_Util; use Exp_Util;
45 with 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_Ch6;  use Sem_Ch6;
58 with Sem_Ch8;  use Sem_Ch8;
59 with Sem_Ch12; use Sem_Ch12;
60 with Sem_Ch13; use Sem_Ch13;
61 with Sem_Eval; use Sem_Eval;
62 with Sem_Disp; use Sem_Disp;
63 with Sem_Dist; use Sem_Dist;
64 with Sem_Mech; use Sem_Mech;
65 with Sem_Res;  use Sem_Res;
66 with Sem_Util; use Sem_Util;
67 with Sinfo;    use Sinfo;
68 with Snames;   use Snames;
69 with Stand;    use Stand;
70 with Targparm; use Targparm;
71 with Tbuild;   use Tbuild;
72 with Uintp;    use Uintp;
73 with Validsw;  use Validsw;
74
75 package body Exp_Ch6 is
76
77    -----------------------
78    -- Local Subprograms --
79    -----------------------
80
81    procedure Add_Access_Actual_To_Build_In_Place_Call
82      (Function_Call : Node_Id;
83       Function_Id   : Entity_Id;
84       Return_Object : Node_Id;
85       Is_Access     : Boolean := False);
86    --  Ada 2005 (AI-318-02): Apply the Unrestricted_Access attribute to the
87    --  object name given by Return_Object and add the attribute to the end of
88    --  the actual parameter list associated with the build-in-place function
89    --  call denoted by Function_Call. However, if Is_Access is True, then
90    --  Return_Object is already an access expression, in which case it's passed
91    --  along directly to the build-in-place function. Finally, if Return_Object
92    --  is empty, then pass a null literal as the actual.
93
94    procedure Add_Alloc_Form_Actual_To_Build_In_Place_Call
95      (Function_Call  : Node_Id;
96       Function_Id    : Entity_Id;
97       Alloc_Form     : BIP_Allocation_Form := Unspecified;
98       Alloc_Form_Exp : Node_Id             := Empty);
99    --  Ada 2005 (AI-318-02): Add an actual indicating the form of allocation,
100    --  if any, to be done by a build-in-place function. If Alloc_Form_Exp is
101    --  present, then use it, otherwise pass a literal corresponding to the
102    --  Alloc_Form parameter (which must not be Unspecified in that case).
103
104    procedure Add_Extra_Actual_To_Call
105      (Subprogram_Call : Node_Id;
106       Extra_Formal    : Entity_Id;
107       Extra_Actual    : Node_Id);
108    --  Adds Extra_Actual as a named parameter association for the formal
109    --  Extra_Formal in Subprogram_Call.
110
111    procedure Add_Final_List_Actual_To_Build_In_Place_Call
112      (Function_Call : Node_Id;
113       Function_Id   : Entity_Id;
114       Acc_Type      : Entity_Id);
115    --  Ada 2005 (AI-318-02): For a build-in-place call, if the result type has
116    --  controlled parts, add an actual parameter that is a pointer to
117    --  appropriate finalization list. The finalization list is that of the
118    --  current scope, except for "new Acc'(F(...))" in which case it's the
119    --  finalization list of the access type returned by the allocator. Acc_Type
120    --  is that type in the allocator case; Empty otherwise.
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
133    --  a return object, we pass along the master passed in by the caller. The
134    --  activation chain to pass is always the local one.
135
136    procedure Check_Overriding_Operation (Subp : Entity_Id);
137    --  Subp is a dispatching operation. Check whether it may override an
138    --  inherited private operation, in which case its DT entry is that of
139    --  the hidden operation, not the one it may have received earlier.
140    --  This must be done before emitting the code to set the corresponding
141    --  DT to the address of the subprogram. The actual placement of Subp in
142    --  the proper place in the list of primitive operations is done in
143    --  Declare_Inherited_Private_Subprograms, which also has to deal with
144    --  implicit operations. This duplication is unavoidable for now???
145
146    procedure Detect_Infinite_Recursion (N : Node_Id; Spec : Entity_Id);
147    --  This procedure is called only if the subprogram body N, whose spec
148    --  has the given entity Spec, contains a parameterless recursive call.
149    --  It attempts to generate runtime code to detect if this a case of
150    --  infinite recursion.
151    --
152    --  The body is scanned to determine dependencies. If the only external
153    --  dependencies are on a small set of scalar variables, then the values
154    --  of these variables are captured on entry to the subprogram, and if
155    --  the values are not changed for the call, we know immediately that
156    --  we have an infinite recursion.
157
158    procedure Expand_Actuals (N : Node_Id; Subp : Entity_Id);
159    --  For each actual of an in-out or out parameter which is a numeric
160    --  (view) conversion of the form T (A), where A denotes a variable,
161    --  we insert the declaration:
162    --
163    --    Temp : T[ := T (A)];
164    --
165    --  prior to the call. Then we replace the actual with a reference to Temp,
166    --  and append the assignment:
167    --
168    --    A := TypeA (Temp);
169    --
170    --  after the call. Here TypeA is the actual type of variable A.
171    --  For out parameters, the initial declaration has no expression.
172    --  If A is not an entity name, we generate instead:
173    --
174    --    Var  : TypeA renames A;
175    --    Temp : T := Var;       --  omitting expression for out parameter.
176    --    ...
177    --    Var := TypeA (Temp);
178    --
179    --  For other in-out parameters, we emit the required constraint checks
180    --  before and/or after the call.
181    --
182    --  For all parameter modes, actuals that denote components and slices
183    --  of packed arrays are expanded into suitable temporaries.
184    --
185    --  For non-scalar objects that are possibly unaligned, add call by copy
186    --  code (copy in for IN and IN OUT, copy out for OUT and IN OUT).
187
188    procedure Expand_Inlined_Call
189     (N         : Node_Id;
190      Subp      : Entity_Id;
191      Orig_Subp : Entity_Id);
192    --  If called subprogram can be inlined by the front-end, retrieve the
193    --  analyzed body, replace formals with actuals and expand call in place.
194    --  Generate thunks for actuals that are expressions, and insert the
195    --  corresponding constant declarations before the call. If the original
196    --  call is to a derived operation, the return type is the one of the
197    --  derived operation, but the body is that of the original, so return
198    --  expressions in the body must be converted to the desired type (which
199    --  is simply not noted in the tree without inline expansion).
200
201    function Expand_Protected_Object_Reference
202      (N    : Node_Id;
203       Scop : Entity_Id) return Node_Id;
204
205    procedure Expand_Protected_Subprogram_Call
206      (N    : Node_Id;
207       Subp : Entity_Id;
208       Scop : Entity_Id);
209    --  A call to a protected subprogram within the protected object may appear
210    --  as a regular call. The list of actuals must be expanded to contain a
211    --  reference to the object itself, and the call becomes a call to the
212    --  corresponding protected subprogram.
213
214    ----------------------------------------------
215    -- Add_Access_Actual_To_Build_In_Place_Call --
216    ----------------------------------------------
217
218    procedure Add_Access_Actual_To_Build_In_Place_Call
219      (Function_Call : Node_Id;
220       Function_Id   : Entity_Id;
221       Return_Object : Node_Id;
222       Is_Access     : Boolean := False)
223    is
224       Loc            : constant Source_Ptr := Sloc (Function_Call);
225       Obj_Address    : Node_Id;
226       Obj_Acc_Formal : Entity_Id;
227
228    begin
229       --  Locate the implicit access parameter in the called function
230
231       Obj_Acc_Formal := Build_In_Place_Formal (Function_Id, BIP_Object_Access);
232
233       --  If no return object is provided, then pass null
234
235       if not Present (Return_Object) then
236          Obj_Address := Make_Null (Loc);
237          Set_Parent (Obj_Address, Function_Call);
238
239       --  If Return_Object is already an expression of an access type, then use
240       --  it directly, since it must be an access value denoting the return
241       --  object, and couldn't possibly be the return object itself.
242
243       elsif Is_Access then
244          Obj_Address := Return_Object;
245          Set_Parent (Obj_Address, Function_Call);
246
247       --  Apply Unrestricted_Access to caller's return object
248
249       else
250          Obj_Address :=
251             Make_Attribute_Reference (Loc,
252               Prefix         => Return_Object,
253               Attribute_Name => Name_Unrestricted_Access);
254
255          Set_Parent (Return_Object, Obj_Address);
256          Set_Parent (Obj_Address, Function_Call);
257       end if;
258
259       Analyze_And_Resolve (Obj_Address, Etype (Obj_Acc_Formal));
260
261       --  Build the parameter association for the new actual and add it to the
262       --  end of the function's actuals.
263
264       Add_Extra_Actual_To_Call (Function_Call, Obj_Acc_Formal, Obj_Address);
265    end Add_Access_Actual_To_Build_In_Place_Call;
266
267    --------------------------------------------------
268    -- Add_Alloc_Form_Actual_To_Build_In_Place_Call --
269    --------------------------------------------------
270
271    procedure Add_Alloc_Form_Actual_To_Build_In_Place_Call
272      (Function_Call  : Node_Id;
273       Function_Id    : Entity_Id;
274       Alloc_Form     : BIP_Allocation_Form := Unspecified;
275       Alloc_Form_Exp : Node_Id             := Empty)
276    is
277       Loc               : constant Source_Ptr := Sloc (Function_Call);
278       Alloc_Form_Actual : Node_Id;
279       Alloc_Form_Formal : Node_Id;
280
281    begin
282       --  The allocation form generally doesn't need to be passed in the case
283       --  of a constrained result subtype, since normally the caller performs
284       --  the allocation in that case. However this formal is still needed in
285       --  the case where the function has a tagged result, because generally
286       --  such functions can be called in a dispatching context and such calls
287       --  must be handled like calls to class-wide functions.
288
289       if Is_Constrained (Underlying_Type (Etype (Function_Id)))
290         and then not Is_Tagged_Type (Underlying_Type (Etype (Function_Id)))
291       then
292          return;
293       end if;
294
295       --  Locate the implicit allocation form parameter in the called function.
296       --  Maybe it would be better for each implicit formal of a build-in-place
297       --  function to have a flag or a Uint attribute to identify it. ???
298
299       Alloc_Form_Formal := Build_In_Place_Formal (Function_Id, BIP_Alloc_Form);
300
301       if Present (Alloc_Form_Exp) then
302          pragma Assert (Alloc_Form = Unspecified);
303
304          Alloc_Form_Actual := Alloc_Form_Exp;
305
306       else
307          pragma Assert (Alloc_Form /= Unspecified);
308
309          Alloc_Form_Actual :=
310            Make_Integer_Literal (Loc,
311              Intval => UI_From_Int (BIP_Allocation_Form'Pos (Alloc_Form)));
312       end if;
313
314       Analyze_And_Resolve (Alloc_Form_Actual, Etype (Alloc_Form_Formal));
315
316       --  Build the parameter association for the new actual and add it to the
317       --  end of the function's actuals.
318
319       Add_Extra_Actual_To_Call
320         (Function_Call, Alloc_Form_Formal, Alloc_Form_Actual);
321    end Add_Alloc_Form_Actual_To_Build_In_Place_Call;
322
323    ------------------------------
324    -- Add_Extra_Actual_To_Call --
325    ------------------------------
326
327    procedure Add_Extra_Actual_To_Call
328      (Subprogram_Call : Node_Id;
329       Extra_Formal    : Entity_Id;
330       Extra_Actual    : Node_Id)
331    is
332       Loc         : constant Source_Ptr := Sloc (Subprogram_Call);
333       Param_Assoc : Node_Id;
334
335    begin
336       Param_Assoc :=
337         Make_Parameter_Association (Loc,
338           Selector_Name             => New_Occurrence_Of (Extra_Formal, Loc),
339           Explicit_Actual_Parameter => Extra_Actual);
340
341       Set_Parent (Param_Assoc, Subprogram_Call);
342       Set_Parent (Extra_Actual, Param_Assoc);
343
344       if Present (Parameter_Associations (Subprogram_Call)) then
345          if Nkind (Last (Parameter_Associations (Subprogram_Call))) =
346               N_Parameter_Association
347          then
348
349             --  Find last named actual, and append
350
351             declare
352                L : Node_Id;
353             begin
354                L := First_Actual (Subprogram_Call);
355                while Present (L) loop
356                   if No (Next_Actual (L)) then
357                      Set_Next_Named_Actual (Parent (L), Extra_Actual);
358                      exit;
359                   end if;
360                   Next_Actual (L);
361                end loop;
362             end;
363
364          else
365             Set_First_Named_Actual (Subprogram_Call, Extra_Actual);
366          end if;
367
368          Append (Param_Assoc, To => Parameter_Associations (Subprogram_Call));
369
370       else
371          Set_Parameter_Associations (Subprogram_Call, New_List (Param_Assoc));
372          Set_First_Named_Actual (Subprogram_Call, Extra_Actual);
373       end if;
374    end Add_Extra_Actual_To_Call;
375
376    --------------------------------------------------
377    -- Add_Final_List_Actual_To_Build_In_Place_Call --
378    --------------------------------------------------
379
380    procedure Add_Final_List_Actual_To_Build_In_Place_Call
381      (Function_Call : Node_Id;
382       Function_Id   : Entity_Id;
383       Acc_Type      : Entity_Id)
384    is
385       Loc               : constant Source_Ptr := Sloc (Function_Call);
386       Final_List        : Node_Id;
387       Final_List_Actual : Node_Id;
388       Final_List_Formal : Node_Id;
389
390    begin
391       --  No such extra parameter is needed if there are no controlled parts.
392       --  The test for Controlled_Type accounts for class-wide results (which
393       --  potentially have controlled parts, even if the root type doesn't),
394       --  and the test for a tagged result type is needed because calls to
395       --  such a function can in general occur in dispatching contexts, which
396       --  must be treated the same as a call to class-wide functions. Both of
397       --  these situations require that a finalization list be passed.
398
399       if not Controlled_Type (Underlying_Type (Etype (Function_Id)))
400         and then not Is_Tagged_Type (Underlying_Type (Etype (Function_Id)))
401       then
402          return;
403       end if;
404
405       --  Locate implicit finalization list parameter in the called function
406
407       Final_List_Formal := Build_In_Place_Formal (Function_Id, BIP_Final_List);
408
409       --  Create the actual which is a pointer to the appropriate finalization
410       --  list. Acc_Type is present if and only if this call is the
411       --  initialization of an allocator. Use the Current_Scope or the Acc_Type
412       --  as appropriate.
413
414       if Present (Acc_Type)
415         and then (Ekind (Acc_Type) = E_Anonymous_Access_Type
416                    or else
417                      Present (Associated_Final_Chain (Base_Type (Acc_Type))))
418       then
419          Final_List := Find_Final_List (Acc_Type);
420       else
421          Final_List := Find_Final_List (Current_Scope);
422       end if;
423
424       Final_List_Actual :=
425         Make_Attribute_Reference (Loc,
426           Prefix         => Final_List,
427           Attribute_Name => Name_Unrestricted_Access);
428
429       Analyze_And_Resolve (Final_List_Actual, Etype (Final_List_Formal));
430
431       --  Build the parameter association for the new actual and add it to the
432       --  end of the function's actuals.
433
434       Add_Extra_Actual_To_Call
435         (Function_Call, Final_List_Formal, Final_List_Actual);
436    end Add_Final_List_Actual_To_Build_In_Place_Call;
437
438    ---------------------------------------------
439    -- Add_Task_Actuals_To_Build_In_Place_Call --
440    ---------------------------------------------
441
442    procedure Add_Task_Actuals_To_Build_In_Place_Call
443      (Function_Call : Node_Id;
444       Function_Id   : Entity_Id;
445       Master_Actual : Node_Id)
446       --  Note: Master_Actual can be Empty, but only if there are no tasks
447    is
448       Loc               : constant Source_Ptr := Sloc (Function_Call);
449
450    begin
451       --  No such extra parameters are needed if there are no tasks
452
453       if not Has_Task (Etype (Function_Id)) then
454          return;
455       end if;
456
457       --  The master
458
459       declare
460          Master_Formal : Node_Id;
461       begin
462          --  Locate implicit master parameter in the called function
463
464          Master_Formal := Build_In_Place_Formal (Function_Id, BIP_Master);
465
466          Analyze_And_Resolve (Master_Actual, Etype (Master_Formal));
467
468          --  Build the parameter association for the new actual and add it to
469          --  the end of the function's actuals.
470
471          Add_Extra_Actual_To_Call
472            (Function_Call, Master_Formal, Master_Actual);
473       end;
474
475       --  The activation chain
476
477       declare
478          Activation_Chain_Actual : Node_Id;
479          Activation_Chain_Formal : Node_Id;
480       begin
481          --  Locate implicit activation chain parameter in the called function
482
483          Activation_Chain_Formal := Build_In_Place_Formal
484            (Function_Id, BIP_Activation_Chain);
485
486          --  Create the actual which is a pointer to the current activation
487          --  chain
488
489          Activation_Chain_Actual :=
490            Make_Attribute_Reference (Loc,
491              Prefix         => Make_Identifier (Loc, Name_uChain),
492              Attribute_Name => Name_Unrestricted_Access);
493
494          Analyze_And_Resolve
495            (Activation_Chain_Actual, Etype (Activation_Chain_Formal));
496
497          --  Build the parameter association for the new actual and add it to
498          --  the end of the function's actuals.
499
500          Add_Extra_Actual_To_Call
501            (Function_Call, Activation_Chain_Formal, Activation_Chain_Actual);
502       end;
503    end Add_Task_Actuals_To_Build_In_Place_Call;
504
505    -----------------------
506    -- BIP_Formal_Suffix --
507    -----------------------
508
509    function BIP_Formal_Suffix (Kind : BIP_Formal_Kind) return String is
510    begin
511       case Kind is
512          when BIP_Alloc_Form       =>
513             return "BIPalloc";
514          when BIP_Final_List       =>
515             return "BIPfinallist";
516          when BIP_Master           =>
517             return "BIPmaster";
518          when BIP_Activation_Chain =>
519             return "BIPactivationchain";
520          when BIP_Object_Access    =>
521             return "BIPaccess";
522       end case;
523    end BIP_Formal_Suffix;
524
525    ---------------------------
526    -- Build_In_Place_Formal --
527    ---------------------------
528
529    function Build_In_Place_Formal
530      (Func : Entity_Id;
531       Kind : BIP_Formal_Kind) return Entity_Id
532    is
533       Extra_Formal : Entity_Id := Extra_Formals (Func);
534
535    begin
536       --  Maybe it would be better for each implicit formal of a build-in-place
537       --  function to have a flag or a Uint attribute to identify it. ???
538
539       loop
540          pragma Assert (Present (Extra_Formal));
541          exit when
542            Chars (Extra_Formal) =
543              New_External_Name (Chars (Func), BIP_Formal_Suffix (Kind));
544          Next_Formal_With_Extras (Extra_Formal);
545       end loop;
546
547       return Extra_Formal;
548    end Build_In_Place_Formal;
549
550    --------------------------------
551    -- Check_Overriding_Operation --
552    --------------------------------
553
554    procedure Check_Overriding_Operation (Subp : Entity_Id) is
555       Typ     : constant Entity_Id := Find_Dispatching_Type (Subp);
556       Op_List : constant Elist_Id  := Primitive_Operations (Typ);
557       Op_Elmt : Elmt_Id;
558       Prim_Op : Entity_Id;
559       Par_Op  : Entity_Id;
560
561    begin
562       if Is_Derived_Type (Typ)
563         and then not Is_Private_Type (Typ)
564         and then In_Open_Scopes (Scope (Etype (Typ)))
565         and then Typ = Base_Type (Typ)
566       then
567          --  Subp overrides an inherited private operation if there is an
568          --  inherited operation with a different name than Subp (see
569          --  Derive_Subprogram) whose Alias is a hidden subprogram with the
570          --  same name as Subp.
571
572          Op_Elmt := First_Elmt (Op_List);
573          while Present (Op_Elmt) loop
574             Prim_Op := Node (Op_Elmt);
575             Par_Op  := Alias (Prim_Op);
576
577             if Present (Par_Op)
578               and then not Comes_From_Source (Prim_Op)
579               and then Chars (Prim_Op) /= Chars (Par_Op)
580               and then Chars (Par_Op) = Chars (Subp)
581               and then Is_Hidden (Par_Op)
582               and then Type_Conformant (Prim_Op, Subp)
583             then
584                Set_DT_Position (Subp, DT_Position (Prim_Op));
585             end if;
586
587             Next_Elmt (Op_Elmt);
588          end loop;
589       end if;
590    end Check_Overriding_Operation;
591
592    -------------------------------
593    -- Detect_Infinite_Recursion --
594    -------------------------------
595
596    procedure Detect_Infinite_Recursion (N : Node_Id; Spec : Entity_Id) is
597       Loc : constant Source_Ptr := Sloc (N);
598
599       Var_List : constant Elist_Id := New_Elmt_List;
600       --  List of globals referenced by body of procedure
601
602       Call_List : constant Elist_Id := New_Elmt_List;
603       --  List of recursive calls in body of procedure
604
605       Shad_List : constant Elist_Id := New_Elmt_List;
606       --  List of entity id's for entities created to capture the value of
607       --  referenced globals on entry to the procedure.
608
609       Scop : constant Uint := Scope_Depth (Spec);
610       --  This is used to record the scope depth of the current procedure, so
611       --  that we can identify global references.
612
613       Max_Vars : constant := 4;
614       --  Do not test more than four global variables
615
616       Count_Vars : Natural := 0;
617       --  Count variables found so far
618
619       Var  : Entity_Id;
620       Elm  : Elmt_Id;
621       Ent  : Entity_Id;
622       Call : Elmt_Id;
623       Decl : Node_Id;
624       Test : Node_Id;
625       Elm1 : Elmt_Id;
626       Elm2 : Elmt_Id;
627       Last : Node_Id;
628
629       function Process (Nod : Node_Id) return Traverse_Result;
630       --  Function to traverse the subprogram body (using Traverse_Func)
631
632       -------------
633       -- Process --
634       -------------
635
636       function Process (Nod : Node_Id) return Traverse_Result is
637       begin
638          --  Procedure call
639
640          if Nkind (Nod) = N_Procedure_Call_Statement then
641
642             --  Case of one of the detected recursive calls
643
644             if Is_Entity_Name (Name (Nod))
645               and then Has_Recursive_Call (Entity (Name (Nod)))
646               and then Entity (Name (Nod)) = Spec
647             then
648                Append_Elmt (Nod, Call_List);
649                return Skip;
650
651             --  Any other procedure call may have side effects
652
653             else
654                return Abandon;
655             end if;
656
657          --  A call to a pure function can always be ignored
658
659          elsif Nkind (Nod) = N_Function_Call
660            and then Is_Entity_Name (Name (Nod))
661            and then Is_Pure (Entity (Name (Nod)))
662          then
663             return Skip;
664
665          --  Case of an identifier reference
666
667          elsif Nkind (Nod) = N_Identifier then
668             Ent := Entity (Nod);
669
670             --  If no entity, then ignore the reference
671
672             --  Not clear why this can happen. To investigate, remove this
673             --  test and look at the crash that occurs here in 3401-004 ???
674
675             if No (Ent) then
676                return Skip;
677
678             --  Ignore entities with no Scope, again not clear how this
679             --  can happen, to investigate, look at 4108-008 ???
680
681             elsif No (Scope (Ent)) then
682                return Skip;
683
684             --  Ignore the reference if not to a more global object
685
686             elsif Scope_Depth (Scope (Ent)) >= Scop then
687                return Skip;
688
689             --  References to types, exceptions and constants are always OK
690
691             elsif Is_Type (Ent)
692               or else Ekind (Ent) = E_Exception
693               or else Ekind (Ent) = E_Constant
694             then
695                return Skip;
696
697             --  If other than a non-volatile scalar variable, we have some
698             --  kind of global reference (e.g. to a function) that we cannot
699             --  deal with so we forget the attempt.
700
701             elsif Ekind (Ent) /= E_Variable
702               or else not Is_Scalar_Type (Etype (Ent))
703               or else Treat_As_Volatile (Ent)
704             then
705                return Abandon;
706
707             --  Otherwise we have a reference to a global scalar
708
709             else
710                --  Loop through global entities already detected
711
712                Elm := First_Elmt (Var_List);
713                loop
714                   --  If not detected before, record this new global reference
715
716                   if No (Elm) then
717                      Count_Vars := Count_Vars + 1;
718
719                      if Count_Vars <= Max_Vars then
720                         Append_Elmt (Entity (Nod), Var_List);
721                      else
722                         return Abandon;
723                      end if;
724
725                      exit;
726
727                   --  If recorded before, ignore
728
729                   elsif Node (Elm) = Entity (Nod) then
730                      return Skip;
731
732                   --  Otherwise keep looking
733
734                   else
735                      Next_Elmt (Elm);
736                   end if;
737                end loop;
738
739                return Skip;
740             end if;
741
742          --  For all other node kinds, recursively visit syntactic children
743
744          else
745             return OK;
746          end if;
747       end Process;
748
749       function Traverse_Body is new Traverse_Func (Process);
750
751    --  Start of processing for Detect_Infinite_Recursion
752
753    begin
754       --  Do not attempt detection in No_Implicit_Conditional mode, since we
755       --  won't be able to generate the code to handle the recursion in any
756       --  case.
757
758       if Restriction_Active (No_Implicit_Conditionals) then
759          return;
760       end if;
761
762       --  Otherwise do traversal and quit if we get abandon signal
763
764       if Traverse_Body (N) = Abandon then
765          return;
766
767       --  We must have a call, since Has_Recursive_Call was set. If not just
768       --  ignore (this is only an error check, so if we have a funny situation,
769       --  due to bugs or errors, we do not want to bomb!)
770
771       elsif Is_Empty_Elmt_List (Call_List) then
772          return;
773       end if;
774
775       --  Here is the case where we detect recursion at compile time
776
777       --  Push our current scope for analyzing the declarations and code that
778       --  we will insert for the checking.
779
780       Push_Scope (Spec);
781
782       --  This loop builds temporary variables for each of the referenced
783       --  globals, so that at the end of the loop the list Shad_List contains
784       --  these temporaries in one-to-one correspondence with the elements in
785       --  Var_List.
786
787       Last := Empty;
788       Elm := First_Elmt (Var_List);
789       while Present (Elm) loop
790          Var := Node (Elm);
791          Ent :=
792            Make_Defining_Identifier (Loc,
793              Chars => New_Internal_Name ('S'));
794          Append_Elmt (Ent, Shad_List);
795
796          --  Insert a declaration for this temporary at the start of the
797          --  declarations for the procedure. The temporaries are declared as
798          --  constant objects initialized to the current values of the
799          --  corresponding temporaries.
800
801          Decl :=
802            Make_Object_Declaration (Loc,
803              Defining_Identifier => Ent,
804              Object_Definition   => New_Occurrence_Of (Etype (Var), Loc),
805              Constant_Present    => True,
806              Expression          => New_Occurrence_Of (Var, Loc));
807
808          if No (Last) then
809             Prepend (Decl, Declarations (N));
810          else
811             Insert_After (Last, Decl);
812          end if;
813
814          Last := Decl;
815          Analyze (Decl);
816          Next_Elmt (Elm);
817       end loop;
818
819       --  Loop through calls
820
821       Call := First_Elmt (Call_List);
822       while Present (Call) loop
823
824          --  Build a predicate expression of the form
825
826          --    True
827          --      and then global1 = temp1
828          --      and then global2 = temp2
829          --      ...
830
831          --  This predicate determines if any of the global values
832          --  referenced by the procedure have changed since the
833          --  current call, if not an infinite recursion is assured.
834
835          Test := New_Occurrence_Of (Standard_True, Loc);
836
837          Elm1 := First_Elmt (Var_List);
838          Elm2 := First_Elmt (Shad_List);
839          while Present (Elm1) loop
840             Test :=
841               Make_And_Then (Loc,
842                 Left_Opnd  => Test,
843                 Right_Opnd =>
844                   Make_Op_Eq (Loc,
845                     Left_Opnd  => New_Occurrence_Of (Node (Elm1), Loc),
846                     Right_Opnd => New_Occurrence_Of (Node (Elm2), Loc)));
847
848             Next_Elmt (Elm1);
849             Next_Elmt (Elm2);
850          end loop;
851
852          --  Now we replace the call with the sequence
853
854          --    if no-changes (see above) then
855          --       raise Storage_Error;
856          --    else
857          --       original-call
858          --    end if;
859
860          Rewrite (Node (Call),
861            Make_If_Statement (Loc,
862              Condition       => Test,
863              Then_Statements => New_List (
864                Make_Raise_Storage_Error (Loc,
865                  Reason => SE_Infinite_Recursion)),
866
867              Else_Statements => New_List (
868                Relocate_Node (Node (Call)))));
869
870          Analyze (Node (Call));
871
872          Next_Elmt (Call);
873       end loop;
874
875       --  Remove temporary scope stack entry used for analysis
876
877       Pop_Scope;
878    end Detect_Infinite_Recursion;
879
880    --------------------
881    -- Expand_Actuals --
882    --------------------
883
884    procedure Expand_Actuals (N : Node_Id; Subp : Entity_Id) is
885       Loc       : constant Source_Ptr := Sloc (N);
886       Actual    : Node_Id;
887       Formal    : Entity_Id;
888       N_Node    : Node_Id;
889       Post_Call : List_Id;
890       E_Formal  : Entity_Id;
891
892       procedure Add_Call_By_Copy_Code;
893       --  For cases where the parameter must be passed by copy, this routine
894       --  generates a temporary variable into which the actual is copied and
895       --  then passes this as the parameter. For an OUT or IN OUT parameter,
896       --  an assignment is also generated to copy the result back. The call
897       --  also takes care of any constraint checks required for the type
898       --  conversion case (on both the way in and the way out).
899
900       procedure Add_Simple_Call_By_Copy_Code;
901       --  This is similar to the above, but is used in cases where we know
902       --  that all that is needed is to simply create a temporary and copy
903       --  the value in and out of the temporary.
904
905       procedure Check_Fortran_Logical;
906       --  A value of type Logical that is passed through a formal parameter
907       --  must be normalized because .TRUE. usually does not have the same
908       --  representation as True. We assume that .FALSE. = False = 0.
909       --  What about functions that return a logical type ???
910
911       function Is_Legal_Copy return Boolean;
912       --  Check that an actual can be copied before generating the temporary
913       --  to be used in the call. If the actual is of a by_reference type then
914       --  the program is illegal (this can only happen in the presence of
915       --  rep. clauses that force an incorrect alignment). If the formal is
916       --  a by_reference parameter imposed by a DEC pragma, emit a warning to
917       --  the effect that this might lead to unaligned arguments.
918
919       function Make_Var (Actual : Node_Id) return Entity_Id;
920       --  Returns an entity that refers to the given actual parameter,
921       --  Actual (not including any type conversion). If Actual is an
922       --  entity name, then this entity is returned unchanged, otherwise
923       --  a renaming is created to provide an entity for the actual.
924
925       procedure Reset_Packed_Prefix;
926       --  The expansion of a packed array component reference is delayed in
927       --  the context of a call. Now we need to complete the expansion, so we
928       --  unmark the analyzed bits in all prefixes.
929
930       ---------------------------
931       -- Add_Call_By_Copy_Code --
932       ---------------------------
933
934       procedure Add_Call_By_Copy_Code is
935          Expr  : Node_Id;
936          Init  : Node_Id;
937          Temp  : Entity_Id;
938          Indic : Node_Id;
939          Var   : Entity_Id;
940          F_Typ : constant Entity_Id := Etype (Formal);
941          V_Typ : Entity_Id;
942          Crep  : Boolean;
943
944       begin
945          if not Is_Legal_Copy then
946             return;
947          end if;
948
949          Temp :=
950            Make_Defining_Identifier (Loc,
951              Chars => New_Internal_Name ('T'));
952
953          --  Use formal type for temp, unless formal type is an unconstrained
954          --  array, in which case we don't have to worry about bounds checks,
955          --  and we use the actual type, since that has appropriate bounds.
956
957          if Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ) then
958             Indic := New_Occurrence_Of (Etype (Actual), Loc);
959          else
960             Indic := New_Occurrence_Of (Etype (Formal), Loc);
961          end if;
962
963          if Nkind (Actual) = N_Type_Conversion then
964             V_Typ := Etype (Expression (Actual));
965
966             --  If the formal is an (in-)out parameter, capture the name
967             --  of the variable in order to build the post-call assignment.
968
969             Var := Make_Var (Expression (Actual));
970
971             Crep := not Same_Representation
972                           (F_Typ, Etype (Expression (Actual)));
973
974          else
975             V_Typ := Etype (Actual);
976             Var   := Make_Var (Actual);
977             Crep  := False;
978          end if;
979
980          --  Setup initialization for case of in out parameter, or an out
981          --  parameter where the formal is an unconstrained array (in the
982          --  latter case, we have to pass in an object with bounds).
983
984          --  If this is an out parameter, the initial copy is wasteful, so as
985          --  an optimization for the one-dimensional case we extract the
986          --  bounds of the actual and build an uninitialized temporary of the
987          --  right size.
988
989          if Ekind (Formal) = E_In_Out_Parameter
990            or else (Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ))
991          then
992             if Nkind (Actual) = N_Type_Conversion then
993                if Conversion_OK (Actual) then
994                   Init := OK_Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
995                else
996                   Init := Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
997                end if;
998
999             elsif Ekind (Formal) = E_Out_Parameter
1000               and then Is_Array_Type (F_Typ)
1001               and then Number_Dimensions (F_Typ) = 1
1002               and then not Has_Non_Null_Base_Init_Proc (F_Typ)
1003             then
1004                --  Actual is a one-dimensional array or slice, and the type
1005                --  requires no initialization. Create a temporary of the
1006                --  right size, but do not copy actual into it (optimization).
1007
1008                Init := Empty;
1009                Indic :=
1010                  Make_Subtype_Indication (Loc,
1011                    Subtype_Mark =>
1012                      New_Occurrence_Of (F_Typ, Loc),
1013                    Constraint   =>
1014                      Make_Index_Or_Discriminant_Constraint (Loc,
1015                        Constraints => New_List (
1016                          Make_Range (Loc,
1017                            Low_Bound  =>
1018                              Make_Attribute_Reference (Loc,
1019                                Prefix => New_Occurrence_Of (Var, Loc),
1020                                Attribute_name => Name_First),
1021                            High_Bound =>
1022                              Make_Attribute_Reference (Loc,
1023                                Prefix => New_Occurrence_Of (Var, Loc),
1024                                Attribute_Name => Name_Last)))));
1025
1026             else
1027                Init := New_Occurrence_Of (Var, Loc);
1028             end if;
1029
1030          --  An initialization is created for packed conversions as
1031          --  actuals for out parameters to enable Make_Object_Declaration
1032          --  to determine the proper subtype for N_Node. Note that this
1033          --  is wasteful because the extra copying on the call side is
1034          --  not required for such out parameters. ???
1035
1036          elsif Ekind (Formal) = E_Out_Parameter
1037            and then Nkind (Actual) = N_Type_Conversion
1038            and then (Is_Bit_Packed_Array (F_Typ)
1039                        or else
1040                      Is_Bit_Packed_Array (Etype (Expression (Actual))))
1041          then
1042             if Conversion_OK (Actual) then
1043                Init := OK_Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1044             else
1045                Init := Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1046             end if;
1047
1048          elsif Ekind (Formal) = E_In_Parameter then
1049
1050             --  Handle the case in which the actual is a type conversion
1051
1052             if Nkind (Actual) = N_Type_Conversion then
1053                if Conversion_OK (Actual) then
1054                   Init := OK_Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1055                else
1056                   Init := Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1057                end if;
1058             else
1059                Init := New_Occurrence_Of (Var, Loc);
1060             end if;
1061
1062          else
1063             Init := Empty;
1064          end if;
1065
1066          N_Node :=
1067            Make_Object_Declaration (Loc,
1068              Defining_Identifier => Temp,
1069              Object_Definition   => Indic,
1070              Expression          => Init);
1071          Set_Assignment_OK (N_Node);
1072          Insert_Action (N, N_Node);
1073
1074          --  Now, normally the deal here is that we use the defining
1075          --  identifier created by that object declaration. There is
1076          --  one exception to this. In the change of representation case
1077          --  the above declaration will end up looking like:
1078
1079          --    temp : type := identifier;
1080
1081          --  And in this case we might as well use the identifier directly
1082          --  and eliminate the temporary. Note that the analysis of the
1083          --  declaration was not a waste of time in that case, since it is
1084          --  what generated the necessary change of representation code. If
1085          --  the change of representation introduced additional code, as in
1086          --  a fixed-integer conversion, the expression is not an identifier
1087          --  and must be kept.
1088
1089          if Crep
1090            and then Present (Expression (N_Node))
1091            and then Is_Entity_Name (Expression (N_Node))
1092          then
1093             Temp := Entity (Expression (N_Node));
1094             Rewrite (N_Node, Make_Null_Statement (Loc));
1095          end if;
1096
1097          --  For IN parameter, all we do is to replace the actual
1098
1099          if Ekind (Formal) = E_In_Parameter then
1100             Rewrite (Actual, New_Reference_To (Temp, Loc));
1101             Analyze (Actual);
1102
1103          --  Processing for OUT or IN OUT parameter
1104
1105          else
1106             --  Kill current value indications for the temporary variable we
1107             --  created, since we just passed it as an OUT parameter.
1108
1109             Kill_Current_Values (Temp);
1110
1111             --  If type conversion, use reverse conversion on exit
1112
1113             if Nkind (Actual) = N_Type_Conversion then
1114                if Conversion_OK (Actual) then
1115                   Expr := OK_Convert_To (V_Typ, New_Occurrence_Of (Temp, Loc));
1116                else
1117                   Expr := Convert_To (V_Typ, New_Occurrence_Of (Temp, Loc));
1118                end if;
1119             else
1120                Expr := New_Occurrence_Of (Temp, Loc);
1121             end if;
1122
1123             Rewrite (Actual, New_Reference_To (Temp, Loc));
1124             Analyze (Actual);
1125
1126             --  If the actual is a conversion of a packed reference, it may
1127             --  already have been expanded by Remove_Side_Effects, and the
1128             --  resulting variable is a temporary which does not designate
1129             --  the proper out-parameter, which may not be addressable. In
1130             --  that case, generate an assignment to the original expression
1131             --  (before expansion of the  packed reference) so that the proper
1132             --  expansion of assignment to a packed component can take place.
1133
1134             declare
1135                Obj : Node_Id;
1136                Lhs : Node_Id;
1137
1138             begin
1139                if Is_Renaming_Of_Object (Var)
1140                  and then Nkind (Renamed_Object (Var)) = N_Selected_Component
1141                  and then Is_Entity_Name (Prefix (Renamed_Object (Var)))
1142                  and then Nkind (Original_Node (Prefix (Renamed_Object (Var))))
1143                    = N_Indexed_Component
1144                  and then
1145                    Has_Non_Standard_Rep (Etype (Prefix (Renamed_Object (Var))))
1146                then
1147                   Obj := Renamed_Object (Var);
1148                   Lhs :=
1149                     Make_Selected_Component (Loc,
1150                       Prefix        =>
1151                         New_Copy_Tree (Original_Node (Prefix (Obj))),
1152                       Selector_Name => New_Copy (Selector_Name (Obj)));
1153                   Reset_Analyzed_Flags (Lhs);
1154
1155                else
1156                   Lhs :=  New_Occurrence_Of (Var, Loc);
1157                end if;
1158
1159                Set_Assignment_OK (Lhs);
1160
1161                Append_To (Post_Call,
1162                  Make_Assignment_Statement (Loc,
1163                    Name       => Lhs,
1164                    Expression => Expr));
1165             end;
1166          end if;
1167
1168       end Add_Call_By_Copy_Code;
1169
1170       ----------------------------------
1171       -- Add_Simple_Call_By_Copy_Code --
1172       ----------------------------------
1173
1174       procedure Add_Simple_Call_By_Copy_Code is
1175          Temp   : Entity_Id;
1176          Decl   : Node_Id;
1177          Incod  : Node_Id;
1178          Outcod : Node_Id;
1179          Lhs    : Node_Id;
1180          Rhs    : Node_Id;
1181          Indic  : Node_Id;
1182          F_Typ  : constant Entity_Id := Etype (Formal);
1183
1184       begin
1185          if not Is_Legal_Copy then
1186             return;
1187          end if;
1188
1189          --  Use formal type for temp, unless formal type is an unconstrained
1190          --  array, in which case we don't have to worry about bounds checks,
1191          --  and we use the actual type, since that has appropriate bounds.
1192
1193          if Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ) then
1194             Indic := New_Occurrence_Of (Etype (Actual), Loc);
1195          else
1196             Indic := New_Occurrence_Of (Etype (Formal), Loc);
1197          end if;
1198
1199          --  Prepare to generate code
1200
1201          Reset_Packed_Prefix;
1202
1203          Temp :=
1204            Make_Defining_Identifier (Loc,
1205              Chars => New_Internal_Name ('T'));
1206          Incod  := Relocate_Node (Actual);
1207          Outcod := New_Copy_Tree (Incod);
1208
1209          --  Generate declaration of temporary variable, initializing it
1210          --  with the input parameter unless we have an OUT formal or
1211          --  this is an initialization call.
1212
1213          --  If the formal is an out parameter with discriminants, the
1214          --  discriminants must be captured even if the rest of the object
1215          --  is in principle uninitialized, because the discriminants may
1216          --  be read by the called subprogram.
1217
1218          if Ekind (Formal) = E_Out_Parameter then
1219             Incod := Empty;
1220
1221             if Has_Discriminants (Etype (Formal)) then
1222                Indic := New_Occurrence_Of (Etype (Actual), Loc);
1223             end if;
1224
1225          elsif Inside_Init_Proc then
1226
1227             --  Could use a comment here to match comment below ???
1228
1229             if Nkind (Actual) /= N_Selected_Component
1230               or else
1231                 not Has_Discriminant_Dependent_Constraint
1232                   (Entity (Selector_Name (Actual)))
1233             then
1234                Incod := Empty;
1235
1236             --  Otherwise, keep the component in order to generate the proper
1237             --  actual subtype, that depends on enclosing discriminants.
1238
1239             else
1240                null;
1241             end if;
1242          end if;
1243
1244          Decl :=
1245            Make_Object_Declaration (Loc,
1246              Defining_Identifier => Temp,
1247              Object_Definition   => Indic,
1248              Expression          => Incod);
1249
1250          if Inside_Init_Proc
1251            and then No (Incod)
1252          then
1253             --  If the call is to initialize a component of a composite type,
1254             --  and the component does not depend on discriminants, use the
1255             --  actual type of the component. This is required in case the
1256             --  component is constrained, because in general the formal of the
1257             --  initialization procedure will be unconstrained. Note that if
1258             --  the component being initialized is constrained by an enclosing
1259             --  discriminant, the presence of the initialization in the
1260             --  declaration will generate an expression for the actual subtype.
1261
1262             Set_No_Initialization (Decl);
1263             Set_Object_Definition (Decl,
1264               New_Occurrence_Of (Etype (Actual), Loc));
1265          end if;
1266
1267          Insert_Action (N, Decl);
1268
1269          --  The actual is simply a reference to the temporary
1270
1271          Rewrite (Actual, New_Occurrence_Of (Temp, Loc));
1272
1273          --  Generate copy out if OUT or IN OUT parameter
1274
1275          if Ekind (Formal) /= E_In_Parameter then
1276             Lhs := Outcod;
1277             Rhs := New_Occurrence_Of (Temp, Loc);
1278
1279             --  Deal with conversion
1280
1281             if Nkind (Lhs) = N_Type_Conversion then
1282                Lhs := Expression (Lhs);
1283                Rhs := Convert_To (Etype (Actual), Rhs);
1284             end if;
1285
1286             Append_To (Post_Call,
1287               Make_Assignment_Statement (Loc,
1288                 Name       => Lhs,
1289                 Expression => Rhs));
1290             Set_Assignment_OK (Name (Last (Post_Call)));
1291          end if;
1292       end Add_Simple_Call_By_Copy_Code;
1293
1294       ---------------------------
1295       -- Check_Fortran_Logical --
1296       ---------------------------
1297
1298       procedure Check_Fortran_Logical is
1299          Logical : constant Entity_Id := Etype (Formal);
1300          Var     : Entity_Id;
1301
1302       --  Note: this is very incomplete, e.g. it does not handle arrays
1303       --  of logical values. This is really not the right approach at all???)
1304
1305       begin
1306          if Convention (Subp) = Convention_Fortran
1307            and then Root_Type (Etype (Formal)) = Standard_Boolean
1308            and then Ekind (Formal) /= E_In_Parameter
1309          then
1310             Var := Make_Var (Actual);
1311             Append_To (Post_Call,
1312               Make_Assignment_Statement (Loc,
1313                 Name => New_Occurrence_Of (Var, Loc),
1314                 Expression =>
1315                   Unchecked_Convert_To (
1316                     Logical,
1317                     Make_Op_Ne (Loc,
1318                       Left_Opnd  => New_Occurrence_Of (Var, Loc),
1319                       Right_Opnd =>
1320                         Unchecked_Convert_To (
1321                           Logical,
1322                           New_Occurrence_Of (Standard_False, Loc))))));
1323          end if;
1324       end Check_Fortran_Logical;
1325
1326       -------------------
1327       -- Is_Legal_Copy --
1328       -------------------
1329
1330       function Is_Legal_Copy return Boolean is
1331       begin
1332          --  An attempt to copy a value of such a type can only occur if
1333          --  representation clauses give the actual a misaligned address.
1334
1335          if Is_By_Reference_Type (Etype (Formal)) then
1336             Error_Msg_N
1337               ("misaligned actual cannot be passed by reference", Actual);
1338             return False;
1339
1340          --  For users of Starlet, we assume that the specification of by-
1341          --  reference mechanism is mandatory. This may lead to unaligned
1342          --  objects but at least for DEC legacy code it is known to work.
1343          --  The warning will alert users of this code that a problem may
1344          --  be lurking.
1345
1346          elsif Mechanism (Formal) = By_Reference
1347            and then Is_Valued_Procedure (Scope (Formal))
1348          then
1349             Error_Msg_N
1350               ("by_reference actual may be misaligned?", Actual);
1351             return False;
1352
1353          else
1354             return True;
1355          end if;
1356       end Is_Legal_Copy;
1357
1358       --------------
1359       -- Make_Var --
1360       --------------
1361
1362       function Make_Var (Actual : Node_Id) return Entity_Id is
1363          Var : Entity_Id;
1364
1365       begin
1366          if Is_Entity_Name (Actual) then
1367             return Entity (Actual);
1368
1369          else
1370             Var :=
1371               Make_Defining_Identifier (Loc,
1372                 Chars => New_Internal_Name ('T'));
1373
1374             N_Node :=
1375               Make_Object_Renaming_Declaration (Loc,
1376                 Defining_Identifier => Var,
1377                 Subtype_Mark        =>
1378                   New_Occurrence_Of (Etype (Actual), Loc),
1379                 Name                => Relocate_Node (Actual));
1380
1381             Insert_Action (N, N_Node);
1382             return Var;
1383          end if;
1384       end Make_Var;
1385
1386       -------------------------
1387       -- Reset_Packed_Prefix --
1388       -------------------------
1389
1390       procedure Reset_Packed_Prefix is
1391          Pfx : Node_Id := Actual;
1392       begin
1393          loop
1394             Set_Analyzed (Pfx, False);
1395             exit when Nkind (Pfx) /= N_Selected_Component
1396               and then Nkind (Pfx) /= N_Indexed_Component;
1397             Pfx := Prefix (Pfx);
1398          end loop;
1399       end Reset_Packed_Prefix;
1400
1401    --  Start of processing for Expand_Actuals
1402
1403    begin
1404       Post_Call := New_List;
1405
1406       Formal := First_Formal (Subp);
1407       Actual := First_Actual (N);
1408       while Present (Formal) loop
1409          E_Formal := Etype (Formal);
1410
1411          if Is_Scalar_Type (E_Formal)
1412            or else Nkind (Actual) = N_Slice
1413          then
1414             Check_Fortran_Logical;
1415
1416          --  RM 6.4.1 (11)
1417
1418          elsif Ekind (Formal) /= E_Out_Parameter then
1419
1420             --  The unusual case of the current instance of a protected type
1421             --  requires special handling. This can only occur in the context
1422             --  of a call within the body of a protected operation.
1423
1424             if Is_Entity_Name (Actual)
1425               and then Ekind (Entity (Actual)) = E_Protected_Type
1426               and then In_Open_Scopes (Entity (Actual))
1427             then
1428                if Scope (Subp) /= Entity (Actual) then
1429                   Error_Msg_N ("operation outside protected type may not "
1430                     & "call back its protected operations?", Actual);
1431                end if;
1432
1433                Rewrite (Actual,
1434                  Expand_Protected_Object_Reference (N, Entity (Actual)));
1435             end if;
1436
1437             --  Ada 2005 (AI-318-02): If the actual parameter is a call to a
1438             --  build-in-place function, then a temporary return object needs
1439             --  to be created and access to it must be passed to the function.
1440             --  Currently we limit such functions to those with inherently
1441             --  limited result subtypes, but eventually we plan to expand the
1442             --  functions that are treated as build-in-place to include other
1443             --  composite result types.
1444
1445             if Ada_Version >= Ada_05
1446               and then Is_Build_In_Place_Function_Call (Actual)
1447             then
1448                Make_Build_In_Place_Call_In_Anonymous_Context (Actual);
1449             end if;
1450
1451             Apply_Constraint_Check (Actual, E_Formal);
1452
1453          --  Out parameter case. No constraint checks on access type
1454          --  RM 6.4.1 (13)
1455
1456          elsif Is_Access_Type (E_Formal) then
1457             null;
1458
1459          --  RM 6.4.1 (14)
1460
1461          elsif Has_Discriminants (Base_Type (E_Formal))
1462            or else Has_Non_Null_Base_Init_Proc (E_Formal)
1463          then
1464             Apply_Constraint_Check (Actual, E_Formal);
1465
1466          --  RM 6.4.1 (15)
1467
1468          else
1469             Apply_Constraint_Check (Actual, Base_Type (E_Formal));
1470          end if;
1471
1472          --  Processing for IN-OUT and OUT parameters
1473
1474          if Ekind (Formal) /= E_In_Parameter then
1475
1476             --  For type conversions of arrays, apply length/range checks
1477
1478             if Is_Array_Type (E_Formal)
1479               and then Nkind (Actual) = N_Type_Conversion
1480             then
1481                if Is_Constrained (E_Formal) then
1482                   Apply_Length_Check (Expression (Actual), E_Formal);
1483                else
1484                   Apply_Range_Check (Expression (Actual), E_Formal);
1485                end if;
1486             end if;
1487
1488             --  If argument is a type conversion for a type that is passed
1489             --  by copy, then we must pass the parameter by copy.
1490
1491             if Nkind (Actual) = N_Type_Conversion
1492               and then
1493                 (Is_Numeric_Type (E_Formal)
1494                   or else Is_Access_Type (E_Formal)
1495                   or else Is_Enumeration_Type (E_Formal)
1496                   or else Is_Bit_Packed_Array (Etype (Formal))
1497                   or else Is_Bit_Packed_Array (Etype (Expression (Actual)))
1498
1499                   --  Also pass by copy if change of representation
1500
1501                   or else not Same_Representation
1502                                (Etype (Formal),
1503                                 Etype (Expression (Actual))))
1504             then
1505                Add_Call_By_Copy_Code;
1506
1507             --  References to components of bit packed arrays are expanded
1508             --  at this point, rather than at the point of analysis of the
1509             --  actuals, to handle the expansion of the assignment to
1510             --  [in] out parameters.
1511
1512             elsif Is_Ref_To_Bit_Packed_Array (Actual) then
1513                Add_Simple_Call_By_Copy_Code;
1514
1515             --  If a non-scalar actual is possibly bit-aligned, we need a copy
1516             --  because the back-end cannot cope with such objects. In other
1517             --  cases where alignment forces a copy, the back-end generates
1518             --  it properly. It should not be generated unconditionally in the
1519             --  front-end because it does not know precisely the alignment
1520             --  requirements of the target, and makes too conservative an
1521             --  estimate, leading to superfluous copies or spurious errors
1522             --  on by-reference parameters.
1523
1524             elsif Nkind (Actual) = N_Selected_Component
1525               and then
1526                 Component_May_Be_Bit_Aligned (Entity (Selector_Name (Actual)))
1527               and then not Represented_As_Scalar (Etype (Formal))
1528             then
1529                Add_Simple_Call_By_Copy_Code;
1530
1531             --  References to slices of bit packed arrays are expanded
1532
1533             elsif Is_Ref_To_Bit_Packed_Slice (Actual) then
1534                Add_Call_By_Copy_Code;
1535
1536             --  References to possibly unaligned slices of arrays are expanded
1537
1538             elsif Is_Possibly_Unaligned_Slice (Actual) then
1539                Add_Call_By_Copy_Code;
1540
1541             --  Deal with access types where the actual subtype and the
1542             --  formal subtype are not the same, requiring a check.
1543
1544             --  It is necessary to exclude tagged types because of "downward
1545             --  conversion" errors and a strange assertion error in namet
1546             --  from gnatf in bug 1215-001 ???
1547
1548             elsif Is_Access_Type (E_Formal)
1549               and then not Same_Type (E_Formal, Etype (Actual))
1550               and then not Is_Tagged_Type (Designated_Type (E_Formal))
1551             then
1552                Add_Call_By_Copy_Code;
1553
1554             --  If the actual is not a scalar and is marked for volatile
1555             --  treatment, whereas the formal is not volatile, then pass
1556             --  by copy unless it is a by-reference type.
1557
1558             elsif Is_Entity_Name (Actual)
1559               and then Treat_As_Volatile (Entity (Actual))
1560               and then not Is_By_Reference_Type (Etype (Actual))
1561               and then not Is_Scalar_Type (Etype (Entity (Actual)))
1562               and then not Treat_As_Volatile (E_Formal)
1563             then
1564                Add_Call_By_Copy_Code;
1565
1566             elsif Nkind (Actual) = N_Indexed_Component
1567               and then Is_Entity_Name (Prefix (Actual))
1568               and then Has_Volatile_Components (Entity (Prefix (Actual)))
1569             then
1570                Add_Call_By_Copy_Code;
1571             end if;
1572
1573          --  Processing for IN parameters
1574
1575          else
1576             --  For IN parameters is in the packed array case, we expand an
1577             --  indexed component (the circuit in Exp_Ch4 deliberately left
1578             --  indexed components appearing as actuals untouched, so that
1579             --  the special processing above for the OUT and IN OUT cases
1580             --  could be performed. We could make the test in Exp_Ch4 more
1581             --  complex and have it detect the parameter mode, but it is
1582             --  easier simply to handle all cases here.)
1583
1584             if Nkind (Actual) = N_Indexed_Component
1585               and then Is_Packed (Etype (Prefix (Actual)))
1586             then
1587                Reset_Packed_Prefix;
1588                Expand_Packed_Element_Reference (Actual);
1589
1590             --  If we have a reference to a bit packed array, we copy it,
1591             --  since the actual must be byte aligned.
1592
1593             --  Is this really necessary in all cases???
1594
1595             elsif Is_Ref_To_Bit_Packed_Array (Actual) then
1596                Add_Simple_Call_By_Copy_Code;
1597
1598             --  If a non-scalar actual is possibly unaligned, we need a copy
1599
1600             elsif Is_Possibly_Unaligned_Object (Actual)
1601               and then not Represented_As_Scalar (Etype (Formal))
1602             then
1603                Add_Simple_Call_By_Copy_Code;
1604
1605             --  Similarly, we have to expand slices of packed arrays here
1606             --  because the result must be byte aligned.
1607
1608             elsif Is_Ref_To_Bit_Packed_Slice (Actual) then
1609                Add_Call_By_Copy_Code;
1610
1611             --  Only processing remaining is to pass by copy if this is a
1612             --  reference to a possibly unaligned slice, since the caller
1613             --  expects an appropriately aligned argument.
1614
1615             elsif Is_Possibly_Unaligned_Slice (Actual) then
1616                Add_Call_By_Copy_Code;
1617             end if;
1618          end if;
1619
1620          Next_Formal (Formal);
1621          Next_Actual (Actual);
1622       end loop;
1623
1624       --  Find right place to put post call stuff if it is present
1625
1626       if not Is_Empty_List (Post_Call) then
1627
1628          --  If call is not a list member, it must be the triggering statement
1629          --  of a triggering alternative or an entry call alternative, and we
1630          --  can add the post call stuff to the corresponding statement list.
1631
1632          if not Is_List_Member (N) then
1633             declare
1634                P : constant Node_Id := Parent (N);
1635
1636             begin
1637                pragma Assert (Nkind (P) = N_Triggering_Alternative
1638                  or else Nkind (P) = N_Entry_Call_Alternative);
1639
1640                if Is_Non_Empty_List (Statements (P)) then
1641                   Insert_List_Before_And_Analyze
1642                     (First (Statements (P)), Post_Call);
1643                else
1644                   Set_Statements (P, Post_Call);
1645                end if;
1646             end;
1647
1648          --  Otherwise, normal case where N is in a statement sequence,
1649          --  just put the post-call stuff after the call statement.
1650
1651          else
1652             Insert_Actions_After (N, Post_Call);
1653          end if;
1654       end if;
1655
1656       --  The call node itself is re-analyzed in Expand_Call
1657
1658    end Expand_Actuals;
1659
1660    -----------------
1661    -- Expand_Call --
1662    -----------------
1663
1664    --  This procedure handles expansion of function calls and procedure call
1665    --  statements (i.e. it serves as the body for Expand_N_Function_Call and
1666    --  Expand_N_Procedure_Call_Statement. Processing for calls includes:
1667
1668    --    Replace call to Raise_Exception by Raise_Exception always if possible
1669    --    Provide values of actuals for all formals in Extra_Formals list
1670    --    Replace "call" to enumeration literal function by literal itself
1671    --    Rewrite call to predefined operator as operator
1672    --    Replace actuals to in-out parameters that are numeric conversions,
1673    --     with explicit assignment to temporaries before and after the call.
1674    --    Remove optional actuals if First_Optional_Parameter specified.
1675
1676    --   Note that the list of actuals has been filled with default expressions
1677    --   during semantic analysis of the call. Only the extra actuals required
1678    --   for the 'Constrained attribute and for accessibility checks are added
1679    --   at this point.
1680
1681    procedure Expand_Call (N : Node_Id) is
1682       Loc           : constant Source_Ptr := Sloc (N);
1683       Remote        : constant Boolean    := Is_Remote_Call (N);
1684       Subp          : Entity_Id;
1685       Orig_Subp     : Entity_Id := Empty;
1686       Parent_Subp   : Entity_Id;
1687       Parent_Formal : Entity_Id;
1688       Actual        : Node_Id;
1689       Formal        : Entity_Id;
1690       Prev          : Node_Id := Empty;
1691
1692       Prev_Orig : Node_Id;
1693       --  Original node for an actual, which may have been rewritten. If the
1694       --  actual is a function call that has been transformed from a selected
1695       --  component, the original node is unanalyzed. Otherwise, it carries
1696       --  semantic information used to generate additional actuals.
1697
1698       Scop          : Entity_Id;
1699       Extra_Actuals : List_Id := No_List;
1700
1701       CW_Interface_Formals_Present : Boolean := False;
1702
1703       procedure Add_Actual_Parameter (Insert_Param : Node_Id);
1704       --  Adds one entry to the end of the actual parameter list. Used for
1705       --  default parameters and for extra actuals (for Extra_Formals). The
1706       --  argument is an N_Parameter_Association node.
1707
1708       procedure Add_Extra_Actual (Expr : Node_Id; EF : Entity_Id);
1709       --  Adds an extra actual to the list of extra actuals. Expr is the
1710       --  expression for the value of the actual, EF is the entity for the
1711       --  extra formal.
1712
1713       function Inherited_From_Formal (S : Entity_Id) return Entity_Id;
1714       --  Within an instance, a type derived from a non-tagged formal derived
1715       --  type inherits from the original parent, not from the actual. This is
1716       --  tested in 4723-003. The current derivation mechanism has the derived
1717       --  type inherit from the actual, which is only correct outside of the
1718       --  instance. If the subprogram is inherited, we test for this particular
1719       --  case through a convoluted tree traversal before setting the proper
1720       --  subprogram to be called.
1721
1722       --------------------------
1723       -- Add_Actual_Parameter --
1724       --------------------------
1725
1726       procedure Add_Actual_Parameter (Insert_Param : Node_Id) is
1727          Actual_Expr : constant Node_Id :=
1728                          Explicit_Actual_Parameter (Insert_Param);
1729
1730       begin
1731          --  Case of insertion is first named actual
1732
1733          if No (Prev) or else
1734             Nkind (Parent (Prev)) /= N_Parameter_Association
1735          then
1736             Set_Next_Named_Actual (Insert_Param, First_Named_Actual (N));
1737             Set_First_Named_Actual (N, Actual_Expr);
1738
1739             if No (Prev) then
1740                if No (Parameter_Associations (N)) then
1741                   Set_Parameter_Associations (N, New_List);
1742                   Append (Insert_Param, Parameter_Associations (N));
1743                end if;
1744             else
1745                Insert_After (Prev, Insert_Param);
1746             end if;
1747
1748          --  Case of insertion is not first named actual
1749
1750          else
1751             Set_Next_Named_Actual
1752               (Insert_Param, Next_Named_Actual (Parent (Prev)));
1753             Set_Next_Named_Actual (Parent (Prev), Actual_Expr);
1754             Append (Insert_Param, Parameter_Associations (N));
1755          end if;
1756
1757          Prev := Actual_Expr;
1758       end Add_Actual_Parameter;
1759
1760       ----------------------
1761       -- Add_Extra_Actual --
1762       ----------------------
1763
1764       procedure Add_Extra_Actual (Expr : Node_Id; EF : Entity_Id) is
1765          Loc : constant Source_Ptr := Sloc (Expr);
1766
1767       begin
1768          if Extra_Actuals = No_List then
1769             Extra_Actuals := New_List;
1770             Set_Parent (Extra_Actuals, N);
1771          end if;
1772
1773          Append_To (Extra_Actuals,
1774            Make_Parameter_Association (Loc,
1775              Explicit_Actual_Parameter => Expr,
1776              Selector_Name =>
1777                Make_Identifier (Loc, Chars (EF))));
1778
1779          Analyze_And_Resolve (Expr, Etype (EF));
1780       end Add_Extra_Actual;
1781
1782       ---------------------------
1783       -- Inherited_From_Formal --
1784       ---------------------------
1785
1786       function Inherited_From_Formal (S : Entity_Id) return Entity_Id is
1787          Par      : Entity_Id;
1788          Gen_Par  : Entity_Id;
1789          Gen_Prim : Elist_Id;
1790          Elmt     : Elmt_Id;
1791          Indic    : Node_Id;
1792
1793       begin
1794          --  If the operation is inherited, it is attached to the corresponding
1795          --  type derivation. If the parent in the derivation is a generic
1796          --  actual, it is a subtype of the actual, and we have to recover the
1797          --  original derived type declaration to find the proper parent.
1798
1799          if Nkind (Parent (S)) /= N_Full_Type_Declaration
1800            or else not Is_Derived_Type (Defining_Identifier (Parent (S)))
1801            or else Nkind (Type_Definition (Original_Node (Parent (S)))) /=
1802                                                    N_Derived_Type_Definition
1803            or else not In_Instance
1804          then
1805             return Empty;
1806
1807          else
1808             Indic :=
1809               (Subtype_Indication
1810                 (Type_Definition (Original_Node (Parent (S)))));
1811
1812             if Nkind (Indic) = N_Subtype_Indication then
1813                Par := Entity (Subtype_Mark (Indic));
1814             else
1815                Par := Entity (Indic);
1816             end if;
1817          end if;
1818
1819          if not Is_Generic_Actual_Type (Par)
1820            or else Is_Tagged_Type (Par)
1821            or else Nkind (Parent (Par)) /= N_Subtype_Declaration
1822            or else not In_Open_Scopes (Scope (Par))
1823          then
1824             return Empty;
1825
1826          else
1827             Gen_Par := Generic_Parent_Type (Parent (Par));
1828          end if;
1829
1830          --  If the actual has no generic parent type, the formal is not
1831          --  a formal derived type, so nothing to inherit.
1832
1833          if No (Gen_Par) then
1834             return Empty;
1835          end if;
1836
1837          --  If the generic parent type is still the generic type, this is a
1838          --  private formal, not a derived formal, and there are no operations
1839          --  inherited from the formal.
1840
1841          if Nkind (Parent (Gen_Par)) = N_Formal_Type_Declaration then
1842             return Empty;
1843          end if;
1844
1845          Gen_Prim := Collect_Primitive_Operations (Gen_Par);
1846
1847          Elmt := First_Elmt (Gen_Prim);
1848          while Present (Elmt) loop
1849             if Chars (Node (Elmt)) = Chars (S) then
1850                declare
1851                   F1 : Entity_Id;
1852                   F2 : Entity_Id;
1853
1854                begin
1855                   F1 := First_Formal (S);
1856                   F2 := First_Formal (Node (Elmt));
1857                   while Present (F1)
1858                     and then Present (F2)
1859                   loop
1860                      if Etype (F1) = Etype (F2)
1861                        or else Etype (F2) = Gen_Par
1862                      then
1863                         Next_Formal (F1);
1864                         Next_Formal (F2);
1865                      else
1866                         Next_Elmt (Elmt);
1867                         exit;   --  not the right subprogram
1868                      end if;
1869
1870                      return Node (Elmt);
1871                   end loop;
1872                end;
1873
1874             else
1875                Next_Elmt (Elmt);
1876             end if;
1877          end loop;
1878
1879          raise Program_Error;
1880       end Inherited_From_Formal;
1881
1882    --  Start of processing for Expand_Call
1883
1884    begin
1885       --  Ignore if previous error
1886
1887       if Nkind (N) in N_Has_Etype and then Etype (N) = Any_Type then
1888          return;
1889       end if;
1890
1891       --  Call using access to subprogram with explicit dereference
1892
1893       if Nkind (Name (N)) = N_Explicit_Dereference then
1894          Subp        := Etype (Name (N));
1895          Parent_Subp := Empty;
1896
1897       --  Case of call to simple entry, where the Name is a selected component
1898       --  whose prefix is the task, and whose selector name is the entry name
1899
1900       elsif Nkind (Name (N)) = N_Selected_Component then
1901          Subp        := Entity (Selector_Name (Name (N)));
1902          Parent_Subp := Empty;
1903
1904       --  Case of call to member of entry family, where Name is an indexed
1905       --  component, with the prefix being a selected component giving the
1906       --  task and entry family name, and the index being the entry index.
1907
1908       elsif Nkind (Name (N)) = N_Indexed_Component then
1909          Subp        := Entity (Selector_Name (Prefix (Name (N))));
1910          Parent_Subp := Empty;
1911
1912       --  Normal case
1913
1914       else
1915          Subp        := Entity (Name (N));
1916          Parent_Subp := Alias (Subp);
1917
1918          --  Replace call to Raise_Exception by call to Raise_Exception_Always
1919          --  if we can tell that the first parameter cannot possibly be null.
1920          --  This helps optimization and also generation of warnings.
1921
1922          --  We do not do this if Raise_Exception_Always does not exist, which
1923          --  can happen in configurable run time profiles which provide only a
1924          --  Raise_Exception, which is in fact an unconditional raise anyway.
1925
1926          if Is_RTE (Subp, RE_Raise_Exception)
1927            and then RTE_Available (RE_Raise_Exception_Always)
1928          then
1929             declare
1930                FA : constant Node_Id := Original_Node (First_Actual (N));
1931
1932             begin
1933                --  The case we catch is where the first argument is obtained
1934                --  using the Identity attribute (which must always be
1935                --  non-null).
1936
1937                if Nkind (FA) = N_Attribute_Reference
1938                  and then Attribute_Name (FA) = Name_Identity
1939                then
1940                   Subp := RTE (RE_Raise_Exception_Always);
1941                   Set_Name (N, New_Occurrence_Of (Subp, Loc));
1942                end if;
1943             end;
1944          end if;
1945
1946          if Ekind (Subp) = E_Entry then
1947             Parent_Subp := Empty;
1948          end if;
1949       end if;
1950
1951       --  Ada 2005 (AI-345): We have a procedure call as a triggering
1952       --  alternative in an asynchronous select or as an entry call in
1953       --  a conditional or timed select. Check whether the procedure call
1954       --  is a renaming of an entry and rewrite it as an entry call.
1955
1956       if Ada_Version >= Ada_05
1957         and then Nkind (N) = N_Procedure_Call_Statement
1958         and then
1959            ((Nkind (Parent (N)) = N_Triggering_Alternative
1960                and then Triggering_Statement (Parent (N)) = N)
1961           or else
1962             (Nkind (Parent (N)) = N_Entry_Call_Alternative
1963                and then Entry_Call_Statement (Parent (N)) = N))
1964       then
1965          declare
1966             Ren_Decl : Node_Id;
1967             Ren_Root : Entity_Id := Subp;
1968
1969          begin
1970             --  This may be a chain of renamings, find the root
1971
1972             if Present (Alias (Ren_Root)) then
1973                Ren_Root := Alias (Ren_Root);
1974             end if;
1975
1976             if Present (Original_Node (Parent (Parent (Ren_Root)))) then
1977                Ren_Decl := Original_Node (Parent (Parent (Ren_Root)));
1978
1979                if Nkind (Ren_Decl) = N_Subprogram_Renaming_Declaration then
1980                   Rewrite (N,
1981                     Make_Entry_Call_Statement (Loc,
1982                       Name =>
1983                         New_Copy_Tree (Name (Ren_Decl)),
1984                       Parameter_Associations =>
1985                         New_Copy_List_Tree (Parameter_Associations (N))));
1986
1987                   return;
1988                end if;
1989             end if;
1990          end;
1991       end if;
1992
1993       --  First step, compute extra actuals, corresponding to any
1994       --  Extra_Formals present. Note that we do not access Extra_Formals
1995       --  directly, instead we simply note the presence of the extra
1996       --  formals as we process the regular formals and collect the
1997       --  corresponding actuals in Extra_Actuals.
1998
1999       --  We also generate any required range checks for actuals as we go
2000       --  through the loop, since this is a convenient place to do this.
2001
2002       Formal := First_Formal (Subp);
2003       Actual := First_Actual (N);
2004       while Present (Formal) loop
2005
2006          --  Generate range check if required (not activated yet ???)
2007
2008 --         if Do_Range_Check (Actual) then
2009 --            Set_Do_Range_Check (Actual, False);
2010 --            Generate_Range_Check
2011 --              (Actual, Etype (Formal), CE_Range_Check_Failed);
2012 --         end if;
2013
2014          --  Prepare to examine current entry
2015
2016          Prev := Actual;
2017          Prev_Orig := Original_Node (Prev);
2018
2019          --  The original actual may have been a call written in prefix
2020          --  form, and rewritten before analysis.
2021
2022          if not Analyzed (Prev_Orig)
2023            and then
2024              (Nkind (Actual) = N_Function_Call
2025                 or else
2026               Nkind (Actual) = N_Identifier)
2027          then
2028             Prev_Orig := Prev;
2029          end if;
2030
2031          --  Ada 2005 (AI-251): Check if any formal is a class-wide interface
2032          --  to expand it in a further round.
2033
2034          CW_Interface_Formals_Present :=
2035            CW_Interface_Formals_Present
2036              or else
2037                (Ekind (Etype (Formal)) = E_Class_Wide_Type
2038                   and then Is_Interface (Etype (Etype (Formal))))
2039              or else
2040                (Ekind (Etype (Formal)) = E_Anonymous_Access_Type
2041                  and then Is_Interface (Directly_Designated_Type
2042                                          (Etype (Etype (Formal)))));
2043
2044          --  Create possible extra actual for constrained case. Usually, the
2045          --  extra actual is of the form actual'constrained, but since this
2046          --  attribute is only available for unconstrained records, TRUE is
2047          --  expanded if the type of the formal happens to be constrained (for
2048          --  instance when this procedure is inherited from an unconstrained
2049          --  record to a constrained one) or if the actual has no discriminant
2050          --  (its type is constrained). An exception to this is the case of a
2051          --  private type without discriminants. In this case we pass FALSE
2052          --  because the object has underlying discriminants with defaults.
2053
2054          if Present (Extra_Constrained (Formal)) then
2055             if Ekind (Etype (Prev)) in Private_Kind
2056               and then not Has_Discriminants (Base_Type (Etype (Prev)))
2057             then
2058                Add_Extra_Actual (
2059                  New_Occurrence_Of (Standard_False, Loc),
2060                  Extra_Constrained (Formal));
2061
2062             elsif Is_Constrained (Etype (Formal))
2063               or else not Has_Discriminants (Etype (Prev))
2064             then
2065                Add_Extra_Actual (
2066                  New_Occurrence_Of (Standard_True, Loc),
2067                  Extra_Constrained (Formal));
2068
2069             --  Do not produce extra actuals for Unchecked_Union parameters.
2070             --  Jump directly to the end of the loop.
2071
2072             elsif Is_Unchecked_Union (Base_Type (Etype (Actual))) then
2073                goto Skip_Extra_Actual_Generation;
2074
2075             else
2076                --  If the actual is a type conversion, then the constrained
2077                --  test applies to the actual, not the target type.
2078
2079                declare
2080                   Act_Prev : Node_Id;
2081
2082                begin
2083                   --  Test for unchecked conversions as well, which can occur
2084                   --  as out parameter actuals on calls to stream procedures.
2085
2086                   Act_Prev := Prev;
2087                   while Nkind (Act_Prev) = N_Type_Conversion
2088                     or else Nkind (Act_Prev) = N_Unchecked_Type_Conversion
2089                   loop
2090                      Act_Prev := Expression (Act_Prev);
2091                   end loop;
2092
2093                   --  If the expression is a conversion of a dereference,
2094                   --  this is internally generated code that manipulates
2095                   --  addresses, e.g. when building interface tables. No
2096                   --  check should occur in this case, and the discriminated
2097                   --  object is not directly a hand.
2098
2099                   if not Comes_From_Source (Actual)
2100                     and then Nkind (Actual) = N_Unchecked_Type_Conversion
2101                     and then Nkind (Act_Prev) = N_Explicit_Dereference
2102                   then
2103                      Add_Extra_Actual
2104                        (New_Occurrence_Of (Standard_False, Loc),
2105                         Extra_Constrained (Formal));
2106
2107                   else
2108                      Add_Extra_Actual
2109                        (Make_Attribute_Reference (Sloc (Prev),
2110                         Prefix =>
2111                           Duplicate_Subexpr_No_Checks
2112                             (Act_Prev, Name_Req => True),
2113                         Attribute_Name => Name_Constrained),
2114                         Extra_Constrained (Formal));
2115                   end if;
2116                end;
2117             end if;
2118          end if;
2119
2120          --  Create possible extra actual for accessibility level
2121
2122          if Present (Extra_Accessibility (Formal)) then
2123
2124             --  Ada 2005 (AI-252): If the actual was rewritten as an Access
2125             --  attribute, then the original actual may be an aliased object
2126             --  occurring as the prefix in a call using "Object.Operation"
2127             --  notation. In that case we must pass the level of the object,
2128             --  so Prev_Orig is reset to Prev and the attribute will be
2129             --  processed by the code for Access attributes further below.
2130
2131             if Prev_Orig /= Prev
2132               and then Nkind (Prev) = N_Attribute_Reference
2133               and then
2134                 Get_Attribute_Id (Attribute_Name (Prev)) = Attribute_Access
2135               and then Is_Aliased_View (Prev_Orig)
2136             then
2137                Prev_Orig := Prev;
2138             end if;
2139
2140             if Is_Entity_Name (Prev_Orig) then
2141
2142                --  When passing an access parameter, or a renaming of an access
2143                --  parameter, as the actual to another access parameter we need
2144                --  to pass along the actual's own access level parameter. This
2145                --  is done if we are within the scope of the formal access
2146                --  parameter (if this is an inlined body the extra formal is
2147                --  irrelevant).
2148
2149                if (Is_Formal (Entity (Prev_Orig))
2150                     or else
2151                       (Present (Renamed_Object (Entity (Prev_Orig)))
2152                         and then
2153                           Is_Entity_Name (Renamed_Object (Entity (Prev_Orig)))
2154                         and then
2155                           Is_Formal
2156                             (Entity (Renamed_Object (Entity (Prev_Orig))))))
2157                  and then Ekind (Etype (Prev_Orig)) = E_Anonymous_Access_Type
2158                  and then In_Open_Scopes (Scope (Entity (Prev_Orig)))
2159                then
2160                   declare
2161                      Parm_Ent : constant Entity_Id := Param_Entity (Prev_Orig);
2162
2163                   begin
2164                      pragma Assert (Present (Parm_Ent));
2165
2166                      if Present (Extra_Accessibility (Parm_Ent)) then
2167                         Add_Extra_Actual
2168                           (New_Occurrence_Of
2169                              (Extra_Accessibility (Parm_Ent), Loc),
2170                            Extra_Accessibility (Formal));
2171
2172                      --  If the actual access parameter does not have an
2173                      --  associated extra formal providing its scope level,
2174                      --  then treat the actual as having library-level
2175                      --  accessibility.
2176
2177                      else
2178                         Add_Extra_Actual
2179                           (Make_Integer_Literal (Loc,
2180                            Intval => Scope_Depth (Standard_Standard)),
2181                            Extra_Accessibility (Formal));
2182                      end if;
2183                   end;
2184
2185                --  The actual is a normal access value, so just pass the level
2186                --  of the actual's access type.
2187
2188                else
2189                   Add_Extra_Actual
2190                     (Make_Integer_Literal (Loc,
2191                      Intval => Type_Access_Level (Etype (Prev_Orig))),
2192                      Extra_Accessibility (Formal));
2193                end if;
2194
2195             else
2196                case Nkind (Prev_Orig) is
2197
2198                   when N_Attribute_Reference =>
2199
2200                      case Get_Attribute_Id (Attribute_Name (Prev_Orig)) is
2201
2202                         --  For X'Access, pass on the level of the prefix X
2203
2204                         when Attribute_Access =>
2205                            Add_Extra_Actual (
2206                              Make_Integer_Literal (Loc,
2207                                Intval =>
2208                                  Object_Access_Level (Prefix (Prev_Orig))),
2209                              Extra_Accessibility (Formal));
2210
2211                         --  Treat the unchecked attributes as library-level
2212
2213                         when Attribute_Unchecked_Access |
2214                            Attribute_Unrestricted_Access =>
2215                            Add_Extra_Actual (
2216                              Make_Integer_Literal (Loc,
2217                                Intval => Scope_Depth (Standard_Standard)),
2218                              Extra_Accessibility (Formal));
2219
2220                         --  No other cases of attributes returning access
2221                         --  values that can be passed to access parameters
2222
2223                         when others =>
2224                            raise Program_Error;
2225
2226                      end case;
2227
2228                   --  For allocators we pass the level of the execution of
2229                   --  the called subprogram, which is one greater than the
2230                   --  current scope level.
2231
2232                   when N_Allocator =>
2233                      Add_Extra_Actual (
2234                        Make_Integer_Literal (Loc,
2235                         Scope_Depth (Current_Scope) + 1),
2236                        Extra_Accessibility (Formal));
2237
2238                   --  For other cases we simply pass the level of the
2239                   --  actual's access type.
2240
2241                   when others =>
2242                      Add_Extra_Actual (
2243                        Make_Integer_Literal (Loc,
2244                          Intval => Type_Access_Level (Etype (Prev_Orig))),
2245                        Extra_Accessibility (Formal));
2246
2247                end case;
2248             end if;
2249          end if;
2250
2251          --  Perform the check of 4.6(49) that prevents a null value from being
2252          --  passed as an actual to an access parameter. Note that the check is
2253          --  elided in the common cases of passing an access attribute or
2254          --  access parameter as an actual. Also, we currently don't enforce
2255          --  this check for expander-generated actuals and when -gnatdj is set.
2256
2257          if Ada_Version >= Ada_05 then
2258
2259             --  Ada 2005 (AI-231): Check null-excluding access types
2260
2261             if Is_Access_Type (Etype (Formal))
2262               and then Can_Never_Be_Null (Etype (Formal))
2263               and then Nkind (Prev) /= N_Raise_Constraint_Error
2264               and then (Known_Null (Prev)
2265                           or else not Can_Never_Be_Null (Etype (Prev)))
2266             then
2267                Install_Null_Excluding_Check (Prev);
2268             end if;
2269
2270          --  Ada_Version < Ada_05
2271
2272          else
2273             if Ekind (Etype (Formal)) /= E_Anonymous_Access_Type
2274               or else Access_Checks_Suppressed (Subp)
2275             then
2276                null;
2277
2278             elsif Debug_Flag_J then
2279                null;
2280
2281             elsif not Comes_From_Source (Prev) then
2282                null;
2283
2284             elsif Is_Entity_Name (Prev)
2285               and then Ekind (Etype (Prev)) = E_Anonymous_Access_Type
2286             then
2287                null;
2288
2289             elsif Nkind (Prev) = N_Allocator
2290               or else Nkind (Prev) = N_Attribute_Reference
2291             then
2292                null;
2293
2294             --  Suppress null checks when passing to access parameters of Java
2295             --  and CIL subprograms. (Should this be done for other foreign
2296             --  conventions as well ???)
2297
2298             elsif Convention (Subp) = Convention_Java
2299               or else Convention (Subp) = Convention_CIL
2300             then
2301                null;
2302
2303             else
2304                Install_Null_Excluding_Check (Prev);
2305             end if;
2306          end if;
2307
2308          --  Perform appropriate validity checks on parameters that
2309          --  are entities.
2310
2311          if Validity_Checks_On then
2312             if  (Ekind (Formal) = E_In_Parameter
2313                    and then Validity_Check_In_Params)
2314               or else
2315                 (Ekind (Formal) = E_In_Out_Parameter
2316                    and then Validity_Check_In_Out_Params)
2317             then
2318                --  If the actual is an indexed component of a packed type (or
2319                --  is an indexed or selected component whose prefix recursively
2320                --  meets this condition), it has not been expanded yet. It will
2321                --  be copied in the validity code that follows, and has to be
2322                --  expanded appropriately, so reanalyze it.
2323
2324                --  What we do is just to unset analyzed bits on prefixes till
2325                --  we reach something that does not have a prefix.
2326
2327                declare
2328                   Nod : Node_Id;
2329
2330                begin
2331                   Nod := Actual;
2332                   while Nkind (Nod) = N_Indexed_Component
2333                           or else
2334                         Nkind (Nod) = N_Selected_Component
2335                   loop
2336                      Set_Analyzed (Nod, False);
2337                      Nod := Prefix (Nod);
2338                   end loop;
2339                end;
2340
2341                Ensure_Valid (Actual);
2342             end if;
2343          end if;
2344
2345          --  For IN OUT and OUT parameters, ensure that subscripts are valid
2346          --  since this is a left side reference. We only do this for calls
2347          --  from the source program since we assume that compiler generated
2348          --  calls explicitly generate any required checks. We also need it
2349          --  only if we are doing standard validity checks, since clearly it
2350          --  is not needed if validity checks are off, and in subscript
2351          --  validity checking mode, all indexed components are checked with
2352          --  a call directly from Expand_N_Indexed_Component.
2353
2354          if Comes_From_Source (N)
2355            and then Ekind (Formal) /= E_In_Parameter
2356            and then Validity_Checks_On
2357            and then Validity_Check_Default
2358            and then not Validity_Check_Subscripts
2359          then
2360             Check_Valid_Lvalue_Subscripts (Actual);
2361          end if;
2362
2363          --  Mark any scalar OUT parameter that is a simple variable as no
2364          --  longer known to be valid (unless the type is always valid). This
2365          --  reflects the fact that if an OUT parameter is never set in a
2366          --  procedure, then it can become invalid on the procedure return.
2367
2368          if Ekind (Formal) = E_Out_Parameter
2369            and then Is_Entity_Name (Actual)
2370            and then Ekind (Entity (Actual)) = E_Variable
2371            and then not Is_Known_Valid (Etype (Actual))
2372          then
2373             Set_Is_Known_Valid (Entity (Actual), False);
2374          end if;
2375
2376          --  For an OUT or IN OUT parameter, if the actual is an entity, then
2377          --  clear current values, since they can be clobbered. We are probably
2378          --  doing this in more places than we need to, but better safe than
2379          --  sorry when it comes to retaining bad current values!
2380
2381          if Ekind (Formal) /= E_In_Parameter
2382            and then Is_Entity_Name (Actual)
2383          then
2384             Kill_Current_Values (Entity (Actual));
2385          end if;
2386
2387          --  If the formal is class wide and the actual is an aggregate, force
2388          --  evaluation so that the back end who does not know about class-wide
2389          --  type, does not generate a temporary of the wrong size.
2390
2391          if not Is_Class_Wide_Type (Etype (Formal)) then
2392             null;
2393
2394          elsif Nkind (Actual) = N_Aggregate
2395            or else (Nkind (Actual) = N_Qualified_Expression
2396                      and then Nkind (Expression (Actual)) = N_Aggregate)
2397          then
2398             Force_Evaluation (Actual);
2399          end if;
2400
2401          --  In a remote call, if the formal is of a class-wide type, check
2402          --  that the actual meets the requirements described in E.4(18).
2403
2404          if Remote and then Is_Class_Wide_Type (Etype (Formal)) then
2405             Insert_Action (Actual,
2406               Make_Transportable_Check (Loc,
2407                 Duplicate_Subexpr_Move_Checks (Actual)));
2408          end if;
2409
2410          --  This label is required when skipping extra actual generation for
2411          --  Unchecked_Union parameters.
2412
2413          <<Skip_Extra_Actual_Generation>>
2414
2415          Next_Actual (Actual);
2416          Next_Formal (Formal);
2417       end loop;
2418
2419       --  If we are expanding a rhs of an assignment we need to check if tag
2420       --  propagation is needed. You might expect this processing to be in
2421       --  Analyze_Assignment but has to be done earlier (bottom-up) because the
2422       --  assignment might be transformed to a declaration for an unconstrained
2423       --  value if the expression is classwide.
2424
2425       if Nkind (N) = N_Function_Call
2426         and then Is_Tag_Indeterminate (N)
2427         and then Is_Entity_Name (Name (N))
2428       then
2429          declare
2430             Ass : Node_Id := Empty;
2431
2432          begin
2433             if Nkind (Parent (N)) = N_Assignment_Statement then
2434                Ass := Parent (N);
2435
2436             elsif Nkind (Parent (N)) = N_Qualified_Expression
2437               and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
2438             then
2439                Ass := Parent (Parent (N));
2440
2441             elsif Nkind (Parent (N)) = N_Explicit_Dereference
2442               and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
2443             then
2444                Ass := Parent (Parent (N));
2445             end if;
2446
2447             if Present (Ass)
2448               and then Is_Class_Wide_Type (Etype (Name (Ass)))
2449             then
2450                if Is_Access_Type (Etype (N)) then
2451                   if Designated_Type (Etype (N)) /=
2452                     Root_Type (Etype (Name (Ass)))
2453                   then
2454                      Error_Msg_NE
2455                        ("tag-indeterminate expression "
2456                          & " must have designated type& (RM 5.2 (6))",
2457                            N, Root_Type (Etype (Name (Ass))));
2458                   else
2459                      Propagate_Tag (Name (Ass), N);
2460                   end if;
2461
2462                elsif Etype (N) /= Root_Type (Etype (Name (Ass))) then
2463                   Error_Msg_NE
2464                     ("tag-indeterminate expression must have type&"
2465                      & "(RM 5.2 (6))", N, Root_Type (Etype (Name (Ass))));
2466
2467                else
2468                   Propagate_Tag (Name (Ass), N);
2469                end if;
2470
2471                --  The call will be rewritten as a dispatching call, and
2472                --  expanded as such.
2473
2474                return;
2475             end if;
2476          end;
2477       end if;
2478
2479       --  Ada 2005 (AI-251): If some formal is a class-wide interface, expand
2480       --  it to point to the correct secondary virtual table
2481
2482       if (Nkind (N) = N_Function_Call
2483            or else Nkind (N) = N_Procedure_Call_Statement)
2484         and then CW_Interface_Formals_Present
2485       then
2486          Expand_Interface_Actuals (N);
2487       end if;
2488
2489       --  Deals with Dispatch_Call if we still have a call, before expanding
2490       --  extra actuals since this will be done on the re-analysis of the
2491       --  dispatching call. Note that we do not try to shorten the actual
2492       --  list for a dispatching call, it would not make sense to do so.
2493       --  Expansion of dispatching calls is suppressed when VM_Target, because
2494       --  the VM back-ends directly handle the generation of dispatching
2495       --  calls and would have to undo any expansion to an indirect call.
2496
2497       if (Nkind (N) = N_Function_Call
2498            or else Nkind (N) =  N_Procedure_Call_Statement)
2499         and then Present (Controlling_Argument (N))
2500         and then VM_Target = No_VM
2501       then
2502          Expand_Dispatching_Call (N);
2503
2504          --  The following return is worrisome. Is it really OK to
2505          --  skip all remaining processing in this procedure ???
2506
2507          return;
2508
2509       --  Similarly, expand calls to RCI subprograms on which pragma
2510       --  All_Calls_Remote applies. The rewriting will be reanalyzed
2511       --  later. Do this only when the call comes from source since we do
2512       --  not want such a rewritting to occur in expanded code.
2513
2514       elsif Is_All_Remote_Call (N) then
2515          Expand_All_Calls_Remote_Subprogram_Call (N);
2516
2517       --  Similarly, do not add extra actuals for an entry call whose entity
2518       --  is a protected procedure, or for an internal protected subprogram
2519       --  call, because it will be rewritten as a protected subprogram call
2520       --  and reanalyzed (see Expand_Protected_Subprogram_Call).
2521
2522       elsif Is_Protected_Type (Scope (Subp))
2523          and then (Ekind (Subp) = E_Procedure
2524                     or else Ekind (Subp) = E_Function)
2525       then
2526          null;
2527
2528       --  During that loop we gathered the extra actuals (the ones that
2529       --  correspond to Extra_Formals), so now they can be appended.
2530
2531       else
2532          while Is_Non_Empty_List (Extra_Actuals) loop
2533             Add_Actual_Parameter (Remove_Head (Extra_Actuals));
2534          end loop;
2535       end if;
2536
2537       --  At this point we have all the actuals, so this is the point at
2538       --  which the various expansion activities for actuals is carried out.
2539
2540       Expand_Actuals (N, Subp);
2541
2542       --  If the subprogram is a renaming, or if it is inherited, replace it
2543       --  in the call with the name of the actual subprogram being called.
2544       --  If this is a dispatching call, the run-time decides what to call.
2545       --  The Alias attribute does not apply to entries.
2546
2547       if Nkind (N) /= N_Entry_Call_Statement
2548         and then No (Controlling_Argument (N))
2549         and then Present (Parent_Subp)
2550       then
2551          if Present (Inherited_From_Formal (Subp)) then
2552             Parent_Subp := Inherited_From_Formal (Subp);
2553          else
2554             while Present (Alias (Parent_Subp)) loop
2555                Parent_Subp := Alias (Parent_Subp);
2556             end loop;
2557          end if;
2558
2559          --  The below setting of Entity is suspect, see F109-018 discussion???
2560
2561          Set_Entity (Name (N), Parent_Subp);
2562
2563          if Is_Abstract_Subprogram (Parent_Subp)
2564            and then not In_Instance
2565          then
2566             Error_Msg_NE
2567               ("cannot call abstract subprogram &!", Name (N), Parent_Subp);
2568          end if;
2569
2570          --  Add an explicit conversion for parameter of the derived type.
2571          --  This is only done for scalar and access in-parameters. Others
2572          --  have been expanded in expand_actuals.
2573
2574          Formal := First_Formal (Subp);
2575          Parent_Formal := First_Formal (Parent_Subp);
2576          Actual := First_Actual (N);
2577
2578          --  It is not clear that conversion is needed for intrinsic
2579          --  subprograms, but it certainly is for those that are user-
2580          --  defined, and that can be inherited on derivation, namely
2581          --  unchecked conversion and deallocation.
2582          --  General case needs study ???
2583
2584          if not Is_Intrinsic_Subprogram (Parent_Subp)
2585            or else Is_Generic_Instance (Parent_Subp)
2586          then
2587             while Present (Formal) loop
2588                if Etype (Formal) /= Etype (Parent_Formal)
2589                  and then Is_Scalar_Type (Etype (Formal))
2590                  and then Ekind (Formal) = E_In_Parameter
2591                  and then
2592                    not Subtypes_Statically_Match
2593                          (Etype (Parent_Formal), Etype (Actual))
2594                  and then not Raises_Constraint_Error (Actual)
2595                then
2596                   Rewrite (Actual,
2597                     OK_Convert_To (Etype (Parent_Formal),
2598                       Relocate_Node (Actual)));
2599
2600                   Analyze (Actual);
2601                   Resolve (Actual, Etype (Parent_Formal));
2602                   Enable_Range_Check (Actual);
2603
2604                elsif Is_Access_Type (Etype (Formal))
2605                  and then Base_Type (Etype (Parent_Formal)) /=
2606                           Base_Type (Etype (Actual))
2607                then
2608                   if Ekind (Formal) /= E_In_Parameter then
2609                      Rewrite (Actual,
2610                        Convert_To (Etype (Parent_Formal),
2611                          Relocate_Node (Actual)));
2612
2613                      Analyze (Actual);
2614                      Resolve (Actual, Etype (Parent_Formal));
2615
2616                   elsif
2617                     Ekind (Etype (Parent_Formal)) = E_Anonymous_Access_Type
2618                       and then Designated_Type (Etype (Parent_Formal))
2619                                  /=
2620                                Designated_Type (Etype (Actual))
2621                       and then not Is_Controlling_Formal (Formal)
2622                   then
2623                      --  This unchecked conversion is not necessary unless
2624                      --  inlining is enabled, because in that case the type
2625                      --  mismatch may become visible in the body about to be
2626                      --  inlined.
2627
2628                      Rewrite (Actual,
2629                        Unchecked_Convert_To (Etype (Parent_Formal),
2630                          Relocate_Node (Actual)));
2631
2632                      Analyze (Actual);
2633                      Resolve (Actual, Etype (Parent_Formal));
2634                   end if;
2635                end if;
2636
2637                Next_Formal (Formal);
2638                Next_Formal (Parent_Formal);
2639                Next_Actual (Actual);
2640             end loop;
2641          end if;
2642
2643          Orig_Subp := Subp;
2644          Subp := Parent_Subp;
2645       end if;
2646
2647       --  Check for violation of No_Abort_Statements
2648
2649       if Is_RTE (Subp, RE_Abort_Task) then
2650          Check_Restriction (No_Abort_Statements, N);
2651
2652       --  Check for violation of No_Dynamic_Attachment
2653
2654       elsif RTU_Loaded (Ada_Interrupts)
2655         and then (Is_RTE (Subp, RE_Is_Reserved)      or else
2656                   Is_RTE (Subp, RE_Is_Attached)      or else
2657                   Is_RTE (Subp, RE_Current_Handler)  or else
2658                   Is_RTE (Subp, RE_Attach_Handler)   or else
2659                   Is_RTE (Subp, RE_Exchange_Handler) or else
2660                   Is_RTE (Subp, RE_Detach_Handler)   or else
2661                   Is_RTE (Subp, RE_Reference))
2662       then
2663          Check_Restriction (No_Dynamic_Attachment, N);
2664       end if;
2665
2666       --  Deal with case where call is an explicit dereference
2667
2668       if Nkind (Name (N)) = N_Explicit_Dereference then
2669
2670       --  Handle case of access to protected subprogram type
2671
2672          if Is_Access_Protected_Subprogram_Type
2673             (Base_Type (Etype (Prefix (Name (N)))))
2674          then
2675             --  If this is a call through an access to protected operation,
2676             --  the prefix has the form (object'address, operation'access).
2677             --  Rewrite as a for other protected calls: the object is the
2678             --  first parameter of the list of actuals.
2679
2680             declare
2681                Call : Node_Id;
2682                Parm : List_Id;
2683                Nam  : Node_Id;
2684                Obj  : Node_Id;
2685                Ptr  : constant Node_Id := Prefix (Name (N));
2686
2687                T : constant Entity_Id :=
2688                      Equivalent_Type (Base_Type (Etype (Ptr)));
2689
2690                D_T : constant Entity_Id :=
2691                        Designated_Type (Base_Type (Etype (Ptr)));
2692
2693             begin
2694                Obj :=
2695                  Make_Selected_Component (Loc,
2696                    Prefix        => Unchecked_Convert_To (T, Ptr),
2697                    Selector_Name =>
2698                      New_Occurrence_Of (First_Entity (T), Loc));
2699
2700                Nam :=
2701                  Make_Selected_Component (Loc,
2702                    Prefix        => Unchecked_Convert_To (T, Ptr),
2703                    Selector_Name =>
2704                      New_Occurrence_Of (Next_Entity (First_Entity (T)), Loc));
2705
2706                Nam :=
2707                  Make_Explicit_Dereference (Loc,
2708                    Prefix => Nam);
2709
2710                if Present (Parameter_Associations (N))  then
2711                   Parm := Parameter_Associations (N);
2712                else
2713                   Parm := New_List;
2714                end if;
2715
2716                Prepend (Obj, Parm);
2717
2718                if Etype (D_T) = Standard_Void_Type then
2719                   Call :=
2720                     Make_Procedure_Call_Statement (Loc,
2721                       Name                   => Nam,
2722                       Parameter_Associations => Parm);
2723                else
2724                   Call :=
2725                     Make_Function_Call (Loc,
2726                       Name                   => Nam,
2727                       Parameter_Associations => Parm);
2728                end if;
2729
2730                Set_First_Named_Actual (Call, First_Named_Actual (N));
2731                Set_Etype (Call, Etype (D_T));
2732
2733                --  We do not re-analyze the call to avoid infinite recursion.
2734                --  We analyze separately the prefix and the object, and set
2735                --  the checks on the prefix that would otherwise be emitted
2736                --  when resolving a call.
2737
2738                Rewrite (N, Call);
2739                Analyze (Nam);
2740                Apply_Access_Check (Nam);
2741                Analyze (Obj);
2742                return;
2743             end;
2744          end if;
2745       end if;
2746
2747       --  If this is a call to an intrinsic subprogram, then perform the
2748       --  appropriate expansion to the corresponding tree node and we
2749       --  are all done (since after that the call is gone!)
2750
2751       --  In the case where the intrinsic is to be processed by the back end,
2752       --  the call to Expand_Intrinsic_Call will do nothing, which is fine,
2753       --  since the idea in this case is to pass the call unchanged.
2754       --  If the intrinsic is an inherited unchecked conversion, and the
2755       --  derived type is the target type of the conversion, we must retain
2756       --  it as the return type of the expression. Otherwise the expansion
2757       --  below, which uses the parent operation, will yield the wrong type.
2758
2759       if Is_Intrinsic_Subprogram (Subp) then
2760          Expand_Intrinsic_Call (N, Subp);
2761
2762          if Nkind (N) = N_Unchecked_Type_Conversion
2763            and then Parent_Subp /= Orig_Subp
2764            and then Etype (Parent_Subp) /= Etype (Orig_Subp)
2765          then
2766             Set_Etype (N, Etype (Orig_Subp));
2767          end if;
2768
2769          return;
2770       end if;
2771
2772       if Ekind (Subp) = E_Function
2773         or else Ekind (Subp) = E_Procedure
2774       then
2775          if Is_Inlined (Subp) then
2776
2777             Inlined_Subprogram : declare
2778                Bod         : Node_Id;
2779                Must_Inline : Boolean := False;
2780                Spec        : constant Node_Id := Unit_Declaration_Node (Subp);
2781                Scop        : constant Entity_Id := Scope (Subp);
2782
2783                function In_Unfrozen_Instance return Boolean;
2784                --  If the subprogram comes from an instance in the same
2785                --  unit, and the instance is not yet frozen, inlining might
2786                --  trigger order-of-elaboration problems in gigi.
2787
2788                --------------------------
2789                -- In_Unfrozen_Instance --
2790                --------------------------
2791
2792                function In_Unfrozen_Instance return Boolean is
2793                   S : Entity_Id;
2794
2795                begin
2796                   S := Scop;
2797                   while Present (S)
2798                     and then S /= Standard_Standard
2799                   loop
2800                      if Is_Generic_Instance (S)
2801                        and then Present (Freeze_Node (S))
2802                        and then not Analyzed (Freeze_Node (S))
2803                      then
2804                         return True;
2805                      end if;
2806
2807                      S := Scope (S);
2808                   end loop;
2809
2810                   return False;
2811                end In_Unfrozen_Instance;
2812
2813             --  Start of processing for Inlined_Subprogram
2814
2815             begin
2816                --  Verify that the body to inline has already been seen, and
2817                --  that if the body is in the current unit the inlining does
2818                --  not occur earlier. This avoids order-of-elaboration problems
2819                --  in the back end.
2820
2821                --  This should be documented in sinfo/einfo ???
2822
2823                if No (Spec)
2824                  or else Nkind (Spec) /= N_Subprogram_Declaration
2825                  or else No (Body_To_Inline (Spec))
2826                then
2827                   Must_Inline := False;
2828
2829                --  If this an inherited function that returns a private
2830                --  type, do not inline if the full view is an unconstrained
2831                --  array, because such calls cannot be inlined.
2832
2833                elsif Present (Orig_Subp)
2834                  and then Is_Array_Type (Etype (Orig_Subp))
2835                  and then not Is_Constrained (Etype (Orig_Subp))
2836                then
2837                   Must_Inline := False;
2838
2839                elsif In_Unfrozen_Instance then
2840                   Must_Inline := False;
2841
2842                else
2843                   Bod := Body_To_Inline (Spec);
2844
2845                   if (In_Extended_Main_Code_Unit (N)
2846                         or else In_Extended_Main_Code_Unit (Parent (N))
2847                         or else Is_Always_Inlined (Subp))
2848                     and then (not In_Same_Extended_Unit (Sloc (Bod), Loc)
2849                                or else
2850                                  Earlier_In_Extended_Unit (Sloc (Bod), Loc))
2851                   then
2852                      Must_Inline := True;
2853
2854                   --  If we are compiling a package body that is not the main
2855                   --  unit, it must be for inlining/instantiation purposes,
2856                   --  in which case we inline the call to insure that the same
2857                   --  temporaries are generated when compiling the body by
2858                   --  itself. Otherwise link errors can occur.
2859
2860                   --  If the function being called is itself in the main unit,
2861                   --  we cannot inline, because there is a risk of double
2862                   --  elaboration and/or circularity: the inlining can make
2863                   --  visible a private entity in the body of the main unit,
2864                   --  that gigi will see before its sees its proper definition.
2865
2866                   elsif not (In_Extended_Main_Code_Unit (N))
2867                     and then In_Package_Body
2868                   then
2869                      Must_Inline := not In_Extended_Main_Source_Unit (Subp);
2870                   end if;
2871                end if;
2872
2873                if Must_Inline then
2874                   Expand_Inlined_Call (N, Subp, Orig_Subp);
2875
2876                else
2877                   --  Let the back end handle it
2878
2879                   Add_Inlined_Body (Subp);
2880
2881                   if Front_End_Inlining
2882                     and then Nkind (Spec) = N_Subprogram_Declaration
2883                     and then (In_Extended_Main_Code_Unit (N))
2884                     and then No (Body_To_Inline (Spec))
2885                     and then not Has_Completion (Subp)
2886                     and then In_Same_Extended_Unit (Sloc (Spec), Loc)
2887                   then
2888                      Cannot_Inline
2889                       ("cannot inline& (body not seen yet)?",
2890                        N, Subp);
2891                   end if;
2892                end if;
2893             end Inlined_Subprogram;
2894          end if;
2895       end if;
2896
2897       --  Check for a protected subprogram. This is either an intra-object
2898       --  call, or a protected function call. Protected procedure calls are
2899       --  rewritten as entry calls and handled accordingly.
2900
2901       --  In Ada 2005, this may be an indirect call to an access parameter
2902       --  that is an access_to_subprogram. In that case the anonymous type
2903       --  has a scope that is a protected operation, but the call is a
2904       --  regular one.
2905
2906       Scop := Scope (Subp);
2907
2908       if Nkind (N) /= N_Entry_Call_Statement
2909         and then Is_Protected_Type (Scop)
2910         and then Ekind (Subp) /= E_Subprogram_Type
2911       then
2912          --  If the call is an internal one, it is rewritten as a call to
2913          --  to the corresponding unprotected subprogram.
2914
2915          Expand_Protected_Subprogram_Call (N, Subp, Scop);
2916       end if;
2917
2918       --  Functions returning controlled objects need special attention
2919       --  If the return type is limited the context is an initialization
2920       --  and different processing applies.
2921
2922       if Controlled_Type (Etype (Subp))
2923         and then not Is_Inherently_Limited_Type (Etype (Subp))
2924         and then not Is_Limited_Interface (Etype (Subp))
2925       then
2926          Expand_Ctrl_Function_Call (N);
2927       end if;
2928
2929       --  Test for First_Optional_Parameter, and if so, truncate parameter
2930       --  list if there are optional parameters at the trailing end.
2931       --  Note we never delete procedures for call via a pointer.
2932
2933       if (Ekind (Subp) = E_Procedure or else Ekind (Subp) = E_Function)
2934         and then Present (First_Optional_Parameter (Subp))
2935       then
2936          declare
2937             Last_Keep_Arg : Node_Id;
2938
2939          begin
2940             --  Last_Keep_Arg will hold the last actual that should be
2941             --  retained. If it remains empty at the end, it means that
2942             --  all parameters are optional.
2943
2944             Last_Keep_Arg := Empty;
2945
2946             --  Find first optional parameter, must be present since we
2947             --  checked the validity of the parameter before setting it.
2948
2949             Formal := First_Formal (Subp);
2950             Actual := First_Actual (N);
2951             while Formal /= First_Optional_Parameter (Subp) loop
2952                Last_Keep_Arg := Actual;
2953                Next_Formal (Formal);
2954                Next_Actual (Actual);
2955             end loop;
2956
2957             --  We have Formal and Actual pointing to the first potentially
2958             --  droppable argument. We can drop all the trailing arguments
2959             --  whose actual matches the default. Note that we know that all
2960             --  remaining formals have defaults, because we checked that this
2961             --  requirement was met before setting First_Optional_Parameter.
2962
2963             --  We use Fully_Conformant_Expressions to check for identity
2964             --  between formals and actuals, which may miss some cases, but
2965             --  on the other hand, this is only an optimization (if we fail
2966             --  to truncate a parameter it does not affect functionality).
2967             --  So if the default is 3 and the actual is 1+2, we consider
2968             --  them unequal, which hardly seems worrisome.
2969
2970             while Present (Formal) loop
2971                if not Fully_Conformant_Expressions
2972                     (Actual, Default_Value (Formal))
2973                then
2974                   Last_Keep_Arg := Actual;
2975                end if;
2976
2977                Next_Formal (Formal);
2978                Next_Actual (Actual);
2979             end loop;
2980
2981             --  If no arguments, delete entire list, this is the easy case
2982
2983             if No (Last_Keep_Arg) then
2984                while Is_Non_Empty_List (Parameter_Associations (N)) loop
2985                   Delete_Tree (Remove_Head (Parameter_Associations (N)));
2986                end loop;
2987
2988                Set_Parameter_Associations (N, No_List);
2989                Set_First_Named_Actual (N, Empty);
2990
2991             --  Case where at the last retained argument is positional. This
2992             --  is also an easy case, since the retained arguments are already
2993             --  in the right form, and we don't need to worry about the order
2994             --  of arguments that get eliminated.
2995
2996             elsif Is_List_Member (Last_Keep_Arg) then
2997                while Present (Next (Last_Keep_Arg)) loop
2998                   Delete_Tree (Remove_Next (Last_Keep_Arg));
2999                end loop;
3000
3001                Set_First_Named_Actual (N, Empty);
3002
3003             --  This is the annoying case where the last retained argument
3004             --  is a named parameter. Since the original arguments are not
3005             --  in declaration order, we may have to delete some fairly
3006             --  random collection of arguments.
3007
3008             else
3009                declare
3010                   Temp   : Node_Id;
3011                   Passoc : Node_Id;
3012
3013                begin
3014                   --  First step, remove all the named parameters from the
3015                   --  list (they are still chained using First_Named_Actual
3016                   --  and Next_Named_Actual, so we have not lost them!)
3017
3018                   Temp := First (Parameter_Associations (N));
3019
3020                   --  Case of all parameters named, remove them all
3021
3022                   if Nkind (Temp) = N_Parameter_Association then
3023                      while Is_Non_Empty_List (Parameter_Associations (N)) loop
3024                         Temp := Remove_Head (Parameter_Associations (N));
3025                      end loop;
3026
3027                   --  Case of mixed positional/named, remove named parameters
3028
3029                   else
3030                      while Nkind (Next (Temp)) /= N_Parameter_Association loop
3031                         Next (Temp);
3032                      end loop;
3033
3034                      while Present (Next (Temp)) loop
3035                         Remove (Next (Temp));
3036                      end loop;
3037                   end if;
3038
3039                   --  Now we loop through the named parameters, till we get
3040                   --  to the last one to be retained, adding them to the list.
3041                   --  Note that the Next_Named_Actual list does not need to be
3042                   --  touched since we are only reordering them on the actual
3043                   --  parameter association list.
3044
3045                   Passoc := Parent (First_Named_Actual (N));
3046                   loop
3047                      Temp := Relocate_Node (Passoc);
3048                      Append_To
3049                        (Parameter_Associations (N), Temp);
3050                      exit when
3051                        Last_Keep_Arg = Explicit_Actual_Parameter (Passoc);
3052                      Passoc := Parent (Next_Named_Actual (Passoc));
3053                   end loop;
3054
3055                   Set_Next_Named_Actual (Temp, Empty);
3056
3057                   loop
3058                      Temp := Next_Named_Actual (Passoc);
3059                      exit when No (Temp);
3060                      Set_Next_Named_Actual
3061                        (Passoc, Next_Named_Actual (Parent (Temp)));
3062                      Delete_Tree (Temp);
3063                   end loop;
3064                end;
3065             end if;
3066          end;
3067       end if;
3068
3069       --  Special processing for Ada 2005 AI-329, which requires a call to
3070       --  Raise_Exception to raise Constraint_Error if the Exception_Id is
3071       --  null. Note that we never need to do this in GNAT mode, or if the
3072       --  parameter to Raise_Exception is a use of Identity, since in these
3073       --  cases we know that the parameter is never null.
3074
3075       --  Note: We must check that the node has not been inlined. This is
3076       --  required because under zfp the Raise_Exception subprogram has the
3077       --  pragma inline_always (and hence the call has been expanded above
3078       --  into a block containing the code of the subprogram).
3079
3080       if Ada_Version >= Ada_05
3081         and then not GNAT_Mode
3082         and then Is_RTE (Subp, RE_Raise_Exception)
3083         and then Nkind (N) = N_Procedure_Call_Statement
3084         and then (Nkind (First_Actual (N)) /= N_Attribute_Reference
3085                    or else Attribute_Name (First_Actual (N)) /= Name_Identity)
3086       then
3087          declare
3088             RCE : constant Node_Id :=
3089                     Make_Raise_Constraint_Error (Loc,
3090                       Reason => CE_Null_Exception_Id);
3091          begin
3092             Insert_After (N, RCE);
3093             Analyze (RCE);
3094          end;
3095       end if;
3096    end Expand_Call;
3097
3098    --------------------------
3099    -- Expand_Inlined_Call --
3100    --------------------------
3101
3102    procedure Expand_Inlined_Call
3103     (N         : Node_Id;
3104      Subp      : Entity_Id;
3105      Orig_Subp : Entity_Id)
3106    is
3107       Loc       : constant Source_Ptr := Sloc (N);
3108       Is_Predef : constant Boolean :=
3109                    Is_Predefined_File_Name
3110                      (Unit_File_Name (Get_Source_Unit (Subp)));
3111       Orig_Bod  : constant Node_Id :=
3112                     Body_To_Inline (Unit_Declaration_Node (Subp));
3113
3114       Blk      : Node_Id;
3115       Bod      : Node_Id;
3116       Decl     : Node_Id;
3117       Decls    : constant List_Id := New_List;
3118       Exit_Lab : Entity_Id := Empty;
3119       F        : Entity_Id;
3120       A        : Node_Id;
3121       Lab_Decl : Node_Id;
3122       Lab_Id   : Node_Id;
3123       New_A    : Node_Id;
3124       Num_Ret  : Int := 0;
3125       Ret_Type : Entity_Id;
3126       Targ     : Node_Id;
3127       Targ1    : Node_Id;
3128       Temp     : Entity_Id;
3129       Temp_Typ : Entity_Id;
3130
3131       Is_Unc : constant Boolean :=
3132                     Is_Array_Type (Etype (Subp))
3133                       and then not Is_Constrained (Etype (Subp));
3134       --  If the type returned by the function is unconstrained and the
3135       --  call can be inlined, special processing is required.
3136
3137       function Is_Null_Procedure return Boolean;
3138       --  Predicate to recognize stubbed procedures and null procedures, for
3139       --  which there is no need for the full inlining mechanism.
3140
3141       procedure Make_Exit_Label;
3142       --  Build declaration for exit label to be used in Return statements
3143
3144       function Process_Formals (N : Node_Id) return Traverse_Result;
3145       --  Replace occurrence of a formal with the corresponding actual, or
3146       --  the thunk generated for it.
3147
3148       function Process_Sloc (Nod : Node_Id) return Traverse_Result;
3149       --  If the call being expanded is that of an internal subprogram,
3150       --  set the sloc of the generated block to that of the call itself,
3151       --  so that the expansion is skipped by the -next- command in gdb.
3152       --  Same processing for a subprogram in a predefined file, e.g.
3153       --  Ada.Tags. If Debug_Generated_Code is true, suppress this change
3154       --  to simplify our own development.
3155
3156       procedure Rewrite_Function_Call (N : Node_Id; Blk : Node_Id);
3157       --  If the function body is a single expression, replace call with
3158       --  expression, else insert block appropriately.
3159
3160       procedure Rewrite_Procedure_Call (N : Node_Id; Blk : Node_Id);
3161       --  If procedure body has no local variables, inline body without
3162       --  creating block, otherwise rewrite call with block.
3163
3164       function Formal_Is_Used_Once (Formal : Entity_Id) return Boolean;
3165       --  Determine whether a formal parameter is used only once in Orig_Bod
3166
3167       -----------------------
3168       -- Is_Null_Procedure --
3169       -----------------------
3170
3171       function Is_Null_Procedure return Boolean is
3172          Decl : constant Node_Id := Unit_Declaration_Node (Subp);
3173
3174       begin
3175          if Ekind (Subp) /= E_Procedure then
3176             return False;
3177
3178          elsif Nkind (Orig_Bod) /= N_Subprogram_Body then
3179             return False;
3180
3181          --  Check if this is an Ada 2005 null procedure
3182
3183          elsif Nkind (Decl) = N_Subprogram_Declaration
3184            and then Null_Present (Specification (Decl))
3185          then
3186             return True;
3187
3188          --  Check if the body contains only a null statement, followed by the
3189          --  return statement added during expansion.
3190
3191          else
3192             declare
3193                Stat : constant Node_Id :=
3194                         First
3195                           (Statements (Handled_Statement_Sequence (Orig_Bod)));
3196
3197                Stat2 : constant Node_Id := Next (Stat);
3198
3199             begin
3200                return
3201                  Nkind (Stat) = N_Null_Statement
3202                    and then
3203                      (No (Stat2)
3204                        or else
3205                          (Nkind (Stat2) = N_Simple_Return_Statement
3206                            and then No (Next (Stat2))));
3207             end;
3208          end if;
3209       end Is_Null_Procedure;
3210
3211       ---------------------
3212       -- Make_Exit_Label --
3213       ---------------------
3214
3215       procedure Make_Exit_Label is
3216       begin
3217          --  Create exit label for subprogram if one does not exist yet
3218
3219          if No (Exit_Lab) then
3220             Lab_Id :=
3221               Make_Identifier (Loc,
3222                 Chars => New_Internal_Name ('L'));
3223             Set_Entity (Lab_Id,
3224               Make_Defining_Identifier (Loc, Chars (Lab_Id)));
3225             Exit_Lab := Make_Label (Loc, Lab_Id);
3226
3227             Lab_Decl :=
3228               Make_Implicit_Label_Declaration (Loc,
3229                 Defining_Identifier  => Entity (Lab_Id),
3230                 Label_Construct      => Exit_Lab);
3231          end if;
3232       end Make_Exit_Label;
3233
3234       ---------------------
3235       -- Process_Formals --
3236       ---------------------
3237
3238       function Process_Formals (N : Node_Id) return Traverse_Result is
3239          A   : Entity_Id;
3240          E   : Entity_Id;
3241          Ret : Node_Id;
3242
3243       begin
3244          if Is_Entity_Name (N)
3245            and then Present (Entity (N))
3246          then
3247             E := Entity (N);
3248
3249             if Is_Formal (E)
3250               and then Scope (E) = Subp
3251             then
3252                A := Renamed_Object (E);
3253
3254                --  Rewrite the occurrence of the formal into an occurrence of
3255                --  the actual. Also establish visibility on the proper view of
3256                --  the actual's subtype for the body's context (if the actual's
3257                --  subtype is private at the call point but its full view is
3258                --  visible to the body, then the inlined tree here must be
3259                --  analyzed with the full view).
3260
3261                if Is_Entity_Name (A) then
3262                   Rewrite (N, New_Occurrence_Of (Entity (A), Loc));
3263                   Check_Private_View (N);
3264
3265                elsif Nkind (A) = N_Defining_Identifier then
3266                   Rewrite (N, New_Occurrence_Of (A, Loc));
3267                   Check_Private_View (N);
3268
3269                --  Numeric literal
3270
3271                else
3272                   Rewrite (N, New_Copy (A));
3273                end if;
3274             end if;
3275
3276             return Skip;
3277
3278          elsif Nkind (N) = N_Simple_Return_Statement then
3279             if No (Expression (N)) then
3280                Make_Exit_Label;
3281                Rewrite (N,
3282                  Make_Goto_Statement (Loc,
3283                    Name => New_Copy (Lab_Id)));
3284
3285             else
3286                if Nkind (Parent (N)) = N_Handled_Sequence_Of_Statements
3287                  and then Nkind (Parent (Parent (N))) = N_Subprogram_Body
3288                then
3289                   --  Function body is a single expression. No need for
3290                   --  exit label.
3291
3292                   null;
3293
3294                else
3295                   Num_Ret := Num_Ret + 1;
3296                   Make_Exit_Label;
3297                end if;
3298
3299                --  Because of the presence of private types, the views of the
3300                --  expression and the context may be different, so place an
3301                --  unchecked conversion to the context type to avoid spurious
3302                --  errors, eg. when the expression is a numeric literal and
3303                --  the context is private. If the expression is an aggregate,
3304                --  use a qualified expression, because an aggregate is not a
3305                --  legal argument of a conversion.
3306
3307                if Nkind (Expression (N)) = N_Aggregate
3308                  or else Nkind (Expression (N)) = N_Null
3309                then
3310                   Ret :=
3311                     Make_Qualified_Expression (Sloc (N),
3312                        Subtype_Mark => New_Occurrence_Of (Ret_Type, Sloc (N)),
3313                        Expression => Relocate_Node (Expression (N)));
3314                else
3315                   Ret :=
3316                     Unchecked_Convert_To
3317                       (Ret_Type, Relocate_Node (Expression (N)));
3318                end if;
3319
3320                if Nkind (Targ) = N_Defining_Identifier then
3321                   Rewrite (N,
3322                     Make_Assignment_Statement (Loc,
3323                       Name => New_Occurrence_Of (Targ, Loc),
3324                       Expression => Ret));
3325                else
3326                   Rewrite (N,
3327                     Make_Assignment_Statement (Loc,
3328                       Name => New_Copy (Targ),
3329                       Expression => Ret));
3330                end if;
3331
3332                Set_Assignment_OK (Name (N));
3333
3334                if Present (Exit_Lab) then
3335                   Insert_After (N,
3336                     Make_Goto_Statement (Loc,
3337                       Name => New_Copy (Lab_Id)));
3338                end if;
3339             end if;
3340
3341             return OK;
3342
3343          --  Remove pragma Unreferenced since it may refer to formals that
3344          --  are not visible in the inlined body, and in any case we will
3345          --  not be posting warnings on the inlined body so it is unneeded.
3346
3347          elsif Nkind (N) = N_Pragma
3348            and then Chars (N) = Name_Unreferenced
3349          then
3350             Rewrite (N, Make_Null_Statement (Sloc (N)));
3351             return OK;
3352
3353          else
3354             return OK;
3355          end if;
3356       end Process_Formals;
3357
3358       procedure Replace_Formals is new Traverse_Proc (Process_Formals);
3359
3360       ------------------
3361       -- Process_Sloc --
3362       ------------------
3363
3364       function Process_Sloc (Nod : Node_Id) return Traverse_Result is
3365       begin
3366          if not Debug_Generated_Code then
3367             Set_Sloc (Nod, Sloc (N));
3368             Set_Comes_From_Source (Nod, False);
3369          end if;
3370
3371          return OK;
3372       end Process_Sloc;
3373
3374       procedure Reset_Slocs is new Traverse_Proc (Process_Sloc);
3375
3376       ---------------------------
3377       -- Rewrite_Function_Call --
3378       ---------------------------
3379
3380       procedure Rewrite_Function_Call (N : Node_Id; Blk : Node_Id) is
3381          HSS : constant Node_Id := Handled_Statement_Sequence (Blk);
3382          Fst : constant Node_Id := First (Statements (HSS));
3383
3384       begin
3385          --  Optimize simple case: function body is a single return statement,
3386          --  which has been expanded into an assignment.
3387
3388          if Is_Empty_List (Declarations (Blk))
3389            and then Nkind (Fst) = N_Assignment_Statement
3390            and then No (Next (Fst))
3391          then
3392
3393             --  The function call may have been rewritten as the temporary
3394             --  that holds the result of the call, in which case remove the
3395             --  now useless declaration.
3396
3397             if Nkind (N) = N_Identifier
3398               and then Nkind (Parent (Entity (N))) = N_Object_Declaration
3399             then
3400                Rewrite (Parent (Entity (N)), Make_Null_Statement (Loc));
3401             end if;
3402
3403             Rewrite (N, Expression (Fst));
3404
3405          elsif Nkind (N) = N_Identifier
3406            and then Nkind (Parent (Entity (N))) = N_Object_Declaration
3407          then
3408             --  The block assigns the result of the call to the temporary
3409
3410             Insert_After (Parent (Entity (N)), Blk);
3411
3412          elsif Nkind (Parent (N)) = N_Assignment_Statement
3413            and then
3414             (Is_Entity_Name (Name (Parent (N)))
3415                or else
3416                   (Nkind (Name (Parent (N))) = N_Explicit_Dereference
3417                     and then Is_Entity_Name (Prefix (Name (Parent (N))))))
3418          then
3419             --  Replace assignment with the block
3420
3421             declare
3422                Original_Assignment : constant Node_Id := Parent (N);
3423
3424             begin
3425                --  Preserve the original assignment node to keep the complete
3426                --  assignment subtree consistent enough for Analyze_Assignment
3427                --  to proceed (specifically, the original Lhs node must still
3428                --  have an assignment statement as its parent).
3429
3430                --  We cannot rely on Original_Node to go back from the block
3431                --  node to the assignment node, because the assignment might
3432                --  already be a rewrite substitution.
3433
3434                Discard_Node (Relocate_Node (Original_Assignment));
3435                Rewrite (Original_Assignment, Blk);
3436             end;
3437
3438          elsif Nkind (Parent (N)) = N_Object_Declaration then
3439             Set_Expression (Parent (N), Empty);
3440             Insert_After (Parent (N), Blk);
3441
3442          elsif Is_Unc then
3443             Insert_Before (Parent (N), Blk);
3444          end if;
3445       end Rewrite_Function_Call;
3446
3447       ----------------------------
3448       -- Rewrite_Procedure_Call --
3449       ----------------------------
3450
3451       procedure Rewrite_Procedure_Call (N : Node_Id; Blk : Node_Id) is
3452          HSS  : constant Node_Id := Handled_Statement_Sequence (Blk);
3453       begin
3454          --  If there is a transient scope for N, this will be the scope of the
3455          --  actions for N, and the statements in Blk need to be within this
3456          --  scope. For example, they need to have visibility on the constant
3457          --  declarations created for the formals.
3458
3459          --  If N needs no transient scope, and if there are no declarations in
3460          --  the inlined body, we can do a little optimization and insert the
3461          --  statements for the body directly after N, and rewrite N to a
3462          --  null statement, instead of rewriting N into a full-blown block
3463          --  statement.
3464
3465          if not Scope_Is_Transient
3466            and then Is_Empty_List (Declarations (Blk))
3467          then
3468             Insert_List_After (N, Statements (HSS));
3469             Rewrite (N, Make_Null_Statement (Loc));
3470          else
3471             Rewrite (N, Blk);
3472          end if;
3473       end Rewrite_Procedure_Call;
3474
3475       -------------------------
3476       -- Formal_Is_Used_Once --
3477       -------------------------
3478
3479       function Formal_Is_Used_Once (Formal : Entity_Id) return Boolean is
3480          Use_Counter : Int := 0;
3481
3482          function Count_Uses (N : Node_Id) return Traverse_Result;
3483          --  Traverse the tree and count the uses of the formal parameter.
3484          --  In this case, for optimization purposes, we do not need to
3485          --  continue the traversal once more than one use is encountered.
3486
3487          ----------------
3488          -- Count_Uses --
3489          ----------------
3490
3491          function Count_Uses (N : Node_Id) return Traverse_Result is
3492          begin
3493             --  The original node is an identifier
3494
3495             if Nkind (N) = N_Identifier
3496               and then Present (Entity (N))
3497
3498                --  Original node's entity points to the one in the copied body
3499
3500               and then Nkind (Entity (N)) = N_Identifier
3501               and then Present (Entity (Entity (N)))
3502
3503                --  The entity of the copied node is the formal parameter
3504
3505               and then Entity (Entity (N)) = Formal
3506             then
3507                Use_Counter := Use_Counter + 1;
3508
3509                if Use_Counter > 1 then
3510
3511                   --  Denote more than one use and abandon the traversal
3512
3513                   Use_Counter := 2;
3514                   return Abandon;
3515
3516                end if;
3517             end if;
3518
3519             return OK;
3520          end Count_Uses;
3521
3522          procedure Count_Formal_Uses is new Traverse_Proc (Count_Uses);
3523
3524       --  Start of processing for Formal_Is_Used_Once
3525
3526       begin
3527          Count_Formal_Uses (Orig_Bod);
3528          return Use_Counter = 1;
3529       end Formal_Is_Used_Once;
3530
3531    --  Start of processing for Expand_Inlined_Call
3532
3533    begin
3534       --  Check for special case of To_Address call, and if so, just do an
3535       --  unchecked conversion instead of expanding the call. Not only is this
3536       --  more efficient, but it also avoids problem with order of elaboration
3537       --  when address clauses are inlined (address expression elaborated at
3538       --  wrong point).
3539
3540       if Subp = RTE (RE_To_Address) then
3541          Rewrite (N,
3542            Unchecked_Convert_To
3543             (RTE (RE_Address),
3544              Relocate_Node (First_Actual (N))));
3545          return;
3546
3547       elsif Is_Null_Procedure  then
3548          Rewrite (N, Make_Null_Statement (Loc));
3549          return;
3550       end if;
3551
3552       --  Check for an illegal attempt to inline a recursive procedure. If the
3553       --  subprogram has parameters this is detected when trying to supply a
3554       --  binding for parameters that already have one. For parameterless
3555       --  subprograms this must be done explicitly.
3556
3557       if In_Open_Scopes (Subp) then
3558          Error_Msg_N ("call to recursive subprogram cannot be inlined?", N);
3559          Set_Is_Inlined (Subp, False);
3560          return;
3561       end if;
3562
3563       if Nkind (Orig_Bod) = N_Defining_Identifier
3564         or else Nkind (Orig_Bod) = N_Defining_Operator_Symbol
3565       then
3566          --  Subprogram is a renaming_as_body. Calls appearing after the
3567          --  renaming can be replaced with calls to the renamed entity
3568          --  directly, because the subprograms are subtype conformant. If
3569          --  the renamed subprogram is an inherited operation, we must redo
3570          --  the expansion because implicit conversions may be needed.
3571
3572          Set_Name (N, New_Occurrence_Of (Orig_Bod, Loc));
3573
3574          if Present (Alias (Orig_Bod)) then
3575             Expand_Call (N);
3576          end if;
3577
3578          return;
3579       end if;
3580
3581       --  Use generic machinery to copy body of inlined subprogram, as if it
3582       --  were an instantiation, resetting source locations appropriately, so
3583       --  that nested inlined calls appear in the main unit.
3584
3585       Save_Env (Subp, Empty);
3586       Set_Copied_Sloc_For_Inlined_Body (N, Defining_Entity (Orig_Bod));
3587
3588       Bod := Copy_Generic_Node (Orig_Bod, Empty, Instantiating => True);
3589       Blk :=
3590         Make_Block_Statement (Loc,
3591           Declarations => Declarations (Bod),
3592           Handled_Statement_Sequence => Handled_Statement_Sequence (Bod));
3593
3594       if No (Declarations (Bod)) then
3595          Set_Declarations (Blk, New_List);
3596       end if;
3597
3598       --  For the unconstrained case, capture the name of the local
3599       --  variable that holds the result. This must be the first declaration
3600       --  in the block, because its bounds cannot depend on local variables.
3601       --  Otherwise there is no way to declare the result outside of the
3602       --  block. Needless to say, in general the bounds will depend on the
3603       --  actuals in the call.
3604
3605       if Is_Unc then
3606          Targ1 := Defining_Identifier (First (Declarations (Blk)));
3607       end if;
3608
3609       --  If this is a derived function, establish the proper return type
3610
3611       if Present (Orig_Subp)
3612         and then Orig_Subp /= Subp
3613       then
3614          Ret_Type := Etype (Orig_Subp);
3615       else
3616          Ret_Type := Etype (Subp);
3617       end if;
3618
3619       --  Create temporaries for the actuals that are expressions, or that
3620       --  are scalars and require copying to preserve semantics.
3621
3622       F := First_Formal (Subp);
3623       A := First_Actual (N);
3624       while Present (F) loop
3625          if Present (Renamed_Object (F)) then
3626             Error_Msg_N ("cannot inline call to recursive subprogram", N);
3627             return;
3628          end if;
3629
3630          --  If the argument may be a controlling argument in a call within
3631          --  the inlined body, we must preserve its classwide nature to insure
3632          --  that dynamic dispatching take place subsequently. If the formal
3633          --  has a constraint it must be preserved to retain the semantics of
3634          --  the body.
3635
3636          if Is_Class_Wide_Type (Etype (F))
3637            or else (Is_Access_Type (Etype (F))
3638                       and then
3639                     Is_Class_Wide_Type (Designated_Type (Etype (F))))
3640          then
3641             Temp_Typ := Etype (F);
3642
3643          elsif Base_Type (Etype (F)) = Base_Type (Etype (A))
3644            and then Etype (F) /= Base_Type (Etype (F))
3645          then
3646             Temp_Typ := Etype (F);
3647
3648          else
3649             Temp_Typ := Etype (A);
3650          end if;
3651
3652          --  If the actual is a simple name or a literal, no need to
3653          --  create a temporary, object can be used directly.
3654
3655          --  If the actual is a literal and the formal has its address taken,
3656          --  we cannot pass the literal itself as an argument, so its value
3657          --  must be captured in a temporary.
3658
3659          if (Is_Entity_Name (A)
3660               and then
3661                (not Is_Scalar_Type (Etype (A))
3662                  or else Ekind (Entity (A)) = E_Enumeration_Literal))
3663
3664          --  When the actual is an identifier and the corresponding formal
3665          --  is used only once in the original body, the formal can be
3666          --  substituted directly with the actual parameter.
3667
3668            or else (Nkind (A) = N_Identifier
3669              and then Formal_Is_Used_Once (F))
3670
3671            or else
3672              ((Nkind (A) = N_Real_Literal    or else
3673                Nkind (A) = N_Integer_Literal or else
3674                Nkind (A) = N_Character_Literal)
3675               and then not Address_Taken (F))
3676          then
3677             if Etype (F) /= Etype (A) then
3678                Set_Renamed_Object
3679                 (F, Unchecked_Convert_To (Etype (F), Relocate_Node (A)));
3680             else
3681                Set_Renamed_Object (F, A);
3682             end if;
3683
3684          else
3685             Temp :=
3686               Make_Defining_Identifier (Loc,
3687                 Chars => New_Internal_Name ('C'));
3688
3689             --  If the actual for an in/in-out parameter is a view conversion,
3690             --  make it into an unchecked conversion, given that an untagged
3691             --  type conversion is not a proper object for a renaming.
3692
3693             --  In-out conversions that involve real conversions have already
3694             --  been transformed in Expand_Actuals.
3695
3696             if Nkind (A) = N_Type_Conversion
3697               and then Ekind (F) /= E_In_Parameter
3698             then
3699                New_A :=
3700                  Make_Unchecked_Type_Conversion (Loc,
3701                    Subtype_Mark => New_Occurrence_Of (Etype (F), Loc),
3702                    Expression   => Relocate_Node (Expression (A)));
3703
3704             elsif Etype (F) /= Etype (A) then
3705                New_A := Unchecked_Convert_To (Etype (F), Relocate_Node (A));
3706                Temp_Typ := Etype (F);
3707
3708             else
3709                New_A := Relocate_Node (A);
3710             end if;
3711
3712             Set_Sloc (New_A, Sloc (N));
3713
3714             --  If the actual has a by-reference type, it cannot be copied, so
3715             --  its value is captured in a renaming declaration. Otherwise
3716             --  declare a local constant initialized with the actual.
3717
3718             if Ekind (F) = E_In_Parameter
3719               and then not Is_Limited_Type (Etype (A))
3720               and then not Is_Tagged_Type  (Etype (A))
3721             then
3722                Decl :=
3723                  Make_Object_Declaration (Loc,
3724                    Defining_Identifier => Temp,
3725                    Constant_Present => True,
3726                    Object_Definition => New_Occurrence_Of (Temp_Typ, Loc),
3727                    Expression => New_A);
3728             else
3729                Decl :=
3730                  Make_Object_Renaming_Declaration (Loc,
3731                    Defining_Identifier => Temp,
3732                    Subtype_Mark        => New_Occurrence_Of (Temp_Typ, Loc),
3733                    Name                => New_A);
3734             end if;
3735
3736             Append (Decl, Decls);
3737             Set_Renamed_Object (F, Temp);
3738          end if;
3739
3740          Next_Formal (F);
3741          Next_Actual (A);
3742       end loop;
3743
3744       --  Establish target of function call. If context is not assignment or
3745       --  declaration, create a temporary as a target. The declaration for
3746       --  the temporary may be subsequently optimized away if the body is a
3747       --  single expression, or if the left-hand side of the assignment is
3748       --  simple enough, i.e. an entity or an explicit dereference of one.
3749
3750       if Ekind (Subp) = E_Function then
3751          if Nkind (Parent (N)) = N_Assignment_Statement
3752            and then Is_Entity_Name (Name (Parent (N)))
3753          then
3754             Targ := Name (Parent (N));
3755
3756          elsif Nkind (Parent (N)) = N_Assignment_Statement
3757            and then Nkind (Name (Parent (N))) = N_Explicit_Dereference
3758            and then Is_Entity_Name (Prefix (Name (Parent (N))))
3759          then
3760             Targ := Name (Parent (N));
3761
3762          else
3763             --  Replace call with temporary and create its declaration
3764
3765             Temp :=
3766               Make_Defining_Identifier (Loc, New_Internal_Name ('C'));
3767             Set_Is_Internal (Temp);
3768
3769             --  For the unconstrained case. the generated temporary has the
3770             --  same constrained declaration as the result variable.
3771             --  It may eventually be possible to remove that temporary and
3772             --  use the result variable directly.
3773
3774             if Is_Unc then
3775                Decl :=
3776                  Make_Object_Declaration (Loc,
3777                    Defining_Identifier => Temp,
3778                    Object_Definition =>
3779                      New_Copy_Tree (Object_Definition (Parent (Targ1))));
3780
3781                Replace_Formals (Decl);
3782
3783             else
3784                Decl :=
3785                  Make_Object_Declaration (Loc,
3786                    Defining_Identifier => Temp,
3787                    Object_Definition =>
3788                      New_Occurrence_Of (Ret_Type, Loc));
3789
3790                Set_Etype (Temp, Ret_Type);
3791             end if;
3792
3793             Set_No_Initialization (Decl);
3794             Append (Decl, Decls);
3795             Rewrite (N, New_Occurrence_Of (Temp, Loc));
3796             Targ := Temp;
3797          end if;
3798       end if;
3799
3800       Insert_Actions (N, Decls);
3801
3802       --  Traverse the tree and replace formals with actuals or their thunks.
3803       --  Attach block to tree before analysis and rewriting.
3804
3805       Replace_Formals (Blk);
3806       Set_Parent (Blk, N);
3807
3808       if not Comes_From_Source (Subp)
3809         or else Is_Predef
3810       then
3811          Reset_Slocs (Blk);
3812       end if;
3813
3814       if Present (Exit_Lab) then
3815
3816          --  If the body was a single expression, the single return statement
3817          --  and the corresponding label are useless.
3818
3819          if Num_Ret = 1
3820            and then
3821              Nkind (Last (Statements (Handled_Statement_Sequence (Blk)))) =
3822                N_Goto_Statement
3823          then
3824             Remove (Last (Statements (Handled_Statement_Sequence (Blk))));
3825          else
3826             Append (Lab_Decl, (Declarations (Blk)));
3827             Append (Exit_Lab, Statements (Handled_Statement_Sequence (Blk)));
3828          end if;
3829       end if;
3830
3831       --  Analyze Blk with In_Inlined_Body set, to avoid spurious errors on
3832       --  conflicting private views that Gigi would ignore. If this is
3833       --  predefined unit, analyze with checks off, as is done in the non-
3834       --  inlined run-time units.
3835
3836       declare
3837          I_Flag : constant Boolean := In_Inlined_Body;
3838
3839       begin
3840          In_Inlined_Body := True;
3841
3842          if Is_Predef then
3843             declare
3844                Style : constant Boolean := Style_Check;
3845             begin
3846                Style_Check := False;
3847                Analyze (Blk, Suppress => All_Checks);
3848                Style_Check := Style;
3849             end;
3850
3851          else
3852             Analyze (Blk);
3853          end if;
3854
3855          In_Inlined_Body := I_Flag;
3856       end;
3857
3858       if Ekind (Subp) = E_Procedure then
3859          Rewrite_Procedure_Call (N, Blk);
3860       else
3861          Rewrite_Function_Call (N, Blk);
3862
3863          --  For the unconstrained case, the replacement of the call has been
3864          --  made prior to the complete analysis of the generated declarations.
3865          --  Propagate the proper type now.
3866
3867          if Is_Unc then
3868             if Nkind (N) = N_Identifier then
3869                Set_Etype (N, Etype (Entity (N)));
3870             else
3871                Set_Etype (N, Etype (Targ1));
3872             end if;
3873          end if;
3874       end if;
3875
3876       Restore_Env;
3877
3878       --  Cleanup mapping between formals and actuals for other expansions
3879
3880       F := First_Formal (Subp);
3881       while Present (F) loop
3882          Set_Renamed_Object (F, Empty);
3883          Next_Formal (F);
3884       end loop;
3885    end Expand_Inlined_Call;
3886
3887    ----------------------------
3888    -- Expand_N_Function_Call --
3889    ----------------------------
3890
3891    procedure Expand_N_Function_Call (N : Node_Id) is
3892       Typ   : constant Entity_Id := Etype (N);
3893
3894       function Returned_By_Reference return Boolean;
3895       --  If the return type is returned through the secondary stack; that is
3896       --  by reference, we don't want to create a temp to force stack checking.
3897       --  ???"sec stack" is not right -- Ada 95 return-by-reference object are
3898       --  returned wherever they are.
3899       --  Shouldn't this function be moved to exp_util???
3900
3901       function Rhs_Of_Assign_Or_Decl (N : Node_Id) return Boolean;
3902       --  If the call is the right side of an assignment or the expression in
3903       --  an object declaration, we don't need to create a temp as the left
3904       --  side will already trigger stack checking if necessary.
3905       --
3906       --  If the call is a component in an extension aggregate, it will be
3907       --  expanded into assignments as well, so no temporary is needed. This
3908       --  also solves the problem of functions returning types with unknown
3909       --  discriminants, where it is not possible to declare an object of the
3910       --  type altogether.
3911
3912       ---------------------------
3913       -- Returned_By_Reference --
3914       ---------------------------
3915
3916       function Returned_By_Reference return Boolean is
3917          S : Entity_Id;
3918
3919       begin
3920          if Is_Inherently_Limited_Type (Typ) then
3921             return True;
3922
3923          elsif Nkind (Parent (N)) /= N_Simple_Return_Statement then
3924             return False;
3925
3926          elsif Requires_Transient_Scope (Typ) then
3927
3928             --  Verify that the return type of the enclosing function has the
3929             --  same constrained status as that of the expression.
3930
3931             S := Current_Scope;
3932             while Ekind (S) /= E_Function loop
3933                S := Scope (S);
3934             end loop;
3935
3936             return Is_Constrained (Typ) = Is_Constrained (Etype (S));
3937          else
3938             return False;
3939          end if;
3940       end Returned_By_Reference;
3941
3942       ---------------------------
3943       -- Rhs_Of_Assign_Or_Decl --
3944       ---------------------------
3945
3946       function Rhs_Of_Assign_Or_Decl (N : Node_Id) return Boolean is
3947       begin
3948          if (Nkind (Parent (N)) = N_Assignment_Statement
3949                and then Expression (Parent (N)) = N)
3950            or else
3951              (Nkind (Parent (N)) = N_Qualified_Expression
3952                 and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
3953                   and then Expression (Parent (Parent (N))) = Parent (N))
3954            or else
3955              (Nkind (Parent (N)) = N_Object_Declaration
3956                 and then Expression (Parent (N)) = N)
3957            or else
3958              (Nkind (Parent (N)) = N_Component_Association
3959                 and then Expression (Parent (N)) = N
3960                   and then Nkind (Parent (Parent (N))) = N_Aggregate
3961                     and then Rhs_Of_Assign_Or_Decl (Parent (Parent (N))))
3962            or else
3963              (Nkind (Parent (N)) = N_Extension_Aggregate
3964                and then Is_Private_Type (Etype (Typ)))
3965          then
3966             return True;
3967          else
3968             return False;
3969          end if;
3970       end Rhs_Of_Assign_Or_Decl;
3971
3972    --  Start of processing for Expand_N_Function_Call
3973
3974    begin
3975       --  A special check. If stack checking is enabled, and the return type
3976       --  might generate a large temporary, and the call is not the right side
3977       --  of an assignment, then generate an explicit temporary. We do this
3978       --  because otherwise gigi may generate a large temporary on the fly and
3979       --  this can cause trouble with stack checking.
3980
3981       --  This is unnecessary if the call is the expression in an object
3982       --  declaration, or if it appears outside of any library unit. This can
3983       --  only happen if it appears as an actual in a library-level instance,
3984       --  in which case a temporary will be generated for it once the instance
3985       --  itself is installed.
3986
3987       if May_Generate_Large_Temp (Typ)
3988         and then not Rhs_Of_Assign_Or_Decl (N)
3989         and then not Returned_By_Reference
3990         and then Current_Scope /= Standard_Standard
3991       then
3992          if Stack_Checking_Enabled then
3993
3994             --  Note: it might be thought that it would be OK to use a call to
3995             --  Force_Evaluation here, but that's not good enough, because
3996             --  that can results in a 'Reference construct that may still need
3997             --  a temporary.
3998
3999             declare
4000                Loc      : constant Source_Ptr := Sloc (N);
4001                Temp_Obj : constant Entity_Id :=
4002                             Make_Defining_Identifier (Loc,
4003                               Chars => New_Internal_Name ('F'));
4004                Temp_Typ : Entity_Id := Typ;
4005                Decl     : Node_Id;
4006                A        : Node_Id;
4007                F        : Entity_Id;
4008                Proc     : Entity_Id;
4009
4010             begin
4011                if Is_Tagged_Type (Typ)
4012                  and then Present (Controlling_Argument (N))
4013                then
4014                   if Nkind (Parent (N)) /= N_Procedure_Call_Statement
4015                     and then Nkind (Parent (N)) /= N_Function_Call
4016                   then
4017                      --  If this is a tag-indeterminate call, the object must
4018                      --  be classwide.
4019
4020                      if Is_Tag_Indeterminate (N) then
4021                         Temp_Typ := Class_Wide_Type (Typ);
4022                      end if;
4023
4024                   else
4025                      --  If this is a dispatching call that is itself the
4026                      --  controlling argument of an enclosing call, the
4027                      --  nominal subtype of the object that replaces it must
4028                      --  be classwide, so that dispatching will take place
4029                      --  properly. If it is not a controlling argument, the
4030                      --  object is not classwide.
4031
4032                      Proc := Entity (Name (Parent (N)));
4033
4034                      F := First_Formal (Proc);
4035                      A := First_Actual (Parent (N));
4036                      while A /= N loop
4037                         Next_Formal (F);
4038                         Next_Actual (A);
4039                      end loop;
4040
4041                      if Is_Controlling_Formal (F) then
4042                         Temp_Typ := Class_Wide_Type (Typ);
4043                      end if;
4044                   end if;
4045                end if;
4046
4047                Decl :=
4048                  Make_Object_Declaration (Loc,
4049                    Defining_Identifier => Temp_Obj,
4050                    Object_Definition   => New_Occurrence_Of (Temp_Typ, Loc),
4051                    Constant_Present    => True,
4052                    Expression          => Relocate_Node (N));
4053                Set_Assignment_OK (Decl);
4054
4055                Insert_Actions (N, New_List (Decl));
4056                Rewrite (N, New_Occurrence_Of (Temp_Obj, Loc));
4057             end;
4058
4059          else
4060             --  If stack-checking is not enabled, increment serial number
4061             --  for internal names, so that subsequent symbols are consistent
4062             --  with and without stack-checking.
4063
4064             Synchronize_Serial_Number;
4065
4066             --  Now we can expand the call with consistent symbol names
4067
4068             Expand_Call (N);
4069          end if;
4070
4071       --  Normal case, expand the call
4072
4073       else
4074          Expand_Call (N);
4075       end if;
4076    end Expand_N_Function_Call;
4077
4078    ---------------------------------------
4079    -- Expand_N_Procedure_Call_Statement --
4080    ---------------------------------------
4081
4082    procedure Expand_N_Procedure_Call_Statement (N : Node_Id) is
4083    begin
4084       Expand_Call (N);
4085    end Expand_N_Procedure_Call_Statement;
4086
4087    ------------------------------
4088    -- Expand_N_Subprogram_Body --
4089    ------------------------------
4090
4091    --  Add poll call if ATC polling is enabled, unless the body will be
4092    --  inlined by the back-end.
4093
4094    --  Add dummy push/pop label nodes at start and end to clear any local
4095    --  exception indications if local-exception-to-goto optimization active.
4096
4097    --  Add return statement if last statement in body is not a return statement
4098    --  (this makes things easier on Gigi which does not want to have to handle
4099    --  a missing return).
4100
4101    --  Add call to Activate_Tasks if body is a task activator
4102
4103    --  Deal with possible detection of infinite recursion
4104
4105    --  Eliminate body completely if convention stubbed
4106
4107    --  Encode entity names within body, since we will not need to reference
4108    --  these entities any longer in the front end.
4109
4110    --  Initialize scalar out parameters if Initialize/Normalize_Scalars
4111
4112    --  Reset Pure indication if any parameter has root type System.Address
4113
4114    --  Wrap thread body
4115
4116    procedure Expand_N_Subprogram_Body (N : Node_Id) is
4117       Loc      : constant Source_Ptr := Sloc (N);
4118       H        : constant Node_Id    := Handled_Statement_Sequence (N);
4119       Body_Id  : Entity_Id;
4120       Spec_Id  : Entity_Id;
4121       Except_H : Node_Id;
4122       Scop     : Entity_Id;
4123       Dec      : Node_Id;
4124       Next_Op  : Node_Id;
4125       L        : List_Id;
4126
4127       procedure Add_Return (S : List_Id);
4128       --  Append a return statement to the statement sequence S if the last
4129       --  statement is not already a return or a goto statement. Note that
4130       --  the latter test is not critical, it does not matter if we add a
4131       --  few extra returns, since they get eliminated anyway later on.
4132
4133       ----------------
4134       -- Add_Return --
4135       ----------------
4136
4137       procedure Add_Return (S : List_Id) is
4138          Last_Stm : Node_Id;
4139          Loc      : Source_Ptr;
4140
4141       begin
4142          --  Get last statement, ignoring any Pop_xxx_Label nodes, which are
4143          --  not relevant in this context since they are not executable.
4144
4145          Last_Stm := Last (S);
4146          while Nkind (Last_Stm) in N_Pop_xxx_Label loop
4147             Prev (Last_Stm);
4148          end loop;
4149
4150          --  Now insert return unless last statement is a transfer
4151
4152          if not Is_Transfer (Last_Stm) then
4153
4154             --  The source location for the return is the end label of the
4155             --  procedure if present. Otherwise use the sloc of the last
4156             --  statement in the list. If the list comes from a generated
4157             --  exception handler and we are not debugging generated code,
4158             --  all the statements within the handler are made invisible
4159             --  to the debugger.
4160
4161             if Nkind (Parent (S)) = N_Exception_Handler
4162               and then not Comes_From_Source (Parent (S))
4163             then
4164                Loc := Sloc (Last_Stm);
4165
4166             elsif Present (End_Label (H)) then
4167                Loc := Sloc (End_Label (H));
4168
4169             else
4170                Loc := Sloc (Last_Stm);
4171             end if;
4172
4173             Append_To (S, Make_Simple_Return_Statement (Loc));
4174          end if;
4175       end Add_Return;
4176
4177    --  Start of processing for Expand_N_Subprogram_Body
4178
4179    begin
4180       --  Set L to either the list of declarations if present, or
4181       --  to the list of statements if no declarations are present.
4182       --  This is used to insert new stuff at the start.
4183
4184       if Is_Non_Empty_List (Declarations (N)) then
4185          L := Declarations (N);
4186       else
4187          L := Statements (H);
4188       end if;
4189
4190       --  If local-exception-to-goto optimization active, insert dummy push
4191       --  statements at start, and dummy pop statements at end.
4192
4193       if (Debug_Flag_Dot_G
4194            or else Restriction_Active (No_Exception_Propagation))
4195         and then Is_Non_Empty_List (L)
4196       then
4197          declare
4198             FS  : constant Node_Id    := First (L);
4199             FL  : constant Source_Ptr := Sloc (FS);
4200             LS  : Node_Id;
4201             LL  : Source_Ptr;
4202
4203          begin
4204             --  LS points to either last statement, if statements are present
4205             --  or to the last declaration if there are no statements present.
4206             --  It is the node after which the pop's are generated.
4207
4208             if Is_Non_Empty_List (Statements (H)) then
4209                LS := Last (Statements (H));
4210             else
4211                LS := Last (L);
4212             end if;
4213
4214             LL := Sloc (LS);
4215
4216             Insert_List_Before_And_Analyze (FS, New_List (
4217               Make_Push_Constraint_Error_Label (FL),
4218               Make_Push_Program_Error_Label    (FL),
4219               Make_Push_Storage_Error_Label    (FL)));
4220
4221             Insert_List_After_And_Analyze (LS, New_List (
4222               Make_Pop_Constraint_Error_Label  (LL),
4223               Make_Pop_Program_Error_Label     (LL),
4224               Make_Pop_Storage_Error_Label     (LL)));
4225          end;
4226       end if;
4227
4228       --  Find entity for subprogram
4229
4230       Body_Id := Defining_Entity (N);
4231
4232       if Present (Corresponding_Spec (N)) then
4233          Spec_Id := Corresponding_Spec (N);
4234       else
4235          Spec_Id := Body_Id;
4236       end if;
4237
4238       --  Need poll on entry to subprogram if polling enabled. We only do this
4239       --  for non-empty subprograms, since it does not seem necessary to poll
4240       --  for a dummy null subprogram. Do not add polling point if calls to
4241       --  this subprogram will be inlined by the back-end, to avoid repeated
4242       --  polling points in nested inlinings.
4243
4244       if Is_Non_Empty_List (L) then
4245          if Is_Inlined (Spec_Id)
4246            and then Front_End_Inlining
4247            and then Optimization_Level > 1
4248          then
4249             null;
4250          else
4251             Generate_Poll_Call (First (L));
4252          end if;
4253       end if;
4254
4255       --  If this is a Pure function which has any parameters whose root
4256       --  type is System.Address, reset the Pure indication, since it will
4257       --  likely cause incorrect code to be generated as the parameter is
4258       --  probably a pointer, and the fact that the same pointer is passed
4259       --  does not mean that the same value is being referenced.
4260
4261       --  Note that if the programmer gave an explicit Pure_Function pragma,
4262       --  then we believe the programmer, and leave the subprogram Pure.
4263
4264       --  This code should probably be at the freeze point, so that it
4265       --  happens even on a -gnatc (or more importantly -gnatt) compile
4266       --  so that the semantic tree has Is_Pure set properly ???
4267
4268       if Is_Pure (Spec_Id)
4269         and then Is_Subprogram (Spec_Id)
4270         and then not Has_Pragma_Pure_Function (Spec_Id)
4271       then
4272          declare
4273             F : Entity_Id;
4274
4275          begin
4276             F := First_Formal (Spec_Id);
4277             while Present (F) loop
4278                if Is_Descendent_Of_Address (Etype (F)) then
4279                   Set_Is_Pure (Spec_Id, False);
4280
4281                   if Spec_Id /= Body_Id then
4282                      Set_Is_Pure (Body_Id, False);
4283                   end if;
4284
4285                   exit;
4286                end if;
4287
4288                Next_Formal (F);
4289             end loop;
4290          end;
4291       end if;
4292
4293       --  Initialize any scalar OUT args if Initialize/Normalize_Scalars
4294
4295       if Init_Or_Norm_Scalars and then Is_Subprogram (Spec_Id) then
4296          declare
4297             F : Entity_Id;
4298
4299          begin
4300             --  Loop through formals
4301
4302             F := First_Formal (Spec_Id);
4303             while Present (F) loop
4304                if Is_Scalar_Type (Etype (F))
4305                  and then Ekind (F) = E_Out_Parameter
4306                then
4307                   --  Insert the initialization. We turn off validity checks
4308                   --  for this assignment, since we do not want any check on
4309                   --  the initial value itself (which may well be invalid).
4310
4311                   Insert_Before_And_Analyze (First (L),
4312                     Make_Assignment_Statement (Loc,
4313                       Name       => New_Occurrence_Of (F, Loc),
4314                       Expression => Get_Simple_Init_Val (Etype (F), Loc)),
4315                     Suppress => Validity_Check);
4316                end if;
4317
4318                Next_Formal (F);
4319             end loop;
4320          end;
4321       end if;
4322
4323       Scop := Scope (Spec_Id);
4324
4325       --  Add discriminal renamings to protected subprograms. Install new
4326       --  discriminals for expansion of the next subprogram of this protected
4327       --  type, if any.
4328
4329       if Is_List_Member (N)
4330         and then Present (Parent (List_Containing (N)))
4331         and then Nkind (Parent (List_Containing (N))) = N_Protected_Body
4332       then
4333          Add_Discriminal_Declarations
4334            (Declarations (N), Scop, Name_uObject, Loc);
4335          Add_Private_Declarations
4336            (Declarations (N), Scop, Name_uObject, Loc);
4337
4338          --  Associate privals and discriminals with the next protected
4339          --  operation body to be expanded. These are used to expand references
4340          --  to private data objects and discriminants, respectively.
4341
4342          Next_Op := Next_Protected_Operation (N);
4343
4344          if Present (Next_Op) then
4345             Dec := Parent (Base_Type (Scop));
4346             Set_Privals (Dec, Next_Op, Loc);
4347             Set_Discriminals (Dec);
4348          end if;
4349       end if;
4350
4351       --  Clear out statement list for stubbed procedure
4352
4353       if Present (Corresponding_Spec (N)) then
4354          Set_Elaboration_Flag (N, Spec_Id);
4355
4356          if Convention (Spec_Id) = Convention_Stubbed
4357            or else Is_Eliminated (Spec_Id)
4358          then
4359             Set_Declarations (N, Empty_List);
4360             Set_Handled_Statement_Sequence (N,
4361               Make_Handled_Sequence_Of_Statements (Loc,
4362                 Statements => New_List (
4363                   Make_Null_Statement (Loc))));
4364             return;
4365          end if;
4366       end if;
4367
4368       --  Returns_By_Ref flag is normally set when the subprogram is frozen
4369       --  but subprograms with no specs are not frozen.
4370
4371       declare
4372          Typ  : constant Entity_Id := Etype (Spec_Id);
4373          Utyp : constant Entity_Id := Underlying_Type (Typ);
4374
4375       begin
4376          if not Acts_As_Spec (N)
4377            and then Nkind (Parent (Parent (Spec_Id))) /=
4378              N_Subprogram_Body_Stub
4379          then
4380             null;
4381
4382          elsif Is_Inherently_Limited_Type (Typ) then
4383             Set_Returns_By_Ref (Spec_Id);
4384
4385          elsif Present (Utyp) and then CW_Or_Controlled_Type (Utyp) then
4386             Set_Returns_By_Ref (Spec_Id);
4387          end if;
4388       end;
4389
4390       --  For a procedure, we add a return for all possible syntactic ends
4391       --  of the subprogram. Note that reanalysis is not necessary in this
4392       --  case since it would require a lot of work and accomplish nothing.
4393
4394       if Ekind (Spec_Id) = E_Procedure
4395         or else Ekind (Spec_Id) = E_Generic_Procedure
4396       then
4397          Add_Return (Statements (H));
4398
4399          if Present (Exception_Handlers (H)) then
4400             Except_H := First_Non_Pragma (Exception_Handlers (H));
4401             while Present (Except_H) loop
4402                Add_Return (Statements (Except_H));
4403                Next_Non_Pragma (Except_H);
4404             end loop;
4405          end if;
4406
4407       --  For a function, we must deal with the case where there is at least
4408       --  one missing return. What we do is to wrap the entire body of the
4409       --  function in a block:
4410
4411       --    begin
4412       --      ...
4413       --    end;
4414
4415       --  becomes
4416
4417       --    begin
4418       --       begin
4419       --          ...
4420       --       end;
4421
4422       --       raise Program_Error;
4423       --    end;
4424
4425       --  This approach is necessary because the raise must be signalled
4426       --  to the caller, not handled by any local handler (RM 6.4(11)).
4427
4428       --  Note: we do not need to analyze the constructed sequence here,
4429       --  since it has no handler, and an attempt to analyze the handled
4430       --  statement sequence twice is risky in various ways (e.g. the
4431       --  issue of expanding cleanup actions twice).
4432
4433       elsif Has_Missing_Return (Spec_Id) then
4434          declare
4435             Hloc : constant Source_Ptr := Sloc (H);
4436             Blok : constant Node_Id    :=
4437                      Make_Block_Statement (Hloc,
4438                        Handled_Statement_Sequence => H);
4439             Rais : constant Node_Id    :=
4440                      Make_Raise_Program_Error (Hloc,
4441                        Reason => PE_Missing_Return);
4442
4443          begin
4444             Set_Handled_Statement_Sequence (N,
4445               Make_Handled_Sequence_Of_Statements (Hloc,
4446                 Statements => New_List (Blok, Rais)));
4447
4448             Push_Scope (Spec_Id);
4449             Analyze (Blok);
4450             Analyze (Rais);
4451             Pop_Scope;
4452          end;
4453       end if;
4454
4455       --  If subprogram contains a parameterless recursive call, then we may
4456       --  have an infinite recursion, so see if we can generate code to check
4457       --  for this possibility if storage checks are not suppressed.
4458
4459       if Ekind (Spec_Id) = E_Procedure
4460         and then Has_Recursive_Call (Spec_Id)
4461         and then not Storage_Checks_Suppressed (Spec_Id)
4462       then
4463          Detect_Infinite_Recursion (N, Spec_Id);
4464       end if;
4465
4466       --  Finally, if we are in Normalize_Scalars mode, then any scalar out
4467       --  parameters must be initialized to the appropriate default value.
4468
4469       if Ekind (Spec_Id) = E_Procedure and then Normalize_Scalars then
4470          declare
4471             Floc   : Source_Ptr;
4472             Formal : Entity_Id;
4473             Stm    : Node_Id;
4474
4475          begin
4476             Formal := First_Formal (Spec_Id);
4477             while Present (Formal) loop
4478                Floc := Sloc (Formal);
4479
4480                if Ekind (Formal) = E_Out_Parameter
4481                  and then Is_Scalar_Type (Etype (Formal))
4482                then
4483                   Stm :=
4484                     Make_Assignment_Statement (Floc,
4485                       Name => New_Occurrence_Of (Formal, Floc),
4486                       Expression =>
4487                         Get_Simple_Init_Val (Etype (Formal), Floc));
4488                   Prepend (Stm, Declarations (N));
4489                   Analyze (Stm);
4490                end if;
4491
4492                Next_Formal (Formal);
4493             end loop;
4494          end;
4495       end if;
4496
4497       --  Set to encode entity names in package body before gigi is called
4498
4499       Qualify_Entity_Names (N);
4500    end Expand_N_Subprogram_Body;
4501
4502    -----------------------------------
4503    -- Expand_N_Subprogram_Body_Stub --
4504    -----------------------------------
4505
4506    procedure Expand_N_Subprogram_Body_Stub (N : Node_Id) is
4507    begin
4508       if Present (Corresponding_Body (N)) then
4509          Expand_N_Subprogram_Body (
4510            Unit_Declaration_Node (Corresponding_Body (N)));
4511       end if;
4512    end Expand_N_Subprogram_Body_Stub;
4513
4514    -------------------------------------
4515    -- Expand_N_Subprogram_Declaration --
4516    -------------------------------------
4517
4518    --  If the declaration appears within a protected body, it is a private
4519    --  operation of the protected type. We must create the corresponding
4520    --  protected subprogram an associated formals. For a normal protected
4521    --  operation, this is done when expanding the protected type declaration.
4522
4523    --  If the declaration is for a null procedure, emit null body
4524
4525    procedure Expand_N_Subprogram_Declaration (N : Node_Id) is
4526       Loc       : constant Source_Ptr := Sloc (N);
4527       Subp      : constant Entity_Id  := Defining_Entity (N);
4528       Scop      : constant Entity_Id  := Scope (Subp);
4529       Prot_Decl : Node_Id;
4530       Prot_Bod  : Node_Id;
4531       Prot_Id   : Entity_Id;
4532
4533    begin
4534       --  Deal with case of protected subprogram. Do not generate protected
4535       --  operation if operation is flagged as eliminated.
4536
4537       if Is_List_Member (N)
4538         and then Present (Parent (List_Containing (N)))
4539         and then Nkind (Parent (List_Containing (N))) = N_Protected_Body
4540         and then Is_Protected_Type (Scop)
4541       then
4542          if No (Protected_Body_Subprogram (Subp))
4543            and then not Is_Eliminated (Subp)
4544          then
4545             Prot_Decl :=
4546               Make_Subprogram_Declaration (Loc,
4547                 Specification =>
4548                   Build_Protected_Sub_Specification
4549                     (N, Scop, Unprotected_Mode));
4550
4551             --  The protected subprogram is declared outside of the protected
4552             --  body. Given that the body has frozen all entities so far, we
4553             --  analyze the subprogram and perform freezing actions explicitly.
4554             --  including the generation of an explicit freeze node, to ensure
4555             --  that gigi has the proper order of elaboration.
4556             --  If the body is a subunit, the insertion point is before the
4557             --  stub in the parent.
4558
4559             Prot_Bod := Parent (List_Containing (N));
4560
4561             if Nkind (Parent (Prot_Bod)) = N_Subunit then
4562                Prot_Bod := Corresponding_Stub (Parent (Prot_Bod));
4563             end if;
4564
4565             Insert_Before (Prot_Bod, Prot_Decl);
4566             Prot_Id := Defining_Unit_Name (Specification (Prot_Decl));
4567             Set_Has_Delayed_Freeze (Prot_Id);
4568
4569             Push_Scope (Scope (Scop));
4570             Analyze (Prot_Decl);
4571             Insert_Actions (N, Freeze_Entity (Prot_Id, Loc));
4572             Set_Protected_Body_Subprogram (Subp, Prot_Id);
4573             Pop_Scope;
4574          end if;
4575
4576       --  Ada 2005 (AI-348): Generation of the null body
4577
4578       elsif Nkind (Specification (N)) = N_Procedure_Specification
4579         and then Null_Present (Specification (N))
4580       then
4581          declare
4582             Bod : constant Node_Id :=
4583                     Make_Subprogram_Body (Loc,
4584                       Specification =>
4585                         New_Copy_Tree (Specification (N)),
4586                       Declarations => New_List,
4587                      Handled_Statement_Sequence =>
4588                         Make_Handled_Sequence_Of_Statements (Loc,
4589                           Statements => New_List (Make_Null_Statement (Loc))));
4590          begin
4591             Set_Body_To_Inline (N, Bod);
4592             Insert_After (N, Bod);
4593             Analyze (Bod);
4594
4595             --  Corresponding_Spec isn't being set by Analyze_Subprogram_Body,
4596             --  evidently because Set_Has_Completion is called earlier for null
4597             --  procedures in Analyze_Subprogram_Declaration, so we force its
4598             --  setting here. If the setting of Has_Completion is not set
4599             --  earlier, then it can result in missing body errors if other
4600             --  errors were already reported (since expansion is turned off).
4601
4602             --  Should creation of the empty body be moved to the analyzer???
4603
4604             Set_Corresponding_Spec (Bod, Defining_Entity (Specification (N)));
4605          end;
4606       end if;
4607    end Expand_N_Subprogram_Declaration;
4608
4609    ---------------------------------------
4610    -- Expand_Protected_Object_Reference --
4611    ---------------------------------------
4612
4613    function Expand_Protected_Object_Reference
4614      (N    : Node_Id;
4615       Scop : Entity_Id) return Node_Id
4616    is
4617       Loc   : constant Source_Ptr := Sloc (N);
4618       Corr  : Entity_Id;
4619       Rec   : Node_Id;
4620       Param : Entity_Id;
4621       Proc  : Entity_Id;
4622
4623    begin
4624       Rec :=
4625         Make_Identifier (Loc,
4626           Chars => Name_uObject);
4627       Set_Etype (Rec, Corresponding_Record_Type (Scop));
4628
4629       --  Find enclosing protected operation, and retrieve its first parameter,
4630       --  which denotes the enclosing protected object. If the enclosing
4631       --  operation is an entry, we are immediately within the protected body,
4632       --  and we can retrieve the object from the service entries procedure. A
4633       --  barrier function has has the same signature as an entry. A barrier
4634       --  function is compiled within the protected object, but unlike
4635       --  protected operations its never needs locks, so that its protected
4636       --  body subprogram points to itself.
4637
4638       Proc := Current_Scope;
4639       while Present (Proc)
4640         and then Scope (Proc) /= Scop
4641       loop
4642          Proc := Scope (Proc);
4643       end loop;
4644
4645       Corr := Protected_Body_Subprogram (Proc);
4646
4647       if No (Corr) then
4648
4649          --  Previous error left expansion incomplete.
4650          --  Nothing to do on this call.
4651
4652          return Empty;
4653       end if;
4654
4655       Param :=
4656         Defining_Identifier
4657           (First (Parameter_Specifications (Parent (Corr))));
4658
4659       if Is_Subprogram (Proc)
4660         and then Proc /= Corr
4661       then
4662          --  Protected function or procedure
4663
4664          Set_Entity (Rec, Param);
4665
4666          --  Rec is a reference to an entity which will not be in scope when
4667          --  the call is reanalyzed, and needs no further analysis.
4668
4669          Set_Analyzed (Rec);
4670
4671       else
4672          --  Entry or barrier function for entry body. The first parameter of
4673          --  the entry body procedure is pointer to the object. We create a
4674          --  local variable of the proper type, duplicating what is done to
4675          --  define _object later on.
4676
4677          declare
4678             Decls : List_Id;
4679             Obj_Ptr : constant Entity_Id :=  Make_Defining_Identifier (Loc,
4680                                                Chars =>
4681                                                  New_Internal_Name ('T'));
4682
4683          begin
4684             Decls := New_List (
4685               Make_Full_Type_Declaration (Loc,
4686                 Defining_Identifier => Obj_Ptr,
4687                   Type_Definition =>
4688                      Make_Access_To_Object_Definition (Loc,
4689                        Subtype_Indication =>
4690                          New_Reference_To
4691                       (Corresponding_Record_Type (Scop), Loc))));
4692
4693             Insert_Actions (N, Decls);
4694             Insert_Actions (N, Freeze_Entity (Obj_Ptr, Sloc (N)));
4695
4696             Rec :=
4697               Make_Explicit_Dereference (Loc,
4698                 Unchecked_Convert_To (Obj_Ptr,
4699                   New_Occurrence_Of (Param, Loc)));
4700
4701             --  Analyze new actual. Other actuals in calls are already analyzed
4702             --  and the list of actuals is not reanalyzed after rewriting.
4703
4704             Set_Parent (Rec, N);
4705             Analyze (Rec);
4706          end;
4707       end if;
4708
4709       return Rec;
4710    end Expand_Protected_Object_Reference;
4711
4712    --------------------------------------
4713    -- Expand_Protected_Subprogram_Call --
4714    --------------------------------------
4715
4716    procedure Expand_Protected_Subprogram_Call
4717      (N    : Node_Id;
4718       Subp : Entity_Id;
4719       Scop : Entity_Id)
4720    is
4721       Rec   : Node_Id;
4722
4723    begin
4724       --  If the protected object is not an enclosing scope, this is
4725       --  an inter-object function call. Inter-object procedure
4726       --  calls are expanded by Exp_Ch9.Build_Simple_Entry_Call.
4727       --  The call is intra-object only if the subprogram being
4728       --  called is in the protected body being compiled, and if the
4729       --  protected object in the call is statically the enclosing type.
4730       --  The object may be an component of some other data structure,
4731       --  in which case this must be handled as an inter-object call.
4732
4733       if not In_Open_Scopes (Scop)
4734         or else not Is_Entity_Name (Name (N))
4735       then
4736          if Nkind (Name (N)) = N_Selected_Component then
4737             Rec := Prefix (Name (N));
4738
4739          else
4740             pragma Assert (Nkind (Name (N)) = N_Indexed_Component);
4741             Rec := Prefix (Prefix (Name (N)));
4742          end if;
4743
4744          Build_Protected_Subprogram_Call (N,
4745            Name => New_Occurrence_Of (Subp, Sloc (N)),
4746            Rec =>  Convert_Concurrent (Rec, Etype (Rec)),
4747            External => True);
4748
4749       else
4750          Rec := Expand_Protected_Object_Reference (N, Scop);
4751
4752          if No (Rec) then
4753             return;
4754          end if;
4755
4756          Build_Protected_Subprogram_Call (N,
4757            Name     => Name (N),
4758            Rec      => Rec,
4759            External => False);
4760
4761       end if;
4762
4763       Analyze (N);
4764
4765       --  If it is a function call it can appear in elaboration code and
4766       --  the called entity must be frozen here.
4767
4768       if Ekind (Subp) = E_Function then
4769          Freeze_Expression (Name (N));
4770       end if;
4771    end Expand_Protected_Subprogram_Call;
4772
4773    --------------------------------
4774    -- Is_Build_In_Place_Function --
4775    --------------------------------
4776
4777    function Is_Build_In_Place_Function (E : Entity_Id) return Boolean is
4778    begin
4779       --  For now we test whether E denotes a function or access-to-function
4780       --  type whose result subtype is inherently limited. Later this test may
4781       --  be revised to allow composite nonlimited types. Functions with a
4782       --  foreign convention or whose result type has a foreign convention
4783       --  never qualify.
4784
4785       if Ekind (E) = E_Function
4786         or else Ekind (E) = E_Generic_Function
4787         or else (Ekind (E) = E_Subprogram_Type
4788                   and then Etype (E) /= Standard_Void_Type)
4789       then
4790          --  Note: If you have Convention (C) on an inherently limited type,
4791          --  you're on your own. That is, the C code will have to be carefully
4792          --  written to know about the Ada conventions.
4793
4794          if Has_Foreign_Convention (E)
4795            or else Has_Foreign_Convention (Etype (E))
4796          then
4797             return False;
4798
4799          --  If the return type is a limited interface it has to be treated
4800          --  as a return in place, even if the actual object is some non-
4801          --  limited descendant.
4802
4803          elsif Is_Limited_Interface (Etype (E)) then
4804             return True;
4805
4806          else
4807             return Is_Inherently_Limited_Type (Etype (E))
4808               and then Ada_Version >= Ada_05
4809               and then not Debug_Flag_Dot_L;
4810          end if;
4811
4812       else
4813          return False;
4814       end if;
4815    end Is_Build_In_Place_Function;
4816
4817    -------------------------------------
4818    -- Is_Build_In_Place_Function_Call --
4819    -------------------------------------
4820
4821    function Is_Build_In_Place_Function_Call (N : Node_Id) return Boolean is
4822       Exp_Node    : Node_Id := N;
4823       Function_Id : Entity_Id;
4824
4825    begin
4826       --  Step past qualification or unchecked conversion (the latter can occur
4827       --  in cases of calls to 'Input).
4828
4829       if Nkind (Exp_Node) = N_Qualified_Expression
4830         or else Nkind (Exp_Node) = N_Unchecked_Type_Conversion
4831       then
4832          Exp_Node := Expression (N);
4833       end if;
4834
4835       if Nkind (Exp_Node) /= N_Function_Call then
4836          return False;
4837
4838       else
4839          if Is_Entity_Name (Name (Exp_Node)) then
4840             Function_Id := Entity (Name (Exp_Node));
4841
4842          elsif Nkind (Name (Exp_Node)) = N_Explicit_Dereference then
4843             Function_Id := Etype (Name (Exp_Node));
4844          end if;
4845
4846          return Is_Build_In_Place_Function (Function_Id);
4847       end if;
4848    end Is_Build_In_Place_Function_Call;
4849
4850    ---------------------------------------
4851    -- Is_Build_In_Place_Function_Return --
4852    ---------------------------------------
4853
4854    function Is_Build_In_Place_Function_Return (N : Node_Id) return Boolean is
4855    begin
4856       if Nkind (N) = N_Simple_Return_Statement
4857         or else Nkind (N) = N_Extended_Return_Statement
4858       then
4859          return Is_Build_In_Place_Function
4860                   (Return_Applies_To (Return_Statement_Entity (N)));
4861       else
4862          return False;
4863       end if;
4864    end Is_Build_In_Place_Function_Return;
4865
4866    -----------------------
4867    -- Freeze_Subprogram --
4868    -----------------------
4869
4870    procedure Freeze_Subprogram (N : Node_Id) is
4871       Loc : constant Source_Ptr := Sloc (N);
4872
4873       procedure Register_Predefined_DT_Entry (Prim : Entity_Id);
4874       --  (Ada 2005): Register a predefined primitive in all the secondary
4875       --  dispatch tables of its primitive type.
4876
4877       ----------------------------------
4878       -- Register_Predefined_DT_Entry --
4879       ----------------------------------
4880
4881       procedure Register_Predefined_DT_Entry (Prim : Entity_Id) is
4882          Iface_DT_Ptr : Elmt_Id;
4883          Tagged_Typ   : Entity_Id;
4884          Thunk_Id     : Entity_Id;
4885          Thunk_Code   : Node_Id;
4886
4887       begin
4888          Tagged_Typ := Find_Dispatching_Type (Prim);
4889
4890          if No (Access_Disp_Table (Tagged_Typ))
4891            or else not Has_Abstract_Interfaces (Tagged_Typ)
4892            or else not RTE_Available (RE_Interface_Tag)
4893            or else Restriction_Active (No_Dispatching_Calls)
4894          then
4895             return;
4896          end if;
4897
4898          --  Skip the first access-to-dispatch-table pointer since it leads
4899          --  to the primary dispatch table. We are only concerned with the
4900          --  secondary dispatch table pointers. Note that the access-to-
4901          --  dispatch-table pointer corresponds to the first implemented
4902          --  interface retrieved below.
4903
4904          Iface_DT_Ptr :=
4905            Next_Elmt (First_Elmt (Access_Disp_Table (Tagged_Typ)));
4906
4907          while Present (Iface_DT_Ptr)
4908             and then Ekind (Node (Iface_DT_Ptr)) = E_Constant
4909          loop
4910             Expand_Interface_Thunk (Prim, Thunk_Id, Thunk_Code);
4911
4912             if Present (Thunk_Code) then
4913                Insert_Actions (N, New_List (
4914                  Thunk_Code,
4915
4916                  Build_Set_Predefined_Prim_Op_Address (Loc,
4917                    Tag_Node => New_Reference_To (Node (Iface_DT_Ptr), Loc),
4918                    Position => DT_Position (Prim),
4919                    Address_Node =>
4920                      Make_Attribute_Reference (Loc,
4921                        Prefix         => New_Reference_To (Thunk_Id, Loc),
4922                        Attribute_Name => Name_Address))));
4923             end if;
4924
4925             Next_Elmt (Iface_DT_Ptr);
4926          end loop;
4927       end Register_Predefined_DT_Entry;
4928
4929       --  Local variables
4930
4931       Subp : constant Entity_Id := Entity (N);
4932
4933    begin
4934       --  We suppress the initialization of the dispatch table entry when
4935       --  VM_Target because the dispatching mechanism is handled internally
4936       --  by the VM.
4937
4938       if Is_Dispatching_Operation (Subp)
4939         and then not Is_Abstract_Subprogram (Subp)
4940         and then Present (DTC_Entity (Subp))
4941         and then Present (Scope (DTC_Entity (Subp)))
4942         and then VM_Target = No_VM
4943         and then not Restriction_Active (No_Dispatching_Calls)
4944         and then RTE_Available (RE_Tag)
4945       then
4946          declare
4947             Typ : constant Entity_Id := Scope (DTC_Entity (Subp));
4948
4949          begin
4950             --  Handle private overriden primitives
4951
4952             if not Is_CPP_Class (Typ) then
4953                Check_Overriding_Operation (Subp);
4954             end if;
4955
4956             --  We assume that imported CPP primitives correspond with objects
4957             --  whose constructor is in the CPP side; therefore we don't need
4958             --  to generate code to register them in the dispatch table.
4959
4960             if Is_CPP_Class (Typ) then
4961                null;
4962
4963             --  Handle CPP primitives found in derivations of CPP_Class types.
4964             --  These primitives must have been inherited from some parent, and
4965             --  there is no need to register them in the dispatch table because
4966             --  Build_Inherit_Prims takes care of the initialization of these
4967             --  slots.
4968
4969             elsif Is_Imported (Subp)
4970                     and then (Convention (Subp) = Convention_CPP
4971                                 or else Convention (Subp) = Convention_C)
4972             then
4973                null;
4974
4975             --  Generate code to register the primitive in non statically
4976             --  allocated dispatch tables
4977
4978             elsif not Static_Dispatch_Tables
4979               or else not
4980                 Is_Library_Level_Tagged_Type (Scope (DTC_Entity (Subp)))
4981             then
4982                --  When a primitive is frozen, enter its name in its dispatch
4983                --  table slot.
4984
4985                if not Is_Interface (Typ)
4986                  or else Present (Abstract_Interface_Alias (Subp))
4987                then
4988                   if Is_Predefined_Dispatching_Operation (Subp) then
4989                      Register_Predefined_DT_Entry (Subp);
4990                   end if;
4991
4992                   Register_Primitive (Loc,
4993                     Prim    => Subp,
4994                     Ins_Nod => N);
4995                end if;
4996             end if;
4997          end;
4998       end if;
4999
5000       --  Mark functions that return by reference. Note that it cannot be part
5001       --  of the normal semantic analysis of the spec since the underlying
5002       --  returned type may not be known yet (for private types).
5003
5004       declare
5005          Typ  : constant Entity_Id := Etype (Subp);
5006          Utyp : constant Entity_Id := Underlying_Type (Typ);
5007       begin
5008          if Is_Inherently_Limited_Type (Typ) then
5009             Set_Returns_By_Ref (Subp);
5010          elsif Present (Utyp) and then CW_Or_Controlled_Type (Utyp) then
5011             Set_Returns_By_Ref (Subp);
5012          end if;
5013       end;
5014    end Freeze_Subprogram;
5015
5016    -------------------------------------------
5017    -- Make_Build_In_Place_Call_In_Allocator --
5018    -------------------------------------------
5019
5020    procedure Make_Build_In_Place_Call_In_Allocator
5021      (Allocator     : Node_Id;
5022       Function_Call : Node_Id)
5023    is
5024       Loc               : Source_Ptr;
5025       Func_Call         : Node_Id := Function_Call;
5026       Function_Id       : Entity_Id;
5027       Result_Subt       : Entity_Id;
5028       Acc_Type          : constant Entity_Id := Etype (Allocator);
5029       New_Allocator     : Node_Id;
5030       Return_Obj_Access : Entity_Id;
5031
5032    begin
5033       --  Step past qualification or unchecked conversion (the latter can occur
5034       --  in cases of calls to 'Input).
5035
5036       if Nkind (Func_Call) = N_Qualified_Expression
5037         or else Nkind (Func_Call) = N_Unchecked_Type_Conversion
5038       then
5039          Func_Call := Expression (Func_Call);
5040       end if;
5041
5042       Loc := Sloc (Function_Call);
5043
5044       if Is_Entity_Name (Name (Func_Call)) then
5045          Function_Id := Entity (Name (Func_Call));
5046
5047       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
5048          Function_Id := Etype (Name (Func_Call));
5049
5050       else
5051          raise Program_Error;
5052       end if;
5053
5054       Result_Subt := Etype (Function_Id);
5055
5056       --  When the result subtype is constrained, the return object must be
5057       --  allocated on the caller side, and access to it is passed to the
5058       --  function.
5059
5060       --  Here and in related routines, we must examine the full view of the
5061       --  type, because the view at the point of call may differ from that
5062       --  that in the function body, and the expansion mechanism depends on
5063       --  the characteristics of the full view.
5064
5065       if Is_Constrained (Underlying_Type (Result_Subt)) then
5066
5067          --  Replace the initialized allocator of form "new T'(Func (...))"
5068          --  with an uninitialized allocator of form "new T", where T is the
5069          --  result subtype of the called function. The call to the function
5070          --  is handled separately further below.
5071
5072          New_Allocator :=
5073            Make_Allocator (Loc, New_Reference_To (Result_Subt, Loc));
5074
5075          Set_Storage_Pool      (New_Allocator, Storage_Pool (Allocator));
5076          Set_Procedure_To_Call (New_Allocator, Procedure_To_Call (Allocator));
5077          Set_No_Initialization (New_Allocator);
5078
5079          Rewrite (Allocator, New_Allocator);
5080
5081          --  Create a new access object and initialize it to the result of the
5082          --  new uninitialized allocator.
5083
5084          Return_Obj_Access :=
5085            Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
5086          Set_Etype (Return_Obj_Access, Acc_Type);
5087
5088          Insert_Action (Allocator,
5089            Make_Object_Declaration (Loc,
5090              Defining_Identifier => Return_Obj_Access,
5091              Object_Definition   => New_Reference_To (Acc_Type, Loc),
5092              Expression          => Relocate_Node (Allocator)));
5093
5094          --  When the function has a controlling result, an allocation-form
5095          --  parameter must be passed indicating that the caller is allocating
5096          --  the result object. This is needed because such a function can be
5097          --  called as a dispatching operation and must be treated similarly
5098          --  to functions with unconstrained result subtypes.
5099
5100          Add_Alloc_Form_Actual_To_Build_In_Place_Call
5101            (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
5102
5103          Add_Final_List_Actual_To_Build_In_Place_Call
5104            (Func_Call, Function_Id, Acc_Type);
5105
5106          Add_Task_Actuals_To_Build_In_Place_Call
5107            (Func_Call, Function_Id, Master_Actual => Master_Id (Acc_Type));
5108
5109          --  Add an implicit actual to the function call that provides access
5110          --  to the allocated object. An unchecked conversion to the (specific)
5111          --  result subtype of the function is inserted to handle cases where
5112          --  the access type of the allocator has a class-wide designated type.
5113
5114          Add_Access_Actual_To_Build_In_Place_Call
5115            (Func_Call,
5116             Function_Id,
5117             Make_Unchecked_Type_Conversion (Loc,
5118               Subtype_Mark => New_Reference_To (Result_Subt, Loc),
5119               Expression   =>
5120                 Make_Explicit_Dereference (Loc,
5121                   Prefix => New_Reference_To (Return_Obj_Access, Loc))));
5122
5123       --  When the result subtype is unconstrained, the function itself must
5124       --  perform the allocation of the return object, so we pass parameters
5125       --  indicating that. We don't yet handle the case where the allocation
5126       --  must be done in a user-defined storage pool, which will require
5127       --  passing another actual or two to provide allocation/deallocation
5128       --  operations. ???
5129
5130       else
5131
5132          --  Pass an allocation parameter indicating that the function should
5133          --  allocate its result on the heap.
5134
5135          Add_Alloc_Form_Actual_To_Build_In_Place_Call
5136            (Func_Call, Function_Id, Alloc_Form => Global_Heap);
5137
5138          Add_Final_List_Actual_To_Build_In_Place_Call
5139            (Func_Call, Function_Id, Acc_Type);
5140
5141          Add_Task_Actuals_To_Build_In_Place_Call
5142            (Func_Call, Function_Id, Master_Actual => Master_Id (Acc_Type));
5143
5144          --  The caller does not provide the return object in this case, so we
5145          --  have to pass null for the object access actual.
5146
5147          Add_Access_Actual_To_Build_In_Place_Call
5148            (Func_Call, Function_Id, Return_Object => Empty);
5149       end if;
5150
5151       --  Finally, replace the allocator node with a reference to the result
5152       --  of the function call itself (which will effectively be an access
5153       --  to the object created by the allocator).
5154
5155       Rewrite (Allocator, Make_Reference (Loc, Relocate_Node (Function_Call)));
5156       Analyze_And_Resolve (Allocator, Acc_Type);
5157    end Make_Build_In_Place_Call_In_Allocator;
5158
5159    ---------------------------------------------------
5160    -- Make_Build_In_Place_Call_In_Anonymous_Context --
5161    ---------------------------------------------------
5162
5163    procedure Make_Build_In_Place_Call_In_Anonymous_Context
5164      (Function_Call : Node_Id)
5165    is
5166       Loc             : Source_Ptr;
5167       Func_Call       : Node_Id := Function_Call;
5168       Function_Id     : Entity_Id;
5169       Result_Subt     : Entity_Id;
5170       Return_Obj_Id   : Entity_Id;
5171       Return_Obj_Decl : Entity_Id;
5172
5173    begin
5174       --  Step past qualification or unchecked conversion (the latter can occur
5175       --  in cases of calls to 'Input).
5176
5177       if Nkind (Func_Call) = N_Qualified_Expression
5178         or else Nkind (Func_Call) = N_Unchecked_Type_Conversion
5179       then
5180          Func_Call := Expression (Func_Call);
5181       end if;
5182
5183       Loc := Sloc (Function_Call);
5184
5185       if Is_Entity_Name (Name (Func_Call)) then
5186          Function_Id := Entity (Name (Func_Call));
5187
5188       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
5189          Function_Id := Etype (Name (Func_Call));
5190
5191       else
5192          raise Program_Error;
5193       end if;
5194
5195       Result_Subt := Etype (Function_Id);
5196
5197       --  When the result subtype is constrained, an object of the subtype is
5198       --  declared and an access value designating it is passed as an actual.
5199
5200       if Is_Constrained (Underlying_Type (Result_Subt)) then
5201
5202          --  Create a temporary object to hold the function result
5203
5204          Return_Obj_Id :=
5205            Make_Defining_Identifier (Loc,
5206              Chars => New_Internal_Name ('R'));
5207          Set_Etype (Return_Obj_Id, Result_Subt);
5208
5209          Return_Obj_Decl :=
5210            Make_Object_Declaration (Loc,
5211              Defining_Identifier => Return_Obj_Id,
5212              Aliased_Present     => True,
5213              Object_Definition   => New_Reference_To (Result_Subt, Loc));
5214
5215          Set_No_Initialization (Return_Obj_Decl);
5216
5217          Insert_Action (Func_Call, Return_Obj_Decl);
5218
5219          --  When the function has a controlling result, an allocation-form
5220          --  parameter must be passed indicating that the caller is allocating
5221          --  the result object. This is needed because such a function can be
5222          --  called as a dispatching operation and must be treated similarly
5223          --  to functions with unconstrained result subtypes.
5224
5225          Add_Alloc_Form_Actual_To_Build_In_Place_Call
5226            (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
5227
5228          Add_Final_List_Actual_To_Build_In_Place_Call
5229            (Func_Call, Function_Id, Acc_Type => Empty);
5230
5231          Add_Task_Actuals_To_Build_In_Place_Call
5232            (Func_Call, Function_Id, Make_Identifier (Loc, Name_uMaster));
5233
5234          --  Add an implicit actual to the function call that provides access
5235          --  to the caller's return object.
5236
5237          Add_Access_Actual_To_Build_In_Place_Call
5238            (Func_Call, Function_Id, New_Reference_To (Return_Obj_Id, Loc));
5239
5240       --  When the result subtype is unconstrained, the function must allocate
5241       --  the return object in the secondary stack, so appropriate implicit
5242       --  parameters are added to the call to indicate that. A transient
5243       --  scope is established to ensure eventual cleanup of the result.
5244
5245       else
5246
5247          --  Pass an allocation parameter indicating that the function should
5248          --  allocate its result on the secondary stack.
5249
5250          Add_Alloc_Form_Actual_To_Build_In_Place_Call
5251            (Func_Call, Function_Id, Alloc_Form => Secondary_Stack);
5252
5253          Add_Final_List_Actual_To_Build_In_Place_Call
5254            (Func_Call, Function_Id, Acc_Type => Empty);
5255
5256          Add_Task_Actuals_To_Build_In_Place_Call
5257            (Func_Call, Function_Id, Make_Identifier (Loc, Name_uMaster));
5258
5259          --  Pass a null value to the function since no return object is
5260          --  available on the caller side.
5261
5262          Add_Access_Actual_To_Build_In_Place_Call
5263            (Func_Call, Function_Id, Empty);
5264
5265          Establish_Transient_Scope (Func_Call, Sec_Stack => True);
5266       end if;
5267    end Make_Build_In_Place_Call_In_Anonymous_Context;
5268
5269    ---------------------------------------------------
5270    -- Make_Build_In_Place_Call_In_Assignment --
5271    ---------------------------------------------------
5272
5273    procedure Make_Build_In_Place_Call_In_Assignment
5274      (Assign        : Node_Id;
5275       Function_Call : Node_Id)
5276    is
5277       Lhs             : constant Node_Id := Name (Assign);
5278       Loc             : Source_Ptr;
5279       Func_Call       : Node_Id := Function_Call;
5280       Function_Id     : Entity_Id;
5281       Result_Subt     : Entity_Id;
5282       Ref_Type        : Entity_Id;
5283       Ptr_Typ_Decl    : Node_Id;
5284       Def_Id          : Entity_Id;
5285       New_Expr        : Node_Id;
5286
5287    begin
5288       --  Step past qualification or unchecked conversion (the latter can occur
5289       --  in cases of calls to 'Input).
5290
5291       if Nkind (Func_Call) = N_Qualified_Expression
5292         or else Nkind (Func_Call) = N_Unchecked_Type_Conversion
5293       then
5294          Func_Call := Expression (Func_Call);
5295       end if;
5296
5297       Loc := Sloc (Function_Call);
5298
5299       if Is_Entity_Name (Name (Func_Call)) then
5300          Function_Id := Entity (Name (Func_Call));
5301
5302       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
5303          Function_Id := Etype (Name (Func_Call));
5304
5305       else
5306          raise Program_Error;
5307       end if;
5308
5309       Result_Subt := Etype (Function_Id);
5310
5311       --  When the result subtype is unconstrained, an additional actual must
5312       --  be passed to indicate that the caller is providing the return object.
5313       --  This parameter must also be passed when the called function has a
5314       --  controlling result, because dispatching calls to the function needs
5315       --  to be treated effectively the same as calls to class-wide functions.
5316
5317       Add_Alloc_Form_Actual_To_Build_In_Place_Call
5318         (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
5319
5320       Add_Final_List_Actual_To_Build_In_Place_Call
5321         (Func_Call, Function_Id, Acc_Type => Empty);
5322
5323       Add_Task_Actuals_To_Build_In_Place_Call
5324         (Func_Call, Function_Id, Make_Identifier (Loc, Name_uMaster));
5325
5326       --  Add an implicit actual to the function call that provides access to
5327       --  the caller's return object.
5328
5329       Add_Access_Actual_To_Build_In_Place_Call
5330         (Func_Call,
5331          Function_Id,
5332          Make_Unchecked_Type_Conversion (Loc,
5333            Subtype_Mark => New_Reference_To (Result_Subt, Loc),
5334            Expression   => Relocate_Node (Lhs)));
5335
5336       --  Create an access type designating the function's result subtype
5337
5338       Ref_Type :=
5339         Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
5340
5341       Ptr_Typ_Decl :=
5342         Make_Full_Type_Declaration (Loc,
5343           Defining_Identifier => Ref_Type,
5344           Type_Definition =>
5345             Make_Access_To_Object_Definition (Loc,
5346               All_Present => True,
5347               Subtype_Indication =>
5348                 New_Reference_To (Result_Subt, Loc)));
5349
5350       Insert_After_And_Analyze (Assign, Ptr_Typ_Decl);
5351
5352       --  Finally, create an access object initialized to a reference to the
5353       --  function call.
5354
5355       Def_Id :=
5356         Make_Defining_Identifier (Loc,
5357           Chars => New_Internal_Name ('R'));
5358       Set_Etype (Def_Id, Ref_Type);
5359
5360       New_Expr :=
5361         Make_Reference (Loc,
5362           Prefix => Relocate_Node (Func_Call));
5363
5364       Insert_After_And_Analyze (Ptr_Typ_Decl,
5365         Make_Object_Declaration (Loc,
5366           Defining_Identifier => Def_Id,
5367           Object_Definition   => New_Reference_To (Ref_Type, Loc),
5368           Expression          => New_Expr));
5369
5370       Rewrite (Assign, Make_Null_Statement (Loc));
5371    end Make_Build_In_Place_Call_In_Assignment;
5372
5373    ----------------------------------------------------
5374    -- Make_Build_In_Place_Call_In_Object_Declaration --
5375    ----------------------------------------------------
5376
5377    procedure Make_Build_In_Place_Call_In_Object_Declaration
5378      (Object_Decl   : Node_Id;
5379       Function_Call : Node_Id)
5380    is
5381       Loc             : Source_Ptr;
5382       Obj_Def_Id      : constant Entity_Id :=
5383                           Defining_Identifier (Object_Decl);
5384
5385       Func_Call       : Node_Id := Function_Call;
5386       Function_Id     : Entity_Id;
5387       Result_Subt     : Entity_Id;
5388       Caller_Object   : Node_Id;
5389       Call_Deref      : Node_Id;
5390       Ref_Type        : Entity_Id;
5391       Ptr_Typ_Decl    : Node_Id;
5392       Def_Id          : Entity_Id;
5393       New_Expr        : Node_Id;
5394       Enclosing_Func  : Entity_Id;
5395       Pass_Caller_Acc : Boolean := False;
5396
5397    begin
5398       --  Step past qualification or unchecked conversion (the latter can occur
5399       --  in cases of calls to 'Input).
5400
5401       if Nkind (Func_Call) = N_Qualified_Expression
5402         or else Nkind (Func_Call) = N_Unchecked_Type_Conversion
5403       then
5404          Func_Call := Expression (Func_Call);
5405       end if;
5406
5407       Loc := Sloc (Function_Call);
5408
5409       if Is_Entity_Name (Name (Func_Call)) then
5410          Function_Id := Entity (Name (Func_Call));
5411
5412       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
5413          Function_Id := Etype (Name (Func_Call));
5414
5415       else
5416          raise Program_Error;
5417       end if;
5418
5419       Result_Subt := Etype (Function_Id);
5420
5421       --  In the constrained case, add an implicit actual to the function call
5422       --  that provides access to the declared object. An unchecked conversion
5423       --  to the (specific) result type of the function is inserted to handle
5424       --  the case where the object is declared with a class-wide type.
5425
5426       if Is_Constrained (Underlying_Type (Result_Subt)) then
5427          Caller_Object :=
5428             Make_Unchecked_Type_Conversion (Loc,
5429               Subtype_Mark => New_Reference_To (Result_Subt, Loc),
5430               Expression   => New_Reference_To (Obj_Def_Id, Loc));
5431
5432          --  When the function has a controlling result, an allocation-form
5433          --  parameter must be passed indicating that the caller is allocating
5434          --  the result object. This is needed because such a function can be
5435          --  called as a dispatching operation and must be treated similarly
5436          --  to functions with unconstrained result subtypes.
5437
5438          Add_Alloc_Form_Actual_To_Build_In_Place_Call
5439            (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
5440
5441       --  If the function's result subtype is unconstrained and the object is
5442       --  a return object of an enclosing build-in-place function, then the
5443       --  implicit build-in-place parameters of the enclosing function must be
5444       --  passed along to the called function.
5445
5446       elsif Nkind (Parent (Object_Decl)) = N_Extended_Return_Statement then
5447          Pass_Caller_Acc := True;
5448
5449          Enclosing_Func := Enclosing_Subprogram (Obj_Def_Id);
5450
5451          --  If the enclosing function has a constrained result type, then
5452          --  caller allocation will be used.
5453
5454          if Is_Constrained (Etype (Enclosing_Func)) then
5455             Add_Alloc_Form_Actual_To_Build_In_Place_Call
5456               (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
5457
5458          --  Otherwise, when the enclosing function has an unconstrained result
5459          --  type, the BIP_Alloc_Form formal of the enclosing function must be
5460          --  passed along to the callee.
5461
5462          else
5463             Add_Alloc_Form_Actual_To_Build_In_Place_Call
5464               (Func_Call,
5465                Function_Id,
5466                Alloc_Form_Exp =>
5467                  New_Reference_To
5468                    (Build_In_Place_Formal (Enclosing_Func, BIP_Alloc_Form),
5469                     Loc));
5470          end if;
5471
5472          --  Retrieve the BIPacc formal from the enclosing function and convert
5473          --  it to the access type of the callee's BIP_Object_Access formal.
5474
5475          Caller_Object :=
5476             Make_Unchecked_Type_Conversion (Loc,
5477               Subtype_Mark =>
5478                 New_Reference_To
5479                   (Etype
5480                      (Build_In_Place_Formal (Function_Id, BIP_Object_Access)),
5481                    Loc),
5482               Expression   =>
5483                 New_Reference_To
5484                   (Build_In_Place_Formal (Enclosing_Func, BIP_Object_Access),
5485                    Loc));
5486
5487       --  In other unconstrained cases, pass an indication to do the allocation
5488       --  on the secondary stack and set Caller_Object to Empty so that a null
5489       --  value will be passed for the caller's object address. A transient
5490       --  scope is established to ensure eventual cleanup of the result.
5491
5492       else
5493          Add_Alloc_Form_Actual_To_Build_In_Place_Call
5494            (Func_Call,
5495             Function_Id,
5496             Alloc_Form => Secondary_Stack);
5497          Caller_Object := Empty;
5498
5499          Establish_Transient_Scope (Object_Decl, Sec_Stack => True);
5500       end if;
5501
5502       Add_Final_List_Actual_To_Build_In_Place_Call
5503         (Func_Call, Function_Id, Acc_Type => Empty);
5504
5505       if Nkind (Parent (Object_Decl)) = N_Extended_Return_Statement
5506         and then Has_Task (Result_Subt)
5507       then
5508          Enclosing_Func := Enclosing_Subprogram (Obj_Def_Id);
5509
5510          --  Here we're passing along the master that was passed in to this
5511          --  function.
5512
5513          Add_Task_Actuals_To_Build_In_Place_Call
5514            (Func_Call, Function_Id,
5515             Master_Actual =>
5516               New_Reference_To
5517                 (Build_In_Place_Formal (Enclosing_Func, BIP_Master), Loc));
5518
5519       else
5520          Add_Task_Actuals_To_Build_In_Place_Call
5521            (Func_Call, Function_Id, Make_Identifier (Loc, Name_uMaster));
5522       end if;
5523
5524       Add_Access_Actual_To_Build_In_Place_Call
5525         (Func_Call, Function_Id, Caller_Object, Is_Access => Pass_Caller_Acc);
5526
5527       --  Create an access type designating the function's result subtype
5528
5529       Ref_Type :=
5530         Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
5531
5532       Ptr_Typ_Decl :=
5533         Make_Full_Type_Declaration (Loc,
5534           Defining_Identifier => Ref_Type,
5535           Type_Definition =>
5536             Make_Access_To_Object_Definition (Loc,
5537               All_Present => True,
5538               Subtype_Indication =>
5539                 New_Reference_To (Result_Subt, Loc)));
5540
5541       --  The access type and its accompanying object must be inserted after
5542       --  the object declaration in the constrained case, so that the function
5543       --  call can be passed access to the object. In the unconstrained case,
5544       --  the access type and object must be inserted before the object, since
5545       --  the object declaration is rewritten to be a renaming of a dereference
5546       --  of the access object.
5547
5548       if Is_Constrained (Underlying_Type (Result_Subt)) then
5549          Insert_After_And_Analyze (Object_Decl, Ptr_Typ_Decl);
5550       else
5551          Insert_Before_And_Analyze (Object_Decl, Ptr_Typ_Decl);
5552       end if;
5553
5554       --  Finally, create an access object initialized to a reference to the
5555       --  function call.
5556
5557       Def_Id :=
5558         Make_Defining_Identifier (Loc,
5559           Chars => New_Internal_Name ('R'));
5560       Set_Etype (Def_Id, Ref_Type);
5561
5562       New_Expr :=
5563         Make_Reference (Loc,
5564           Prefix => Relocate_Node (Func_Call));
5565
5566       Insert_After_And_Analyze (Ptr_Typ_Decl,
5567         Make_Object_Declaration (Loc,
5568           Defining_Identifier => Def_Id,
5569           Object_Definition   => New_Reference_To (Ref_Type, Loc),
5570           Expression          => New_Expr));
5571
5572       if Is_Constrained (Underlying_Type (Result_Subt)) then
5573          Set_Expression (Object_Decl, Empty);
5574          Set_No_Initialization (Object_Decl);
5575
5576       --  In case of an unconstrained result subtype, rewrite the object
5577       --  declaration as an object renaming where the renamed object is a
5578       --  dereference of <function_Call>'reference:
5579       --
5580       --      Obj : Subt renames <function_call>'Ref.all;
5581
5582       else
5583          Call_Deref :=
5584            Make_Explicit_Dereference (Loc,
5585              Prefix => New_Reference_To (Def_Id, Loc));
5586
5587          Rewrite (Object_Decl,
5588            Make_Object_Renaming_Declaration (Loc,
5589              Defining_Identifier => Make_Defining_Identifier (Loc,
5590                                       New_Internal_Name ('D')),
5591              Access_Definition   => Empty,
5592              Subtype_Mark        => New_Occurrence_Of (Result_Subt, Loc),
5593              Name                => Call_Deref));
5594
5595          Set_Renamed_Object (Defining_Identifier (Object_Decl), Call_Deref);
5596
5597          Analyze (Object_Decl);
5598
5599          --  Replace the internal identifier of the renaming declaration's
5600          --  entity with identifier of the original object entity. We also have
5601          --  to exchange the entities containing their defining identifiers to
5602          --  ensure the correct replacement of the object declaration by the
5603          --  object renaming declaration to avoid homograph conflicts (since
5604          --  the object declaration's defining identifier was already entered
5605          --  in current scope).
5606
5607          Set_Chars (Defining_Identifier (Object_Decl), Chars (Obj_Def_Id));
5608          Exchange_Entities (Defining_Identifier (Object_Decl), Obj_Def_Id);
5609       end if;
5610
5611       --  If the object entity has a class-wide Etype, then we need to change
5612       --  it to the result subtype of the function call, because otherwise the
5613       --  object will be class-wide without an explicit intialization and won't
5614       --  be allocated properly by the back end. It seems unclean to make such
5615       --  a revision to the type at this point, and we should try to improve
5616       --  this treatment when build-in-place functions with class-wide results
5617       --  are implemented. ???
5618
5619       if Is_Class_Wide_Type (Etype (Defining_Identifier (Object_Decl))) then
5620          Set_Etype (Defining_Identifier (Object_Decl), Result_Subt);
5621       end if;
5622    end Make_Build_In_Place_Call_In_Object_Declaration;
5623
5624 end Exp_Ch6;