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"
29 #define DEBUG_TYPE "function-import"
31 /// Limit on instruction count of imported functions.
32 static cl::opt<unsigned> ImportInstrLimit(
33 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
34 cl::desc("Only import functions with less than N instructions"));
36 // Load lazily a module from \p FileName in \p Context.
37 static std::unique_ptr<Module> loadFile(const std::string &FileName,
38 LLVMContext &Context) {
40 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
41 std::unique_ptr<Module> Result = getLazyIRFileModule(FileName, Err, Context);
43 Err.print("function-import", errs());
47 Result->materializeMetadata();
48 UpgradeDebugInfo(*Result);
53 // Get a Module for \p FileName from the cache, or load it lazily.
54 Module &ModuleLazyLoaderCache::operator()(StringRef FileName) {
55 auto &Module = ModuleMap[FileName];
57 Module = loadFile(FileName, Context);
61 /// Walk through the instructions in \p F looking for external
62 /// calls not already in the \p CalledFunctions set. If any are
63 /// found they are added to the \p Worklist for importing.
64 static void findExternalCalls(const Function &F, StringSet<> &CalledFunctions,
65 SmallVector<StringRef, 64> &Worklist) {
68 if (isa<CallInst>(I)) {
69 auto CalledFunction = cast<CallInst>(I).getCalledFunction();
70 // Insert any new external calls that have not already been
71 // added to set/worklist.
72 if (CalledFunction && CalledFunction->hasName() &&
73 CalledFunction->isDeclaration() &&
74 !CalledFunctions.count(CalledFunction->getName())) {
75 CalledFunctions.insert(CalledFunction->getName());
76 Worklist.push_back(CalledFunction->getName());
84 // Helper function: given a worklist and an index, will process all the worklist
85 // and import them based on the summary information
86 static unsigned ProcessImportWorklist(Module &DestModule, SmallVector<StringRef, 64> &Worklist,
87 StringSet<> &CalledFunctions,
88 Linker &TheLinker, const FunctionInfoIndex &Index,
89 std::function<Module &(StringRef FileName)> &LazyModuleLoader) {
90 unsigned ImportCount = 0;
91 while (!Worklist.empty()) {
92 auto CalledFunctionName = Worklist.pop_back_val();
93 DEBUG(dbgs() << "Process import for " << CalledFunctionName << "\n");
95 // Try to get a summary for this function call.
96 auto InfoList = Index.findFunctionInfoList(CalledFunctionName);
97 if (InfoList == Index.end()) {
98 DEBUG(dbgs() << "No summary for " << CalledFunctionName
102 assert(!InfoList->second.empty() && "No summary, error at import?");
104 // Comdat can have multiple entries, FIXME: what do we do with them?
105 auto &Info = InfoList->second[0];
106 assert(Info && "Nullptr in list, error importing summaries?\n");
108 auto *Summary = Info->functionSummary();
110 // FIXME: in case we are lazyloading summaries, we can do it now.
111 DEBUG(dbgs() << "Missing summary for " << CalledFunctionName
112 << ", error at import?\n");
113 llvm_unreachable("Missing summary");
116 if (Summary->instCount() > ImportInstrLimit) {
117 DEBUG(dbgs() << "Skip import of " << CalledFunctionName << " with "
118 << Summary->instCount() << " instructions (limit "
119 << ImportInstrLimit << ")\n");
123 // Get the module path from the summary.
124 auto FileName = Summary->modulePath();
125 DEBUG(dbgs() << "Importing " << CalledFunctionName << " from " << FileName
128 // Get the module for the import (potentially from the cache).
129 auto &Module = LazyModuleLoader(FileName);
130 assert(&Module.getContext() == &DestModule.getContext());
132 // The function that we will import!
133 GlobalValue *SGV = Module.getNamedValue(CalledFunctionName);
134 StringRef ImportFunctionName = CalledFunctionName;
136 // Might be local in source Module, promoted/renamed in DestModule.
137 std::pair<StringRef, StringRef> Split =
138 CalledFunctionName.split(".llvm.");
139 SGV = Module.getNamedValue(Split.first);
141 // Assert that Split.second is module id
143 assert(!Split.second.getAsInteger(10, ModuleId));
144 assert(ModuleId == Index.getModuleId(FileName));
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();
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");
159 // We cannot import weak_any functions/aliases without possibly affecting
160 // the order they are seen and selected by the linker, changing program
162 if (SGV->hasWeakAnyLinkage()) {
163 DEBUG(dbgs() << "Ignoring import request for weak-any "
164 << (isa<Function>(SGV) ? "function " : "alias ")
165 << CalledFunctionName << " from " << FileName << "\n");
169 // Link in the specified function.
170 DenseSet<const GlobalValue *> FunctionsToImport;
171 FunctionsToImport.insert(F);
172 if (TheLinker.linkInModule(Module, Linker::Flags::None, &Index,
174 report_fatal_error("Function Import: link error");
176 // Process the newly imported function and add callees to the worklist.
177 GlobalValue *NewGV = DestModule.getNamedValue(ImportFunctionName);
179 Function *NewF = dyn_cast<Function>(NewGV);
181 findExternalCalls(*NewF, CalledFunctions, Worklist);
187 // Automatically import functions in Module \p DestModule based on the summaries
190 // The current implementation imports every called functions that exists in the
192 bool FunctionImporter::importFunctions(Module &DestModule) {
193 DEBUG(errs() << "Starting import for Module " << DestModule.getModuleIdentifier()
195 unsigned ImportedCount = 0;
197 /// First step is collecting the called external functions.
198 StringSet<> CalledFunctions;
199 SmallVector<StringRef, 64> Worklist;
200 for (auto &F : DestModule) {
201 if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
203 findExternalCalls(F, CalledFunctions, Worklist);
205 if (Worklist.empty())
208 /// Second step: for every call to an external function, try to import it.
210 // Linker that will be used for importing function
211 Linker TheLinker(DestModule, DiagnosticHandler);
213 ImportedCount += ProcessImportWorklist(DestModule, Worklist, CalledFunctions, TheLinker, Index, getLazyModule );
215 DEBUG(errs() << "Imported " << ImportedCount << " functions for Module "
216 << DestModule.getModuleIdentifier() << "\n");
217 return ImportedCount;
220 /// Summary file to use for function importing when using -function-import from
221 /// the command line.
222 static cl::opt<std::string>
223 SummaryFile("summary-file",
224 cl::desc("The summary file to use for function importing."));
226 static void diagnosticHandler(const DiagnosticInfo &DI) {
227 raw_ostream &OS = errs();
228 DiagnosticPrinterRawOStream DP(OS);
233 /// Parse the function index out of an IR file and return the function
234 /// index object if found, or nullptr if not.
235 static std::unique_ptr<FunctionInfoIndex>
236 getFunctionIndexForFile(StringRef Path, std::string &Error,
237 DiagnosticHandlerFunction DiagnosticHandler) {
238 std::unique_ptr<MemoryBuffer> Buffer;
239 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
240 MemoryBuffer::getFile(Path);
241 if (std::error_code EC = BufferOrErr.getError()) {
242 Error = EC.message();
245 Buffer = std::move(BufferOrErr.get());
246 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
247 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
249 if (std::error_code EC = ObjOrErr.getError()) {
250 Error = EC.message();
253 return (*ObjOrErr)->takeIndex();
256 /// Pass that performs cross-module function import provided a summary file.
257 class FunctionImportPass : public ModulePass {
260 /// Pass identification, replacement for typeid
263 explicit FunctionImportPass() : ModulePass(ID) {}
265 bool runOnModule(Module &M) override {
266 if (SummaryFile.empty()) {
267 report_fatal_error("error: -function-import requires -summary-file\n");
270 std::unique_ptr<FunctionInfoIndex> Index =
271 getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
273 errs() << "Error loading file '" << SummaryFile << "': " << Error << "\n";
277 // Perform the import now.
278 ModuleLazyLoaderCache Loader(M.getContext());
279 FunctionImporter Importer(*Index, diagnosticHandler,
281 -> Module &{ return Loader(Name); });
282 return Importer.importFunctions(M);
288 char FunctionImportPass::ID = 0;
289 INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
290 "Summary Based Function Import", false, false)
291 INITIALIZE_PASS_END(FunctionImportPass, "function-import",
292 "Summary Based Function Import", false, false)
295 Pass *createFunctionImportPass() { return new FunctionImportPass(); }