c9874fc371496aa091bcad484498a34fef96d186
[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
28 #include <map>
29
30 using namespace llvm;
31
32 #define DEBUG_TYPE "function-import"
33
34 /// Limit on instruction count of imported functions.
35 static cl::opt<unsigned> ImportInstrLimit(
36     "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
37     cl::desc("Only import functions with less than N instructions"));
38
39 // Load lazily a module from \p FileName in \p Context.
40 static std::unique_ptr<Module> loadFile(const std::string &FileName,
41                                         LLVMContext &Context) {
42   SMDiagnostic Err;
43   DEBUG(dbgs() << "Loading '" << FileName << "'\n");
44   std::unique_ptr<Module> Result = getLazyIRFileModule(FileName, Err, Context);
45   if (!Result) {
46     Err.print("function-import", errs());
47     return nullptr;
48   }
49
50   Result->materializeMetadata();
51   UpgradeDebugInfo(*Result);
52
53   return Result;
54 }
55
56 namespace {
57 /// Helper to load on demand a Module from file and cache it for subsequent
58 /// queries. It can be used with the FunctionImporter.
59 class ModuleLazyLoaderCache {
60   /// Cache of lazily loaded module for import.
61   StringMap<std::unique_ptr<Module>> ModuleMap;
62
63   /// Retrieve a Module from the cache or lazily load it on demand.
64   std::function<std::unique_ptr<Module>(StringRef FileName)> createLazyModule;
65
66 public:
67   /// Create the loader, Module will be initialized in \p Context.
68   ModuleLazyLoaderCache(std::function<
69       std::unique_ptr<Module>(StringRef FileName)> createLazyModule)
70       : createLazyModule(createLazyModule) {}
71
72   /// Retrieve a Module from the cache or lazily load it on demand.
73   Module &operator()(StringRef FileName);
74 };
75
76 // Get a Module for \p FileName from the cache, or load it lazily.
77 Module &ModuleLazyLoaderCache::operator()(StringRef Identifier) {
78   auto &Module = ModuleMap[Identifier];
79   if (!Module)
80     Module = createLazyModule(Identifier);
81   return *Module;
82 }
83 } // anonymous namespace
84
85 /// Walk through the instructions in \p F looking for external
86 /// calls not already in the \p CalledFunctions set. If any are
87 /// found they are added to the \p Worklist for importing.
88 static void findExternalCalls(const Module &DestModule, Function &F,
89                               const FunctionInfoIndex &Index,
90                               StringSet<> &CalledFunctions,
91                               SmallVector<StringRef, 64> &Worklist) {
92   // We need to suffix internal function calls imported from other modules,
93   // prepare the suffix ahead of time.
94   StringRef Suffix;
95   if (F.getParent() != &DestModule)
96     Suffix =
97         (Twine(".llvm.") +
98          Twine(Index.getModuleId(F.getParent()->getModuleIdentifier()))).str();
99
100   for (auto &BB : F) {
101     for (auto &I : BB) {
102       if (isa<CallInst>(I)) {
103         auto CalledFunction = cast<CallInst>(I).getCalledFunction();
104         // Insert any new external calls that have not already been
105         // added to set/worklist.
106         if (!CalledFunction || !CalledFunction->hasName())
107           continue;
108         // Ignore intrinsics early
109         if (CalledFunction->isIntrinsic()) {
110           assert(CalledFunction->getIntrinsicID() != 0);
111           continue;
112         }
113         auto ImportedName = CalledFunction->getName();
114         auto Renamed = (ImportedName + Suffix).str();
115         // Rename internal functions
116         if (CalledFunction->hasInternalLinkage()) {
117           ImportedName = Renamed;
118         }
119         auto It = CalledFunctions.insert(ImportedName);
120         if (!It.second) {
121           // This is a call to a function we already considered, skip.
122           continue;
123         }
124         // Ignore functions already present in the destination module
125         auto *SrcGV = DestModule.getNamedValue(ImportedName);
126         if (SrcGV) {
127           assert(isa<Function>(SrcGV) && "Name collision during import");
128           if (!cast<Function>(SrcGV)->isDeclaration()) {
129             DEBUG(dbgs() << DestModule.getModuleIdentifier() << "Ignoring "
130                          << ImportedName << " already in DestinationModule\n");
131             continue;
132           }
133         }
134
135         Worklist.push_back(It.first->getKey());
136         DEBUG(dbgs() << DestModule.getModuleIdentifier()
137                      << " Adding callee for : " << ImportedName << " : "
138                      << F.getName() << "\n");
139       }
140     }
141   }
142 }
143
144 // Helper function: given a worklist and an index, will process all the worklist
145 // and decide what to import based on the summary information.
146 //
147 // Nothing is actually imported, functions are materialized in their source
148 // module and analyzed there.
149 //
150 // \p ModuleToFunctionsToImportMap is filled with the set of Function to import
151 // per Module.
152 static void GetImportList(
153     Module &DestModule, SmallVector<StringRef, 64> &Worklist,
154     StringSet<> &CalledFunctions,
155     std::map<StringRef, std::pair<Module *, DenseSet<const GlobalValue *>>> &
156         ModuleToFunctionsToImportMap,
157     const FunctionInfoIndex &Index, ModuleLazyLoaderCache &ModuleLoaderCache) {
158   while (!Worklist.empty()) {
159     auto CalledFunctionName = Worklist.pop_back_val();
160     DEBUG(dbgs() << DestModule.getModuleIdentifier() << "Process import for "
161                  << CalledFunctionName << "\n");
162
163     // Try to get a summary for this function call.
164     auto InfoList = Index.findFunctionInfoList(CalledFunctionName);
165     if (InfoList == Index.end()) {
166       DEBUG(dbgs() << DestModule.getModuleIdentifier() << "No summary for "
167                    << CalledFunctionName << " Ignoring.\n");
168       continue;
169     }
170     assert(!InfoList->second.empty() && "No summary, error at import?");
171
172     // Comdat can have multiple entries, FIXME: what do we do with them?
173     auto &Info = InfoList->second[0];
174     assert(Info && "Nullptr in list, error importing summaries?\n");
175
176     auto *Summary = Info->functionSummary();
177     if (!Summary) {
178       // FIXME: in case we are lazyloading summaries, we can do it now.
179       DEBUG(dbgs() << DestModule.getModuleIdentifier()
180                    << " Missing summary for  " << CalledFunctionName
181                    << ", error at import?\n");
182       llvm_unreachable("Missing summary");
183     }
184
185     if (Summary->instCount() > ImportInstrLimit) {
186       DEBUG(dbgs() << DestModule.getModuleIdentifier() << " Skip import of "
187                    << CalledFunctionName << " with " << Summary->instCount()
188                    << " instructions (limit " << ImportInstrLimit << ")\n");
189       continue;
190     }
191
192     // Get the module path from the summary.
193     auto ModuleIdentifier = Summary->modulePath();
194     DEBUG(dbgs() << DestModule.getModuleIdentifier() << " Importing "
195                  << CalledFunctionName << " from " << ModuleIdentifier << "\n");
196
197     auto &SrcModule = ModuleLoaderCache(ModuleIdentifier);
198
199     // The function that we will import!
200     GlobalValue *SGV = SrcModule.getNamedValue(CalledFunctionName);
201
202     if (!SGV) {
203       // The destination module is referencing function using their renamed name
204       // when importing a function that was originally local in the source
205       // module. The source module we have might not have been renamed so we try
206       // to remove the suffix added during the renaming to recover the original
207       // name in the source module.
208       std::pair<StringRef, StringRef> Split =
209           CalledFunctionName.split(".llvm.");
210       SGV = SrcModule.getNamedValue(Split.first);
211       assert(SGV && "Can't find function to import in source module");
212     }
213     if (!SGV) {
214       report_fatal_error(Twine("Can't load function '") + CalledFunctionName +
215                          "' in Module '" + SrcModule.getModuleIdentifier() +
216                          "', error in the summary?\n");
217     }
218
219     Function *F = dyn_cast<Function>(SGV);
220     if (!F && isa<GlobalAlias>(SGV)) {
221       auto *SGA = dyn_cast<GlobalAlias>(SGV);
222       F = dyn_cast<Function>(SGA->getBaseObject());
223       CalledFunctionName = F->getName();
224     }
225     assert(F && "Imported Function is ... not a Function");
226
227     // We cannot import weak_any functions/aliases without possibly affecting
228     // the order they are seen and selected by the linker, changing program
229     // semantics.
230     if (SGV->hasWeakAnyLinkage()) {
231       DEBUG(dbgs() << DestModule.getModuleIdentifier()
232                    << " Ignoring import request for weak-any "
233                    << (isa<Function>(SGV) ? "function " : "alias ")
234                    << CalledFunctionName << " from "
235                    << SrcModule.getModuleIdentifier() << "\n");
236       continue;
237     }
238
239     // Add the function to the import list
240     auto &Entry = ModuleToFunctionsToImportMap[SrcModule.getModuleIdentifier()];
241     Entry.first = &SrcModule;
242     Entry.second.insert(F);
243
244     // Process the newly imported functions and add callees to the worklist.
245     F->materialize();
246     findExternalCalls(DestModule, *F, Index, CalledFunctions, Worklist);
247   }
248 }
249
250 // Automatically import functions in Module \p DestModule based on the summaries
251 // index.
252 //
253 // The current implementation imports every called functions that exists in the
254 // summaries index.
255 bool FunctionImporter::importFunctions(Module &DestModule) {
256   DEBUG(dbgs() << "Starting import for Module "
257                << DestModule.getModuleIdentifier() << "\n");
258   unsigned ImportedCount = 0;
259
260   /// First step is collecting the called external functions.
261   StringSet<> CalledFunctions;
262   SmallVector<StringRef, 64> Worklist;
263   for (auto &F : DestModule) {
264     if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
265       continue;
266     findExternalCalls(DestModule, F, Index, CalledFunctions, Worklist);
267   }
268   if (Worklist.empty())
269     return false;
270
271   /// Second step: for every call to an external function, try to import it.
272
273   // Linker that will be used for importing function
274   Linker TheLinker(DestModule, DiagnosticHandler);
275
276   // Map of Module -> List of Function to import from the Module
277   std::map<StringRef, std::pair<Module *, DenseSet<const GlobalValue *>>>
278       ModuleToFunctionsToImportMap;
279
280   // Analyze the summaries and get the list of functions to import by
281   // populating ModuleToFunctionsToImportMap
282   ModuleLazyLoaderCache ModuleLoaderCache(ModuleLoader);
283   GetImportList(DestModule, Worklist, CalledFunctions,
284                 ModuleToFunctionsToImportMap, Index, ModuleLoaderCache);
285   assert(Worklist.empty() && "Worklist hasn't been flushed in GetImportList");
286
287   // Do the actual import of functions now, one Module at a time
288   for (auto &FunctionsToImportPerModule : ModuleToFunctionsToImportMap) {
289     // Get the module for the import
290     auto &FunctionsToImport = FunctionsToImportPerModule.second.second;
291     auto *SrcModule = FunctionsToImportPerModule.second.first;
292     assert(&DestModule.getContext() == &SrcModule->getContext() &&
293            "Context mismatch");
294
295     // Link in the specified functions.
296     if (TheLinker.linkInModule(*SrcModule, Linker::Flags::None, &Index,
297                                &FunctionsToImport))
298       report_fatal_error("Function Import: link error");
299
300     ImportedCount += FunctionsToImport.size();
301   }
302   DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
303                << DestModule.getModuleIdentifier() << "\n");
304   return ImportedCount;
305 }
306
307 /// Summary file to use for function importing when using -function-import from
308 /// the command line.
309 static cl::opt<std::string>
310     SummaryFile("summary-file",
311                 cl::desc("The summary file to use for function importing."));
312
313 static void diagnosticHandler(const DiagnosticInfo &DI) {
314   raw_ostream &OS = errs();
315   DiagnosticPrinterRawOStream DP(OS);
316   DI.print(DP);
317   OS << '\n';
318 }
319
320 /// Parse the function index out of an IR file and return the function
321 /// index object if found, or nullptr if not.
322 static std::unique_ptr<FunctionInfoIndex>
323 getFunctionIndexForFile(StringRef Path, std::string &Error,
324                         DiagnosticHandlerFunction DiagnosticHandler) {
325   std::unique_ptr<MemoryBuffer> Buffer;
326   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
327       MemoryBuffer::getFile(Path);
328   if (std::error_code EC = BufferOrErr.getError()) {
329     Error = EC.message();
330     return nullptr;
331   }
332   Buffer = std::move(BufferOrErr.get());
333   ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
334       object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
335                                               DiagnosticHandler);
336   if (std::error_code EC = ObjOrErr.getError()) {
337     Error = EC.message();
338     return nullptr;
339   }
340   return (*ObjOrErr)->takeIndex();
341 }
342
343 /// Pass that performs cross-module function import provided a summary file.
344 class FunctionImportPass : public ModulePass {
345   /// Optional function summary index to use for importing, otherwise
346   /// the summary-file option must be specified.
347   const FunctionInfoIndex *Index;
348
349 public:
350   /// Pass identification, replacement for typeid
351   static char ID;
352
353   /// Specify pass name for debug output
354   const char *getPassName() const override {
355     return "Function Importing";
356   }
357
358   explicit FunctionImportPass(const FunctionInfoIndex *Index = nullptr)
359       : ModulePass(ID), Index(Index) {}
360
361   bool runOnModule(Module &M) override {
362     if (SummaryFile.empty() && !Index)
363       report_fatal_error("error: -function-import requires -summary-file or "
364                          "file from frontend\n");
365     std::unique_ptr<FunctionInfoIndex> IndexPtr;
366     if (!SummaryFile.empty()) {
367       if (Index)
368         report_fatal_error("error: -summary-file and index from frontend\n");
369       std::string Error;
370       IndexPtr = getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
371       if (!IndexPtr) {
372         errs() << "Error loading file '" << SummaryFile << "': " << Error
373                << "\n";
374         return false;
375       }
376       Index = IndexPtr.get();
377     }
378
379     // Perform the import now.
380     auto ModuleLoader = [&M](StringRef Identifier) {
381       return loadFile(Identifier, M.getContext());
382     };
383     FunctionImporter Importer(*Index, diagnosticHandler, ModuleLoader);
384     return Importer.importFunctions(M);
385
386     return false;
387   }
388 };
389
390 char FunctionImportPass::ID = 0;
391 INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
392                       "Summary Based Function Import", false, false)
393 INITIALIZE_PASS_END(FunctionImportPass, "function-import",
394                     "Summary Based Function Import", false, false)
395
396 namespace llvm {
397 Pass *createFunctionImportPass(const FunctionInfoIndex *Index = nullptr) {
398   return new FunctionImportPass(Index);
399 }
400 }