OSDN Git Service

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