OSDN Git Service

2011-08-03 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / inline.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                               I N L I N E                                --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2011, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Einfo;    use Einfo;
28 with Elists;   use Elists;
29 with Errout;   use Errout;
30 with Exp_Ch7;  use Exp_Ch7;
31 with Exp_Tss;  use Exp_Tss;
32 with Fname;    use Fname;
33 with Fname.UF; use Fname.UF;
34 with Lib;      use Lib;
35 with Namet;    use Namet;
36 with Nlists;   use Nlists;
37 with Sem_Aux;  use Sem_Aux;
38 with Sem_Ch8;  use Sem_Ch8;
39 with Sem_Ch10; use Sem_Ch10;
40 with Sem_Ch12; use Sem_Ch12;
41 with Sem_Util; use Sem_Util;
42 with Sinfo;    use Sinfo;
43 with Snames;   use Snames;
44 with Stand;    use Stand;
45 with Uname;    use Uname;
46
47 package body Inline is
48
49    --------------------
50    -- Inlined Bodies --
51    --------------------
52
53    --  Inlined functions are actually placed in line by the backend if the
54    --  corresponding bodies are available (i.e. compiled). Whenever we find
55    --  a call to an inlined subprogram, we add the name of the enclosing
56    --  compilation unit to a worklist. After all compilation, and after
57    --  expansion of generic bodies, we traverse the list of pending bodies
58    --  and compile them as well.
59
60    package Inlined_Bodies is new Table.Table (
61      Table_Component_Type => Entity_Id,
62      Table_Index_Type     => Int,
63      Table_Low_Bound      => 0,
64      Table_Initial        => Alloc.Inlined_Bodies_Initial,
65      Table_Increment      => Alloc.Inlined_Bodies_Increment,
66      Table_Name           => "Inlined_Bodies");
67
68    -----------------------
69    -- Inline Processing --
70    -----------------------
71
72    --  For each call to an inlined subprogram, we make entries in a table
73    --  that stores caller and callee, and indicates a prerequisite from
74    --  one to the other. We also record the compilation unit that contains
75    --  the callee. After analyzing the bodies of all such compilation units,
76    --  we produce a list of subprograms in  topological order, for use by the
77    --  back-end. If P2 is a prerequisite of P1, then P1 calls P2, and for
78    --  proper inlining the back-end must analyze the body of P2 before that of
79    --  P1. The code below guarantees that the transitive closure of inlined
80    --  subprograms called from the main compilation unit is made available to
81    --  the code generator.
82
83    Last_Inlined : Entity_Id := Empty;
84
85    --  For each entry in the table we keep a list of successors in topological
86    --  order, i.e. callers of the current subprogram.
87
88    type Subp_Index is new Nat;
89    No_Subp : constant Subp_Index := 0;
90
91    --  The subprogram entities are hashed into the Inlined table
92
93    Num_Hash_Headers : constant := 512;
94
95    Hash_Headers : array (Subp_Index range 0 .. Num_Hash_Headers - 1)
96                                                           of Subp_Index;
97
98    type Succ_Index is new Nat;
99    No_Succ : constant Succ_Index := 0;
100
101    type Succ_Info is record
102       Subp : Subp_Index;
103       Next : Succ_Index;
104    end record;
105
106    --  The following table stores list elements for the successor lists.
107    --  These lists cannot be chained directly through entries in the Inlined
108    --  table, because a given subprogram can appear in several such lists.
109
110    package Successors is new Table.Table (
111       Table_Component_Type => Succ_Info,
112       Table_Index_Type     => Succ_Index,
113       Table_Low_Bound      => 1,
114       Table_Initial        => Alloc.Successors_Initial,
115       Table_Increment      => Alloc.Successors_Increment,
116       Table_Name           => "Successors");
117
118    type Subp_Info is record
119       Name        : Entity_Id  := Empty;
120       First_Succ  : Succ_Index := No_Succ;
121       Count       : Integer    := 0;
122       Listed      : Boolean    := False;
123       Main_Call   : Boolean    := False;
124       Next        : Subp_Index := No_Subp;
125       Next_Nopred : Subp_Index := No_Subp;
126    end record;
127
128    package Inlined is new Table.Table (
129       Table_Component_Type => Subp_Info,
130       Table_Index_Type     => Subp_Index,
131       Table_Low_Bound      => 1,
132       Table_Initial        => Alloc.Inlined_Initial,
133       Table_Increment      => Alloc.Inlined_Increment,
134       Table_Name           => "Inlined");
135
136    -----------------------
137    -- Local Subprograms --
138    -----------------------
139
140    function Get_Code_Unit_Entity (E : Entity_Id) return Entity_Id;
141    pragma Inline (Get_Code_Unit_Entity);
142    --  Return the entity node for the unit containing E
143
144    function Scope_In_Main_Unit (Scop : Entity_Id) return Boolean;
145    --  Return True if Scop is in the main unit or its spec
146
147    procedure Add_Call (Called : Entity_Id; Caller : Entity_Id := Empty);
148    --  Make two entries in Inlined table, for an inlined subprogram being
149    --  called, and for the inlined subprogram that contains the call. If
150    --  the call is in the main compilation unit, Caller is Empty.
151
152    function Add_Subp (E : Entity_Id) return Subp_Index;
153    --  Make entry in Inlined table for subprogram E, or return table index
154    --  that already holds E.
155
156    function Has_Initialized_Type (E : Entity_Id) return Boolean;
157    --  If a candidate for inlining contains type declarations for types with
158    --  non-trivial initialization procedures, they are not worth inlining.
159
160    function Is_Nested (E : Entity_Id) return Boolean;
161    --  If the function is nested inside some other function, it will
162    --  always be compiled if that function is, so don't add it to the
163    --  inline list. We cannot compile a nested function outside the
164    --  scope of the containing function anyway. This is also the case if
165    --  the function is defined in a task body or within an entry (for
166    --  example, an initialization procedure).
167
168    procedure Add_Inlined_Subprogram (Index : Subp_Index);
169    --  Add subprogram to Inlined List once all of its predecessors have been
170    --  placed on the list. Decrement the count of all its successors, and
171    --  add them to list (recursively) if count drops to zero.
172
173    ------------------------------
174    -- Deferred Cleanup Actions --
175    ------------------------------
176
177    --  The cleanup actions for scopes that contain instantiations is delayed
178    --  until after expansion of those instantiations, because they may
179    --  contain finalizable objects or tasks that affect the cleanup code.
180    --  A scope that contains instantiations only needs to be finalized once,
181    --  even if it contains more than one instance. We keep a list of scopes
182    --  that must still be finalized, and call cleanup_actions after all the
183    --  instantiations have been completed.
184
185    To_Clean : Elist_Id;
186
187    procedure Add_Scope_To_Clean (Inst : Entity_Id);
188    --  Build set of scopes on which cleanup actions must be performed
189
190    procedure Cleanup_Scopes;
191    --  Complete cleanup actions on scopes that need it
192
193    --------------
194    -- Add_Call --
195    --------------
196
197    procedure Add_Call (Called : Entity_Id; Caller : Entity_Id := Empty) is
198       P1 : constant Subp_Index := Add_Subp (Called);
199       P2 : Subp_Index;
200       J  : Succ_Index;
201
202    begin
203       if Present (Caller) then
204          P2 := Add_Subp (Caller);
205
206          --  Add P2 to the list of successors of P1, if not already there.
207          --  Note that P2 may contain more than one call to P1, and only
208          --  one needs to be recorded.
209
210          J := Inlined.Table (P1).First_Succ;
211          while J /= No_Succ loop
212             if Successors.Table (J).Subp = P2 then
213                return;
214             end if;
215
216             J := Successors.Table (J).Next;
217          end loop;
218
219          --  On exit, make a successor entry for P2
220
221          Successors.Increment_Last;
222          Successors.Table (Successors.Last).Subp := P2;
223          Successors.Table (Successors.Last).Next :=
224                              Inlined.Table (P1).First_Succ;
225          Inlined.Table (P1).First_Succ := Successors.Last;
226
227          Inlined.Table (P2).Count := Inlined.Table (P2).Count + 1;
228
229       else
230          Inlined.Table (P1).Main_Call := True;
231       end if;
232    end Add_Call;
233
234    ----------------------
235    -- Add_Inlined_Body --
236    ----------------------
237
238    procedure Add_Inlined_Body (E : Entity_Id) is
239
240       function Must_Inline return Boolean;
241       --  Inlining is only done if the call statement N is in the main unit,
242       --  or within the body of another inlined subprogram.
243
244       -----------------
245       -- Must_Inline --
246       -----------------
247
248       function Must_Inline return Boolean is
249          Scop : Entity_Id;
250          Comp : Node_Id;
251
252       begin
253          --  Check if call is in main unit
254
255          Scop := Current_Scope;
256
257          --  Do not try to inline if scope is standard. This could happen, for
258          --  example, for a call to Add_Global_Declaration, and it causes
259          --  trouble to try to inline at this level.
260
261          if Scop = Standard_Standard then
262             return False;
263          end if;
264
265          --  Otherwise lookup scope stack to outer scope
266
267          while Scope (Scop) /= Standard_Standard
268            and then not Is_Child_Unit (Scop)
269          loop
270             Scop := Scope (Scop);
271          end loop;
272
273          Comp := Parent (Scop);
274          while Nkind (Comp) /= N_Compilation_Unit loop
275             Comp := Parent (Comp);
276          end loop;
277
278          if Comp = Cunit (Main_Unit)
279            or else Comp = Library_Unit (Cunit (Main_Unit))
280          then
281             Add_Call (E);
282             return True;
283          end if;
284
285          --  Call is not in main unit. See if it's in some inlined subprogram
286
287          Scop := Current_Scope;
288          while Scope (Scop) /= Standard_Standard
289            and then not Is_Child_Unit (Scop)
290          loop
291             if Is_Overloadable (Scop)
292               and then Is_Inlined (Scop)
293             then
294                Add_Call (E, Scop);
295                return True;
296             end if;
297
298             Scop := Scope (Scop);
299          end loop;
300
301          return False;
302       end Must_Inline;
303
304    --  Start of processing for Add_Inlined_Body
305
306    begin
307       --  Find unit containing E, and add to list of inlined bodies if needed.
308       --  If the body is already present, no need to load any other unit. This
309       --  is the case for an initialization procedure, which appears in the
310       --  package declaration that contains the type. It is also the case if
311       --  the body has already been analyzed. Finally, if the unit enclosing
312       --  E is an instance, the instance body will be analyzed in any case,
313       --  and there is no need to add the enclosing unit (whose body might not
314       --  be available).
315
316       --  Library-level functions must be handled specially, because there is
317       --  no enclosing package to retrieve. In this case, it is the body of
318       --  the function that will have to be loaded.
319
320       if not Is_Abstract_Subprogram (E)
321         and then not Is_Nested (E)
322         and then Convention (E) /= Convention_Protected
323         and then Must_Inline
324       then
325          declare
326             Pack : constant Entity_Id := Get_Code_Unit_Entity (E);
327
328          begin
329             if Pack = E then
330
331                --  Library-level inlined function. Add function itself to
332                --  list of needed units.
333
334                Set_Is_Called (E);
335                Inlined_Bodies.Increment_Last;
336                Inlined_Bodies.Table (Inlined_Bodies.Last) := E;
337
338             elsif Ekind (Pack) = E_Package then
339                Set_Is_Called (E);
340
341                if Is_Generic_Instance (Pack) then
342                   null;
343
344                elsif not Is_Inlined (Pack)
345                  and then
346                    (not Has_Completion (E)
347                      or else Is_Init_Proc (E)
348                      or else Is_Expression_Function (E))
349                then
350                   Set_Is_Inlined (Pack);
351                   Inlined_Bodies.Increment_Last;
352                   Inlined_Bodies.Table (Inlined_Bodies.Last) := Pack;
353                end if;
354             end if;
355          end;
356       end if;
357    end Add_Inlined_Body;
358
359    ----------------------------
360    -- Add_Inlined_Subprogram --
361    ----------------------------
362
363    procedure Add_Inlined_Subprogram (Index : Subp_Index) is
364       E    : constant Entity_Id := Inlined.Table (Index).Name;
365       Pack : constant Entity_Id := Get_Code_Unit_Entity (E);
366       Succ : Succ_Index;
367       Subp : Subp_Index;
368
369       function Back_End_Cannot_Inline (Subp : Entity_Id) return Boolean;
370       --  There are various conditions under which back-end inlining cannot
371       --  be done reliably:
372       --
373       --    a) If a body has handlers, it must not be inlined, because this
374       --    may violate program semantics, and because in zero-cost exception
375       --    mode it will lead to undefined symbols at link time.
376       --
377       --    b) If a body contains inlined function instances, it cannot be
378       --    inlined under ZCX because the numeric suffix generated by gigi
379       --    will be different in the body and the place of the inlined call.
380       --
381       --  This procedure must be carefully coordinated with the back end.
382
383       ----------------------------
384       -- Back_End_Cannot_Inline --
385       ----------------------------
386
387       function Back_End_Cannot_Inline (Subp : Entity_Id) return Boolean is
388          Decl     : constant Node_Id := Unit_Declaration_Node (Subp);
389          Body_Ent : Entity_Id;
390          Ent      : Entity_Id;
391
392       begin
393          if Nkind (Decl) = N_Subprogram_Declaration
394            and then Present (Corresponding_Body (Decl))
395          then
396             Body_Ent := Corresponding_Body (Decl);
397          else
398             return False;
399          end if;
400
401          --  If subprogram is marked Inline_Always, inlining is mandatory
402
403          if Has_Pragma_Inline_Always (Subp) then
404             return False;
405          end if;
406
407          if Present
408           (Exception_Handlers
409             (Handled_Statement_Sequence
410               (Unit_Declaration_Node (Corresponding_Body (Decl)))))
411          then
412             return True;
413          end if;
414
415          Ent := First_Entity (Body_Ent);
416          while Present (Ent) loop
417             if Is_Subprogram (Ent)
418               and then Is_Generic_Instance (Ent)
419             then
420                return True;
421             end if;
422
423             Next_Entity (Ent);
424          end loop;
425
426          return False;
427       end Back_End_Cannot_Inline;
428
429    --  Start of processing for Add_Inlined_Subprogram
430
431    begin
432       --  Insert the current subprogram in the list of inlined subprograms, if
433       --  it can actually be inlined by the back-end, and if its unit is known
434       --  to be inlined, or is an instance whose body will be analyzed anyway.
435
436       if (Is_Inlined (Pack) or else Is_Generic_Instance (Pack))
437         and then not Scope_In_Main_Unit (E)
438         and then Is_Inlined (E)
439         and then not Is_Nested (E)
440         and then not Has_Initialized_Type (E)
441       then
442          if Back_End_Cannot_Inline (E) then
443             Set_Is_Inlined (E, False);
444
445          else
446             if No (Last_Inlined) then
447                Set_First_Inlined_Subprogram (Cunit (Main_Unit), E);
448             else
449                Set_Next_Inlined_Subprogram (Last_Inlined, E);
450             end if;
451
452             Last_Inlined := E;
453          end if;
454       end if;
455
456       Inlined.Table (Index).Listed := True;
457
458       --  Now add to the list those callers of the current subprogram that
459       --  are themselves called. They may appear on the graph as callers
460       --  of the current one, even if they are themselves not called, and
461       --  there is no point in including them in the list for the backend.
462       --  Furthermore, they might not even be public, in which case the
463       --  back-end cannot handle them at all.
464
465       Succ := Inlined.Table (Index).First_Succ;
466       while Succ /= No_Succ loop
467          Subp := Successors.Table (Succ).Subp;
468          Inlined.Table (Subp).Count := Inlined.Table (Subp).Count - 1;
469
470          if Inlined.Table (Subp).Count = 0
471            and then Is_Called (Inlined.Table (Subp).Name)
472          then
473             Add_Inlined_Subprogram (Subp);
474          end if;
475
476          Succ := Successors.Table (Succ).Next;
477       end loop;
478    end Add_Inlined_Subprogram;
479
480    ------------------------
481    -- Add_Scope_To_Clean --
482    ------------------------
483
484    procedure Add_Scope_To_Clean (Inst : Entity_Id) is
485       Scop : constant Entity_Id := Enclosing_Dynamic_Scope (Inst);
486       Elmt : Elmt_Id;
487
488    begin
489       --  If the instance appears in a library-level package declaration,
490       --  all finalization is global, and nothing needs doing here.
491
492       if Scop = Standard_Standard then
493          return;
494       end if;
495
496       --  If the instance appears within a generic subprogram there is nothing
497       --  to finalize either.
498
499       declare
500          S : Entity_Id;
501
502       begin
503          S := Scope (Inst);
504          while Present (S) and then S /= Standard_Standard loop
505             if Is_Generic_Subprogram (S) then
506                return;
507             end if;
508
509             S := Scope (S);
510          end loop;
511       end;
512
513       Elmt := First_Elmt (To_Clean);
514       while Present (Elmt) loop
515          if Node (Elmt) = Scop then
516             return;
517          end if;
518
519          Elmt := Next_Elmt (Elmt);
520       end loop;
521
522       Append_Elmt (Scop, To_Clean);
523    end Add_Scope_To_Clean;
524
525    --------------
526    -- Add_Subp --
527    --------------
528
529    function Add_Subp (E : Entity_Id) return Subp_Index is
530       Index : Subp_Index := Subp_Index (E) mod Num_Hash_Headers;
531       J     : Subp_Index;
532
533       procedure New_Entry;
534       --  Initialize entry in Inlined table
535
536       procedure New_Entry is
537       begin
538          Inlined.Increment_Last;
539          Inlined.Table (Inlined.Last).Name        := E;
540          Inlined.Table (Inlined.Last).First_Succ  := No_Succ;
541          Inlined.Table (Inlined.Last).Count       := 0;
542          Inlined.Table (Inlined.Last).Listed      := False;
543          Inlined.Table (Inlined.Last).Main_Call   := False;
544          Inlined.Table (Inlined.Last).Next        := No_Subp;
545          Inlined.Table (Inlined.Last).Next_Nopred := No_Subp;
546       end New_Entry;
547
548    --  Start of processing for Add_Subp
549
550    begin
551       if Hash_Headers (Index) = No_Subp then
552          New_Entry;
553          Hash_Headers (Index) := Inlined.Last;
554          return Inlined.Last;
555
556       else
557          J := Hash_Headers (Index);
558          while J /= No_Subp loop
559             if Inlined.Table (J).Name = E then
560                return J;
561             else
562                Index := J;
563                J := Inlined.Table (J).Next;
564             end if;
565          end loop;
566
567          --  On exit, subprogram was not found. Enter in table. Index is
568          --  the current last entry on the hash chain.
569
570          New_Entry;
571          Inlined.Table (Index).Next := Inlined.Last;
572          return Inlined.Last;
573       end if;
574    end Add_Subp;
575
576    ----------------------------
577    -- Analyze_Inlined_Bodies --
578    ----------------------------
579
580    procedure Analyze_Inlined_Bodies is
581       Comp_Unit : Node_Id;
582       J         : Int;
583       Pack      : Entity_Id;
584       S         : Succ_Index;
585
586       function Is_Ancestor_Of_Main
587         (U_Name : Entity_Id;
588          Nam    : Node_Id) return Boolean;
589       --  Determine whether the unit whose body is loaded is an ancestor of
590       --  the main unit, and has a with_clause on it. The body is not
591       --  analyzed yet, so the check is purely lexical: the name of the with
592       --  clause is a selected component, and names of ancestors must match.
593
594       -------------------------
595       -- Is_Ancestor_Of_Main --
596       -------------------------
597
598       function Is_Ancestor_Of_Main
599         (U_Name : Entity_Id;
600          Nam    : Node_Id) return Boolean
601       is
602          Pref : Node_Id;
603
604       begin
605          if Nkind (Nam) /= N_Selected_Component then
606             return False;
607
608          else
609             if Chars (Selector_Name (Nam)) /=
610                Chars (Cunit_Entity (Main_Unit))
611             then
612                return False;
613             end if;
614
615             Pref := Prefix (Nam);
616             if Nkind (Pref) = N_Identifier then
617
618                --  Par is an ancestor of Par.Child.
619
620                return Chars (Pref) = Chars (U_Name);
621
622             elsif Nkind (Pref) = N_Selected_Component
623               and then Chars (Selector_Name (Pref)) = Chars (U_Name)
624             then
625                --  Par.Child is an ancestor of Par.Child.Grand.
626
627                return True;   --  should check that ancestor match
628
629             else
630                --  A is an ancestor of A.B.C if it is an ancestor of A.B
631
632                return Is_Ancestor_Of_Main (U_Name, Pref);
633             end if;
634          end if;
635       end Is_Ancestor_Of_Main;
636
637    --  Start of processing for  Analyze_Inlined_Bodies
638
639    begin
640       Analyzing_Inlined_Bodies := False;
641
642       if Serious_Errors_Detected = 0 then
643          Push_Scope (Standard_Standard);
644
645          J := 0;
646          while J <= Inlined_Bodies.Last
647            and then Serious_Errors_Detected = 0
648          loop
649             Pack := Inlined_Bodies.Table (J);
650             while Present (Pack)
651               and then Scope (Pack) /= Standard_Standard
652               and then not Is_Child_Unit (Pack)
653             loop
654                Pack := Scope (Pack);
655             end loop;
656
657             Comp_Unit := Parent (Pack);
658             while Present (Comp_Unit)
659               and then Nkind (Comp_Unit) /= N_Compilation_Unit
660             loop
661                Comp_Unit := Parent (Comp_Unit);
662             end loop;
663
664             --  Load the body, unless it the main unit, or is an instance whose
665             --  body has already been analyzed.
666
667             if Present (Comp_Unit)
668               and then Comp_Unit /= Cunit (Main_Unit)
669               and then Body_Required (Comp_Unit)
670               and then (Nkind (Unit (Comp_Unit)) /= N_Package_Declaration
671                          or else No (Corresponding_Body (Unit (Comp_Unit))))
672             then
673                declare
674                   Bname : constant Unit_Name_Type :=
675                             Get_Body_Name (Get_Unit_Name (Unit (Comp_Unit)));
676
677                   OK : Boolean;
678
679                begin
680                   if not Is_Loaded (Bname) then
681                      Style_Check := False;
682                      Load_Needed_Body (Comp_Unit, OK, Do_Analyze => False);
683
684                      if not OK then
685
686                         --  Warn that a body was not available for inlining
687                         --  by the back-end.
688
689                         Error_Msg_Unit_1 := Bname;
690                         Error_Msg_N
691                           ("one or more inlined subprograms accessed in $!?",
692                            Comp_Unit);
693                         Error_Msg_File_1 :=
694                           Get_File_Name (Bname, Subunit => False);
695                         Error_Msg_N ("\but file{ was not found!?", Comp_Unit);
696
697                      else
698                         --  If the package to be inlined is an ancestor unit of
699                         --  the main unit, and it has a semantic dependence on
700                         --  it, the inlining cannot take place to prevent an
701                         --  elaboration circularity. The desired body is not
702                         --  analyzed yet, to prevent the completion of Taft
703                         --  amendment types that would lead to elaboration
704                         --  circularities in gigi.
705
706                         declare
707                            U_Id      : constant Entity_Id :=
708                                          Defining_Entity (Unit (Comp_Unit));
709                            Body_Unit : constant Node_Id :=
710                                          Library_Unit (Comp_Unit);
711                            Item      : Node_Id;
712
713                         begin
714                            Item := First (Context_Items (Body_Unit));
715                            while Present (Item) loop
716                               if Nkind (Item) = N_With_Clause
717                                 and then
718                                   Is_Ancestor_Of_Main (U_Id, Name (Item))
719                               then
720                                  Set_Is_Inlined (U_Id, False);
721                                  exit;
722                               end if;
723
724                               Next (Item);
725                            end loop;
726
727                            --  If no suspicious with_clauses, analyze the body.
728
729                            if Is_Inlined (U_Id) then
730                               Semantics (Body_Unit);
731                            end if;
732                         end;
733                      end if;
734                   end if;
735                end;
736             end if;
737
738             J := J + 1;
739          end loop;
740
741          --  The analysis of required bodies may have produced additional
742          --  generic instantiations. To obtain further inlining, we perform
743          --  another round of generic body instantiations. Establishing a
744          --  fully recursive loop between inlining and generic instantiations
745          --  is unlikely to yield more than this one additional pass.
746
747          Instantiate_Bodies;
748
749          --  The list of inlined subprograms is an overestimate, because it
750          --  includes inlined functions called from functions that are compiled
751          --  as part of an inlined package, but are not themselves called. An
752          --  accurate computation of just those subprograms that are needed
753          --  requires that we perform a transitive closure over the call graph,
754          --  starting from calls in the main program. Here we do one step of
755          --  the inverse transitive closure, and reset the Is_Called flag on
756          --  subprograms all of whose callers are not.
757
758          for Index in Inlined.First .. Inlined.Last loop
759             S := Inlined.Table (Index).First_Succ;
760
761             if S /= No_Succ
762               and then not Inlined.Table (Index).Main_Call
763             then
764                Set_Is_Called (Inlined.Table (Index).Name, False);
765
766                while S /= No_Succ loop
767                   if Is_Called
768                     (Inlined.Table (Successors.Table (S).Subp).Name)
769                    or else Inlined.Table (Successors.Table (S).Subp).Main_Call
770                   then
771                      Set_Is_Called (Inlined.Table (Index).Name);
772                      exit;
773                   end if;
774
775                   S := Successors.Table (S).Next;
776                end loop;
777             end if;
778          end loop;
779
780          --  Now that the units are compiled, chain the subprograms within
781          --  that are called and inlined. Produce list of inlined subprograms
782          --  sorted in  topological order. Start with all subprograms that
783          --  have no prerequisites, i.e. inlined subprograms that do not call
784          --  other inlined subprograms.
785
786          for Index in Inlined.First .. Inlined.Last loop
787
788             if Is_Called (Inlined.Table (Index).Name)
789               and then Inlined.Table (Index).Count = 0
790               and then not Inlined.Table (Index).Listed
791             then
792                Add_Inlined_Subprogram (Index);
793             end if;
794          end loop;
795
796          --  Because Add_Inlined_Subprogram treats recursively nodes that have
797          --  no prerequisites left, at the end of the loop all subprograms
798          --  must have been listed. If there are any unlisted subprograms
799          --  left, there must be some recursive chains that cannot be inlined.
800
801          for Index in Inlined.First .. Inlined.Last loop
802             if Is_Called (Inlined.Table (Index).Name)
803               and then Inlined.Table (Index).Count /= 0
804               and then not Is_Predefined_File_Name
805                 (Unit_File_Name
806                   (Get_Source_Unit (Inlined.Table (Index).Name)))
807             then
808                Error_Msg_N
809                  ("& cannot be inlined?", Inlined.Table (Index).Name);
810
811                --  A warning on the first one might be sufficient ???
812             end if;
813          end loop;
814
815          Pop_Scope;
816       end if;
817    end Analyze_Inlined_Bodies;
818
819    -----------------------------
820    -- Check_Body_For_Inlining --
821    -----------------------------
822
823    procedure Check_Body_For_Inlining (N : Node_Id; P : Entity_Id) is
824       Bname : Unit_Name_Type;
825       E     : Entity_Id;
826       OK    : Boolean;
827
828    begin
829       if Is_Compilation_Unit (P)
830         and then not Is_Generic_Instance (P)
831       then
832          Bname := Get_Body_Name (Get_Unit_Name (Unit (N)));
833
834          E := First_Entity (P);
835          while Present (E) loop
836             if Has_Pragma_Inline_Always (E)
837               or else (Front_End_Inlining and then Has_Pragma_Inline (E))
838             then
839                if not Is_Loaded (Bname) then
840                   Load_Needed_Body (N, OK);
841
842                   if OK then
843
844                      --  Check we are not trying to inline a parent whose body
845                      --  depends on a child, when we are compiling the body of
846                      --  the child. Otherwise we have a potential elaboration
847                      --  circularity with inlined subprograms and with
848                      --  Taft-Amendment types.
849
850                      declare
851                         Comp        : Node_Id;      --  Body just compiled
852                         Child_Spec  : Entity_Id;    --  Spec of main unit
853                         Ent         : Entity_Id;    --  For iteration
854                         With_Clause : Node_Id;      --  Context of body.
855
856                      begin
857                         if Nkind (Unit (Cunit (Main_Unit))) = N_Package_Body
858                           and then Present (Body_Entity (P))
859                         then
860                            Child_Spec :=
861                              Defining_Entity
862                                ((Unit (Library_Unit (Cunit (Main_Unit)))));
863
864                            Comp :=
865                              Parent (Unit_Declaration_Node (Body_Entity (P)));
866
867                            --  Check whether the context of the body just
868                            --  compiled includes a child of itself, and that
869                            --  child is the spec of the main compilation.
870
871                            With_Clause := First (Context_Items (Comp));
872                            while Present (With_Clause) loop
873                               if Nkind (With_Clause) = N_With_Clause
874                                 and then
875                                   Scope (Entity (Name (With_Clause))) = P
876                                 and then
877                                   Entity (Name (With_Clause)) = Child_Spec
878                               then
879                                  Error_Msg_Node_2 := Child_Spec;
880                                  Error_Msg_NE
881                                    ("body of & depends on child unit&?",
882                                       With_Clause, P);
883                                  Error_Msg_N
884                                    ("\subprograms in body cannot be inlined?",
885                                       With_Clause);
886
887                                  --  Disable further inlining from this unit,
888                                  --  and keep Taft-amendment types incomplete.
889
890                                  Ent := First_Entity (P);
891                                  while Present (Ent) loop
892                                     if Is_Type (Ent)
893                                        and then Has_Completion_In_Body (Ent)
894                                     then
895                                        Set_Full_View (Ent, Empty);
896
897                                     elsif Is_Subprogram (Ent) then
898                                        Set_Is_Inlined (Ent, False);
899                                     end if;
900
901                                     Next_Entity (Ent);
902                                  end loop;
903
904                                  return;
905                               end if;
906
907                               Next (With_Clause);
908                            end loop;
909                         end if;
910                      end;
911
912                   elsif Ineffective_Inline_Warnings then
913                      Error_Msg_Unit_1 := Bname;
914                      Error_Msg_N
915                        ("unable to inline subprograms defined in $?", P);
916                      Error_Msg_N ("\body not found?", P);
917                      return;
918                   end if;
919                end if;
920
921                return;
922             end if;
923
924             Next_Entity (E);
925          end loop;
926       end if;
927    end Check_Body_For_Inlining;
928
929    --------------------
930    -- Cleanup_Scopes --
931    --------------------
932
933    procedure Cleanup_Scopes is
934       Elmt : Elmt_Id;
935       Decl : Node_Id;
936       Scop : Entity_Id;
937
938    begin
939       Elmt := First_Elmt (To_Clean);
940       while Present (Elmt) loop
941          Scop := Node (Elmt);
942
943          if Ekind (Scop) = E_Entry then
944             Scop := Protected_Body_Subprogram (Scop);
945
946          elsif Is_Subprogram (Scop)
947            and then Is_Protected_Type (Scope (Scop))
948            and then Present (Protected_Body_Subprogram (Scop))
949          then
950             --  If a protected operation contains an instance, its
951             --  cleanup operations have been delayed, and the subprogram
952             --  has been rewritten in the expansion of the enclosing
953             --  protected body. It is the corresponding subprogram that
954             --  may require the cleanup operations, so propagate the
955             --  information that triggers cleanup activity.
956
957             Set_Uses_Sec_Stack
958               (Protected_Body_Subprogram (Scop),
959                 Uses_Sec_Stack (Scop));
960             Set_Finalization_Chain_Entity
961               (Protected_Body_Subprogram (Scop),
962                 Finalization_Chain_Entity (Scop));
963             Scop := Protected_Body_Subprogram (Scop);
964          end if;
965
966          if Ekind (Scop) = E_Block then
967             Decl := Parent (Block_Node (Scop));
968
969          else
970             Decl := Unit_Declaration_Node (Scop);
971
972             if Nkind (Decl) = N_Subprogram_Declaration
973               or else Nkind (Decl) = N_Task_Type_Declaration
974               or else Nkind (Decl) = N_Subprogram_Body_Stub
975             then
976                Decl := Unit_Declaration_Node (Corresponding_Body (Decl));
977             end if;
978          end if;
979
980          Push_Scope (Scop);
981          Expand_Cleanup_Actions (Decl);
982          End_Scope;
983
984          Elmt := Next_Elmt (Elmt);
985       end loop;
986    end Cleanup_Scopes;
987
988    --------------------------
989    -- Get_Code_Unit_Entity --
990    --------------------------
991
992    function Get_Code_Unit_Entity (E : Entity_Id) return Entity_Id is
993    begin
994       return Cunit_Entity (Get_Code_Unit (E));
995    end Get_Code_Unit_Entity;
996
997    --------------------------
998    -- Has_Initialized_Type --
999    --------------------------
1000
1001    function Has_Initialized_Type (E : Entity_Id) return Boolean is
1002       E_Body : constant Node_Id := Get_Subprogram_Body (E);
1003       Decl   : Node_Id;
1004
1005    begin
1006       if No (E_Body) then        --  imported subprogram
1007          return False;
1008
1009       else
1010          Decl := First (Declarations (E_Body));
1011          while Present (Decl) loop
1012
1013             if Nkind (Decl) = N_Full_Type_Declaration
1014               and then Present (Init_Proc (Defining_Identifier (Decl)))
1015             then
1016                return True;
1017             end if;
1018
1019             Next (Decl);
1020          end loop;
1021       end if;
1022
1023       return False;
1024    end Has_Initialized_Type;
1025
1026    ----------------
1027    -- Initialize --
1028    ----------------
1029
1030    procedure Initialize is
1031    begin
1032       Analyzing_Inlined_Bodies := False;
1033       Pending_Descriptor.Init;
1034       Pending_Instantiations.Init;
1035       Inlined_Bodies.Init;
1036       Successors.Init;
1037       Inlined.Init;
1038
1039       for J in Hash_Headers'Range loop
1040          Hash_Headers (J) := No_Subp;
1041       end loop;
1042    end Initialize;
1043
1044    ------------------------
1045    -- Instantiate_Bodies --
1046    ------------------------
1047
1048    --  Generic bodies contain all the non-local references, so an
1049    --  instantiation does not need any more context than Standard
1050    --  itself, even if the instantiation appears in an inner scope.
1051    --  Generic associations have verified that the contract model is
1052    --  satisfied, so that any error that may occur in the analysis of
1053    --  the body is an internal error.
1054
1055    procedure Instantiate_Bodies is
1056       J    : Int;
1057       Info : Pending_Body_Info;
1058
1059    begin
1060       if Serious_Errors_Detected = 0 then
1061
1062          Expander_Active := (Operating_Mode = Opt.Generate_Code);
1063          Push_Scope (Standard_Standard);
1064          To_Clean := New_Elmt_List;
1065
1066          if Is_Generic_Unit (Cunit_Entity (Main_Unit)) then
1067             Start_Generic;
1068          end if;
1069
1070          --  A body instantiation may generate additional instantiations, so
1071          --  the following loop must scan to the end of a possibly expanding
1072          --  set (that's why we can't simply use a FOR loop here).
1073
1074          J := 0;
1075          while J <= Pending_Instantiations.Last
1076            and then Serious_Errors_Detected = 0
1077          loop
1078             Info := Pending_Instantiations.Table (J);
1079
1080             --  If the instantiation node is absent, it has been removed
1081             --  as part of unreachable code.
1082
1083             if No (Info.Inst_Node) then
1084                null;
1085
1086             elsif Nkind (Info.Act_Decl) = N_Package_Declaration then
1087                Instantiate_Package_Body (Info);
1088                Add_Scope_To_Clean (Defining_Entity (Info.Act_Decl));
1089
1090             else
1091                Instantiate_Subprogram_Body (Info);
1092             end if;
1093
1094             J := J + 1;
1095          end loop;
1096
1097          --  Reset the table of instantiations. Additional instantiations
1098          --  may be added through inlining, when additional bodies are
1099          --  analyzed.
1100
1101          Pending_Instantiations.Init;
1102
1103          --  We can now complete the cleanup actions of scopes that contain
1104          --  pending instantiations (skipped for generic units, since we
1105          --  never need any cleanups in generic units).
1106          --  pending instantiations.
1107
1108          if Expander_Active
1109            and then not Is_Generic_Unit (Main_Unit_Entity)
1110          then
1111             Cleanup_Scopes;
1112          elsif Is_Generic_Unit (Cunit_Entity (Main_Unit)) then
1113             End_Generic;
1114          end if;
1115
1116          Pop_Scope;
1117       end if;
1118    end Instantiate_Bodies;
1119
1120    ---------------
1121    -- Is_Nested --
1122    ---------------
1123
1124    function Is_Nested (E : Entity_Id) return Boolean is
1125       Scop : Entity_Id;
1126
1127    begin
1128       Scop := Scope (E);
1129       while Scop /= Standard_Standard loop
1130          if Ekind (Scop) in Subprogram_Kind then
1131             return True;
1132
1133          elsif Ekind (Scop) = E_Task_Type
1134            or else Ekind (Scop) = E_Entry
1135            or else Ekind (Scop) = E_Entry_Family then
1136             return True;
1137          end if;
1138
1139          Scop := Scope (Scop);
1140       end loop;
1141
1142       return False;
1143    end Is_Nested;
1144
1145    ----------
1146    -- Lock --
1147    ----------
1148
1149    procedure Lock is
1150    begin
1151       Pending_Instantiations.Locked := True;
1152       Inlined_Bodies.Locked := True;
1153       Successors.Locked := True;
1154       Inlined.Locked := True;
1155       Pending_Instantiations.Release;
1156       Inlined_Bodies.Release;
1157       Successors.Release;
1158       Inlined.Release;
1159    end Lock;
1160
1161    --------------------------
1162    -- Remove_Dead_Instance --
1163    --------------------------
1164
1165    procedure Remove_Dead_Instance (N : Node_Id) is
1166       J : Int;
1167
1168    begin
1169       J := 0;
1170       while J <= Pending_Instantiations.Last loop
1171          if Pending_Instantiations.Table (J).Inst_Node = N then
1172             Pending_Instantiations.Table (J).Inst_Node := Empty;
1173             return;
1174          end if;
1175
1176          J := J + 1;
1177       end loop;
1178    end Remove_Dead_Instance;
1179
1180    ------------------------
1181    -- Scope_In_Main_Unit --
1182    ------------------------
1183
1184    function Scope_In_Main_Unit (Scop : Entity_Id) return Boolean is
1185       Comp : constant Node_Id := Cunit (Get_Code_Unit (Scop));
1186
1187    begin
1188       --  Check whether the scope of the subprogram to inline is within the
1189       --  main unit or within its spec. In either case there are no additional
1190       --  bodies to process. If the subprogram appears in a parent of the
1191       --  current unit, the check on whether inlining is possible is done in
1192       --  Analyze_Inlined_Bodies.
1193
1194       return
1195         Comp = Cunit (Main_Unit)
1196           or else Comp = Library_Unit (Cunit (Main_Unit));
1197    end Scope_In_Main_Unit;
1198
1199 end Inline;