blob: ab0f7114957b465a6154200f51b6630be48b5ff5 [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.
54Module &FunctionImporter::getOrLoadModule(StringRef FileName) {
55 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) {
89 assert(&Context == &M.getContext());
90
91 bool Changed = false;
92
Teresa Johnsond450da32015-11-24 21:15:19 +000093 /// First step is collecting the called external functions.
Mehdi Amini42418ab2015-11-24 06:07:49 +000094 StringSet<> CalledFunctions;
Teresa Johnsond450da32015-11-24 21:15:19 +000095 SmallVector<StringRef, 64> Worklist;
Mehdi Amini42418ab2015-11-24 06:07:49 +000096 for (auto &F : M) {
97 if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
98 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +000099 findExternalCalls(F, CalledFunctions, Worklist);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000100 }
101
102 /// Second step: for every call to an external function, try to import it.
103
104 // Linker that will be used for importing function
105 Linker L(&M, DiagnosticHandler);
106
Mehdi Amini42418ab2015-11-24 06:07:49 +0000107 while (!Worklist.empty()) {
108 auto CalledFunctionName = Worklist.pop_back_val();
109 DEBUG(dbgs() << "Process import for " << CalledFunctionName << "\n");
110
111 // Try to get a summary for this function call.
112 auto InfoList = Index.findFunctionInfoList(CalledFunctionName);
113 if (InfoList == Index.end()) {
114 DEBUG(dbgs() << "No summary for " << CalledFunctionName
115 << " Ignoring.\n");
116 continue;
117 }
118 assert(!InfoList->second.empty() && "No summary, error at import?");
119
120 // Comdat can have multiple entries, FIXME: what do we do with them?
121 auto &Info = InfoList->second[0];
122 assert(Info && "Nullptr in list, error importing summaries?\n");
123
124 auto *Summary = Info->functionSummary();
125 if (!Summary) {
126 // FIXME: in case we are lazyloading summaries, we can do it now.
127 dbgs() << "Missing summary for " << CalledFunctionName
128 << ", error at import?\n";
129 llvm_unreachable("Missing summary");
130 }
131
Teresa Johnson39303612015-11-24 22:55:46 +0000132 if (Summary->instCount() > ImportInstrLimit) {
133 dbgs() << "Skip import of " << CalledFunctionName << " with "
134 << Summary->instCount() << " instructions (limit "
135 << ImportInstrLimit << ")\n";
136 continue;
137 }
138
Mehdi Amini42418ab2015-11-24 06:07:49 +0000139 //
140 // No profitability notion right now, just import all the time...
141 //
142
143 // Get the module path from the summary.
144 auto FileName = Summary->modulePath();
145 DEBUG(dbgs() << "Importing " << CalledFunctionName << " from " << FileName
146 << "\n");
147
148 // Get the module for the import (potentially from the cache).
149 auto &Module = getOrLoadModule(FileName);
150
151 // The function that we will import!
152 GlobalValue *SGV = Module.getNamedValue(CalledFunctionName);
Teresa Johnson130de7a2015-11-24 19:55:04 +0000153 StringRef ImportFunctionName = CalledFunctionName;
154 if (!SGV) {
155 // Might be local in source Module, promoted/renamed in dest Module M.
156 std::pair<StringRef, StringRef> Split =
157 CalledFunctionName.split(".llvm.");
158 SGV = Module.getNamedValue(Split.first);
159#ifndef NDEBUG
160 // Assert that Split.second is module id
161 uint64_t ModuleId;
162 assert(!Split.second.getAsInteger(10, ModuleId));
163 assert(ModuleId == Index.getModuleId(FileName));
164#endif
165 }
Mehdi Amini42418ab2015-11-24 06:07:49 +0000166 Function *F = dyn_cast<Function>(SGV);
167 if (!F && isa<GlobalAlias>(SGV)) {
168 auto *SGA = dyn_cast<GlobalAlias>(SGV);
169 F = dyn_cast<Function>(SGA->getBaseObject());
Teresa Johnson130de7a2015-11-24 19:55:04 +0000170 ImportFunctionName = F->getName();
Mehdi Amini42418ab2015-11-24 06:07:49 +0000171 }
172 if (!F) {
173 errs() << "Can't load function '" << CalledFunctionName << "' in Module '"
174 << FileName << "', error in the summary?\n";
175 llvm_unreachable("Can't load function in Module");
176 }
177
Teresa Johnson17626652015-11-24 16:10:43 +0000178 // We cannot import weak_any functions/aliases without possibly affecting
179 // the order they are seen and selected by the linker, changing program
Mehdi Amini42418ab2015-11-24 06:07:49 +0000180 // semantics.
Teresa Johnson17626652015-11-24 16:10:43 +0000181 if (SGV->hasWeakAnyLinkage()) {
182 DEBUG(dbgs() << "Ignoring import request for weak-any "
183 << (isa<Function>(SGV) ? "function " : "alias ")
Mehdi Amini42418ab2015-11-24 06:07:49 +0000184 << CalledFunctionName << " from " << FileName << "\n");
185 continue;
186 }
187
188 // Link in the specified function.
189 if (L.linkInModule(&Module, Linker::Flags::None, &Index, F))
190 report_fatal_error("Function Import: link error");
191
Teresa Johnson130de7a2015-11-24 19:55:04 +0000192 // Process the newly imported function and add callees to the worklist.
193 GlobalValue *NewGV = M.getNamedValue(ImportFunctionName);
194 assert(NewGV);
195 Function *NewF = dyn_cast<Function>(NewGV);
196 assert(NewF);
Teresa Johnsond450da32015-11-24 21:15:19 +0000197 findExternalCalls(*NewF, CalledFunctions, Worklist);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000198
199 Changed = true;
200 }
201 return Changed;
202}
203
204/// Summary file to use for function importing when using -function-import from
205/// the command line.
206static cl::opt<std::string>
207 SummaryFile("summary-file",
208 cl::desc("The summary file to use for function importing."));
209
210static void diagnosticHandler(const DiagnosticInfo &DI) {
211 raw_ostream &OS = errs();
212 DiagnosticPrinterRawOStream DP(OS);
213 DI.print(DP);
214 OS << '\n';
215}
216
217/// Parse the function index out of an IR file and return the function
218/// index object if found, or nullptr if not.
219static std::unique_ptr<FunctionInfoIndex>
220getFunctionIndexForFile(StringRef Path, std::string &Error,
221 DiagnosticHandlerFunction DiagnosticHandler) {
222 std::unique_ptr<MemoryBuffer> Buffer;
223 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
224 MemoryBuffer::getFile(Path);
225 if (std::error_code EC = BufferOrErr.getError()) {
226 Error = EC.message();
227 return nullptr;
228 }
229 Buffer = std::move(BufferOrErr.get());
230 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
231 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
232 DiagnosticHandler);
233 if (std::error_code EC = ObjOrErr.getError()) {
234 Error = EC.message();
235 return nullptr;
236 }
237 return (*ObjOrErr)->takeIndex();
238}
239
240/// Pass that performs cross-module function import provided a summary file.
241class FunctionImportPass : public ModulePass {
242
243public:
244 /// Pass identification, replacement for typeid
245 static char ID;
246
247 explicit FunctionImportPass() : ModulePass(ID) {}
248
249 bool runOnModule(Module &M) override {
250 if (SummaryFile.empty()) {
251 report_fatal_error("error: -function-import requires -summary-file\n");
252 }
253 std::string Error;
254 std::unique_ptr<FunctionInfoIndex> Index =
255 getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
256 if (!Index) {
257 errs() << "Error loading file '" << SummaryFile << "': " << Error << "\n";
258 return false;
259 }
260
261 // Perform the import now.
262 FunctionImporter Importer(M.getContext(), *Index, diagnosticHandler);
263 return Importer.importFunctions(M);
264
265 return false;
266 }
267};
268
269char FunctionImportPass::ID = 0;
270INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
271 "Summary Based Function Import", false, false)
272INITIALIZE_PASS_END(FunctionImportPass, "function-import",
273 "Summary Based Function Import", false, false)
274
275namespace llvm {
276Pass *createFunctionImportPass() { return new FunctionImportPass(); }
277}