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 // Load lazily a module from \p FileName in \p Context.
32 static std::unique_ptr<Module> loadFile(const std::string &FileName,
33 LLVMContext &Context) {
35 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
36 std::unique_ptr<Module> Result = getLazyIRFileModule(FileName, Err, Context);
38 Err.print("function-import", errs());
42 Result->materializeMetadata();
43 UpgradeDebugInfo(*Result);
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];
52 Module = loadFile(FileName, Context);
56 // Automatically import functions in Module \p M based on the summaries index.
58 // The current implementation imports every called functions that exists in the
60 bool FunctionImporter::importFunctions(Module &M) {
61 assert(&Context == &M.getContext());
65 /// First step is collecting the called functions and the one defined in this
67 StringSet<> CalledFunctions;
69 if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
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());
84 /// Second step: for every call to an external function, try to import it.
86 // Linker that will be used for importing function
87 Linker L(&M, DiagnosticHandler);
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());
95 while (!Worklist.empty()) {
96 auto CalledFunctionName = Worklist.pop_back_val();
97 DEBUG(dbgs() << "Process import for " << CalledFunctionName << "\n");
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
106 assert(!InfoList->second.empty() && "No summary, error at import?");
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");
112 auto *Summary = Info->functionSummary();
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");
121 // No profitability notion right now, just import all the time...
124 // Get the module path from the summary.
125 auto FileName = Summary->modulePath();
126 DEBUG(dbgs() << "Importing " << CalledFunctionName << " from " << FileName
129 // Get the module for the import (potentially from the cache).
130 auto &Module = getOrLoadModule(FileName);
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 dest Module M.
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 if (L.linkInModule(&Module, Linker::Flags::None, &Index, F))
171 report_fatal_error("Function Import: link error");
173 // Process the newly imported function and add callees to the worklist.
174 GlobalValue *NewGV = M.getNamedValue(ImportFunctionName);
176 Function *NewF = dyn_cast<Function>(NewGV);
179 for (auto &BB : *NewF) {
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());
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."));
207 static void diagnosticHandler(const DiagnosticInfo &DI) {
208 raw_ostream &OS = errs();
209 DiagnosticPrinterRawOStream DP(OS);
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();
226 Buffer = std::move(BufferOrErr.get());
227 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
228 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
230 if (std::error_code EC = ObjOrErr.getError()) {
231 Error = EC.message();
234 return (*ObjOrErr)->takeIndex();
237 /// Pass that performs cross-module function import provided a summary file.
238 class FunctionImportPass : public ModulePass {
241 /// Pass identification, replacement for typeid
244 explicit FunctionImportPass() : ModulePass(ID) {}
246 bool runOnModule(Module &M) override {
247 if (SummaryFile.empty()) {
248 report_fatal_error("error: -function-import requires -summary-file\n");
251 std::unique_ptr<FunctionInfoIndex> Index =
252 getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
254 errs() << "Error loading file '" << SummaryFile << "': " << Error << "\n";
258 // Perform the import now.
259 FunctionImporter Importer(M.getContext(), *Index, diagnosticHandler);
260 return Importer.importFunctions(M);
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)
273 Pass *createFunctionImportPass() { return new FunctionImportPass(); }