[ThinLTO] Enable iterative importing in FunctionImport pass
[oota-llvm.git] / lib / Transforms / IPO / FunctionImport.cpp
1 //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements Function import based on summaries.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Transforms/IPO/FunctionImport.h"
15
16 #include "llvm/ADT/StringSet.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/DiagnosticPrinter.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IRReader/IRReader.h"
22 #include "llvm/Linker/Linker.h"
23 #include "llvm/Object/FunctionIndexObjectFile.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/SourceMgr.h"
27 using namespace llvm;
28
29 #define DEBUG_TYPE "function-import"
30
31 // Load lazily a module from \p FileName in \p Context.
32 static std::unique_ptr<Module> loadFile(const std::string &FileName,
33                                         LLVMContext &Context) {
34   SMDiagnostic Err;
35   DEBUG(dbgs() << "Loading '" << FileName << "'\n");
36   std::unique_ptr<Module> Result = getLazyIRFileModule(FileName, Err, Context);
37   if (!Result) {
38     Err.print("function-import", errs());
39     return nullptr;
40   }
41
42   Result->materializeMetadata();
43   UpgradeDebugInfo(*Result);
44
45   return Result;
46 }
47
48 // Get a Module for \p FileName from the cache, or load it lazily.
49 Module &FunctionImporter::getOrLoadModule(StringRef FileName) {
50   auto &Module = ModuleMap[FileName];
51   if (!Module)
52     Module = loadFile(FileName, Context);
53   return *Module;
54 }
55
56 // Automatically import functions in Module \p M based on the summaries index.
57 //
58 // The current implementation imports every called functions that exists in the
59 // summaries index.
60 bool FunctionImporter::importFunctions(Module &M) {
61   assert(&Context == &M.getContext());
62
63   bool Changed = false;
64
65   /// First step is collecting the called functions and the one defined in this
66   /// module.
67   StringSet<> CalledFunctions;
68   for (auto &F : M) {
69     if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
70       continue;
71     for (auto &BB : F) {
72       for (auto &I : BB) {
73         if (isa<CallInst>(I)) {
74           DEBUG(dbgs() << "Found a call: '" << I << "'\n");
75           auto CalledFunction = cast<CallInst>(I).getCalledFunction();
76           if (CalledFunction && CalledFunction->hasName() &&
77               CalledFunction->isDeclaration())
78             CalledFunctions.insert(CalledFunction->getName());
79         }
80       }
81     }
82   }
83
84   /// Second step: for every call to an external function, try to import it.
85
86   // Linker that will be used for importing function
87   Linker L(&M, DiagnosticHandler);
88
89   /// Insert initial called function set in a worklist, so that we can add
90   /// transively called functions when importing.
91   SmallVector<StringRef, 64> Worklist;
92   for (auto &CalledFunction : CalledFunctions)
93     Worklist.push_back(CalledFunction.first());
94
95   while (!Worklist.empty()) {
96     auto CalledFunctionName = Worklist.pop_back_val();
97     DEBUG(dbgs() << "Process import for " << CalledFunctionName << "\n");
98
99     // Try to get a summary for this function call.
100     auto InfoList = Index.findFunctionInfoList(CalledFunctionName);
101     if (InfoList == Index.end()) {
102       DEBUG(dbgs() << "No summary for " << CalledFunctionName
103                    << " Ignoring.\n");
104       continue;
105     }
106     assert(!InfoList->second.empty() && "No summary, error at import?");
107
108     // Comdat can have multiple entries, FIXME: what do we do with them?
109     auto &Info = InfoList->second[0];
110     assert(Info && "Nullptr in list, error importing summaries?\n");
111
112     auto *Summary = Info->functionSummary();
113     if (!Summary) {
114       // FIXME: in case we are lazyloading summaries, we can do it now.
115       dbgs() << "Missing summary for  " << CalledFunctionName
116              << ", error at import?\n";
117       llvm_unreachable("Missing summary");
118     }
119
120     //
121     // No profitability notion right now, just import all the time...
122     //
123
124     // Get the module path from the summary.
125     auto FileName = Summary->modulePath();
126     DEBUG(dbgs() << "Importing " << CalledFunctionName << " from " << FileName
127                  << "\n");
128
129     // Get the module for the import (potentially from the cache).
130     auto &Module = getOrLoadModule(FileName);
131
132     // The function that we will import!
133     GlobalValue *SGV = Module.getNamedValue(CalledFunctionName);
134     StringRef ImportFunctionName = CalledFunctionName;
135     if (!SGV) {
136       // Might be local in source Module, promoted/renamed in dest Module M.
137       std::pair<StringRef, StringRef> Split =
138           CalledFunctionName.split(".llvm.");
139       SGV = Module.getNamedValue(Split.first);
140 #ifndef NDEBUG
141       // Assert that Split.second is module id
142       uint64_t ModuleId;
143       assert(!Split.second.getAsInteger(10, ModuleId));
144       assert(ModuleId == Index.getModuleId(FileName));
145 #endif
146     }
147     Function *F = dyn_cast<Function>(SGV);
148     if (!F && isa<GlobalAlias>(SGV)) {
149       auto *SGA = dyn_cast<GlobalAlias>(SGV);
150       F = dyn_cast<Function>(SGA->getBaseObject());
151       ImportFunctionName = F->getName();
152     }
153     if (!F) {
154       errs() << "Can't load function '" << CalledFunctionName << "' in Module '"
155              << FileName << "', error in the summary?\n";
156       llvm_unreachable("Can't load function in Module");
157     }
158
159     // We cannot import weak_any functions/aliases without possibly affecting
160     // the order they are seen and selected by the linker, changing program
161     // semantics.
162     if (SGV->hasWeakAnyLinkage()) {
163       DEBUG(dbgs() << "Ignoring import request for weak-any "
164                    << (isa<Function>(SGV) ? "function " : "alias ")
165                    << CalledFunctionName << " from " << FileName << "\n");
166       continue;
167     }
168
169     // Link in the specified function.
170     if (L.linkInModule(&Module, Linker::Flags::None, &Index, F))
171       report_fatal_error("Function Import: link error");
172
173     // Process the newly imported function and add callees to the worklist.
174     GlobalValue *NewGV = M.getNamedValue(ImportFunctionName);
175     assert(NewGV);
176     Function *NewF = dyn_cast<Function>(NewGV);
177     assert(NewF);
178
179     for (auto &BB : *NewF) {
180       for (auto &I : BB) {
181         if (isa<CallInst>(I)) {
182           DEBUG(dbgs() << "Found a call: '" << I << "'\n");
183           auto CalledFunction = cast<CallInst>(I).getCalledFunction();
184           // Insert any new external calls that have not already been
185           // added to set/worklist.
186           if (CalledFunction && CalledFunction->hasName() &&
187               CalledFunction->isDeclaration() &&
188               !CalledFunctions.count(CalledFunction->getName())) {
189             CalledFunctions.insert(CalledFunction->getName());
190             Worklist.push_back(CalledFunction->getName());
191           }
192         }
193       }
194     }
195
196     Changed = true;
197   }
198   return Changed;
199 }
200
201 /// Summary file to use for function importing when using -function-import from
202 /// the command line.
203 static cl::opt<std::string>
204     SummaryFile("summary-file",
205                 cl::desc("The summary file to use for function importing."));
206
207 static void diagnosticHandler(const DiagnosticInfo &DI) {
208   raw_ostream &OS = errs();
209   DiagnosticPrinterRawOStream DP(OS);
210   DI.print(DP);
211   OS << '\n';
212 }
213
214 /// Parse the function index out of an IR file and return the function
215 /// index object if found, or nullptr if not.
216 static std::unique_ptr<FunctionInfoIndex>
217 getFunctionIndexForFile(StringRef Path, std::string &Error,
218                         DiagnosticHandlerFunction DiagnosticHandler) {
219   std::unique_ptr<MemoryBuffer> Buffer;
220   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
221       MemoryBuffer::getFile(Path);
222   if (std::error_code EC = BufferOrErr.getError()) {
223     Error = EC.message();
224     return nullptr;
225   }
226   Buffer = std::move(BufferOrErr.get());
227   ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
228       object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
229                                               DiagnosticHandler);
230   if (std::error_code EC = ObjOrErr.getError()) {
231     Error = EC.message();
232     return nullptr;
233   }
234   return (*ObjOrErr)->takeIndex();
235 }
236
237 /// Pass that performs cross-module function import provided a summary file.
238 class FunctionImportPass : public ModulePass {
239
240 public:
241   /// Pass identification, replacement for typeid
242   static char ID;
243
244   explicit FunctionImportPass() : ModulePass(ID) {}
245
246   bool runOnModule(Module &M) override {
247     if (SummaryFile.empty()) {
248       report_fatal_error("error: -function-import requires -summary-file\n");
249     }
250     std::string Error;
251     std::unique_ptr<FunctionInfoIndex> Index =
252         getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
253     if (!Index) {
254       errs() << "Error loading file '" << SummaryFile << "': " << Error << "\n";
255       return false;
256     }
257
258     // Perform the import now.
259     FunctionImporter Importer(M.getContext(), *Index, diagnosticHandler);
260     return Importer.importFunctions(M);
261
262     return false;
263   }
264 };
265
266 char FunctionImportPass::ID = 0;
267 INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
268                       "Summary Based Function Import", false, false)
269 INITIALIZE_PASS_END(FunctionImportPass, "function-import",
270                     "Summary Based Function Import", false, false)
271
272 namespace llvm {
273 Pass *createFunctionImportPass() { return new FunctionImportPass(); }
274 }