blob: 92764c9e8c3fc70c4e98b728739ff080363e7f47 [file] [log] [blame]
Mehdi Amini42418ab2015-11-24 06:07:49 +00001//===- 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"
27using namespace llvm;
28
29#define DEBUG_TYPE "function-import"
30
Teresa Johnson39303612015-11-24 22:55:46 +000031/// Limit on instruction count of imported functions.
32static 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"));
35
Mehdi Amini42418ab2015-11-24 06:07:49 +000036// Load lazily a module from \p FileName in \p Context.
37static std::unique_ptr<Module> loadFile(const std::string &FileName,
38 LLVMContext &Context) {
39 SMDiagnostic Err;
40 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
41 std::unique_ptr<Module> Result = getLazyIRFileModule(FileName, Err, Context);
42 if (!Result) {
43 Err.print("function-import", errs());
44 return nullptr;
45 }
46
47 Result->materializeMetadata();
48 UpgradeDebugInfo(*Result);
49
50 return Result;
51}
52
53// Get a Module for \p FileName from the cache, or load it lazily.
Mehdi Aminia11bdc82015-12-02 02:00:29 +000054Module &ModuleLazyLoaderCache::operator()(StringRef FileName) {
Mehdi Amini42418ab2015-11-24 06:07:49 +000055 auto &Module = ModuleMap[FileName];
56 if (!Module)
57 Module = loadFile(FileName, Context);
58 return *Module;
59}
60
Teresa Johnsond450da32015-11-24 21:15:19 +000061/// 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.
64static void findExternalCalls(const Function &F, StringSet<> &CalledFunctions,
65 SmallVector<StringRef, 64> &Worklist) {
66 for (auto &BB : F) {
67 for (auto &I : BB) {
68 if (isa<CallInst>(I)) {
69 DEBUG(dbgs() << "Found a call: '" << I << "'\n");
70 auto CalledFunction = cast<CallInst>(I).getCalledFunction();
71 // Insert any new external calls that have not already been
72 // added to set/worklist.
73 if (CalledFunction && CalledFunction->hasName() &&
74 CalledFunction->isDeclaration() &&
75 !CalledFunctions.count(CalledFunction->getName())) {
76 CalledFunctions.insert(CalledFunction->getName());
77 Worklist.push_back(CalledFunction->getName());
78 }
79 }
80 }
81 }
82}
83
Mehdi Amini42418ab2015-11-24 06:07:49 +000084// Automatically import functions in Module \p M based on the summaries index.
85//
86// The current implementation imports every called functions that exists in the
87// summaries index.
88bool FunctionImporter::importFunctions(Module &M) {
Mehdi Amini42418ab2015-11-24 06:07:49 +000089
90 bool Changed = false;
91
Teresa Johnsond450da32015-11-24 21:15:19 +000092 /// First step is collecting the called external functions.
Mehdi Amini42418ab2015-11-24 06:07:49 +000093 StringSet<> CalledFunctions;
Teresa Johnsond450da32015-11-24 21:15:19 +000094 SmallVector<StringRef, 64> Worklist;
Mehdi Amini42418ab2015-11-24 06:07:49 +000095 for (auto &F : M) {
96 if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
97 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +000098 findExternalCalls(F, CalledFunctions, Worklist);
Mehdi Amini42418ab2015-11-24 06:07:49 +000099 }
100
101 /// Second step: for every call to an external function, try to import it.
102
103 // Linker that will be used for importing function
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000104 Linker L(M, DiagnosticHandler);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000105
Mehdi Amini42418ab2015-11-24 06:07:49 +0000106 while (!Worklist.empty()) {
107 auto CalledFunctionName = Worklist.pop_back_val();
108 DEBUG(dbgs() << "Process import for " << CalledFunctionName << "\n");
109
110 // Try to get a summary for this function call.
111 auto InfoList = Index.findFunctionInfoList(CalledFunctionName);
112 if (InfoList == Index.end()) {
113 DEBUG(dbgs() << "No summary for " << CalledFunctionName
114 << " Ignoring.\n");
115 continue;
116 }
117 assert(!InfoList->second.empty() && "No summary, error at import?");
118
119 // Comdat can have multiple entries, FIXME: what do we do with them?
120 auto &Info = InfoList->second[0];
121 assert(Info && "Nullptr in list, error importing summaries?\n");
122
123 auto *Summary = Info->functionSummary();
124 if (!Summary) {
125 // FIXME: in case we are lazyloading summaries, we can do it now.
Teresa Johnson430110c2015-12-01 17:12:10 +0000126 DEBUG(dbgs() << "Missing summary for " << CalledFunctionName
127 << ", error at import?\n");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000128 llvm_unreachable("Missing summary");
129 }
130
Teresa Johnson39303612015-11-24 22:55:46 +0000131 if (Summary->instCount() > ImportInstrLimit) {
Teresa Johnson430110c2015-12-01 17:12:10 +0000132 DEBUG(dbgs() << "Skip import of " << CalledFunctionName << " with "
133 << Summary->instCount() << " instructions (limit "
134 << ImportInstrLimit << ")\n");
Teresa Johnson39303612015-11-24 22:55:46 +0000135 continue;
136 }
137
Mehdi Amini42418ab2015-11-24 06:07:49 +0000138 // Get the module path from the summary.
139 auto FileName = Summary->modulePath();
140 DEBUG(dbgs() << "Importing " << CalledFunctionName << " from " << FileName
141 << "\n");
142
143 // Get the module for the import (potentially from the cache).
Mehdi Aminia11bdc82015-12-02 02:00:29 +0000144 auto &Module = getLazyModule(FileName);
145 assert(&Module.getContext() == &M.getContext());
Mehdi Amini42418ab2015-11-24 06:07:49 +0000146
147 // The function that we will import!
148 GlobalValue *SGV = Module.getNamedValue(CalledFunctionName);
Teresa Johnson130de7a2015-11-24 19:55:04 +0000149 StringRef ImportFunctionName = CalledFunctionName;
150 if (!SGV) {
151 // Might be local in source Module, promoted/renamed in dest Module M.
152 std::pair<StringRef, StringRef> Split =
153 CalledFunctionName.split(".llvm.");
154 SGV = Module.getNamedValue(Split.first);
155#ifndef NDEBUG
156 // Assert that Split.second is module id
157 uint64_t ModuleId;
158 assert(!Split.second.getAsInteger(10, ModuleId));
159 assert(ModuleId == Index.getModuleId(FileName));
160#endif
161 }
Mehdi Amini42418ab2015-11-24 06:07:49 +0000162 Function *F = dyn_cast<Function>(SGV);
163 if (!F && isa<GlobalAlias>(SGV)) {
164 auto *SGA = dyn_cast<GlobalAlias>(SGV);
165 F = dyn_cast<Function>(SGA->getBaseObject());
Teresa Johnson130de7a2015-11-24 19:55:04 +0000166 ImportFunctionName = F->getName();
Mehdi Amini42418ab2015-11-24 06:07:49 +0000167 }
168 if (!F) {
169 errs() << "Can't load function '" << CalledFunctionName << "' in Module '"
170 << FileName << "', error in the summary?\n";
171 llvm_unreachable("Can't load function in Module");
172 }
173
Teresa Johnson17626652015-11-24 16:10:43 +0000174 // We cannot import weak_any functions/aliases without possibly affecting
175 // the order they are seen and selected by the linker, changing program
Mehdi Amini42418ab2015-11-24 06:07:49 +0000176 // semantics.
Teresa Johnson17626652015-11-24 16:10:43 +0000177 if (SGV->hasWeakAnyLinkage()) {
178 DEBUG(dbgs() << "Ignoring import request for weak-any "
179 << (isa<Function>(SGV) ? "function " : "alias ")
Mehdi Amini42418ab2015-11-24 06:07:49 +0000180 << CalledFunctionName << " from " << FileName << "\n");
181 continue;
182 }
183
184 // Link in the specified function.
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000185 if (L.linkInModule(Module, Linker::Flags::None, &Index, F))
Mehdi Amini42418ab2015-11-24 06:07:49 +0000186 report_fatal_error("Function Import: link error");
187
Teresa Johnson130de7a2015-11-24 19:55:04 +0000188 // Process the newly imported function and add callees to the worklist.
189 GlobalValue *NewGV = M.getNamedValue(ImportFunctionName);
190 assert(NewGV);
191 Function *NewF = dyn_cast<Function>(NewGV);
192 assert(NewF);
Teresa Johnsond450da32015-11-24 21:15:19 +0000193 findExternalCalls(*NewF, CalledFunctions, Worklist);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000194
195 Changed = true;
196 }
197 return Changed;
198}
199
200/// Summary file to use for function importing when using -function-import from
201/// the command line.
202static cl::opt<std::string>
203 SummaryFile("summary-file",
204 cl::desc("The summary file to use for function importing."));
205
206static void diagnosticHandler(const DiagnosticInfo &DI) {
207 raw_ostream &OS = errs();
208 DiagnosticPrinterRawOStream DP(OS);
209 DI.print(DP);
210 OS << '\n';
211}
212
213/// Parse the function index out of an IR file and return the function
214/// index object if found, or nullptr if not.
215static std::unique_ptr<FunctionInfoIndex>
216getFunctionIndexForFile(StringRef Path, std::string &Error,
217 DiagnosticHandlerFunction DiagnosticHandler) {
218 std::unique_ptr<MemoryBuffer> Buffer;
219 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
220 MemoryBuffer::getFile(Path);
221 if (std::error_code EC = BufferOrErr.getError()) {
222 Error = EC.message();
223 return nullptr;
224 }
225 Buffer = std::move(BufferOrErr.get());
226 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
227 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
228 DiagnosticHandler);
229 if (std::error_code EC = ObjOrErr.getError()) {
230 Error = EC.message();
231 return nullptr;
232 }
233 return (*ObjOrErr)->takeIndex();
234}
235
236/// Pass that performs cross-module function import provided a summary file.
237class FunctionImportPass : public ModulePass {
238
239public:
240 /// Pass identification, replacement for typeid
241 static char ID;
242
243 explicit FunctionImportPass() : ModulePass(ID) {}
244
245 bool runOnModule(Module &M) override {
246 if (SummaryFile.empty()) {
247 report_fatal_error("error: -function-import requires -summary-file\n");
248 }
249 std::string Error;
250 std::unique_ptr<FunctionInfoIndex> Index =
251 getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
252 if (!Index) {
253 errs() << "Error loading file '" << SummaryFile << "': " << Error << "\n";
254 return false;
255 }
256
257 // Perform the import now.
Mehdi Aminia11bdc82015-12-02 02:00:29 +0000258 ModuleLazyLoaderCache Loader(M.getContext());
259 FunctionImporter Importer(*Index, diagnosticHandler,
260 [&](StringRef Name)
261 -> Module &{ return Loader(Name); });
Mehdi Amini42418ab2015-11-24 06:07:49 +0000262 return Importer.importFunctions(M);
263
264 return false;
265 }
266};
267
268char FunctionImportPass::ID = 0;
269INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
270 "Summary Based Function Import", false, false)
271INITIALIZE_PASS_END(FunctionImportPass, "function-import",
272 "Summary Based Function Import", false, false)
273
274namespace llvm {
275Pass *createFunctionImportPass() { return new FunctionImportPass(); }
276}