1 //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements Function import based on summaries.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/IPO/FunctionImport.h"
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"
32 #define DEBUG_TYPE "function-import"
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"));
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) {
43 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
44 std::unique_ptr<Module> Result = getLazyIRFileModule(FileName, Err, Context);
46 Err.print("function-import", errs());
50 Result->materializeMetadata();
51 UpgradeDebugInfo(*Result);
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;
63 /// Retrieve a Module from the cache or lazily load it on demand.
64 std::function<std::unique_ptr<Module>(StringRef FileName)> createLazyModule;
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) {}
72 /// Retrieve a Module from the cache or lazily load it on demand.
73 Module &operator()(StringRef FileName);
75 std::unique_ptr<Module> takeModule(StringRef FileName) {
76 auto I = ModuleMap.find(FileName);
77 assert(I != ModuleMap.end());
78 std::unique_ptr<Module> Ret = std::move(I->second);
84 // Get a Module for \p FileName from the cache, or load it lazily.
85 Module &ModuleLazyLoaderCache::operator()(StringRef Identifier) {
86 auto &Module = ModuleMap[Identifier];
88 Module = createLazyModule(Identifier);
91 } // anonymous namespace
93 /// Walk through the instructions in \p F looking for external
94 /// calls not already in the \p CalledFunctions set. If any are
95 /// found they are added to the \p Worklist for importing.
96 static void findExternalCalls(const Module &DestModule, Function &F,
97 const FunctionInfoIndex &Index,
98 StringSet<> &CalledFunctions,
99 SmallVector<StringRef, 64> &Worklist) {
100 // We need to suffix internal function calls imported from other modules,
101 // prepare the suffix ahead of time.
103 if (F.getParent() != &DestModule)
106 Twine(Index.getModuleId(F.getParent()->getModuleIdentifier()))).str();
110 if (isa<CallInst>(I)) {
111 auto CalledFunction = cast<CallInst>(I).getCalledFunction();
112 // Insert any new external calls that have not already been
113 // added to set/worklist.
114 if (!CalledFunction || !CalledFunction->hasName())
116 // Ignore intrinsics early
117 if (CalledFunction->isIntrinsic()) {
118 assert(CalledFunction->getIntrinsicID() != 0);
121 auto ImportedName = CalledFunction->getName();
122 auto Renamed = (ImportedName + Suffix).str();
123 // Rename internal functions
124 if (CalledFunction->hasInternalLinkage()) {
125 ImportedName = Renamed;
127 auto It = CalledFunctions.insert(ImportedName);
129 // This is a call to a function we already considered, skip.
132 // Ignore functions already present in the destination module
133 auto *SrcGV = DestModule.getNamedValue(ImportedName);
135 assert(isa<Function>(SrcGV) && "Name collision during import");
136 if (!cast<Function>(SrcGV)->isDeclaration()) {
137 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Ignoring "
138 << ImportedName << " already in DestinationModule\n");
143 Worklist.push_back(It.first->getKey());
144 DEBUG(dbgs() << DestModule.getModuleIdentifier()
145 << ": Adding callee for : " << ImportedName << " : "
146 << F.getName() << "\n");
152 // Helper function: given a worklist and an index, will process all the worklist
153 // and decide what to import based on the summary information.
155 // Nothing is actually imported, functions are materialized in their source
156 // module and analyzed there.
158 // \p ModuleToFunctionsToImportMap is filled with the set of Function to import
160 static void GetImportList(Module &DestModule,
161 SmallVector<StringRef, 64> &Worklist,
162 StringSet<> &CalledFunctions,
163 std::map<StringRef, DenseSet<const GlobalValue *>>
164 &ModuleToFunctionsToImportMap,
165 const FunctionInfoIndex &Index,
166 ModuleLazyLoaderCache &ModuleLoaderCache) {
167 while (!Worklist.empty()) {
168 auto CalledFunctionName = Worklist.pop_back_val();
169 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Process import for "
170 << CalledFunctionName << "\n");
172 // Try to get a summary for this function call.
173 auto InfoList = Index.findFunctionInfoList(CalledFunctionName);
174 if (InfoList == Index.end()) {
175 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": No summary for "
176 << CalledFunctionName << " Ignoring.\n");
179 assert(!InfoList->second.empty() && "No summary, error at import?");
181 // Comdat can have multiple entries, FIXME: what do we do with them?
182 auto &Info = InfoList->second[0];
183 assert(Info && "Nullptr in list, error importing summaries?\n");
185 auto *Summary = Info->functionSummary();
187 // FIXME: in case we are lazyloading summaries, we can do it now.
188 DEBUG(dbgs() << DestModule.getModuleIdentifier()
189 << ": Missing summary for " << CalledFunctionName
190 << ", error at import?\n");
191 llvm_unreachable("Missing summary");
194 if (Summary->instCount() > ImportInstrLimit) {
195 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Skip import of "
196 << CalledFunctionName << " with " << Summary->instCount()
197 << " instructions (limit " << ImportInstrLimit << ")\n");
201 // Get the module path from the summary.
202 auto ModuleIdentifier = Summary->modulePath();
203 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Importing "
204 << CalledFunctionName << " from " << ModuleIdentifier << "\n");
206 auto &SrcModule = ModuleLoaderCache(ModuleIdentifier);
208 // The function that we will import!
209 GlobalValue *SGV = SrcModule.getNamedValue(CalledFunctionName);
212 // The destination module is referencing function using their renamed name
213 // when importing a function that was originally local in the source
214 // module. The source module we have might not have been renamed so we try
215 // to remove the suffix added during the renaming to recover the original
216 // name in the source module.
217 std::pair<StringRef, StringRef> Split =
218 CalledFunctionName.split(".llvm.");
219 SGV = SrcModule.getNamedValue(Split.first);
220 assert(SGV && "Can't find function to import in source module");
223 report_fatal_error(Twine("Can't load function '") + CalledFunctionName +
224 "' in Module '" + SrcModule.getModuleIdentifier() +
225 "', error in the summary?\n");
228 Function *F = dyn_cast<Function>(SGV);
229 if (!F && isa<GlobalAlias>(SGV)) {
230 auto *SGA = dyn_cast<GlobalAlias>(SGV);
231 F = dyn_cast<Function>(SGA->getBaseObject());
232 CalledFunctionName = F->getName();
234 assert(F && "Imported Function is ... not a Function");
236 // We cannot import weak_any functions/aliases without possibly affecting
237 // the order they are seen and selected by the linker, changing program
239 if (SGV->hasWeakAnyLinkage()) {
240 DEBUG(dbgs() << DestModule.getModuleIdentifier()
241 << ": Ignoring import request for weak-any "
242 << (isa<Function>(SGV) ? "function " : "alias ")
243 << CalledFunctionName << " from "
244 << SrcModule.getModuleIdentifier() << "\n");
248 // Add the function to the import list
249 auto &Entry = ModuleToFunctionsToImportMap[SrcModule.getModuleIdentifier()];
252 // Process the newly imported functions and add callees to the worklist.
254 findExternalCalls(DestModule, *F, Index, CalledFunctions, Worklist);
258 // Automatically import functions in Module \p DestModule based on the summaries
261 // The current implementation imports every called functions that exists in the
263 bool FunctionImporter::importFunctions(Module &DestModule) {
264 DEBUG(dbgs() << "Starting import for Module "
265 << DestModule.getModuleIdentifier() << "\n");
266 unsigned ImportedCount = 0;
268 /// First step is collecting the called external functions.
269 StringSet<> CalledFunctions;
270 SmallVector<StringRef, 64> Worklist;
271 for (auto &F : DestModule) {
272 if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
274 findExternalCalls(DestModule, F, Index, CalledFunctions, Worklist);
276 if (Worklist.empty())
279 /// Second step: for every call to an external function, try to import it.
281 // Linker that will be used for importing function
282 Linker TheLinker(DestModule);
284 // Map of Module -> List of Function to import from the Module
285 std::map<StringRef, DenseSet<const GlobalValue *>>
286 ModuleToFunctionsToImportMap;
288 // Analyze the summaries and get the list of functions to import by
289 // populating ModuleToFunctionsToImportMap
290 ModuleLazyLoaderCache ModuleLoaderCache(ModuleLoader);
291 GetImportList(DestModule, Worklist, CalledFunctions,
292 ModuleToFunctionsToImportMap, Index, ModuleLoaderCache);
293 assert(Worklist.empty() && "Worklist hasn't been flushed in GetImportList");
295 // Do the actual import of functions now, one Module at a time
296 for (auto &FunctionsToImportPerModule : ModuleToFunctionsToImportMap) {
297 // Get the module for the import
298 auto &FunctionsToImport = FunctionsToImportPerModule.second;
299 std::unique_ptr<Module> SrcModule =
300 ModuleLoaderCache.takeModule(FunctionsToImportPerModule.first);
301 assert(&DestModule.getContext() == &SrcModule->getContext() &&
304 // Link in the specified functions.
305 if (TheLinker.linkInModule(std::move(SrcModule), Linker::Flags::None,
306 &Index, &FunctionsToImport))
307 report_fatal_error("Function Import: link error");
309 ImportedCount += FunctionsToImport.size();
311 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
312 << DestModule.getModuleIdentifier() << "\n");
313 return ImportedCount;
316 /// Summary file to use for function importing when using -function-import from
317 /// the command line.
318 static cl::opt<std::string>
319 SummaryFile("summary-file",
320 cl::desc("The summary file to use for function importing."));
322 static void diagnosticHandler(const DiagnosticInfo &DI) {
323 raw_ostream &OS = errs();
324 DiagnosticPrinterRawOStream DP(OS);
329 /// Parse the function index out of an IR file and return the function
330 /// index object if found, or nullptr if not.
331 static std::unique_ptr<FunctionInfoIndex>
332 getFunctionIndexForFile(StringRef Path, std::string &Error,
333 DiagnosticHandlerFunction DiagnosticHandler) {
334 std::unique_ptr<MemoryBuffer> Buffer;
335 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
336 MemoryBuffer::getFile(Path);
337 if (std::error_code EC = BufferOrErr.getError()) {
338 Error = EC.message();
341 Buffer = std::move(BufferOrErr.get());
342 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
343 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
345 if (std::error_code EC = ObjOrErr.getError()) {
346 Error = EC.message();
349 return (*ObjOrErr)->takeIndex();
352 /// Pass that performs cross-module function import provided a summary file.
353 class FunctionImportPass : public ModulePass {
354 /// Optional function summary index to use for importing, otherwise
355 /// the summary-file option must be specified.
356 const FunctionInfoIndex *Index;
359 /// Pass identification, replacement for typeid
362 /// Specify pass name for debug output
363 const char *getPassName() const override {
364 return "Function Importing";
367 explicit FunctionImportPass(const FunctionInfoIndex *Index = nullptr)
368 : ModulePass(ID), Index(Index) {}
370 bool runOnModule(Module &M) override {
371 if (SummaryFile.empty() && !Index)
372 report_fatal_error("error: -function-import requires -summary-file or "
373 "file from frontend\n");
374 std::unique_ptr<FunctionInfoIndex> IndexPtr;
375 if (!SummaryFile.empty()) {
377 report_fatal_error("error: -summary-file and index from frontend\n");
379 IndexPtr = getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
381 errs() << "Error loading file '" << SummaryFile << "': " << Error
385 Index = IndexPtr.get();
388 // Perform the import now.
389 auto ModuleLoader = [&M](StringRef Identifier) {
390 return loadFile(Identifier, M.getContext());
392 FunctionImporter Importer(*Index, ModuleLoader);
393 return Importer.importFunctions(M);
399 char FunctionImportPass::ID = 0;
400 INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
401 "Summary Based Function Import", false, false)
402 INITIALIZE_PASS_END(FunctionImportPass, "function-import",
403 "Summary Based Function Import", false, false)
406 Pass *createFunctionImportPass(const FunctionInfoIndex *Index = nullptr) {
407 return new FunctionImportPass(Index);