blob: b585a86b86a6f4cd2e8aa5c456ee38d4ba4509b1 [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
Teresa Johnsond450da32015-11-24 21:15:19 +000053/// Walk through the instructions in \p F looking for external
54/// calls not already in the \p CalledFunctions set. If any are
55/// found they are added to the \p Worklist for importing.
56static void findExternalCalls(const Function &F, StringSet<> &CalledFunctions,
57 SmallVector<StringRef, 64> &Worklist) {
58 for (auto &BB : F) {
59 for (auto &I : BB) {
60 if (isa<CallInst>(I)) {
Teresa Johnsond450da32015-11-24 21:15:19 +000061 auto CalledFunction = cast<CallInst>(I).getCalledFunction();
62 // Insert any new external calls that have not already been
63 // added to set/worklist.
64 if (CalledFunction && CalledFunction->hasName() &&
65 CalledFunction->isDeclaration() &&
66 !CalledFunctions.count(CalledFunction->getName())) {
67 CalledFunctions.insert(CalledFunction->getName());
68 Worklist.push_back(CalledFunction->getName());
69 }
70 }
71 }
72 }
73}
74
Mehdi Aminic8c55172015-12-03 02:37:33 +000075// Helper function: given a worklist and an index, will process all the worklist
76// and import them based on the summary information
Mehdi Amini311fef62015-12-03 02:58:14 +000077static unsigned ProcessImportWorklist(
78 Module &DestModule, SmallVector<StringRef, 64> &Worklist,
79 StringSet<> &CalledFunctions, Linker &TheLinker,
80 const FunctionInfoIndex &Index,
Mehdi Aminid16c8062015-12-08 22:39:40 +000081 std::function<std::unique_ptr<Module>(StringRef FileName)> &
82 LazyModuleLoader) {
Mehdi Aminic8c55172015-12-03 02:37:33 +000083 unsigned ImportCount = 0;
Mehdi Amini42418ab2015-11-24 06:07:49 +000084 while (!Worklist.empty()) {
85 auto CalledFunctionName = Worklist.pop_back_val();
Mehdi Amini5411d052015-12-08 23:04:19 +000086 DEBUG(dbgs() << DestModule.getModuleIdentifier() << "Process import for "
87 << CalledFunctionName << "\n");
Mehdi Amini42418ab2015-11-24 06:07:49 +000088
89 // Try to get a summary for this function call.
90 auto InfoList = Index.findFunctionInfoList(CalledFunctionName);
91 if (InfoList == Index.end()) {
Mehdi Amini5411d052015-12-08 23:04:19 +000092 DEBUG(dbgs() << DestModule.getModuleIdentifier() << "No summary for "
93 << CalledFunctionName << " Ignoring.\n");
Mehdi Amini42418ab2015-11-24 06:07:49 +000094 continue;
95 }
96 assert(!InfoList->second.empty() && "No summary, error at import?");
97
98 // Comdat can have multiple entries, FIXME: what do we do with them?
99 auto &Info = InfoList->second[0];
100 assert(Info && "Nullptr in list, error importing summaries?\n");
101
102 auto *Summary = Info->functionSummary();
103 if (!Summary) {
104 // FIXME: in case we are lazyloading summaries, we can do it now.
Mehdi Amini5411d052015-12-08 23:04:19 +0000105 DEBUG(dbgs() << DestModule.getModuleIdentifier()
106 << " Missing summary for " << CalledFunctionName
Teresa Johnson430110c2015-12-01 17:12:10 +0000107 << ", error at import?\n");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000108 llvm_unreachable("Missing summary");
109 }
110
Teresa Johnson39303612015-11-24 22:55:46 +0000111 if (Summary->instCount() > ImportInstrLimit) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000112 DEBUG(dbgs() << DestModule.getModuleIdentifier() << " Skip import of "
113 << CalledFunctionName << " with " << Summary->instCount()
114 << " instructions (limit " << ImportInstrLimit << ")\n");
Teresa Johnson39303612015-11-24 22:55:46 +0000115 continue;
116 }
117
Mehdi Amini42418ab2015-11-24 06:07:49 +0000118 // Get the module path from the summary.
119 auto FileName = Summary->modulePath();
120 DEBUG(dbgs() << "Importing " << CalledFunctionName << " from " << FileName
121 << "\n");
122
Mehdi Aminid16c8062015-12-08 22:39:40 +0000123 // Get the module for the import
124 auto SrcModule = LazyModuleLoader(FileName);
125 assert(&SrcModule->getContext() == &DestModule.getContext());
Mehdi Amini42418ab2015-11-24 06:07:49 +0000126
127 // The function that we will import!
Mehdi Aminid16c8062015-12-08 22:39:40 +0000128 GlobalValue *SGV = SrcModule->getNamedValue(CalledFunctionName);
Teresa Johnson130de7a2015-11-24 19:55:04 +0000129 StringRef ImportFunctionName = CalledFunctionName;
130 if (!SGV) {
Mehdi Aminic8c55172015-12-03 02:37:33 +0000131 // Might be local in source Module, promoted/renamed in DestModule.
Teresa Johnson130de7a2015-11-24 19:55:04 +0000132 std::pair<StringRef, StringRef> Split =
133 CalledFunctionName.split(".llvm.");
Mehdi Aminid16c8062015-12-08 22:39:40 +0000134 SGV = SrcModule->getNamedValue(Split.first);
Teresa Johnson130de7a2015-11-24 19:55:04 +0000135#ifndef NDEBUG
136 // Assert that Split.second is module id
137 uint64_t ModuleId;
138 assert(!Split.second.getAsInteger(10, ModuleId));
139 assert(ModuleId == Index.getModuleId(FileName));
140#endif
141 }
Mehdi Amini42418ab2015-11-24 06:07:49 +0000142 Function *F = dyn_cast<Function>(SGV);
143 if (!F && isa<GlobalAlias>(SGV)) {
144 auto *SGA = dyn_cast<GlobalAlias>(SGV);
145 F = dyn_cast<Function>(SGA->getBaseObject());
Teresa Johnson130de7a2015-11-24 19:55:04 +0000146 ImportFunctionName = F->getName();
Mehdi Amini42418ab2015-11-24 06:07:49 +0000147 }
148 if (!F) {
149 errs() << "Can't load function '" << CalledFunctionName << "' in Module '"
150 << FileName << "', error in the summary?\n";
151 llvm_unreachable("Can't load function in Module");
152 }
153
Teresa Johnson17626652015-11-24 16:10:43 +0000154 // We cannot import weak_any functions/aliases without possibly affecting
155 // the order they are seen and selected by the linker, changing program
Mehdi Amini42418ab2015-11-24 06:07:49 +0000156 // semantics.
Teresa Johnson17626652015-11-24 16:10:43 +0000157 if (SGV->hasWeakAnyLinkage()) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000158 DEBUG(dbgs() << DestModule.getModuleIdentifier()
159 << " Ignoring import request for weak-any "
Teresa Johnson17626652015-11-24 16:10:43 +0000160 << (isa<Function>(SGV) ? "function " : "alias ")
Mehdi Amini42418ab2015-11-24 06:07:49 +0000161 << CalledFunctionName << " from " << FileName << "\n");
162 continue;
163 }
164
165 // Link in the specified function.
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000166 DenseSet<const GlobalValue *> FunctionsToImport;
167 FunctionsToImport.insert(F);
Mehdi Aminid16c8062015-12-08 22:39:40 +0000168 if (TheLinker.linkInModule(*SrcModule, Linker::Flags::None, &Index,
Mehdi Amini311fef62015-12-03 02:58:14 +0000169 &FunctionsToImport))
Mehdi Amini42418ab2015-11-24 06:07:49 +0000170 report_fatal_error("Function Import: link error");
171
Teresa Johnson130de7a2015-11-24 19:55:04 +0000172 // Process the newly imported function and add callees to the worklist.
Mehdi Aminic8c55172015-12-03 02:37:33 +0000173 GlobalValue *NewGV = DestModule.getNamedValue(ImportFunctionName);
Teresa Johnson130de7a2015-11-24 19:55:04 +0000174 assert(NewGV);
175 Function *NewF = dyn_cast<Function>(NewGV);
176 assert(NewF);
Teresa Johnsond450da32015-11-24 21:15:19 +0000177 findExternalCalls(*NewF, CalledFunctions, Worklist);
Mehdi Aminic8c55172015-12-03 02:37:33 +0000178 ++ImportCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000179 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000180 return ImportCount;
181}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000182
Mehdi Aminic8c55172015-12-03 02:37:33 +0000183// Automatically import functions in Module \p DestModule based on the summaries
184// index.
185//
186// The current implementation imports every called functions that exists in the
187// summaries index.
188bool FunctionImporter::importFunctions(Module &DestModule) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000189 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000190 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000191 unsigned ImportedCount = 0;
192
193 /// First step is collecting the called external functions.
194 StringSet<> CalledFunctions;
195 SmallVector<StringRef, 64> Worklist;
196 for (auto &F : DestModule) {
197 if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
198 continue;
199 findExternalCalls(F, CalledFunctions, Worklist);
200 }
201 if (Worklist.empty())
202 return false;
203
204 /// Second step: for every call to an external function, try to import it.
205
206 // Linker that will be used for importing function
207 Linker TheLinker(DestModule, DiagnosticHandler);
208
Mehdi Amini311fef62015-12-03 02:58:14 +0000209 ImportedCount += ProcessImportWorklist(DestModule, Worklist, CalledFunctions,
Mehdi Aminid16c8062015-12-08 22:39:40 +0000210 TheLinker, Index, ModuleLoader);
Mehdi Aminic8c55172015-12-03 02:37:33 +0000211
212 DEBUG(errs() << "Imported " << ImportedCount << " functions for Module "
213 << DestModule.getModuleIdentifier() << "\n");
214 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000215}
216
217/// Summary file to use for function importing when using -function-import from
218/// the command line.
219static cl::opt<std::string>
220 SummaryFile("summary-file",
221 cl::desc("The summary file to use for function importing."));
222
223static void diagnosticHandler(const DiagnosticInfo &DI) {
224 raw_ostream &OS = errs();
225 DiagnosticPrinterRawOStream DP(OS);
226 DI.print(DP);
227 OS << '\n';
228}
229
230/// Parse the function index out of an IR file and return the function
231/// index object if found, or nullptr if not.
232static std::unique_ptr<FunctionInfoIndex>
233getFunctionIndexForFile(StringRef Path, std::string &Error,
234 DiagnosticHandlerFunction DiagnosticHandler) {
235 std::unique_ptr<MemoryBuffer> Buffer;
236 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
237 MemoryBuffer::getFile(Path);
238 if (std::error_code EC = BufferOrErr.getError()) {
239 Error = EC.message();
240 return nullptr;
241 }
242 Buffer = std::move(BufferOrErr.get());
243 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
244 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
245 DiagnosticHandler);
246 if (std::error_code EC = ObjOrErr.getError()) {
247 Error = EC.message();
248 return nullptr;
249 }
250 return (*ObjOrErr)->takeIndex();
251}
252
253/// Pass that performs cross-module function import provided a summary file.
254class FunctionImportPass : public ModulePass {
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000255 /// Optional function summary index to use for importing, otherwise
256 /// the summary-file option must be specified.
257 FunctionInfoIndex *Index;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000258
259public:
260 /// Pass identification, replacement for typeid
261 static char ID;
262
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000263 /// Specify pass name for debug output
264 const char *getPassName() const override {
265 return "Function Importing";
266 }
267
268 explicit FunctionImportPass(FunctionInfoIndex *Index = nullptr)
269 : ModulePass(ID), Index(Index) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000270
271 bool runOnModule(Module &M) override {
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000272 if (SummaryFile.empty() && !Index)
273 report_fatal_error("error: -function-import requires -summary-file or "
274 "file from frontend\n");
275 std::unique_ptr<FunctionInfoIndex> IndexPtr;
276 if (!SummaryFile.empty()) {
277 if (Index)
278 report_fatal_error("error: -summary-file and index from frontend\n");
279 std::string Error;
280 IndexPtr = getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
281 if (!IndexPtr) {
282 errs() << "Error loading file '" << SummaryFile << "': " << Error
283 << "\n";
284 return false;
285 }
286 Index = IndexPtr.get();
Mehdi Amini42418ab2015-11-24 06:07:49 +0000287 }
288
289 // Perform the import now.
Mehdi Aminid16c8062015-12-08 22:39:40 +0000290 auto ModuleLoader = [&M](StringRef Identifier) {
291 return loadFile(Identifier, M.getContext());
292 };
293 FunctionImporter Importer(*Index, diagnosticHandler, ModuleLoader);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000294 return Importer.importFunctions(M);
295
296 return false;
297 }
298};
299
300char FunctionImportPass::ID = 0;
301INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
302 "Summary Based Function Import", false, false)
303INITIALIZE_PASS_END(FunctionImportPass, "function-import",
304 "Summary Based Function Import", false, false)
305
306namespace llvm {
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000307Pass *createFunctionImportPass(FunctionInfoIndex *Index = nullptr) {
308 return new FunctionImportPass(Index);
309}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000310}