OSDN Git Service

* 41intnam.ads, 42intnam.ads, 4aintnam.ads, 4cintnam.ads,
[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 --                            $Revision$
10 --                                                                          --
11 --          Copyright (C) 1992-2002, Free Software Foundation, Inc.         --
12 --                                                                          --
13 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
14 -- terms of the  GNU General Public License as published  by the Free Soft- --
15 -- ware  Foundation;  either version 2,  or (at your option) any later ver- --
16 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
17 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
18 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
19 -- for  more details.  You should have  received  a copy of the GNU General --
20 -- Public License  distributed with GNAT;  see file COPYING.  If not, write --
21 -- to  the Free Software Foundation,  59 Temple Place - Suite 330,  Boston, --
22 -- MA 02111-1307, USA.                                                      --
23 --                                                                          --
24 -- GNAT was originally developed  by the GNAT team at  New York University. --
25 -- It is now maintained by Ada Core Technologies Inc (http://www.gnat.com). --
26 --                                                                          --
27 ------------------------------------------------------------------------------
28
29 with Atree;    use Atree;
30 with Checks;   use Checks;
31 with Debug;    use Debug;
32 with Einfo;    use Einfo;
33 with Errout;   use Errout;
34 with Elists;   use Elists;
35 with Exp_Ch2;  use Exp_Ch2;
36 with Exp_Ch3;  use Exp_Ch3;
37 with Exp_Ch7;  use Exp_Ch7;
38 with Exp_Ch9;  use Exp_Ch9;
39 with Exp_Ch11; use Exp_Ch11;
40 with Exp_Dbug; use Exp_Dbug;
41 with Exp_Disp; use Exp_Disp;
42 with Exp_Dist; use Exp_Dist;
43 with Exp_Intr; use Exp_Intr;
44 with Exp_Pakd; use Exp_Pakd;
45 with Exp_Tss;  use Exp_Tss;
46 with Exp_Util; use Exp_Util;
47 with Freeze;   use Freeze;
48 with Hostparm; use Hostparm;
49 with Inline;   use Inline;
50 with Lib;      use Lib;
51 with Nlists;   use Nlists;
52 with Nmake;    use Nmake;
53 with Opt;      use Opt;
54 with Restrict; use Restrict;
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_Disp; use Sem_Disp;
62 with Sem_Dist; use Sem_Dist;
63 with Sem_Res;  use Sem_Res;
64 with Sem_Util; use Sem_Util;
65 with Sinfo;    use Sinfo;
66 with Snames;   use Snames;
67 with Stand;    use Stand;
68 with Tbuild;   use Tbuild;
69 with Uintp;    use Uintp;
70 with Validsw;  use Validsw;
71
72 package body Exp_Ch6 is
73
74    -----------------------
75    -- Local Subprograms --
76    -----------------------
77
78    procedure Check_Overriding_Operation (Subp : Entity_Id);
79    --  Subp is a dispatching operation. Check whether it may override an
80    --  inherited private operation, in which case its DT entry is that of
81    --  the hidden operation, not the one it may have received earlier.
82    --  This must be done before emitting the code to set the corresponding
83    --  DT to the address of the subprogram. The actual placement of Subp in
84    --  the proper place in the list of primitive operations is done in
85    --  Declare_Inherited_Private_Subprograms, which also has to deal with
86    --  implicit operations. This duplication is unavoidable for now???
87
88    procedure Detect_Infinite_Recursion (N : Node_Id; Spec : Entity_Id);
89    --  This procedure is called only if the subprogram body N, whose spec
90    --  has the given entity Spec, contains a parameterless recursive call.
91    --  It attempts to generate runtime code to detect if this a case of
92    --  infinite recursion.
93    --
94    --  The body is scanned to determine dependencies. If the only external
95    --  dependencies are on a small set of scalar variables, then the values
96    --  of these variables are captured on entry to the subprogram, and if
97    --  the values are not changed for the call, we know immediately that
98    --  we have an infinite recursion.
99
100    procedure Expand_Actuals (N : Node_Id; Subp : Entity_Id);
101    --  For each actual of an in-out parameter which is a numeric conversion
102    --  of the form T(A), where A denotes a variable, we insert the declaration:
103    --
104    --    Temp : T := T(A);
105    --
106    --  prior to the call. Then we replace the actual with a reference to Temp,
107    --  and append the assignment:
108    --
109    --    A := T' (Temp);
110    --
111    --  after the call. Here T' is the actual type of variable A.
112    --  For out parameters, the initial declaration has no expression.
113    --  If A is not an entity name,  we generate instead:
114    --
115    --    Var  : T' renames A;
116    --    Temp : T := Var;       --  omitting expression for out parameter.
117    --    ...
118    --    Var := T' (Temp);
119    --
120    --  For other in-out parameters, we emit the required constraint checks
121    --  before and/or after the call.
122
123    --  For all parameter modes, actuals that denote components and slices
124    --  of packed arrays are expanded into suitable temporaries.
125
126    procedure Expand_Inlined_Call
127     (N         : Node_Id;
128      Subp      : Entity_Id;
129      Orig_Subp : Entity_Id);
130    --  If called subprogram can be inlined by the front-end, retrieve the
131    --  analyzed body, replace formals with actuals and expand call in place.
132    --  Generate thunks for actuals that are expressions, and insert the
133    --  corresponding constant declarations before the call. If the original
134    --  call is to a derived operation, the return type is the one of the
135    --  derived operation, but the body is that of the original, so return
136    --  expressions in the body must be converted to the desired type (which
137    --  is simply not noted in the tree without inline expansion).
138
139    function Expand_Protected_Object_Reference
140      (N    : Node_Id;
141       Scop : Entity_Id)
142       return Node_Id;
143
144    procedure Expand_Protected_Subprogram_Call
145      (N    : Node_Id;
146       Subp : Entity_Id;
147       Scop : Entity_Id);
148    --  A call to a protected subprogram within the protected object may appear
149    --  as a regular call. The list of actuals must be expanded to contain a
150    --  reference to the object itself, and the call becomes a call to the
151    --  corresponding protected subprogram.
152
153    --------------------------------
154    -- Check_Overriding_Operation --
155    --------------------------------
156
157    procedure Check_Overriding_Operation (Subp : Entity_Id) is
158       Typ     : constant Entity_Id := Find_Dispatching_Type (Subp);
159       Op_List : constant Elist_Id  := Primitive_Operations (Typ);
160       Op_Elmt : Elmt_Id;
161       Prim_Op : Entity_Id;
162       Par_Op  : Entity_Id;
163
164    begin
165       if Is_Derived_Type (Typ)
166         and then not Is_Private_Type (Typ)
167         and then In_Open_Scopes (Scope (Etype (Typ)))
168         and then Typ = Base_Type (Typ)
169       then
170          --  Subp overrides an inherited private operation if there is
171          --  an inherited operation with a different name than Subp (see
172          --  Derive_Subprogram) whose Alias is a hidden  subprogram with
173          --  the same name as Subp.
174
175          Op_Elmt := First_Elmt (Op_List);
176          while Present (Op_Elmt) loop
177             Prim_Op := Node (Op_Elmt);
178             Par_Op  := Alias (Prim_Op);
179
180             if Present (Par_Op)
181               and then not Comes_From_Source (Prim_Op)
182               and then Chars (Prim_Op) /= Chars (Par_Op)
183               and then Chars (Par_Op) = Chars (Subp)
184               and then Is_Hidden (Par_Op)
185               and then Type_Conformant (Prim_Op, Subp)
186             then
187                Set_DT_Position (Subp, DT_Position (Prim_Op));
188             end if;
189
190             Next_Elmt (Op_Elmt);
191          end loop;
192       end if;
193    end Check_Overriding_Operation;
194
195    -------------------------------
196    -- Detect_Infinite_Recursion --
197    -------------------------------
198
199    procedure Detect_Infinite_Recursion (N : Node_Id; Spec : Entity_Id) is
200       Loc : constant Source_Ptr := Sloc (N);
201
202       Var_List : Elist_Id := New_Elmt_List;
203       --  List of globals referenced by body of procedure
204
205       Call_List : Elist_Id := New_Elmt_List;
206       --  List of recursive calls in body of procedure
207
208       Shad_List : Elist_Id := New_Elmt_List;
209       --  List of entity id's for entities created to capture the
210       --  value of referenced globals on entry to the procedure.
211
212       Scop : constant Uint := Scope_Depth (Spec);
213       --  This is used to record the scope depth of the current
214       --  procedure, so that we can identify global references.
215
216       Max_Vars : constant := 4;
217       --  Do not test more than four global variables
218
219       Count_Vars : Natural := 0;
220       --  Count variables found so far
221
222       Var  : Entity_Id;
223       Elm  : Elmt_Id;
224       Ent  : Entity_Id;
225       Call : Elmt_Id;
226       Decl : Node_Id;
227       Test : Node_Id;
228       Elm1 : Elmt_Id;
229       Elm2 : Elmt_Id;
230       Last : Node_Id;
231
232       function Process (Nod : Node_Id) return Traverse_Result;
233       --  Function to traverse the subprogram body (using Traverse_Func)
234
235       -------------
236       -- Process --
237       -------------
238
239       function Process (Nod : Node_Id) return Traverse_Result is
240       begin
241          --  Procedure call
242
243          if Nkind (Nod) = N_Procedure_Call_Statement then
244
245             --  Case of one of the detected recursive calls
246
247             if Is_Entity_Name (Name (Nod))
248               and then Has_Recursive_Call (Entity (Name (Nod)))
249               and then Entity (Name (Nod)) = Spec
250             then
251                Append_Elmt (Nod, Call_List);
252                return Skip;
253
254             --  Any other procedure call may have side effects
255
256             else
257                return Abandon;
258             end if;
259
260          --  A call to a pure function can always be ignored
261
262          elsif Nkind (Nod) = N_Function_Call
263            and then Is_Entity_Name (Name (Nod))
264            and then Is_Pure (Entity (Name (Nod)))
265          then
266             return Skip;
267
268          --  Case of an identifier reference
269
270          elsif Nkind (Nod) = N_Identifier then
271             Ent := Entity (Nod);
272
273             --  If no entity, then ignore the reference
274
275             --  Not clear why this can happen. To investigate, remove this
276             --  test and look at the crash that occurs here in 3401-004 ???
277
278             if No (Ent) then
279                return Skip;
280
281             --  Ignore entities with no Scope, again not clear how this
282             --  can happen, to investigate, look at 4108-008 ???
283
284             elsif No (Scope (Ent)) then
285                return Skip;
286
287             --  Ignore the reference if not to a more global object
288
289             elsif Scope_Depth (Scope (Ent)) >= Scop then
290                return Skip;
291
292             --  References to types, exceptions and constants are always OK
293
294             elsif Is_Type (Ent)
295               or else Ekind (Ent) = E_Exception
296               or else Ekind (Ent) = E_Constant
297             then
298                return Skip;
299
300             --  If other than a non-volatile scalar variable, we have some
301             --  kind of global reference (e.g. to a function) that we cannot
302             --  deal with so we forget the attempt.
303
304             elsif Ekind (Ent) /= E_Variable
305               or else not Is_Scalar_Type (Etype (Ent))
306               or else Is_Volatile (Ent)
307             then
308                return Abandon;
309
310             --  Otherwise we have a reference to a global scalar
311
312             else
313                --  Loop through global entities already detected
314
315                Elm := First_Elmt (Var_List);
316                loop
317                   --  If not detected before, record this new global reference
318
319                   if No (Elm) then
320                      Count_Vars := Count_Vars + 1;
321
322                      if Count_Vars <= Max_Vars then
323                         Append_Elmt (Entity (Nod), Var_List);
324                      else
325                         return Abandon;
326                      end if;
327
328                      exit;
329
330                   --  If recorded before, ignore
331
332                   elsif Node (Elm) = Entity (Nod) then
333                      return Skip;
334
335                   --  Otherwise keep looking
336
337                   else
338                      Next_Elmt (Elm);
339                   end if;
340                end loop;
341
342                return Skip;
343             end if;
344
345          --  For all other node kinds, recursively visit syntactic children
346
347          else
348             return OK;
349          end if;
350       end Process;
351
352       function Traverse_Body is new Traverse_Func;
353
354    --  Start of processing for Detect_Infinite_Recursion
355
356    begin
357       --  Do not attempt detection in No_Implicit_Conditional mode,
358       --  since we won't be able to generate the code to handle the
359       --  recursion in any case.
360
361       if Restrictions (No_Implicit_Conditionals) then
362          return;
363       end if;
364
365       --  Otherwise do traversal and quit if we get abandon signal
366
367       if Traverse_Body (N) = Abandon then
368          return;
369
370       --  We must have a call, since Has_Recursive_Call was set. If not
371       --  just ignore (this is only an error check, so if we have a funny
372       --  situation, due to bugs or errors, we do not want to bomb!)
373
374       elsif Is_Empty_Elmt_List (Call_List) then
375          return;
376       end if;
377
378       --  Here is the case where we detect recursion at compile time
379
380       --  Push our current scope for analyzing the declarations and
381       --  code that we will insert for the checking.
382
383       New_Scope (Spec);
384
385       --  This loop builds temporary variables for each of the
386       --  referenced globals, so that at the end of the loop the
387       --  list Shad_List contains these temporaries in one-to-one
388       --  correspondence with the elements in Var_List.
389
390       Last := Empty;
391       Elm := First_Elmt (Var_List);
392       while Present (Elm) loop
393          Var := Node (Elm);
394          Ent :=
395            Make_Defining_Identifier (Loc,
396              Chars => New_Internal_Name ('S'));
397          Append_Elmt (Ent, Shad_List);
398
399          --  Insert a declaration for this temporary at the start of
400          --  the declarations for the procedure. The temporaries are
401          --  declared as constant objects initialized to the current
402          --  values of the corresponding temporaries.
403
404          Decl :=
405            Make_Object_Declaration (Loc,
406              Defining_Identifier => Ent,
407              Object_Definition   => New_Occurrence_Of (Etype (Var), Loc),
408              Constant_Present    => True,
409              Expression          => New_Occurrence_Of (Var, Loc));
410
411          if No (Last) then
412             Prepend (Decl, Declarations (N));
413          else
414             Insert_After (Last, Decl);
415          end if;
416
417          Last := Decl;
418          Analyze (Decl);
419          Next_Elmt (Elm);
420       end loop;
421
422       --  Loop through calls
423
424       Call := First_Elmt (Call_List);
425       while Present (Call) loop
426
427          --  Build a predicate expression of the form
428
429          --    True
430          --      and then global1 = temp1
431          --      and then global2 = temp2
432          --      ...
433
434          --  This predicate determines if any of the global values
435          --  referenced by the procedure have changed since the
436          --  current call, if not an infinite recursion is assured.
437
438          Test := New_Occurrence_Of (Standard_True, Loc);
439
440          Elm1 := First_Elmt (Var_List);
441          Elm2 := First_Elmt (Shad_List);
442          while Present (Elm1) loop
443             Test :=
444               Make_And_Then (Loc,
445                 Left_Opnd  => Test,
446                 Right_Opnd =>
447                   Make_Op_Eq (Loc,
448                     Left_Opnd  => New_Occurrence_Of (Node (Elm1), Loc),
449                     Right_Opnd => New_Occurrence_Of (Node (Elm2), Loc)));
450
451             Next_Elmt (Elm1);
452             Next_Elmt (Elm2);
453          end loop;
454
455          --  Now we replace the call with the sequence
456
457          --    if no-changes (see above) then
458          --       raise Storage_Error;
459          --    else
460          --       original-call
461          --    end if;
462
463          Rewrite (Node (Call),
464            Make_If_Statement (Loc,
465              Condition       => Test,
466              Then_Statements => New_List (
467                Make_Raise_Storage_Error (Loc,
468                  Reason => SE_Infinite_Recursion)),
469
470              Else_Statements => New_List (
471                Relocate_Node (Node (Call)))));
472
473          Analyze (Node (Call));
474
475          Next_Elmt (Call);
476       end loop;
477
478       --  Remove temporary scope stack entry used for analysis
479
480       Pop_Scope;
481    end Detect_Infinite_Recursion;
482
483    --------------------
484    -- Expand_Actuals --
485    --------------------
486
487    procedure Expand_Actuals (N : Node_Id; Subp : Entity_Id) is
488       Loc       : constant Source_Ptr := Sloc (N);
489       Actual    : Node_Id;
490       Formal    : Entity_Id;
491       N_Node    : Node_Id;
492       Post_Call : List_Id;
493       E_Formal  : Entity_Id;
494
495       procedure Add_Call_By_Copy_Code;
496       --  For In and In-Out parameters, where the parameter must be passed
497       --  by copy, this routine generates a temporary variable into which
498       --  the actual is copied, and then passes this as the parameter. This
499       --  routine also takes care of any constraint checks required for the
500       --  type conversion case (on both the way in and the way out).
501
502       procedure Add_Packed_Call_By_Copy_Code;
503       --  This is used when the actual involves a reference to an element
504       --  of a packed array, where we can appropriately use a simpler
505       --  approach than the full call by copy code. We just copy the value
506       --  in and out of an appropriate temporary.
507
508       procedure Check_Fortran_Logical;
509       --  A value of type Logical that is passed through a formal parameter
510       --  must be normalized because .TRUE. usually does not have the same
511       --  representation as True. We assume that .FALSE. = False = 0.
512       --  What about functions that return a logical type ???
513
514       function Make_Var (Actual : Node_Id) return Entity_Id;
515       --  Returns an entity that refers to the given actual parameter,
516       --  Actual (not including any type conversion). If Actual is an
517       --  entity name, then this entity is returned unchanged, otherwise
518       --  a renaming is created to provide an entity for the actual.
519
520       procedure Reset_Packed_Prefix;
521       --  The expansion of a packed array component reference is delayed in
522       --  the context of a call. Now we need to complete the expansion, so we
523       --  unmark the analyzed bits in all prefixes.
524
525       ---------------------------
526       -- Add_Call_By_Copy_Code --
527       ---------------------------
528
529       procedure Add_Call_By_Copy_Code is
530          Expr    : Node_Id;
531          Init    : Node_Id;
532          Temp    : Entity_Id;
533          Var     : Entity_Id;
534          V_Typ   : Entity_Id;
535          Crep    : Boolean;
536
537       begin
538          Temp := Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
539
540          if Nkind (Actual) = N_Type_Conversion then
541             V_Typ := Etype (Expression (Actual));
542             Var   := Make_Var (Expression (Actual));
543             Crep  := not Same_Representation
544                        (Etype (Formal), Etype (Expression (Actual)));
545          else
546             V_Typ := Etype (Actual);
547             Var   := Make_Var (Actual);
548             Crep  := False;
549          end if;
550
551          --  Setup initialization for case of in out parameter, or an out
552          --  parameter where the formal is an unconstrained array (in the
553          --  latter case, we have to pass in an object with bounds).
554
555          if Ekind (Formal) = E_In_Out_Parameter
556            or else (Is_Array_Type (Etype (Formal))
557                      and then
558                     not Is_Constrained (Etype (Formal)))
559          then
560             if Nkind (Actual) = N_Type_Conversion then
561                if Conversion_OK (Actual) then
562                   Init := OK_Convert_To
563                             (Etype (Formal), New_Occurrence_Of (Var, Loc));
564                else
565                   Init := Convert_To
566                             (Etype (Formal), New_Occurrence_Of (Var, Loc));
567                end if;
568             else
569                Init := New_Occurrence_Of (Var, Loc);
570             end if;
571
572          --  An initialization is created for packed conversions as
573          --  actuals for out parameters to enable Make_Object_Declaration
574          --  to determine the proper subtype for N_Node. Note that this
575          --  is wasteful because the extra copying on the call side is
576          --  not required for such out parameters. ???
577
578          elsif Ekind (Formal) = E_Out_Parameter
579            and then Nkind (Actual) = N_Type_Conversion
580            and then (Is_Bit_Packed_Array (Etype (Formal))
581                        or else
582                      Is_Bit_Packed_Array (Etype (Expression (Actual))))
583          then
584             if Conversion_OK (Actual) then
585                Init :=
586                  OK_Convert_To (Etype (Formal), New_Occurrence_Of (Var, Loc));
587             else
588                Init :=
589                  Convert_To (Etype (Formal), New_Occurrence_Of (Var, Loc));
590             end if;
591          else
592             Init := Empty;
593          end if;
594
595          N_Node :=
596            Make_Object_Declaration (Loc,
597              Defining_Identifier => Temp,
598              Object_Definition   =>
599                New_Occurrence_Of (Etype (Formal), Loc),
600              Expression => Init);
601          Set_Assignment_OK (N_Node);
602          Insert_Action (N, N_Node);
603
604          --  Now, normally the deal here is that we use the defining
605          --  identifier created by that object declaration. There is
606          --  one exception to this. In the change of representation case
607          --  the above declaration will end up looking like:
608
609          --    temp : type := identifier;
610
611          --  And in this case we might as well use the identifier directly
612          --  and eliminate the temporary. Note that the analysis of the
613          --  declaration was not a waste of time in that case, since it is
614          --  what generated the necessary change of representation code. If
615          --  the change of representation introduced additional code, as in
616          --  a fixed-integer conversion, the expression is not an identifier
617          --  and must be kept.
618
619          if Crep
620            and then Present (Expression (N_Node))
621            and then Is_Entity_Name (Expression (N_Node))
622          then
623             Temp := Entity (Expression (N_Node));
624             Rewrite (N_Node, Make_Null_Statement (Loc));
625          end if;
626
627          --  If type conversion, use reverse conversion on exit
628
629          if Nkind (Actual) = N_Type_Conversion then
630             if Conversion_OK (Actual) then
631                Expr := OK_Convert_To (V_Typ, New_Occurrence_Of (Temp, Loc));
632             else
633                Expr := Convert_To (V_Typ, New_Occurrence_Of (Temp, Loc));
634             end if;
635          else
636             Expr := New_Occurrence_Of (Temp, Loc);
637          end if;
638
639          Rewrite (Actual, New_Reference_To (Temp, Loc));
640          Analyze (Actual);
641
642          Append_To (Post_Call,
643            Make_Assignment_Statement (Loc,
644              Name       => New_Occurrence_Of (Var, Loc),
645              Expression => Expr));
646
647          Set_Assignment_OK (Name (Last (Post_Call)));
648       end Add_Call_By_Copy_Code;
649
650       ----------------------------------
651       -- Add_Packed_Call_By_Copy_Code --
652       ----------------------------------
653
654       procedure Add_Packed_Call_By_Copy_Code is
655          Temp   : Entity_Id;
656          Incod  : Node_Id;
657          Outcod : Node_Id;
658          Lhs    : Node_Id;
659          Rhs    : Node_Id;
660
661       begin
662          Reset_Packed_Prefix;
663
664          --  Prepare to generate code
665
666          Temp := Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
667          Incod  := Relocate_Node (Actual);
668          Outcod := New_Copy_Tree (Incod);
669
670          --  Generate declaration of temporary variable, initializing it
671          --  with the input parameter unless we have an OUT variable.
672
673          if Ekind (Formal) = E_Out_Parameter then
674             Incod := Empty;
675          end if;
676
677          Insert_Action (N,
678            Make_Object_Declaration (Loc,
679              Defining_Identifier => Temp,
680              Object_Definition   =>
681                New_Occurrence_Of (Etype (Formal), Loc),
682              Expression => Incod));
683
684          --  The actual is simply a reference to the temporary
685
686          Rewrite (Actual, New_Occurrence_Of (Temp, Loc));
687
688          --  Generate copy out if OUT or IN OUT parameter
689
690          if Ekind (Formal) /= E_In_Parameter then
691             Lhs := Outcod;
692             Rhs := New_Occurrence_Of (Temp, Loc);
693
694             --  Deal with conversion
695
696             if Nkind (Lhs) = N_Type_Conversion then
697                Lhs := Expression (Lhs);
698                Rhs := Convert_To (Etype (Actual), Rhs);
699             end if;
700
701             Append_To (Post_Call,
702               Make_Assignment_Statement (Loc,
703                 Name       => Lhs,
704                 Expression => Rhs));
705          end if;
706       end Add_Packed_Call_By_Copy_Code;
707
708       ---------------------------
709       -- Check_Fortran_Logical --
710       ---------------------------
711
712       procedure Check_Fortran_Logical is
713          Logical : Entity_Id := Etype (Formal);
714          Var     : Entity_Id;
715
716       --  Note: this is very incomplete, e.g. it does not handle arrays
717       --  of logical values. This is really not the right approach at all???)
718
719       begin
720          if Convention (Subp) = Convention_Fortran
721            and then Root_Type (Etype (Formal)) = Standard_Boolean
722            and then Ekind (Formal) /= E_In_Parameter
723          then
724             Var := Make_Var (Actual);
725             Append_To (Post_Call,
726               Make_Assignment_Statement (Loc,
727                 Name => New_Occurrence_Of (Var, Loc),
728                 Expression =>
729                   Unchecked_Convert_To (
730                     Logical,
731                     Make_Op_Ne (Loc,
732                       Left_Opnd  => New_Occurrence_Of (Var, Loc),
733                       Right_Opnd =>
734                         Unchecked_Convert_To (
735                           Logical,
736                           New_Occurrence_Of (Standard_False, Loc))))));
737          end if;
738       end Check_Fortran_Logical;
739
740       --------------
741       -- Make_Var --
742       --------------
743
744       function Make_Var (Actual : Node_Id) return Entity_Id is
745          Var : Entity_Id;
746
747       begin
748          if Is_Entity_Name (Actual) then
749             return Entity (Actual);
750
751          else
752             Var := Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
753
754             N_Node :=
755               Make_Object_Renaming_Declaration (Loc,
756                 Defining_Identifier => Var,
757                 Subtype_Mark        =>
758                   New_Occurrence_Of (Etype (Actual), Loc),
759                 Name                => Relocate_Node (Actual));
760
761             Insert_Action (N, N_Node);
762             return Var;
763          end if;
764       end Make_Var;
765
766       -------------------------
767       -- Reset_Packed_Prefix --
768       -------------------------
769
770       procedure Reset_Packed_Prefix is
771          Pfx : Node_Id := Actual;
772
773       begin
774          loop
775             Set_Analyzed (Pfx, False);
776             exit when Nkind (Pfx) /= N_Selected_Component
777               and then Nkind (Pfx) /= N_Indexed_Component;
778             Pfx := Prefix (Pfx);
779          end loop;
780       end Reset_Packed_Prefix;
781
782    --  Start of processing for Expand_Actuals
783
784    begin
785       Formal := First_Formal (Subp);
786       Actual := First_Actual (N);
787
788       Post_Call := New_List;
789
790       while Present (Formal) loop
791          E_Formal := Etype (Formal);
792
793          if Is_Scalar_Type (E_Formal)
794            or else Nkind (Actual) = N_Slice
795          then
796             Check_Fortran_Logical;
797
798          --  RM 6.4.1 (11)
799
800          elsif Ekind (Formal) /= E_Out_Parameter then
801
802             --  The unusual case of the current instance of a protected type
803             --  requires special handling. This can only occur in the context
804             --  of a call within the body of a protected operation.
805
806             if Is_Entity_Name (Actual)
807               and then Ekind (Entity (Actual)) = E_Protected_Type
808               and then In_Open_Scopes (Entity (Actual))
809             then
810                if Scope (Subp) /= Entity (Actual) then
811                   Error_Msg_N ("operation outside protected type may not "
812                     & "call back its protected operations?", Actual);
813                end if;
814
815                Rewrite (Actual,
816                  Expand_Protected_Object_Reference (N, Entity (Actual)));
817             end if;
818
819             Apply_Constraint_Check (Actual, E_Formal);
820
821          --  Out parameter case. No constraint checks on access type
822          --  RM 6.4.1 (13)
823
824          elsif Is_Access_Type (E_Formal) then
825             null;
826
827          --  RM 6.4.1 (14)
828
829          elsif Has_Discriminants (Base_Type (E_Formal))
830            or else Has_Non_Null_Base_Init_Proc (E_Formal)
831          then
832             Apply_Constraint_Check (Actual, E_Formal);
833
834          --  RM 6.4.1 (15)
835
836          else
837             Apply_Constraint_Check (Actual, Base_Type (E_Formal));
838          end if;
839
840          --  Processing for IN-OUT and OUT parameters
841
842          if Ekind (Formal) /= E_In_Parameter then
843
844             --  For type conversions of arrays, apply length/range checks
845
846             if Is_Array_Type (E_Formal)
847               and then Nkind (Actual) = N_Type_Conversion
848             then
849                if Is_Constrained (E_Formal) then
850                   Apply_Length_Check (Expression (Actual), E_Formal);
851                else
852                   Apply_Range_Check (Expression (Actual), E_Formal);
853                end if;
854             end if;
855
856             --  If argument is a type conversion for a type that is passed
857             --  by copy, then we must pass the parameter by copy.
858
859             if Nkind (Actual) = N_Type_Conversion
860               and then
861                 (Is_Numeric_Type (E_Formal)
862                   or else Is_Access_Type (E_Formal)
863                   or else Is_Enumeration_Type (E_Formal)
864                   or else Is_Bit_Packed_Array (Etype (Formal))
865                   or else Is_Bit_Packed_Array (Etype (Expression (Actual)))
866
867                   --  Also pass by copy if change of representation
868
869                   or else not Same_Representation
870                                (Etype (Formal),
871                                 Etype (Expression (Actual))))
872             then
873                Add_Call_By_Copy_Code;
874
875             --  References to components of bit packed arrays are expanded
876             --  at this point, rather than at the point of analysis of the
877             --  actuals, to handle the expansion of the assignment to
878             --  [in] out parameters.
879
880             elsif Is_Ref_To_Bit_Packed_Array (Actual) then
881                Add_Packed_Call_By_Copy_Code;
882
883             --  References to slices of bit packed arrays are expanded
884
885             elsif Is_Ref_To_Bit_Packed_Slice (Actual) then
886                Add_Call_By_Copy_Code;
887
888             --  Deal with access types where the actual subtpe and the
889             --  formal subtype are not the same, requiring a check.
890
891             --  It is necessary to exclude tagged types because of "downward
892             --  conversion" errors and a strange assertion error in namet
893             --  from gnatf in bug 1215-001 ???
894
895             elsif Is_Access_Type (E_Formal)
896               and then not Same_Type (E_Formal, Etype (Actual))
897               and then not Is_Tagged_Type (Designated_Type (E_Formal))
898             then
899                Add_Call_By_Copy_Code;
900
901             elsif Is_Entity_Name (Actual)
902               and then Is_Volatile (Entity (Actual))
903               and then not Is_Scalar_Type (Etype (Entity (Actual)))
904               and then not Is_Volatile (E_Formal)
905             then
906                Add_Call_By_Copy_Code;
907
908             elsif Nkind (Actual) = N_Indexed_Component
909               and then Is_Entity_Name (Prefix (Actual))
910               and then Has_Volatile_Components (Entity (Prefix (Actual)))
911             then
912                Add_Call_By_Copy_Code;
913             end if;
914
915          --  The only processing required for IN parameters is in the packed
916          --  array case, where we expand the indexed component (the circuit
917          --  in Exp_Ch4 deliberately left indexed components appearing as
918          --  actuals untouched, so that the special processing above for
919          --  the OUT and IN OUT cases could be performed. We could make the
920          --  test in Exp_Ch4 more complex and have it detect the parameter
921          --  mode, but it is easier simply to handle all cases here.
922
923          --  Similarly, we have to expand slices of packed arrays here
924
925          else
926             if Nkind (Actual) = N_Indexed_Component
927               and then Is_Packed (Etype (Prefix (Actual)))
928             then
929                Reset_Packed_Prefix;
930                Expand_Packed_Element_Reference (Actual);
931
932             elsif Is_Ref_To_Bit_Packed_Array (Actual) then
933                Add_Packed_Call_By_Copy_Code;
934
935             elsif Is_Ref_To_Bit_Packed_Slice (Actual) then
936                declare
937                   Typ : constant Entity_Id := Etype (Actual);
938
939                   Ent : constant Entity_Id :=
940                           Make_Defining_Identifier (Loc,
941                             Chars => New_Internal_Name ('T'));
942
943                   Decl : constant Node_Id :=
944                            Make_Object_Declaration (Loc,
945                              Defining_Identifier => Ent,
946                              Object_Definition   =>
947                                New_Occurrence_Of (Typ, Loc));
948
949                begin
950                   Set_No_Initialization (Decl);
951
952                   Insert_Actions (N, New_List (
953                     Decl,
954                     Make_Assignment_Statement (Loc,
955                       Name => New_Occurrence_Of (Ent, Loc),
956                       Expression => Relocate_Node (Actual))));
957
958                   Rewrite
959                     (Actual, New_Occurrence_Of (Ent, Loc));
960                   Analyze_And_Resolve (Actual, Typ);
961                end;
962             end if;
963          end if;
964
965          Next_Formal (Formal);
966          Next_Actual (Actual);
967       end loop;
968
969       --  Find right place to put post call stuff if it is present
970
971       if not Is_Empty_List (Post_Call) then
972
973          --  If call is not a list member, it must be the triggering
974          --  statement of a triggering alternative or an entry call
975          --  alternative, and we can add the post call stuff to the
976          --  corresponding statement list.
977
978          if not Is_List_Member (N) then
979             declare
980                P : constant Node_Id := Parent (N);
981
982             begin
983                pragma Assert (Nkind (P) = N_Triggering_Alternative
984                  or else Nkind (P) = N_Entry_Call_Alternative);
985
986                if Is_Non_Empty_List (Statements (P)) then
987                   Insert_List_Before_And_Analyze
988                     (First (Statements (P)), Post_Call);
989                else
990                   Set_Statements (P, Post_Call);
991                end if;
992             end;
993
994          --  Otherwise, normal case where N is in a statement sequence,
995          --  just put the post-call stuff after the call statement.
996
997          else
998             Insert_Actions_After (N, Post_Call);
999          end if;
1000       end if;
1001
1002       --  The call node itself is re-analyzed in Expand_Call.
1003
1004    end Expand_Actuals;
1005
1006    -----------------
1007    -- Expand_Call --
1008    -----------------
1009
1010    --  This procedure handles expansion of function calls and procedure call
1011    --  statements (i.e. it serves as the body for Expand_N_Function_Call and
1012    --  Expand_N_Procedure_Call_Statement. Processing for calls includes:
1013
1014    --    Replace call to Raise_Exception by Raise_Exception always if possible
1015    --    Provide values of actuals for all formals in Extra_Formals list
1016    --    Replace "call" to enumeration literal function by literal itself
1017    --    Rewrite call to predefined operator as operator
1018    --    Replace actuals to in-out parameters that are numeric conversions,
1019    --     with explicit assignment to temporaries before and after the call.
1020    --    Remove optional actuals if First_Optional_Parameter specified.
1021
1022    --   Note that the list of actuals has been filled with default expressions
1023    --   during semantic analysis of the call. Only the extra actuals required
1024    --   for the 'Constrained attribute and for accessibility checks are added
1025    --   at this point.
1026
1027    procedure Expand_Call (N : Node_Id) is
1028       Loc           : constant Source_Ptr := Sloc (N);
1029       Remote        : constant Boolean    := Is_Remote_Call (N);
1030       Subp          : Entity_Id;
1031       Orig_Subp     : Entity_Id := Empty;
1032       Parent_Subp   : Entity_Id;
1033       Parent_Formal : Entity_Id;
1034       Actual        : Node_Id;
1035       Formal        : Entity_Id;
1036       Prev          : Node_Id := Empty;
1037       Prev_Orig     : Node_Id;
1038       Scop          : Entity_Id;
1039       Extra_Actuals : List_Id := No_List;
1040       Cond          : Node_Id;
1041
1042       procedure Add_Actual_Parameter (Insert_Param : Node_Id);
1043       --  Adds one entry to the end of the actual parameter list. Used for
1044       --  default parameters and for extra actuals (for Extra_Formals).
1045       --  The argument is an N_Parameter_Association node.
1046
1047       procedure Add_Extra_Actual (Expr : Node_Id; EF : Entity_Id);
1048       --  Adds an extra actual to the list of extra actuals. Expr
1049       --  is the expression for the value of the actual, EF is the
1050       --  entity for the extra formal.
1051
1052       function Inherited_From_Formal (S : Entity_Id) return Entity_Id;
1053       --  Within an instance, a type derived from a non-tagged formal derived
1054       --  type inherits from the original parent, not from the actual. This is
1055       --  tested in 4723-003. The current derivation mechanism has the derived
1056       --  type inherit from the actual, which is only correct outside of the
1057       --  instance. If the subprogram is inherited, we test for this particular
1058       --  case through a convoluted tree traversal before setting the proper
1059       --  subprogram to be called.
1060
1061       --------------------------
1062       -- Add_Actual_Parameter --
1063       --------------------------
1064
1065       procedure Add_Actual_Parameter (Insert_Param : Node_Id) is
1066          Actual_Expr : constant Node_Id :=
1067                          Explicit_Actual_Parameter (Insert_Param);
1068
1069       begin
1070          --  Case of insertion is first named actual
1071
1072          if No (Prev) or else
1073             Nkind (Parent (Prev)) /= N_Parameter_Association
1074          then
1075             Set_Next_Named_Actual (Insert_Param, First_Named_Actual (N));
1076             Set_First_Named_Actual (N, Actual_Expr);
1077
1078             if No (Prev) then
1079                if not Present (Parameter_Associations (N)) then
1080                   Set_Parameter_Associations (N, New_List);
1081                   Append (Insert_Param, Parameter_Associations (N));
1082                end if;
1083             else
1084                Insert_After (Prev, Insert_Param);
1085             end if;
1086
1087          --  Case of insertion is not first named actual
1088
1089          else
1090             Set_Next_Named_Actual
1091               (Insert_Param, Next_Named_Actual (Parent (Prev)));
1092             Set_Next_Named_Actual (Parent (Prev), Actual_Expr);
1093             Append (Insert_Param, Parameter_Associations (N));
1094          end if;
1095
1096          Prev := Actual_Expr;
1097       end Add_Actual_Parameter;
1098
1099       ----------------------
1100       -- Add_Extra_Actual --
1101       ----------------------
1102
1103       procedure Add_Extra_Actual (Expr : Node_Id; EF : Entity_Id) is
1104          Loc : constant Source_Ptr := Sloc (Expr);
1105
1106       begin
1107          if Extra_Actuals = No_List then
1108             Extra_Actuals := New_List;
1109             Set_Parent (Extra_Actuals, N);
1110          end if;
1111
1112          Append_To (Extra_Actuals,
1113            Make_Parameter_Association (Loc,
1114              Explicit_Actual_Parameter => Expr,
1115              Selector_Name =>
1116                Make_Identifier (Loc, Chars (EF))));
1117
1118          Analyze_And_Resolve (Expr, Etype (EF));
1119
1120       end Add_Extra_Actual;
1121
1122       ---------------------------
1123       -- Inherited_From_Formal --
1124       ---------------------------
1125
1126       function Inherited_From_Formal (S : Entity_Id) return Entity_Id is
1127          Par      : Entity_Id;
1128          Gen_Par  : Entity_Id;
1129          Gen_Prim : Elist_Id;
1130          Elmt     : Elmt_Id;
1131          Indic    : Node_Id;
1132
1133       begin
1134          --  If the operation is inherited, it is attached to the corresponding
1135          --  type derivation. If the parent in the derivation is a generic
1136          --  actual, it is a subtype of the actual, and we have to recover the
1137          --  original derived type declaration to find the proper parent.
1138
1139          if Nkind (Parent (S)) /= N_Full_Type_Declaration
1140             or else not Is_Derived_Type (Defining_Identifier (Parent (S)))
1141             or else Nkind (Type_Definition (Original_Node (Parent (S))))
1142               /= N_Derived_Type_Definition
1143          then
1144             return Empty;
1145
1146          else
1147             Indic :=
1148               (Subtype_Indication
1149                 (Type_Definition (Original_Node (Parent (S)))));
1150
1151             if Nkind (Indic) = N_Subtype_Indication then
1152                Par := Entity (Subtype_Mark (Indic));
1153             else
1154                Par := Entity (Indic);
1155             end if;
1156          end if;
1157
1158          if not Is_Generic_Actual_Type (Par)
1159            or else Is_Tagged_Type (Par)
1160            or else Nkind (Parent (Par)) /= N_Subtype_Declaration
1161            or else not In_Open_Scopes (Scope (Par))
1162            or else not In_Instance
1163          then
1164             return Empty;
1165
1166          else
1167             Gen_Par := Generic_Parent_Type (Parent (Par));
1168          end if;
1169
1170          Gen_Prim := Collect_Primitive_Operations (Gen_Par);
1171          Elmt := First_Elmt (Gen_Prim);
1172
1173          while Present (Elmt) loop
1174             if Chars (Node (Elmt)) = Chars (S) then
1175                declare
1176                   F1 : Entity_Id;
1177                   F2 : Entity_Id;
1178                begin
1179
1180                   F1 := First_Formal (S);
1181                   F2 := First_Formal (Node (Elmt));
1182
1183                   while Present (F1)
1184                     and then Present (F2)
1185                   loop
1186
1187                      if Etype (F1) = Etype (F2)
1188                        or else Etype (F2) = Gen_Par
1189                      then
1190                         Next_Formal (F1);
1191                         Next_Formal (F2);
1192                      else
1193                         Next_Elmt (Elmt);
1194                         exit;   --  not the right subprogram
1195                      end if;
1196
1197                      return Node (Elmt);
1198                   end loop;
1199                end;
1200
1201             else
1202                Next_Elmt (Elmt);
1203             end if;
1204          end loop;
1205
1206          raise Program_Error;
1207       end Inherited_From_Formal;
1208
1209    --  Start of processing for Expand_Call
1210
1211    begin
1212       --  Ignore if previous error
1213
1214       if Nkind (N) in N_Has_Etype and then Etype (N) = Any_Type then
1215          return;
1216       end if;
1217
1218       --  Call using access to subprogram with explicit dereference
1219
1220       if Nkind (Name (N)) = N_Explicit_Dereference then
1221          Subp        := Etype (Name (N));
1222          Parent_Subp := Empty;
1223
1224       --  Case of call to simple entry, where the Name is a selected component
1225       --  whose prefix is the task, and whose selector name is the entry name
1226
1227       elsif Nkind (Name (N)) = N_Selected_Component then
1228          Subp        := Entity (Selector_Name (Name (N)));
1229          Parent_Subp := Empty;
1230
1231       --  Case of call to member of entry family, where Name is an indexed
1232       --  component, with the prefix being a selected component giving the
1233       --  task and entry family name, and the index being the entry index.
1234
1235       elsif Nkind (Name (N)) = N_Indexed_Component then
1236          Subp        := Entity (Selector_Name (Prefix (Name (N))));
1237          Parent_Subp := Empty;
1238
1239       --  Normal case
1240
1241       else
1242          Subp        := Entity (Name (N));
1243          Parent_Subp := Alias (Subp);
1244
1245          --  Replace call to Raise_Exception by call to Raise_Exception_Always
1246          --  if we can tell that the first parameter cannot possibly be null.
1247
1248          if not Restrictions (No_Exception_Handlers)
1249            and then Is_RTE (Subp, RE_Raise_Exception)
1250          then
1251             declare
1252                FA : constant Node_Id := Original_Node (First_Actual (N));
1253
1254             begin
1255                --  The case we catch is where the first argument is obtained
1256                --  using the Identity attribute (which must always be non-null)
1257
1258                if Nkind (FA) = N_Attribute_Reference
1259                  and then Attribute_Name (FA) = Name_Identity
1260                then
1261                   Subp := RTE (RE_Raise_Exception_Always);
1262                   Set_Entity (Name (N), Subp);
1263                end if;
1264             end;
1265          end if;
1266
1267          if Ekind (Subp) = E_Entry then
1268             Parent_Subp := Empty;
1269          end if;
1270       end if;
1271
1272       --  First step, compute  extra actuals, corresponding to any
1273       --  Extra_Formals present. Note that we do not access Extra_Formals
1274       --  directly, instead we simply  note the presence of the extra
1275       --  formals as we process the regular formals and collect the
1276       --  corresponding actuals in Extra_Actuals.
1277
1278       Formal := First_Formal (Subp);
1279       Actual := First_Actual (N);
1280
1281       while Present (Formal) loop
1282          Prev := Actual;
1283          Prev_Orig := Original_Node (Prev);
1284
1285          --  Create possible extra actual for constrained case. Usually,
1286          --  the extra actual is of the form actual'constrained, but since
1287          --  this attribute is only available for unconstrained records,
1288          --  TRUE is expanded if the type of the formal happens to be
1289          --  constrained (for instance when this procedure is inherited
1290          --  from an unconstrained record to a constrained one) or if the
1291          --  actual has no discriminant (its type is constrained). An
1292          --  exception to this is the case of a private type without
1293          --  discriminants. In this case we pass FALSE because the
1294          --  object has underlying discriminants with defaults.
1295
1296          if Present (Extra_Constrained (Formal)) then
1297             if Ekind (Etype (Prev)) in Private_Kind
1298               and then not Has_Discriminants (Base_Type (Etype (Prev)))
1299             then
1300                Add_Extra_Actual (
1301                  New_Occurrence_Of (Standard_False, Loc),
1302                  Extra_Constrained (Formal));
1303
1304             elsif Is_Constrained (Etype (Formal))
1305               or else not Has_Discriminants (Etype (Prev))
1306             then
1307                Add_Extra_Actual (
1308                  New_Occurrence_Of (Standard_True, Loc),
1309                  Extra_Constrained (Formal));
1310
1311             else
1312                --  If the actual is a type conversion, then the constrained
1313                --  test applies to the actual, not the target type.
1314
1315                declare
1316                   Act_Prev : Node_Id := Prev;
1317
1318                begin
1319                   --  Test for unchecked conversions as well, which can
1320                   --  occur as out parameter actuals on calls to stream
1321                   --  procedures.
1322
1323                   if Nkind (Act_Prev) = N_Type_Conversion
1324                     or else Nkind (Act_Prev) = N_Unchecked_Type_Conversion
1325                   then
1326                      Act_Prev := Expression (Act_Prev);
1327                   end if;
1328
1329                   Add_Extra_Actual (
1330                     Make_Attribute_Reference (Sloc (Prev),
1331                       Prefix => Duplicate_Subexpr (Act_Prev, Name_Req => True),
1332                       Attribute_Name => Name_Constrained),
1333                     Extra_Constrained (Formal));
1334                end;
1335             end if;
1336          end if;
1337
1338          --  Create possible extra actual for accessibility level
1339
1340          if Present (Extra_Accessibility (Formal)) then
1341             if Is_Entity_Name (Prev_Orig) then
1342
1343                --  When passing an access parameter as the actual to another
1344                --  access parameter we need to pass along the actual's own
1345                --  associated access level parameter. This is done is we are
1346                --  in the scope of the formal access parameter (if this is an
1347                --  inlined body the extra formal is irrelevant).
1348
1349                if Ekind (Entity (Prev_Orig)) in Formal_Kind
1350                  and then Ekind (Etype (Prev_Orig)) = E_Anonymous_Access_Type
1351                  and then In_Open_Scopes (Scope (Entity (Prev_Orig)))
1352                then
1353                   declare
1354                      Parm_Ent : constant Entity_Id := Param_Entity (Prev_Orig);
1355
1356                   begin
1357                      pragma Assert (Present (Parm_Ent));
1358
1359                      if Present (Extra_Accessibility (Parm_Ent)) then
1360                         Add_Extra_Actual (
1361                           New_Occurrence_Of
1362                             (Extra_Accessibility (Parm_Ent), Loc),
1363                           Extra_Accessibility (Formal));
1364
1365                      --  If the actual access parameter does not have an
1366                      --  associated extra formal providing its scope level,
1367                      --  then treat the actual as having library-level
1368                      --  accessibility.
1369
1370                      else
1371                         Add_Extra_Actual (
1372                           Make_Integer_Literal (Loc,
1373                             Intval => Scope_Depth (Standard_Standard)),
1374                           Extra_Accessibility (Formal));
1375                      end if;
1376                   end;
1377
1378                --  The actual is a normal access value, so just pass the
1379                --  level of the actual's access type.
1380
1381                else
1382                   Add_Extra_Actual (
1383                     Make_Integer_Literal (Loc,
1384                       Intval => Type_Access_Level (Etype (Prev_Orig))),
1385                     Extra_Accessibility (Formal));
1386                end if;
1387
1388             else
1389                case Nkind (Prev_Orig) is
1390
1391                   when N_Attribute_Reference =>
1392
1393                      case Get_Attribute_Id (Attribute_Name (Prev_Orig)) is
1394
1395                         --  For X'Access, pass on the level of the prefix X
1396
1397                         when Attribute_Access =>
1398                            Add_Extra_Actual (
1399                              Make_Integer_Literal (Loc,
1400                                Intval =>
1401                                  Object_Access_Level (Prefix (Prev_Orig))),
1402                              Extra_Accessibility (Formal));
1403
1404                         --  Treat the unchecked attributes as library-level
1405
1406                         when Attribute_Unchecked_Access |
1407                            Attribute_Unrestricted_Access =>
1408                            Add_Extra_Actual (
1409                              Make_Integer_Literal (Loc,
1410                                Intval => Scope_Depth (Standard_Standard)),
1411                              Extra_Accessibility (Formal));
1412
1413                         --  No other cases of attributes returning access
1414                         --  values that can be passed to access parameters
1415
1416                         when others =>
1417                            raise Program_Error;
1418
1419                      end case;
1420
1421                   --  For allocators we pass the level of the execution of
1422                   --  the called subprogram, which is one greater than the
1423                   --  current scope level.
1424
1425                   when N_Allocator =>
1426                      Add_Extra_Actual (
1427                        Make_Integer_Literal (Loc,
1428                         Scope_Depth (Current_Scope) + 1),
1429                        Extra_Accessibility (Formal));
1430
1431                   --  For other cases we simply pass the level of the
1432                   --  actual's access type.
1433
1434                   when others =>
1435                      Add_Extra_Actual (
1436                        Make_Integer_Literal (Loc,
1437                          Intval => Type_Access_Level (Etype (Prev_Orig))),
1438                        Extra_Accessibility (Formal));
1439
1440                end case;
1441             end if;
1442          end if;
1443
1444          --  Perform the check of 4.6(49) that prevents a null value
1445          --  from being passed as an actual to an access parameter.
1446          --  Note that the check is elided in the common cases of
1447          --  passing an access attribute or access parameter as an
1448          --  actual. Also, we currently don't enforce this check for
1449          --  expander-generated actuals and when -gnatdj is set.
1450
1451          if Ekind (Etype (Formal)) /= E_Anonymous_Access_Type
1452            or else Suppress_Accessibility_Checks (Subp)
1453          then
1454             null;
1455
1456          elsif Debug_Flag_J then
1457             null;
1458
1459          elsif not Comes_From_Source (Prev) then
1460             null;
1461
1462          elsif Is_Entity_Name (Prev)
1463            and then Ekind (Etype (Prev)) = E_Anonymous_Access_Type
1464          then
1465             null;
1466
1467          elsif Nkind (Prev) = N_Allocator
1468            or else Nkind (Prev) = N_Attribute_Reference
1469          then
1470             null;
1471
1472          --  Suppress null checks when passing to access parameters
1473          --  of Java subprograms. (Should this be done for other
1474          --  foreign conventions as well ???)
1475
1476          elsif Convention (Subp) = Convention_Java then
1477             null;
1478
1479          else
1480             Cond :=
1481               Make_Op_Eq (Loc,
1482                 Left_Opnd => Duplicate_Subexpr (Prev),
1483                 Right_Opnd => Make_Null (Loc));
1484             Insert_Action (Prev,
1485               Make_Raise_Constraint_Error (Loc,
1486                 Condition => Cond,
1487                 Reason    => CE_Access_Parameter_Is_Null));
1488          end if;
1489
1490          --  Perform appropriate validity checks on parameters
1491
1492          if Validity_Checks_On then
1493
1494             if Ekind (Formal) = E_In_Parameter
1495               and then Validity_Check_In_Params
1496             then
1497                Ensure_Valid (Actual);
1498
1499             elsif Ekind (Formal) = E_In_Out_Parameter
1500               and then Validity_Check_In_Out_Params
1501             then
1502                Ensure_Valid (Actual);
1503             end if;
1504          end if;
1505
1506          --  For IN OUT and OUT parameters, ensure that subscripts are valid
1507          --  since this is a left side reference. We only do this for calls
1508          --  from the source program since we assume that compiler generated
1509          --  calls explicitly generate any required checks. We also need it
1510          --  only if we are doing standard validity checks, since clearly it
1511          --  is not needed if validity checks are off, and in subscript
1512          --  validity checking mode, all indexed components are checked with
1513          --  a call directly from Expand_N_Indexed_Component.
1514
1515          if Comes_From_Source (N)
1516            and then Ekind (Formal) /= E_In_Parameter
1517            and then Validity_Checks_On
1518            and then Validity_Check_Default
1519            and then not Validity_Check_Subscripts
1520          then
1521             Check_Valid_Lvalue_Subscripts (Actual);
1522          end if;
1523
1524          --  If the formal is class wide and the actual is an aggregate, force
1525          --  evaluation so that the back end who does not know about class-wide
1526          --  type, does not generate a temporary of the wrong size.
1527
1528          if not Is_Class_Wide_Type (Etype (Formal)) then
1529             null;
1530
1531          elsif Nkind (Actual) = N_Aggregate
1532            or else (Nkind (Actual) = N_Qualified_Expression
1533                      and then Nkind (Expression (Actual)) = N_Aggregate)
1534          then
1535             Force_Evaluation (Actual);
1536          end if;
1537
1538          --  In a remote call, if the formal is of a class-wide type, check
1539          --  that the actual meets the requirements described in E.4(18).
1540
1541          if Remote
1542            and then Is_Class_Wide_Type (Etype (Formal))
1543          then
1544             Insert_Action (Actual,
1545               Make_Implicit_If_Statement (N,
1546                 Condition       =>
1547                   Make_Op_Not (Loc,
1548                     Get_Remotely_Callable (Duplicate_Subexpr (Actual))),
1549                 Then_Statements => New_List (
1550                   Make_Procedure_Call_Statement (Loc,
1551                     New_Occurrence_Of (RTE
1552                       (RE_Raise_Program_Error_For_E_4_18), Loc)))));
1553          end if;
1554
1555          Next_Actual (Actual);
1556          Next_Formal (Formal);
1557       end loop;
1558
1559       --  If we are expanding a rhs of an assignement we need to check if
1560       --  tag propagation is needed. This code belongs theorically in Analyze
1561       --  Assignment  but has to be done earlier (bottom-up) because the
1562       --  assignment might be transformed into a declaration for an uncons-
1563       --  trained value, if the expression is classwide.
1564
1565       if Nkind (N) = N_Function_Call
1566         and then Is_Tag_Indeterminate (N)
1567         and then Is_Entity_Name (Name (N))
1568       then
1569          declare
1570             Ass : Node_Id := Empty;
1571
1572          begin
1573             if Nkind (Parent (N)) = N_Assignment_Statement then
1574                Ass := Parent (N);
1575
1576             elsif Nkind (Parent (N)) = N_Qualified_Expression
1577               and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
1578             then
1579                Ass := Parent (Parent (N));
1580             end if;
1581
1582             if Present (Ass)
1583               and then Is_Class_Wide_Type (Etype (Name (Ass)))
1584             then
1585                Propagate_Tag (Name (Ass), N);
1586                return;
1587             end if;
1588          end;
1589       end if;
1590
1591       --  Deals with Dispatch_Call if we still have a call, before expanding
1592       --  extra actuals since this will be done on the re-analysis of the
1593       --  dispatching call. Note that we do not try to shorten the actual
1594       --  list for a dispatching call, it would not make sense to do so.
1595       --  Expansion of dispatching calls is suppressed when Java_VM, because
1596       --  the JVM back end directly handles the generation of dispatching
1597       --  calls and would have to undo any expansion to an indirect call.
1598
1599       if (Nkind (N) = N_Function_Call
1600            or else Nkind (N) =  N_Procedure_Call_Statement)
1601         and then Present (Controlling_Argument (N))
1602         and then not Java_VM
1603       then
1604          Expand_Dispatch_Call (N);
1605          return;
1606
1607       --  Similarly, expand calls to RCI subprograms on which pragma
1608       --  All_Calls_Remote applies. The rewriting will be reanalyzed
1609       --  later. Do this only when the call comes from source since we do
1610       --  not want such a rewritting to occur in expanded code.
1611
1612       elsif Is_All_Remote_Call (N) then
1613          Expand_All_Calls_Remote_Subprogram_Call (N);
1614
1615       --  Similarly, do not add extra actuals for an entry call whose entity
1616       --  is a protected procedure, or for an internal protected subprogram
1617       --  call, because it will be rewritten as a protected subprogram call
1618       --  and reanalyzed (see Expand_Protected_Subprogram_Call).
1619
1620       elsif Is_Protected_Type (Scope (Subp))
1621          and then (Ekind (Subp) = E_Procedure
1622                     or else Ekind (Subp) = E_Function)
1623       then
1624          null;
1625
1626       --  During that loop we gathered the extra actuals (the ones that
1627       --  correspond to Extra_Formals), so now they can be appended.
1628
1629       else
1630          while Is_Non_Empty_List (Extra_Actuals) loop
1631             Add_Actual_Parameter (Remove_Head (Extra_Actuals));
1632          end loop;
1633       end if;
1634
1635       if Ekind (Subp) = E_Procedure
1636          or else (Ekind (Subp) = E_Subprogram_Type
1637                    and then Etype (Subp) = Standard_Void_Type)
1638          or else Is_Entry (Subp)
1639       then
1640          Expand_Actuals (N, Subp);
1641       end if;
1642
1643       --  If the subprogram is a renaming, or if it is inherited, replace it
1644       --  in the call with the name of the actual subprogram being called.
1645       --  If this is a dispatching call, the run-time decides what to call.
1646       --  The Alias attribute does not apply to entries.
1647
1648       if Nkind (N) /= N_Entry_Call_Statement
1649         and then No (Controlling_Argument (N))
1650         and then Present (Parent_Subp)
1651       then
1652          if Present (Inherited_From_Formal (Subp)) then
1653             Parent_Subp := Inherited_From_Formal (Subp);
1654          else
1655             while Present (Alias (Parent_Subp)) loop
1656                Parent_Subp := Alias (Parent_Subp);
1657             end loop;
1658          end if;
1659
1660          Set_Entity (Name (N), Parent_Subp);
1661
1662          if Is_Abstract (Parent_Subp)
1663            and then not In_Instance
1664          then
1665             Error_Msg_NE
1666               ("cannot call abstract subprogram &!", Name (N), Parent_Subp);
1667          end if;
1668
1669          --  Add an explicit conversion for parameter of the derived type.
1670          --  This is only done for scalar and access in-parameters. Others
1671          --  have been expanded in expand_actuals.
1672
1673          Formal := First_Formal (Subp);
1674          Parent_Formal := First_Formal (Parent_Subp);
1675          Actual := First_Actual (N);
1676
1677          --  It is not clear that conversion is needed for intrinsic
1678          --  subprograms, but it certainly is for those that are user-
1679          --  defined, and that can be inherited on derivation, namely
1680          --  unchecked conversion and deallocation.
1681          --  General case needs study ???
1682
1683          if not Is_Intrinsic_Subprogram (Parent_Subp)
1684            or else Is_Generic_Instance (Parent_Subp)
1685          then
1686             while Present (Formal) loop
1687
1688                if Etype (Formal) /= Etype (Parent_Formal)
1689                  and then Is_Scalar_Type (Etype (Formal))
1690                  and then Ekind (Formal) = E_In_Parameter
1691                  and then not Raises_Constraint_Error (Actual)
1692                then
1693                   Rewrite (Actual,
1694                     OK_Convert_To (Etype (Parent_Formal),
1695                       Relocate_Node (Actual)));
1696
1697                   Analyze (Actual);
1698                   Resolve (Actual, Etype (Parent_Formal));
1699                   Enable_Range_Check (Actual);
1700
1701                elsif Is_Access_Type (Etype (Formal))
1702                  and then Base_Type (Etype (Parent_Formal))
1703                    /= Base_Type (Etype (Actual))
1704                then
1705                   if Ekind (Formal) /= E_In_Parameter then
1706                      Rewrite (Actual,
1707                        Convert_To (Etype (Parent_Formal),
1708                          Relocate_Node (Actual)));
1709
1710                      Analyze (Actual);
1711                      Resolve (Actual, Etype (Parent_Formal));
1712
1713                   elsif
1714                     Ekind (Etype (Parent_Formal)) = E_Anonymous_Access_Type
1715                       and then
1716                     Designated_Type (Etype (Parent_Formal))
1717                       /= Designated_Type (Etype (Actual))
1718                       and then not Is_Controlling_Formal (Formal)
1719                   then
1720
1721                      --  This unchecked conversion is not necessary unless
1722                      --  inlining is unabled, because in that case the type
1723                      --  mismatch may become visible in the body about to be
1724                      --  inlined.
1725
1726                      Rewrite (Actual,
1727                        Unchecked_Convert_To (Etype (Parent_Formal),
1728                          Relocate_Node (Actual)));
1729
1730                      Analyze (Actual);
1731                      Resolve (Actual, Etype (Parent_Formal));
1732                   end if;
1733                end if;
1734
1735                Next_Formal (Formal);
1736                Next_Formal (Parent_Formal);
1737                Next_Actual (Actual);
1738             end loop;
1739          end if;
1740
1741          Orig_Subp := Subp;
1742          Subp := Parent_Subp;
1743       end if;
1744
1745       --  Some more special cases for cases other than explicit dereference
1746
1747       if Nkind (Name (N)) /= N_Explicit_Dereference then
1748
1749          --  Calls to an enumeration literal are replaced by the literal
1750          --  This case occurs only when we have a call to a function that
1751          --  is a renaming of an enumeration literal. The normal case of
1752          --  a direct reference to an enumeration literal has already been
1753          --  been dealt with by Resolve_Call. If the function is itself
1754          --  inherited (see 7423-001) the literal of the parent type must
1755          --  be explicitly converted to the return type of the function.
1756
1757          if Ekind (Subp) = E_Enumeration_Literal then
1758             if Base_Type (Etype (Subp)) /= Base_Type (Etype (N)) then
1759                Rewrite
1760                  (N, Convert_To (Etype (N), New_Occurrence_Of (Subp, Loc)));
1761             else
1762                Rewrite (N, New_Occurrence_Of (Subp, Loc));
1763                Resolve (N, Etype (N));
1764             end if;
1765          end if;
1766
1767       --  Handle case of access to protected subprogram type
1768
1769       else
1770          if Ekind (Base_Type (Etype (Prefix (Name (N))))) =
1771                                E_Access_Protected_Subprogram_Type
1772          then
1773             --  If this is a call through an access to protected operation,
1774             --  the prefix has the form (object'address, operation'access).
1775             --  Rewrite as a for other protected calls: the object is the
1776             --  first parameter of the list of actuals.
1777
1778             declare
1779                Call : Node_Id;
1780                Parm : List_Id;
1781                Nam  : Node_Id;
1782                Obj  : Node_Id;
1783                Ptr  : Node_Id := Prefix (Name (N));
1784                T    : Entity_Id := Equivalent_Type (Base_Type (Etype (Ptr)));
1785                D_T  : Entity_Id := Designated_Type (Base_Type (Etype (Ptr)));
1786
1787             begin
1788                Obj := Make_Selected_Component (Loc,
1789                  Prefix => Unchecked_Convert_To (T, Ptr),
1790                  Selector_Name => New_Occurrence_Of (First_Entity (T), Loc));
1791
1792                Nam := Make_Selected_Component (Loc,
1793                  Prefix => Unchecked_Convert_To (T, Ptr),
1794                  Selector_Name => New_Occurrence_Of (
1795                    Next_Entity (First_Entity (T)), Loc));
1796
1797                Nam := Make_Explicit_Dereference (Loc, Nam);
1798
1799                if Present (Parameter_Associations (N))  then
1800                   Parm := Parameter_Associations (N);
1801                else
1802                   Parm := New_List;
1803                end if;
1804
1805                Prepend (Obj, Parm);
1806
1807                if Etype (D_T) = Standard_Void_Type then
1808                   Call := Make_Procedure_Call_Statement (Loc,
1809                     Name => Nam,
1810                     Parameter_Associations => Parm);
1811                else
1812                   Call := Make_Function_Call (Loc,
1813                     Name => Nam,
1814                     Parameter_Associations => Parm);
1815                end if;
1816
1817                Set_First_Named_Actual (Call, First_Named_Actual (N));
1818
1819                Set_Etype (Call, Etype (D_T));
1820
1821                --  We do not re-analyze the call to avoid infinite recursion.
1822                --  We analyze separately the prefix and the object, and set
1823                --  the checks on the prefix that would otherwise be emitted
1824                --  when resolving a call.
1825
1826                Rewrite (N, Call);
1827                Analyze (Nam);
1828                Apply_Access_Check (Nam);
1829                Analyze (Obj);
1830                return;
1831             end;
1832          end if;
1833       end if;
1834
1835       --  If this is a call to an intrinsic subprogram, then perform the
1836       --  appropriate expansion to the corresponding tree node and we
1837       --  are all done (since after that the call is gone!)
1838
1839       if Is_Intrinsic_Subprogram (Subp) then
1840          Expand_Intrinsic_Call (N, Subp);
1841          return;
1842       end if;
1843
1844       if Ekind (Subp) = E_Function
1845         or else Ekind (Subp) = E_Procedure
1846       then
1847          if Is_Inlined (Subp) then
1848
1849             declare
1850                Spec : constant Node_Id := Unit_Declaration_Node (Subp);
1851
1852             begin
1853                --  Verify that the body to inline has already been seen,
1854                --  and that if the body is in the current unit the inlining
1855                --  does not occur earlier. This avoids order-of-elaboration
1856                --  problems in gigi.
1857
1858                if Present (Spec)
1859                  and then Nkind (Spec) = N_Subprogram_Declaration
1860                  and then Present (Body_To_Inline (Spec))
1861                  and then (In_Extended_Main_Code_Unit (N)
1862                             or else In_Extended_Main_Code_Unit (Parent (N)))
1863                  and then (not In_Same_Extended_Unit
1864                               (Sloc (Body_To_Inline (Spec)), Loc)
1865                             or else
1866                            Earlier_In_Extended_Unit
1867                               (Sloc (Body_To_Inline (Spec)), Loc))
1868                then
1869                   Expand_Inlined_Call (N, Subp, Orig_Subp);
1870
1871                else
1872                   --  Let the back-end handle it.
1873
1874                   Add_Inlined_Body (Subp);
1875
1876                   if Front_End_Inlining
1877                     and then Nkind (Spec) = N_Subprogram_Declaration
1878                     and then (In_Extended_Main_Code_Unit (N))
1879                     and then No (Body_To_Inline (Spec))
1880                     and then not Has_Completion (Subp)
1881                     and then In_Same_Extended_Unit (Sloc (Spec), Loc)
1882                     and then Ineffective_Inline_Warnings
1883                   then
1884                      Error_Msg_N
1885                       ("call cannot be inlined before body is seen?", N);
1886                   end if;
1887                end if;
1888             end;
1889          end if;
1890       end if;
1891
1892       --  Check for a protected subprogram. This is either an intra-object
1893       --  call, or a protected function call. Protected procedure calls are
1894       --  rewritten as entry calls and handled accordingly.
1895
1896       Scop := Scope (Subp);
1897
1898       if Nkind (N) /= N_Entry_Call_Statement
1899         and then Is_Protected_Type (Scop)
1900       then
1901          --  If the call is an internal one, it is rewritten as a call to
1902          --  to the corresponding unprotected subprogram.
1903
1904          Expand_Protected_Subprogram_Call (N, Subp, Scop);
1905       end if;
1906
1907       --  Functions returning controlled objects need special attention
1908
1909       if Controlled_Type (Etype (Subp))
1910         and then not Is_Return_By_Reference_Type (Etype (Subp))
1911       then
1912          Expand_Ctrl_Function_Call (N);
1913       end if;
1914
1915       --  Test for First_Optional_Parameter, and if so, truncate parameter
1916       --  list if there are optional parameters at the trailing end.
1917       --  Note we never delete procedures for call via a pointer.
1918
1919       if (Ekind (Subp) = E_Procedure or else Ekind (Subp) = E_Function)
1920         and then Present (First_Optional_Parameter (Subp))
1921       then
1922          declare
1923             Last_Keep_Arg : Node_Id;
1924
1925          begin
1926             --  Last_Keep_Arg will hold the last actual that should be
1927             --  retained. If it remains empty at the end, it means that
1928             --  all parameters are optional.
1929
1930             Last_Keep_Arg := Empty;
1931
1932             --  Find first optional parameter, must be present since we
1933             --  checked the validity of the parameter before setting it.
1934
1935             Formal := First_Formal (Subp);
1936             Actual := First_Actual (N);
1937             while Formal /= First_Optional_Parameter (Subp) loop
1938                Last_Keep_Arg := Actual;
1939                Next_Formal (Formal);
1940                Next_Actual (Actual);
1941             end loop;
1942
1943             --  Now we have Formal and Actual pointing to the first
1944             --  potentially droppable argument. We can drop all the
1945             --  trailing arguments whose actual matches the default.
1946             --  Note that we know that all remaining formals have
1947             --  defaults, because we checked that this requirement
1948             --  was met before setting First_Optional_Parameter.
1949
1950             --  We use Fully_Conformant_Expressions to check for identity
1951             --  between formals and actuals, which may miss some cases, but
1952             --  on the other hand, this is only an optimization (if we fail
1953             --  to truncate a parameter it does not affect functionality).
1954             --  So if the default is 3 and the actual is 1+2, we consider
1955             --  them unequal, which hardly seems worrisome.
1956
1957             while Present (Formal) loop
1958                if not Fully_Conformant_Expressions
1959                     (Actual, Default_Value (Formal))
1960                then
1961                   Last_Keep_Arg := Actual;
1962                end if;
1963
1964                Next_Formal (Formal);
1965                Next_Actual (Actual);
1966             end loop;
1967
1968             --  If no arguments, delete entire list, this is the easy case
1969
1970             if No (Last_Keep_Arg) then
1971                while Is_Non_Empty_List (Parameter_Associations (N)) loop
1972                   Delete_Tree (Remove_Head (Parameter_Associations (N)));
1973                end loop;
1974
1975                Set_Parameter_Associations (N, No_List);
1976                Set_First_Named_Actual (N, Empty);
1977
1978             --  Case where at the last retained argument is positional. This
1979             --  is also an easy case, since the retained arguments are already
1980             --  in the right form, and we don't need to worry about the order
1981             --  of arguments that get eliminated.
1982
1983             elsif Is_List_Member (Last_Keep_Arg) then
1984                while Present (Next (Last_Keep_Arg)) loop
1985                   Delete_Tree (Remove_Next (Last_Keep_Arg));
1986                end loop;
1987
1988                Set_First_Named_Actual (N, Empty);
1989
1990             --  This is the annoying case where the last retained argument
1991             --  is a named parameter. Since the original arguments are not
1992             --  in declaration order, we may have to delete some fairly
1993             --  random collection of arguments.
1994
1995             else
1996                declare
1997                   Temp   : Node_Id;
1998                   Passoc : Node_Id;
1999                   Junk   : Node_Id;
2000
2001                begin
2002                   --  First step, remove all the named parameters from the
2003                   --  list (they are still chained using First_Named_Actual
2004                   --  and Next_Named_Actual, so we have not lost them!)
2005
2006                   Temp := First (Parameter_Associations (N));
2007
2008                   --  Case of all parameters named, remove them all
2009
2010                   if Nkind (Temp) = N_Parameter_Association then
2011                      while Is_Non_Empty_List (Parameter_Associations (N)) loop
2012                         Temp := Remove_Head (Parameter_Associations (N));
2013                      end loop;
2014
2015                   --  Case of mixed positional/named, remove named parameters
2016
2017                   else
2018                      while Nkind (Next (Temp)) /= N_Parameter_Association loop
2019                         Next (Temp);
2020                      end loop;
2021
2022                      while Present (Next (Temp)) loop
2023                         Junk := Remove_Next (Temp);
2024                      end loop;
2025                   end if;
2026
2027                   --  Now we loop through the named parameters, till we get
2028                   --  to the last one to be retained, adding them to the list.
2029                   --  Note that the Next_Named_Actual list does not need to be
2030                   --  touched since we are only reordering them on the actual
2031                   --  parameter association list.
2032
2033                   Passoc := Parent (First_Named_Actual (N));
2034                   loop
2035                      Temp := Relocate_Node (Passoc);
2036                      Append_To
2037                        (Parameter_Associations (N), Temp);
2038                      exit when
2039                        Last_Keep_Arg = Explicit_Actual_Parameter (Passoc);
2040                      Passoc := Parent (Next_Named_Actual (Passoc));
2041                   end loop;
2042
2043                   Set_Next_Named_Actual (Temp, Empty);
2044
2045                   loop
2046                      Temp := Next_Named_Actual (Passoc);
2047                      exit when No (Temp);
2048                      Set_Next_Named_Actual
2049                        (Passoc, Next_Named_Actual (Parent (Temp)));
2050                      Delete_Tree (Temp);
2051                   end loop;
2052                end;
2053             end if;
2054          end;
2055       end if;
2056
2057    end Expand_Call;
2058
2059    --------------------------
2060    -- Expand_Inlined_Call --
2061    --------------------------
2062
2063    procedure Expand_Inlined_Call
2064     (N         : Node_Id;
2065      Subp      : Entity_Id;
2066      Orig_Subp : Entity_Id)
2067    is
2068       Loc      : constant Source_Ptr := Sloc (N);
2069       Blk      : Node_Id;
2070       Bod      : Node_Id;
2071       Decl     : Node_Id;
2072       Exit_Lab : Entity_Id := Empty;
2073       F        : Entity_Id;
2074       A        : Node_Id;
2075       Lab_Decl : Node_Id;
2076       Lab_Id   : Node_Id;
2077       New_A    : Node_Id;
2078       Num_Ret  : Int := 0;
2079       Orig_Bod : constant Node_Id :=
2080                    Body_To_Inline (Unit_Declaration_Node (Subp));
2081       Ret_Type : Entity_Id;
2082       Targ     : Node_Id;
2083       Temp     : Entity_Id;
2084       Temp_Typ : Entity_Id;
2085
2086       procedure Make_Exit_Label;
2087       --  Build declaration for exit label to be used in Return statements.
2088
2089       function Process_Formals (N : Node_Id) return Traverse_Result;
2090       --  Replace occurrence of a formal with the corresponding actual, or
2091       --  the thunk generated for it.
2092
2093       procedure Rewrite_Function_Call (N : Node_Id; Blk : Node_Id);
2094       --  If the function body is a single expression, replace call with
2095       --  expression, else insert block appropriately.
2096
2097       procedure Rewrite_Procedure_Call (N : Node_Id; Blk : Node_Id);
2098       --  If procedure body has no local variables, inline body without
2099       --  creating block,  otherwise rewrite call with block.
2100
2101       ---------------------
2102       -- Make_Exit_Label --
2103       ---------------------
2104
2105       procedure Make_Exit_Label is
2106       begin
2107          --  Create exit label for subprogram, if one doesn't exist yet.
2108
2109          if No (Exit_Lab) then
2110             Lab_Id := Make_Identifier (Loc, New_Internal_Name ('L'));
2111             Set_Entity (Lab_Id,
2112               Make_Defining_Identifier (Loc, Chars (Lab_Id)));
2113             Exit_Lab := Make_Label (Loc, Lab_Id);
2114
2115             Lab_Decl :=
2116               Make_Implicit_Label_Declaration (Loc,
2117                 Defining_Identifier  => Entity (Lab_Id),
2118                 Label_Construct      => Exit_Lab);
2119          end if;
2120       end Make_Exit_Label;
2121
2122       ---------------------
2123       -- Process_Formals --
2124       ---------------------
2125
2126       function Process_Formals (N : Node_Id) return Traverse_Result is
2127          A   : Entity_Id;
2128          E   : Entity_Id;
2129          Ret : Node_Id;
2130
2131       begin
2132          if Is_Entity_Name (N)
2133            and then Present (Entity (N))
2134          then
2135             E := Entity (N);
2136
2137             if Is_Formal (E)
2138               and then Scope (E) = Subp
2139             then
2140                A := Renamed_Object (E);
2141
2142                if Is_Entity_Name (A) then
2143                   Rewrite (N, New_Occurrence_Of (Entity (A), Loc));
2144
2145                elsif Nkind (A) = N_Defining_Identifier then
2146                   Rewrite (N, New_Occurrence_Of (A, Loc));
2147
2148                else   --  numeric literal
2149                   Rewrite (N, New_Copy (A));
2150                end if;
2151             end if;
2152
2153             return Skip;
2154
2155          elsif Nkind (N) = N_Return_Statement then
2156
2157             if No (Expression (N)) then
2158                Make_Exit_Label;
2159                Rewrite (N, Make_Goto_Statement (Loc,
2160                  Name => New_Copy (Lab_Id)));
2161
2162             else
2163                if Nkind (Parent (N)) = N_Handled_Sequence_Of_Statements
2164                  and then Nkind (Parent (Parent (N))) = N_Subprogram_Body
2165                then
2166                   --  function body is a single expression. No need for
2167                   --  exit label.
2168                   null;
2169
2170                else
2171                   Num_Ret := Num_Ret + 1;
2172                   Make_Exit_Label;
2173                end if;
2174
2175                --  Because of the presence of private types, the views of the
2176                --  expression and the context may be different, so place an
2177                --  unchecked conversion to the context type to avoid spurious
2178                --  errors, eg. when the expression is a numeric literal and
2179                --  the context is private. If the expression is an aggregate,
2180                --  use a qualified expression, because an aggregate is not a
2181                --  legal argument of a conversion.
2182
2183                if Nkind (Expression (N)) = N_Aggregate
2184                  or else Nkind (Expression (N)) = N_Null
2185                then
2186                   Ret :=
2187                     Make_Qualified_Expression (Sloc (N),
2188                        Subtype_Mark => New_Occurrence_Of (Ret_Type, Sloc (N)),
2189                        Expression => Relocate_Node (Expression (N)));
2190                else
2191                   Ret :=
2192                     Unchecked_Convert_To
2193                       (Ret_Type, Relocate_Node (Expression (N)));
2194                end if;
2195
2196                if Nkind (Targ) = N_Defining_Identifier then
2197                   Rewrite (N,
2198                     Make_Assignment_Statement (Loc,
2199                       Name => New_Occurrence_Of (Targ, Loc),
2200                       Expression => Ret));
2201                else
2202                   Rewrite (N,
2203                     Make_Assignment_Statement (Loc,
2204                       Name => New_Copy (Targ),
2205                       Expression => Ret));
2206                end if;
2207
2208                Set_Assignment_OK (Name (N));
2209
2210                if Present (Exit_Lab) then
2211                   Insert_After (N,
2212                     Make_Goto_Statement (Loc,
2213                       Name => New_Copy (Lab_Id)));
2214                end if;
2215             end if;
2216
2217             return OK;
2218
2219          else
2220             return OK;
2221          end if;
2222       end Process_Formals;
2223
2224       procedure Replace_Formals is new Traverse_Proc (Process_Formals);
2225
2226       ---------------------------
2227       -- Rewrite_Function_Call --
2228       ---------------------------
2229
2230       procedure Rewrite_Function_Call (N : Node_Id; Blk : Node_Id) is
2231          HSS  : Node_Id := Handled_Statement_Sequence (Blk);
2232          Fst  : Node_Id := First (Statements (HSS));
2233
2234       begin
2235
2236          --  Optimize simple case: function body is a single return statement,
2237          --  which has been expanded into an assignment.
2238
2239          if Is_Empty_List (Declarations (Blk))
2240            and then Nkind (Fst) = N_Assignment_Statement
2241            and then No (Next (Fst))
2242          then
2243
2244             --  The function call may have been rewritten as the temporary
2245             --  that holds the result of the call, in which case remove the
2246             --  now useless declaration.
2247
2248             if Nkind (N) = N_Identifier
2249               and then Nkind (Parent (Entity (N))) = N_Object_Declaration
2250             then
2251                Rewrite (Parent (Entity (N)), Make_Null_Statement (Loc));
2252             end if;
2253
2254             Rewrite (N, Expression (Fst));
2255
2256          elsif Nkind (N) = N_Identifier
2257            and then Nkind (Parent (Entity (N))) = N_Object_Declaration
2258          then
2259
2260             --  The block assigns the result of the call to the temporary.
2261
2262             Insert_After (Parent (Entity (N)), Blk);
2263
2264          elsif Nkind (Parent (N)) = N_Assignment_Statement
2265            and then Is_Entity_Name (Name (Parent (N)))
2266          then
2267
2268             --  replace assignment with the block.
2269
2270             Rewrite (Parent (N), Blk);
2271
2272          elsif Nkind (Parent (N)) = N_Object_Declaration then
2273             Set_Expression (Parent (N), Empty);
2274             Insert_After (Parent (N), Blk);
2275          end if;
2276       end Rewrite_Function_Call;
2277
2278       ----------------------------
2279       -- Rewrite_Procedure_Call --
2280       ----------------------------
2281
2282       procedure Rewrite_Procedure_Call (N : Node_Id; Blk : Node_Id) is
2283          HSS  : Node_Id := Handled_Statement_Sequence (Blk);
2284
2285       begin
2286          if Is_Empty_List (Declarations (Blk)) then
2287             Insert_List_After (N, Statements (HSS));
2288             Rewrite (N, Make_Null_Statement (Loc));
2289          else
2290             Rewrite (N, Blk);
2291          end if;
2292       end Rewrite_Procedure_Call;
2293
2294    --  Start of processing for Expand_Inlined_Call
2295
2296    begin
2297       if Nkind (Orig_Bod) = N_Defining_Identifier then
2298
2299          --  Subprogram is a renaming_as_body. Calls appearing after the
2300          --  renaming can be replaced with calls to the renamed entity
2301          --  directly, because the subprograms are subtype conformant.
2302
2303          Set_Name (N, New_Occurrence_Of (Orig_Bod, Loc));
2304          return;
2305       end if;
2306
2307       --  Use generic machinery to copy body of inlined subprogram, as if it
2308       --  were an instantiation, resetting source locations appropriately, so
2309       --  that nested inlined calls appear in the main unit.
2310
2311       Save_Env (Subp, Empty);
2312       Set_Copied_Sloc (N, Defining_Entity (Orig_Bod));
2313
2314       Bod :=
2315        Copy_Generic_Node (Orig_Bod, Empty, Instantiating => True);
2316
2317       Blk :=
2318         Make_Block_Statement (Loc,
2319           Declarations => Declarations (Bod),
2320           Handled_Statement_Sequence => Handled_Statement_Sequence (Bod));
2321
2322       if No (Declarations (Bod)) then
2323          Set_Declarations (Blk, New_List);
2324       end if;
2325
2326       --  If this is a derived function, establish the proper return type.
2327
2328       if Present (Orig_Subp)
2329         and then Orig_Subp /= Subp
2330       then
2331          Ret_Type := Etype (Orig_Subp);
2332       else
2333          Ret_Type := Etype (Subp);
2334       end if;
2335
2336       F := First_Formal (Subp);
2337       A := First_Actual (N);
2338
2339       --  Create temporaries for the actuals that are expressions, or that
2340       --  are scalars and require copying to preserve semantics.
2341
2342       while Present (F) loop
2343
2344          if Present (Renamed_Object (F)) then
2345             Error_Msg_N (" cannot inline call to recursive subprogram", N);
2346             return;
2347          end if;
2348
2349          --  If the argument may be a controlling argument in a call within
2350          --  the inlined body, we must preserve its classwide nature to
2351          --  insure that dynamic dispatching take place subsequently.
2352          --  If the formal has a constraint it must be preserved to retain
2353          --  the semantics of the body.
2354
2355          if Is_Class_Wide_Type (Etype (F))
2356            or else (Is_Access_Type (Etype (F))
2357                       and then
2358                     Is_Class_Wide_Type (Designated_Type (Etype (F))))
2359          then
2360             Temp_Typ := Etype (F);
2361
2362          elsif Base_Type (Etype (F)) = Base_Type (Etype (A))
2363            and then Etype (F) /= Base_Type (Etype (F))
2364          then
2365             Temp_Typ := Etype (F);
2366
2367          else
2368             Temp_Typ := Etype (A);
2369          end if;
2370
2371          if (not Is_Entity_Name (A)
2372              and then Nkind (A) /= N_Integer_Literal
2373              and then Nkind (A) /= N_Real_Literal)
2374
2375            or else Is_Scalar_Type (Etype (A))
2376          then
2377             Temp :=
2378               Make_Defining_Identifier (Loc,
2379                 Chars => New_Internal_Name ('C'));
2380
2381             --  If the actual for an in/in-out parameter is a view conversion,
2382             --  make it into an unchecked conversion, given that an untagged
2383             --  type conversion is not a proper object for a renaming.
2384             --  In-out conversions that involve real conversions have already
2385             --  been transformed in Expand_Actuals.
2386
2387             if Nkind (A) = N_Type_Conversion
2388               and then
2389                 (Ekind (F) = E_In_Out_Parameter
2390                   or else not Is_Tagged_Type (Etype (F)))
2391             then
2392                New_A := Make_Unchecked_Type_Conversion (Loc,
2393                  Subtype_Mark => New_Occurrence_Of (Etype (F), Loc),
2394                  Expression   => Relocate_Node (Expression (A)));
2395
2396             elsif Etype (F) /= Etype (A) then
2397                New_A := Unchecked_Convert_To (Etype (F), Relocate_Node (A));
2398                Temp_Typ := Etype (F);
2399
2400             else
2401                New_A := Relocate_Node (A);
2402             end if;
2403
2404             Set_Sloc (New_A, Sloc (N));
2405
2406             if Ekind (F) = E_In_Parameter
2407               and then not Is_Limited_Type (Etype (A))
2408             then
2409                Decl :=
2410                  Make_Object_Declaration (Loc,
2411                    Defining_Identifier => Temp,
2412                    Constant_Present => True,
2413                    Object_Definition => New_Occurrence_Of (Temp_Typ, Loc),
2414                    Expression => New_A);
2415             else
2416                Decl :=
2417                  Make_Object_Renaming_Declaration (Loc,
2418                    Defining_Identifier => Temp,
2419                    Subtype_Mark        => New_Occurrence_Of (Temp_Typ, Loc),
2420                    Name                => New_A);
2421             end if;
2422
2423             Prepend (Decl, Declarations (Blk));
2424             Set_Renamed_Object (F, Temp);
2425
2426          else
2427             if Etype (F) /= Etype (A) then
2428                Set_Renamed_Object
2429                 (F, Unchecked_Convert_To (Etype (F), Relocate_Node (A)));
2430             else
2431                Set_Renamed_Object (F, A);
2432             end if;
2433          end if;
2434
2435          Next_Formal (F);
2436          Next_Actual (A);
2437       end loop;
2438
2439       --  Establish target of function call. If context is not assignment or
2440       --  declaration, create a temporary as a target. The declaration for
2441       --  the temporary may be subsequently optimized away if the body is a
2442       --  single expression, or if the left-hand side of the assignment is
2443       --  simple enough.
2444
2445       if Ekind (Subp) = E_Function then
2446          if Nkind (Parent (N)) = N_Assignment_Statement
2447            and then Is_Entity_Name (Name (Parent (N)))
2448          then
2449             Targ := Name (Parent (N));
2450
2451          else
2452             --  Replace call with temporary, and create its declaration.
2453
2454             Temp :=
2455               Make_Defining_Identifier (Loc, New_Internal_Name ('C'));
2456
2457             Decl :=
2458               Make_Object_Declaration (Loc,
2459                 Defining_Identifier => Temp,
2460                 Object_Definition =>
2461                   New_Occurrence_Of (Ret_Type, Loc));
2462
2463             Set_No_Initialization (Decl);
2464             Insert_Action (N, Decl);
2465             Rewrite (N, New_Occurrence_Of (Temp, Loc));
2466             Targ := Temp;
2467          end if;
2468       end if;
2469
2470       --  Traverse the tree and replace  formals with actuals or their thunks.
2471       --  Attach block to tree before analysis and rewriting.
2472
2473       Replace_Formals (Blk);
2474       Set_Parent (Blk, N);
2475
2476       if Present (Exit_Lab) then
2477
2478          --  If the body was a single expression, the single return statement
2479          --  and the corresponding label are useless.
2480
2481          if Num_Ret = 1
2482            and then
2483              Nkind (Last (Statements (Handled_Statement_Sequence (Blk)))) =
2484                N_Goto_Statement
2485          then
2486             Remove (Last (Statements (Handled_Statement_Sequence (Blk))));
2487          else
2488             Append (Lab_Decl, (Declarations (Blk)));
2489             Append (Exit_Lab, Statements (Handled_Statement_Sequence (Blk)));
2490          end if;
2491       end if;
2492
2493       --  Analyze Blk with In_Inlined_Body set, to avoid spurious errors on
2494       --  conflicting private views that Gigi would ignore.
2495
2496       declare
2497          I_Flag : constant Boolean := In_Inlined_Body;
2498
2499       begin
2500          In_Inlined_Body := True;
2501          Analyze (Blk);
2502          In_Inlined_Body := I_Flag;
2503       end;
2504
2505       if Ekind (Subp) = E_Procedure then
2506          Rewrite_Procedure_Call (N, Blk);
2507       else
2508          Rewrite_Function_Call (N, Blk);
2509       end if;
2510
2511       Restore_Env;
2512
2513       --  Cleanup mapping between formals and actuals, for other expansions.
2514
2515       F := First_Formal (Subp);
2516
2517       while Present (F) loop
2518          Set_Renamed_Object (F, Empty);
2519          Next_Formal (F);
2520       end loop;
2521    end Expand_Inlined_Call;
2522
2523    ----------------------------
2524    -- Expand_N_Function_Call --
2525    ----------------------------
2526
2527    procedure Expand_N_Function_Call (N : Node_Id) is
2528       Typ : constant Entity_Id := Etype (N);
2529
2530       function Returned_By_Reference return Boolean;
2531       --  If the return type is returned through the secondary stack. i.e.
2532       --  by reference, we don't want to create a temporary to force stack
2533       --  checking.
2534
2535       function Returned_By_Reference return Boolean is
2536          S : Entity_Id := Current_Scope;
2537
2538       begin
2539          if Is_Return_By_Reference_Type (Typ) then
2540             return True;
2541
2542          elsif Nkind (Parent (N)) /= N_Return_Statement then
2543             return False;
2544
2545          elsif Requires_Transient_Scope (Typ) then
2546
2547             --  Verify that the return type of the enclosing function has
2548             --  the same constrained status as that of the expression.
2549
2550             while Ekind (S) /= E_Function loop
2551                S := Scope (S);
2552             end loop;
2553
2554             return Is_Constrained (Typ) = Is_Constrained (Etype (S));
2555          else
2556             return False;
2557          end if;
2558       end Returned_By_Reference;
2559
2560    --  Start of processing for Expand_N_Function_Call
2561
2562    begin
2563       --  A special check. If stack checking is enabled, and the return type
2564       --  might generate a large temporary, and the call is not the right
2565       --  side of an assignment, then generate an explicit temporary. We do
2566       --  this because otherwise gigi may generate a large temporary on the
2567       --  fly and this can cause trouble with stack checking.
2568
2569       if May_Generate_Large_Temp (Typ)
2570         and then Nkind (Parent (N)) /= N_Assignment_Statement
2571         and then
2572           (Nkind (Parent (N)) /= N_Object_Declaration
2573              or else Expression (Parent (N)) /= N)
2574         and then not Returned_By_Reference
2575       then
2576          --  Note: it might be thought that it would be OK to use a call to
2577          --  Force_Evaluation here, but that's not good enough, because that
2578          --  results in a 'Reference construct that may still need a temporary.
2579
2580          declare
2581             Loc      : constant Source_Ptr := Sloc (N);
2582             Temp_Obj : constant Entity_Id := Make_Defining_Identifier (Loc,
2583                                           New_Internal_Name ('F'));
2584             Temp_Typ : Entity_Id := Typ;
2585             Decl     : Node_Id;
2586             A        : Node_Id;
2587             F        : Entity_Id;
2588             Proc     : Entity_Id;
2589
2590          begin
2591             if Is_Tagged_Type (Typ)
2592               and then Present (Controlling_Argument (N))
2593             then
2594                if Nkind (Parent (N)) /= N_Procedure_Call_Statement
2595                  and then Nkind (Parent (N)) /= N_Function_Call
2596                then
2597                   --  If this is a tag-indeterminate call, the object must
2598                   --  be classwide.
2599
2600                   if Is_Tag_Indeterminate (N) then
2601                      Temp_Typ := Class_Wide_Type (Typ);
2602                   end if;
2603
2604                else
2605                   --  If this is a dispatching call that is itself the
2606                   --  controlling argument of an enclosing call, the nominal
2607                   --  subtype of the object that replaces it must be classwide,
2608                   --  so that dispatching will take place properly. If it is
2609                   --  not a controlling argument, the object is not classwide.
2610
2611                   Proc := Entity (Name (Parent (N)));
2612                   F    := First_Formal (Proc);
2613                   A    := First_Actual (Parent (N));
2614
2615                   while A /= N loop
2616                      Next_Formal (F);
2617                      Next_Actual (A);
2618                   end loop;
2619
2620                   if Is_Controlling_Formal (F) then
2621                      Temp_Typ := Class_Wide_Type (Typ);
2622                   end if;
2623                end if;
2624             end if;
2625
2626             Decl :=
2627               Make_Object_Declaration (Loc,
2628                 Defining_Identifier => Temp_Obj,
2629                 Object_Definition   => New_Occurrence_Of (Temp_Typ, Loc),
2630                 Constant_Present    => True,
2631                 Expression          => Relocate_Node (N));
2632             Set_Assignment_OK (Decl);
2633
2634             Insert_Actions (N, New_List (Decl));
2635             Rewrite (N, New_Occurrence_Of (Temp_Obj, Loc));
2636          end;
2637
2638       --  Normal case, expand the call
2639
2640       else
2641          Expand_Call (N);
2642       end if;
2643    end Expand_N_Function_Call;
2644
2645    ---------------------------------------
2646    -- Expand_N_Procedure_Call_Statement --
2647    ---------------------------------------
2648
2649    procedure Expand_N_Procedure_Call_Statement (N : Node_Id) is
2650    begin
2651       Expand_Call (N);
2652    end Expand_N_Procedure_Call_Statement;
2653
2654    ------------------------------
2655    -- Expand_N_Subprogram_Body --
2656    ------------------------------
2657
2658    --  Add poll call if ATC polling is enabled
2659
2660    --  Add return statement if last statement in body is not a return
2661    --  statement (this makes things easier on Gigi which does not want
2662    --  to have to handle a missing return).
2663
2664    --  Add call to Activate_Tasks if body is a task activator
2665
2666    --  Deal with possible detection of infinite recursion
2667
2668    --  Eliminate body completely if convention stubbed
2669
2670    --  Encode entity names within body, since we will not need to reference
2671    --  these entities any longer in the front end.
2672
2673    --  Initialize scalar out parameters if Initialize/Normalize_Scalars
2674
2675    --  Reset Pure indication if any parameter has root type System.Address
2676
2677    procedure Expand_N_Subprogram_Body (N : Node_Id) is
2678       Loc      : constant Source_Ptr := Sloc (N);
2679       H        : constant Node_Id    := Handled_Statement_Sequence (N);
2680       Body_Id  : Entity_Id;
2681       Spec_Id  : Entity_Id;
2682       Except_H : Node_Id;
2683       Scop     : Entity_Id;
2684       Dec      : Node_Id;
2685       Next_Op  : Node_Id;
2686       L        : List_Id;
2687
2688       procedure Add_Return (S : List_Id);
2689       --  Append a return statement to the statement sequence S if the last
2690       --  statement is not already a return or a goto statement. Note that
2691       --  the latter test is not critical, it does not matter if we add a
2692       --  few extra returns, since they get eliminated anyway later on.
2693
2694       ----------------
2695       -- Add_Return --
2696       ----------------
2697
2698       procedure Add_Return (S : List_Id) is
2699          Last_S : constant Node_Id := Last (S);
2700          --  Get original node, in case raise has been rewritten
2701
2702       begin
2703          if not Is_Transfer (Last_S) then
2704             Append_To (S, Make_Return_Statement (Sloc (Last_S)));
2705          end if;
2706       end Add_Return;
2707
2708    --  Start of processing for Expand_N_Subprogram_Body
2709
2710    begin
2711       --  Set L to either the list of declarations if present, or
2712       --  to the list of statements if no declarations are present.
2713       --  This is used to insert new stuff at the start.
2714
2715       if Is_Non_Empty_List (Declarations (N)) then
2716          L := Declarations (N);
2717       else
2718          L := Statements (Handled_Statement_Sequence (N));
2719       end if;
2720
2721       --  Need poll on entry to subprogram if polling enabled. We only
2722       --  do this for non-empty subprograms, since it does not seem
2723       --  necessary to poll for a dummy null subprogram.
2724
2725       if Is_Non_Empty_List (L) then
2726          Generate_Poll_Call (First (L));
2727       end if;
2728
2729       --  Find entity for subprogram
2730
2731       Body_Id := Defining_Entity (N);
2732
2733       if Present (Corresponding_Spec (N)) then
2734          Spec_Id := Corresponding_Spec (N);
2735       else
2736          Spec_Id := Body_Id;
2737       end if;
2738
2739       --  If this is a Pure function which has any parameters whose root
2740       --  type is System.Address, reset the Pure indication, since it will
2741       --  likely cause incorrect code to be generated.
2742
2743       if Is_Pure (Spec_Id)
2744         and then Is_Subprogram (Spec_Id)
2745         and then not Has_Pragma_Pure_Function (Spec_Id)
2746       then
2747          declare
2748             F : Entity_Id := First_Formal (Spec_Id);
2749
2750          begin
2751             while Present (F) loop
2752                if Is_RTE (Root_Type (Etype (F)), RE_Address) then
2753                   Set_Is_Pure (Spec_Id, False);
2754
2755                   if Spec_Id /= Body_Id then
2756                      Set_Is_Pure (Body_Id, False);
2757                   end if;
2758
2759                   exit;
2760                end if;
2761
2762                Next_Formal (F);
2763             end loop;
2764          end;
2765       end if;
2766
2767       --  Initialize any scalar OUT args if Initialize/Normalize_Scalars
2768
2769       if Init_Or_Norm_Scalars and then Is_Subprogram (Spec_Id) then
2770          declare
2771             F : Entity_Id        := First_Formal (Spec_Id);
2772             V : constant Boolean := Validity_Checks_On;
2773
2774          begin
2775             --  We turn off validity checking, since we do not want any
2776             --  check on the initializing value itself (which we know
2777             --  may well be invalid!)
2778
2779             Validity_Checks_On := False;
2780
2781             --  Loop through formals
2782
2783             while Present (F) loop
2784                if Is_Scalar_Type (Etype (F))
2785                  and then Ekind (F) = E_Out_Parameter
2786                then
2787                   Insert_Before_And_Analyze (First (L),
2788                     Make_Assignment_Statement (Loc,
2789                       Name => New_Occurrence_Of (F, Loc),
2790                       Expression => Get_Simple_Init_Val (Etype (F), Loc)));
2791                end if;
2792
2793                Next_Formal (F);
2794             end loop;
2795
2796             Validity_Checks_On := V;
2797          end;
2798       end if;
2799
2800       --  Clear out statement list for stubbed procedure
2801
2802       if Present (Corresponding_Spec (N)) then
2803          Set_Elaboration_Flag (N, Spec_Id);
2804
2805          if Convention (Spec_Id) = Convention_Stubbed
2806            or else Is_Eliminated (Spec_Id)
2807          then
2808             Set_Declarations (N, Empty_List);
2809             Set_Handled_Statement_Sequence (N,
2810               Make_Handled_Sequence_Of_Statements (Loc,
2811                 Statements => New_List (
2812                   Make_Null_Statement (Loc))));
2813             return;
2814          end if;
2815       end if;
2816
2817       Scop := Scope (Spec_Id);
2818
2819       --  Returns_By_Ref flag is normally set when the subprogram is frozen
2820       --  but subprograms with no specs are not frozen
2821
2822       declare
2823          Typ  : constant Entity_Id := Etype (Spec_Id);
2824          Utyp : constant Entity_Id := Underlying_Type (Typ);
2825
2826       begin
2827          if not Acts_As_Spec (N)
2828            and then Nkind (Parent (Parent (Spec_Id))) /=
2829              N_Subprogram_Body_Stub
2830          then
2831             null;
2832
2833          elsif Is_Return_By_Reference_Type (Typ) then
2834             Set_Returns_By_Ref (Spec_Id);
2835
2836          elsif Present (Utyp) and then Controlled_Type (Utyp) then
2837             Set_Returns_By_Ref (Spec_Id);
2838          end if;
2839       end;
2840
2841       --  For a procedure, we add a return for all possible syntactic ends
2842       --  of the subprogram. Note that reanalysis is not necessary in this
2843       --  case since it would require a lot of work and accomplish nothing.
2844
2845       if Ekind (Spec_Id) = E_Procedure
2846         or else Ekind (Spec_Id) = E_Generic_Procedure
2847       then
2848          Add_Return (Statements (H));
2849
2850          if Present (Exception_Handlers (H)) then
2851             Except_H := First_Non_Pragma (Exception_Handlers (H));
2852
2853             while Present (Except_H) loop
2854                Add_Return (Statements (Except_H));
2855                Next_Non_Pragma (Except_H);
2856             end loop;
2857          end if;
2858
2859       --  For a function, we must deal with the case where there is at
2860       --  least one missing return. What we do is to wrap the entire body
2861       --  of the function in a block:
2862
2863       --    begin
2864       --      ...
2865       --    end;
2866
2867       --  becomes
2868
2869       --    begin
2870       --       begin
2871       --          ...
2872       --       end;
2873
2874       --       raise Program_Error;
2875       --    end;
2876
2877       --  This approach is necessary because the raise must be signalled
2878       --  to the caller, not handled by any local handler (RM 6.4(11)).
2879
2880       --  Note: we do not need to analyze the constructed sequence here,
2881       --  since it has no handler, and an attempt to analyze the handled
2882       --  statement sequence twice is risky in various ways (e.g. the
2883       --  issue of expanding cleanup actions twice).
2884
2885       elsif Has_Missing_Return (Spec_Id) then
2886          declare
2887             Hloc : constant Source_Ptr := Sloc (H);
2888             Blok : constant Node_Id    :=
2889                      Make_Block_Statement (Hloc,
2890                        Handled_Statement_Sequence => H);
2891             Rais : constant Node_Id    :=
2892                      Make_Raise_Program_Error (Hloc,
2893                        Reason => PE_Missing_Return);
2894
2895          begin
2896             Set_Handled_Statement_Sequence (N,
2897               Make_Handled_Sequence_Of_Statements (Hloc,
2898                 Statements => New_List (Blok, Rais)));
2899
2900             New_Scope (Spec_Id);
2901             Analyze (Blok);
2902             Analyze (Rais);
2903             Pop_Scope;
2904          end;
2905       end if;
2906
2907       --  Add discriminal renamings to protected subprograms.
2908       --  Install new discriminals for expansion of the next
2909       --  subprogram of this protected type, if any.
2910
2911       if Is_List_Member (N)
2912         and then Present (Parent (List_Containing (N)))
2913         and then Nkind (Parent (List_Containing (N))) = N_Protected_Body
2914       then
2915          Add_Discriminal_Declarations
2916            (Declarations (N), Scop, Name_uObject, Loc);
2917          Add_Private_Declarations (Declarations (N), Scop, Name_uObject, Loc);
2918
2919          --  Associate privals and discriminals with the next protected
2920          --  operation body to be expanded. These are used to expand
2921          --  references to private data objects and discriminants,
2922          --  respectively.
2923
2924          Next_Op := Next_Protected_Operation (N);
2925
2926          if Present (Next_Op) then
2927             Dec := Parent (Base_Type (Scop));
2928             Set_Privals (Dec, Next_Op, Loc);
2929             Set_Discriminals (Dec);
2930          end if;
2931       end if;
2932
2933       --  If subprogram contains a parameterless recursive call, then we may
2934       --  have an infinite recursion, so see if we can generate code to check
2935       --  for this possibility if storage checks are not suppressed.
2936
2937       if Ekind (Spec_Id) = E_Procedure
2938         and then Has_Recursive_Call (Spec_Id)
2939         and then not Storage_Checks_Suppressed (Spec_Id)
2940       then
2941          Detect_Infinite_Recursion (N, Spec_Id);
2942       end if;
2943
2944       --  Finally, if we are in Normalize_Scalars mode, then any scalar out
2945       --  parameters must be initialized to the appropriate default value.
2946
2947       if Ekind (Spec_Id) = E_Procedure and then Normalize_Scalars then
2948          declare
2949             Floc   : Source_Ptr;
2950             Formal : Entity_Id;
2951             Stm    : Node_Id;
2952
2953          begin
2954             Formal := First_Formal (Spec_Id);
2955
2956             while Present (Formal) loop
2957                Floc := Sloc (Formal);
2958
2959                if Ekind (Formal) = E_Out_Parameter
2960                  and then Is_Scalar_Type (Etype (Formal))
2961                then
2962                   Stm :=
2963                     Make_Assignment_Statement (Floc,
2964                       Name => New_Occurrence_Of (Formal, Floc),
2965                       Expression =>
2966                         Get_Simple_Init_Val (Etype (Formal), Floc));
2967                   Prepend (Stm, Declarations (N));
2968                   Analyze (Stm);
2969                end if;
2970
2971                Next_Formal (Formal);
2972             end loop;
2973          end;
2974       end if;
2975
2976       --  If the subprogram does not have pending instantiations, then we
2977       --  must generate the subprogram descriptor now, since the code for
2978       --  the subprogram is complete, and this is our last chance. However
2979       --  if there are pending instantiations, then the code is not
2980       --  complete, and we will delay the generation.
2981
2982       if Is_Subprogram (Spec_Id)
2983         and then not Delay_Subprogram_Descriptors (Spec_Id)
2984       then
2985          Generate_Subprogram_Descriptor_For_Subprogram (N, Spec_Id);
2986       end if;
2987
2988       --  Set to encode entity names in package body before gigi is called
2989
2990       Qualify_Entity_Names (N);
2991    end Expand_N_Subprogram_Body;
2992
2993    -----------------------------------
2994    -- Expand_N_Subprogram_Body_Stub --
2995    -----------------------------------
2996
2997    procedure Expand_N_Subprogram_Body_Stub (N : Node_Id) is
2998    begin
2999       if Present (Corresponding_Body (N)) then
3000          Expand_N_Subprogram_Body (
3001            Unit_Declaration_Node (Corresponding_Body (N)));
3002       end if;
3003
3004    end Expand_N_Subprogram_Body_Stub;
3005
3006    -------------------------------------
3007    -- Expand_N_Subprogram_Declaration --
3008    -------------------------------------
3009
3010    --  The first task to be performed is the construction of default
3011    --  expression functions for in parameters with default values. These
3012    --  are parameterless inlined functions that are used to evaluate
3013    --  default expressions that are more complicated than simple literals
3014    --  or identifiers referencing constants and variables.
3015
3016    --  If the declaration appears within a protected body, it is a private
3017    --  operation of the protected type. We must create the corresponding
3018    --  protected subprogram an associated formals. For a normal protected
3019    --  operation, this is done when expanding the protected type declaration.
3020
3021    procedure Expand_N_Subprogram_Declaration (N : Node_Id) is
3022       Loc      : constant Source_Ptr := Sloc (N);
3023       Subp     : Entity_Id := Defining_Entity (N);
3024       Scop     : Entity_Id := Scope (Subp);
3025       Prot_Sub : Entity_Id;
3026       Prot_Bod : Node_Id;
3027
3028    begin
3029       --  Deal with case of protected subprogram
3030
3031       if Is_List_Member (N)
3032         and then Present (Parent (List_Containing (N)))
3033         and then Nkind (Parent (List_Containing (N))) = N_Protected_Body
3034         and then Is_Protected_Type (Scop)
3035       then
3036          if No (Protected_Body_Subprogram (Subp)) then
3037             Prot_Sub :=
3038               Make_Subprogram_Declaration (Loc,
3039                 Specification =>
3040                   Build_Protected_Sub_Specification
3041                     (N, Scop, Unprotected => True));
3042
3043             --  The protected subprogram is declared outside of the protected
3044             --  body. Given that the body has frozen all entities so far, we
3045             --  freeze the subprogram explicitly. If the body is a subunit,
3046             --  the insertion point is before the stub in the parent.
3047
3048             Prot_Bod := Parent (List_Containing (N));
3049
3050             if Nkind (Parent (Prot_Bod)) = N_Subunit then
3051                Prot_Bod := Corresponding_Stub (Parent (Prot_Bod));
3052             end if;
3053
3054             Insert_Before (Prot_Bod, Prot_Sub);
3055
3056             New_Scope (Scope (Scop));
3057             Analyze (Prot_Sub);
3058             Set_Protected_Body_Subprogram (Subp,
3059               Defining_Unit_Name (Specification (Prot_Sub)));
3060             Pop_Scope;
3061          end if;
3062       end if;
3063    end Expand_N_Subprogram_Declaration;
3064
3065    ---------------------------------------
3066    -- Expand_Protected_Object_Reference --
3067    ---------------------------------------
3068
3069    function Expand_Protected_Object_Reference
3070      (N    : Node_Id;
3071       Scop : Entity_Id)
3072      return Node_Id
3073    is
3074       Loc   : constant Source_Ptr := Sloc (N);
3075       Corr  : Entity_Id;
3076       Rec   : Node_Id;
3077       Param : Entity_Id;
3078       Proc  : Entity_Id;
3079
3080    begin
3081       Rec := Make_Identifier (Loc, Name_uObject);
3082       Set_Etype (Rec, Corresponding_Record_Type (Scop));
3083
3084       --  Find enclosing protected operation, and retrieve its first
3085       --  parameter, which denotes the enclosing protected object.
3086       --  If the enclosing operation is an entry, we are immediately
3087       --  within the protected body, and we can retrieve the object
3088       --  from the service entries procedure. A barrier function has
3089       --  has the same signature as an entry. A barrier function is
3090       --  compiled within the protected object, but unlike protected
3091       --  operations its never needs locks, so that its protected body
3092       --  subprogram points to itself.
3093
3094       Proc := Current_Scope;
3095
3096       while Present (Proc)
3097         and then Scope (Proc) /= Scop
3098       loop
3099          Proc := Scope (Proc);
3100       end loop;
3101
3102       Corr := Protected_Body_Subprogram (Proc);
3103
3104       if No (Corr) then
3105
3106          --  Previous error left expansion incomplete.
3107          --  Nothing to do on this call.
3108
3109          return Empty;
3110       end if;
3111
3112       Param :=
3113         Defining_Identifier
3114           (First (Parameter_Specifications (Parent (Corr))));
3115
3116       if Is_Subprogram (Proc)
3117         and then Proc /= Corr
3118       then
3119          --  Protected function or procedure.
3120
3121          Set_Entity (Rec, Param);
3122
3123          --  Rec is a reference to an entity which will not be in scope
3124          --  when the call is reanalyzed, and needs no further analysis.
3125
3126          Set_Analyzed (Rec);
3127
3128       else
3129          --  Entry or barrier function for entry body.
3130          --  The first parameter of the entry body procedure is a
3131          --  pointer to the object. We create a local variable
3132          --  of the proper type, duplicating what is done to define
3133          --  _object later on.
3134
3135          declare
3136             Decls : List_Id;
3137             Obj_Ptr : Entity_Id :=  Make_Defining_Identifier
3138                                       (Loc, New_Internal_Name ('T'));
3139          begin
3140             Decls := New_List (
3141               Make_Full_Type_Declaration (Loc,
3142                 Defining_Identifier => Obj_Ptr,
3143                   Type_Definition =>
3144                      Make_Access_To_Object_Definition (Loc,
3145                        Subtype_Indication =>
3146                          New_Reference_To
3147                       (Corresponding_Record_Type (Scop), Loc))));
3148
3149             Insert_Actions (N, Decls);
3150             Insert_Actions (N, Freeze_Entity (Obj_Ptr, Sloc (N)));
3151
3152             Rec :=
3153               Make_Explicit_Dereference (Loc,
3154                 Unchecked_Convert_To (Obj_Ptr,
3155                   New_Occurrence_Of (Param, Loc)));
3156
3157             --  Analyze new actual. Other actuals in calls are already
3158             --  analyzed and the list of actuals is not renalyzed after
3159             --  rewriting.
3160
3161             Set_Parent (Rec, N);
3162             Analyze (Rec);
3163          end;
3164       end if;
3165
3166       return Rec;
3167    end Expand_Protected_Object_Reference;
3168
3169    --------------------------------------
3170    -- Expand_Protected_Subprogram_Call --
3171    --------------------------------------
3172
3173    procedure Expand_Protected_Subprogram_Call
3174      (N    : Node_Id;
3175       Subp : Entity_Id;
3176       Scop : Entity_Id)
3177    is
3178       Rec   : Node_Id;
3179
3180    begin
3181       --  If the protected object is not an enclosing scope, this is
3182       --  an inter-object function call. Inter-object procedure
3183       --  calls are expanded by Exp_Ch9.Build_Simple_Entry_Call.
3184       --  The call is intra-object only if the subprogram being
3185       --  called is in the protected body being compiled, and if the
3186       --  protected object in the call is statically the enclosing type.
3187       --  The object may be an component of some other data structure,
3188       --  in which case this must be handled as an inter-object call.
3189
3190       if not In_Open_Scopes (Scop)
3191         or else not Is_Entity_Name (Name (N))
3192       then
3193          if Nkind (Name (N)) = N_Selected_Component then
3194             Rec := Prefix (Name (N));
3195
3196          else
3197             pragma Assert (Nkind (Name (N)) = N_Indexed_Component);
3198             Rec := Prefix (Prefix (Name (N)));
3199          end if;
3200
3201          Build_Protected_Subprogram_Call (N,
3202            Name => New_Occurrence_Of (Subp, Sloc (N)),
3203            Rec =>  Convert_Concurrent (Rec, Etype (Rec)),
3204            External => True);
3205
3206       else
3207          Rec := Expand_Protected_Object_Reference (N, Scop);
3208
3209          if No (Rec) then
3210             return;
3211          end if;
3212
3213          Build_Protected_Subprogram_Call (N,
3214            Name     => Name (N),
3215            Rec      => Rec,
3216            External => False);
3217
3218       end if;
3219
3220       Analyze (N);
3221
3222       --  If it is a function call it can appear in elaboration code and
3223       --  the called entity must be frozen here.
3224
3225       if Ekind (Subp) = E_Function then
3226          Freeze_Expression (Name (N));
3227       end if;
3228    end Expand_Protected_Subprogram_Call;
3229
3230    -----------------------
3231    -- Freeze_Subprogram --
3232    -----------------------
3233
3234    procedure Freeze_Subprogram (N : Node_Id) is
3235       E : constant Entity_Id := Entity (N);
3236
3237    begin
3238       --  When a primitive is frozen, enter its name in the corresponding
3239       --  dispatch table. If the DTC_Entity field is not set this is an
3240       --  overridden primitive that can be ignored. We suppress the
3241       --  initialization of the dispatch table entry when Java_VM because
3242       --  the dispatching mechanism is handled internally by the JVM.
3243
3244       if Is_Dispatching_Operation (E)
3245         and then not Is_Abstract (E)
3246         and then Present (DTC_Entity (E))
3247         and then not Is_CPP_Class (Scope (DTC_Entity (E)))
3248         and then not Java_VM
3249       then
3250          Check_Overriding_Operation (E);
3251          Insert_After (N, Fill_DT_Entry (Sloc (N), E));
3252       end if;
3253
3254       --  Mark functions that return by reference. Note that it cannot be
3255       --  part of the normal semantic analysis of the spec since the
3256       --  underlying returned type may not be known yet (for private types)
3257
3258       declare
3259          Typ  : constant Entity_Id := Etype (E);
3260          Utyp : constant Entity_Id := Underlying_Type (Typ);
3261
3262       begin
3263          if Is_Return_By_Reference_Type (Typ) then
3264             Set_Returns_By_Ref (E);
3265
3266          elsif Present (Utyp) and then Controlled_Type (Utyp) then
3267             Set_Returns_By_Ref (E);
3268          end if;
3269       end;
3270
3271    end Freeze_Subprogram;
3272
3273 end Exp_Ch6;