OSDN Git Service

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