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());
83 // Helper function: given a worklist and an index, will process all the worklist
84 // and import them based on the summary information
85 static unsigned ProcessImportWorklist(
86 Module &DestModule, SmallVector<StringRef, 64> &Worklist,
87 StringSet<> &CalledFunctions, Linker &TheLinker,
88 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 "
194 << DestModule.getModuleIdentifier() << "\n");
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,
214 TheLinker, Index, getLazyModule);
216 DEBUG(errs() << "Imported " << ImportedCount << " functions for Module "
217 << DestModule.getModuleIdentifier() << "\n");
218 return ImportedCount;
221 /// Summary file to use for function importing when using -function-import from
222 /// the command line.
223 static cl::opt<std::string>
224 SummaryFile("summary-file",
225 cl::desc("The summary file to use for function importing."));
227 static void diagnosticHandler(const DiagnosticInfo &DI) {
228 raw_ostream &OS = errs();
229 DiagnosticPrinterRawOStream DP(OS);
234 /// Parse the function index out of an IR file and return the function
235 /// index object if found, or nullptr if not.
236 static std::unique_ptr<FunctionInfoIndex>
237 getFunctionIndexForFile(StringRef Path, std::string &Error,
238 DiagnosticHandlerFunction DiagnosticHandler) {
239 std::unique_ptr<MemoryBuffer> Buffer;
240 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
241 MemoryBuffer::getFile(Path);
242 if (std::error_code EC = BufferOrErr.getError()) {
243 Error = EC.message();
246 Buffer = std::move(BufferOrErr.get());
247 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
248 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
250 if (std::error_code EC = ObjOrErr.getError()) {
251 Error = EC.message();
254 return (*ObjOrErr)->takeIndex();
257 /// Pass that performs cross-module function import provided a summary file.
258 class FunctionImportPass : public ModulePass {
259 /// Optional function summary index to use for importing, otherwise
260 /// the summary-file option must be specified.
261 FunctionInfoIndex *Index;
264 /// Pass identification, replacement for typeid
267 /// Specify pass name for debug output
268 const char *getPassName() const override {
269 return "Function Importing";
272 explicit FunctionImportPass(FunctionInfoIndex *Index = nullptr)
273 : ModulePass(ID), Index(Index) {}
275 bool runOnModule(Module &M) override {
276 if (SummaryFile.empty() && !Index)
277 report_fatal_error("error: -function-import requires -summary-file or "
278 "file from frontend\n");
279 std::unique_ptr<FunctionInfoIndex> IndexPtr;
280 if (!SummaryFile.empty()) {
282 report_fatal_error("error: -summary-file and index from frontend\n");
284 IndexPtr = getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
286 errs() << "Error loading file '" << SummaryFile << "': " << Error
290 Index = IndexPtr.get();
293 // Perform the import now.
294 ModuleLazyLoaderCache Loader(M.getContext());
295 FunctionImporter Importer(*Index, diagnosticHandler,
297 -> Module &{ return Loader(Name); });
298 return Importer.importFunctions(M);
304 char FunctionImportPass::ID = 0;
305 INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
306 "Summary Based Function Import", false, false)
307 INITIALIZE_PASS_END(FunctionImportPass, "function-import",
308 "Summary Based Function Import", false, false)
311 Pass *createFunctionImportPass(FunctionInfoIndex *Index = nullptr) {
312 return new FunctionImportPass(Index);