blob: 32853b93f28460dd6d6486d8266c8fd89d7984be [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
Mehdi Amini01e32132016-03-26 05:40:34 +000016#include "llvm/ADT/SmallVector.h"
Teresa Johnsond29478f2016-03-27 15:27:30 +000017#include "llvm/ADT/Statistic.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000018#include "llvm/ADT/StringSet.h"
19#include "llvm/IR/AutoUpgrade.h"
20#include "llvm/IR/DiagnosticPrinter.h"
21#include "llvm/IR/IntrinsicInst.h"
22#include "llvm/IR/Module.h"
23#include "llvm/IRReader/IRReader.h"
24#include "llvm/Linker/Linker.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000025#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/SourceMgr.h"
Teresa Johnson488a8002016-02-10 18:11:31 +000029#include "llvm/Transforms/Utils/FunctionImportUtils.h"
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000030
Mehdi Amini01e32132016-03-26 05:40:34 +000031#define DEBUG_TYPE "function-import"
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000032
Mehdi Amini42418ab2015-11-24 06:07:49 +000033using namespace llvm;
34
Teresa Johnsond29478f2016-03-27 15:27:30 +000035STATISTIC(NumImported, "Number of functions imported");
36
Teresa Johnson39303612015-11-24 22:55:46 +000037/// Limit on instruction count of imported functions.
38static cl::opt<unsigned> ImportInstrLimit(
39 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
40 cl::desc("Only import functions with less than N instructions"));
41
Mehdi Amini40641742016-02-10 23:31:45 +000042static cl::opt<float>
43 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
44 cl::Hidden, cl::value_desc("x"),
45 cl::desc("As we import functions, multiply the "
46 "`import-instr-limit` threshold by this factor "
47 "before processing newly imported functions"));
48
Teresa Johnsond29478f2016-03-27 15:27:30 +000049static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
50 cl::desc("Print imported functions"));
51
Mehdi Amini42418ab2015-11-24 06:07:49 +000052// Load lazily a module from \p FileName in \p Context.
53static std::unique_ptr<Module> loadFile(const std::string &FileName,
54 LLVMContext &Context) {
55 SMDiagnostic Err;
56 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +000057 // Metadata isn't loaded until functions are imported, to minimize
58 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +000059 std::unique_ptr<Module> Result =
60 getLazyIRFileModule(FileName, Err, Context,
61 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +000062 if (!Result) {
63 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +000064 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +000065 }
66
Mehdi Amini42418ab2015-11-24 06:07:49 +000067 return Result;
68}
69
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000070namespace {
Mehdi Amini40641742016-02-10 23:31:45 +000071
Mehdi Amini01e32132016-03-26 05:40:34 +000072/// Given a list of possible callee implementation for a call site, select one
73/// that fits the \p Threshold.
74///
75/// FIXME: select "best" instead of first that fits. But what is "best"?
76/// - The smallest: more likely to be inlined.
77/// - The one with the least outgoing edges (already well optimized).
78/// - One from a module already being imported from in order to reduce the
79/// number of source modules parsed/linked.
80/// - One that has PGO data attached.
81/// - [insert you fancy metric here]
82static const FunctionSummary *
83selectCallee(const GlobalValueInfoList &CalleeInfoList, unsigned Threshold) {
84 auto It = llvm::find_if(
85 CalleeInfoList, [&](const std::unique_ptr<GlobalValueInfo> &GlobInfo) {
86 assert(GlobInfo->summary() &&
87 "We should not have a Global Info without summary");
88 auto *Summary = cast<FunctionSummary>(GlobInfo->summary());
Mehdi Amini40641742016-02-10 23:31:45 +000089
Mehdi Amini01e32132016-03-26 05:40:34 +000090 if (GlobalValue::isWeakAnyLinkage(Summary->linkage()))
91 return false;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000092
Mehdi Amini01e32132016-03-26 05:40:34 +000093 if (Summary->instCount() > Threshold)
94 return false;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000095
Mehdi Amini01e32132016-03-26 05:40:34 +000096 return true;
97 });
98 if (It == CalleeInfoList.end())
99 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000100
Mehdi Amini01e32132016-03-26 05:40:34 +0000101 return cast<FunctionSummary>((*It)->summary());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000102}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000103
Mehdi Amini01e32132016-03-26 05:40:34 +0000104/// Return the summary for the function \p GUID that fits the \p Threshold, or
105/// null if there's no match.
Mehdi Aminiad5741b2016-04-02 05:07:53 +0000106static const FunctionSummary *selectCallee(GlobalValue::GUID GUID,
107 unsigned Threshold,
Mehdi Amini01e32132016-03-26 05:40:34 +0000108 const ModuleSummaryIndex &Index) {
109 auto CalleeInfoList = Index.findGlobalValueInfoList(GUID);
110 if (CalleeInfoList == Index.end()) {
111 return nullptr; // This function does not have a summary
112 }
113 return selectCallee(CalleeInfoList->second, Threshold);
114}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000115
Mehdi Amini01e32132016-03-26 05:40:34 +0000116/// Return true if the global \p GUID is exported by module \p ExportModulePath.
117static bool isGlobalExported(const ModuleSummaryIndex &Index,
Mehdi Aminiad5741b2016-04-02 05:07:53 +0000118 StringRef ExportModulePath,
119 GlobalValue::GUID GUID) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000120 auto CalleeInfoList = Index.findGlobalValueInfoList(GUID);
121 if (CalleeInfoList == Index.end())
122 // This global does not have a summary, it is not part of the ThinLTO
123 // process
124 return false;
125 auto DefinedInCalleeModule = llvm::find_if(
126 CalleeInfoList->second,
127 [&](const std::unique_ptr<GlobalValueInfo> &GlobInfo) {
128 auto *Summary = GlobInfo->summary();
129 assert(Summary && "Unexpected GlobalValueInfo without summary");
130 return Summary->modulePath() == ExportModulePath;
131 });
132 return (DefinedInCalleeModule != CalleeInfoList->second.end());
133}
Mehdi Amini40641742016-02-10 23:31:45 +0000134
Mehdi Amini01e32132016-03-26 05:40:34 +0000135using EdgeInfo = std::pair<const FunctionSummary *, unsigned /* Threshold */>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000136
Mehdi Amini01e32132016-03-26 05:40:34 +0000137/// Compute the list of functions to import for a given caller. Mark these
138/// imported functions and the symbols they reference in their source module as
139/// exported from their source module.
140static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000141 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
142 unsigned Threshold,
Mehdi Aminiad5741b2016-04-02 05:07:53 +0000143 const std::map<GlobalValue::GUID, FunctionSummary *> &DefinedFunctions,
Mehdi Amini01e32132016-03-26 05:40:34 +0000144 SmallVectorImpl<EdgeInfo> &Worklist,
145 FunctionImporter::ImportMapTy &ImportsForModule,
146 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
147 for (auto &Edge : Summary.calls()) {
148 auto GUID = Edge.first;
149 DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
150
151 if (DefinedFunctions.count(GUID)) {
152 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
153 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000154 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000155
156 auto *CalleeSummary = selectCallee(GUID, Threshold, Index);
157 if (!CalleeSummary) {
158 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
159 continue;
160 }
161 assert(CalleeSummary->instCount() <= Threshold &&
162 "selectCallee() didn't honor the threshold");
163
164 auto &ProcessedThreshold =
165 ImportsForModule[CalleeSummary->modulePath()][GUID];
166 /// Since the traversal of the call graph is DFS, we can revisit a function
167 /// a second time with a higher threshold. In this case, it is added back to
168 /// the worklist with the new threshold.
169 if (ProcessedThreshold && ProcessedThreshold > Threshold) {
170 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
171 << ProcessedThreshold << "\n");
172 continue;
173 }
174 // Mark this function as imported in this module, with the current Threshold
175 ProcessedThreshold = Threshold;
176
177 // Make exports in the source module.
178 auto ExportModulePath = CalleeSummary->modulePath();
179 auto ExportList = ExportLists[ExportModulePath];
180 ExportList.insert(GUID);
181 // Mark all functions and globals referenced by this function as exported to
182 // the outside if they are defined in the same source module.
183 for (auto &Edge : CalleeSummary->calls()) {
184 auto CalleeGUID = Edge.first;
185 if (isGlobalExported(Index, ExportModulePath, CalleeGUID))
186 ExportList.insert(CalleeGUID);
187 }
188 for (auto &GUID : CalleeSummary->refs()) {
189 if (isGlobalExported(Index, ExportModulePath, GUID))
190 ExportList.insert(GUID);
191 }
192
193 // Insert the newly imported function to the worklist.
194 Worklist.push_back(std::make_pair(CalleeSummary, Threshold));
Teresa Johnsond450da32015-11-24 21:15:19 +0000195 }
196}
197
Mehdi Amini01e32132016-03-26 05:40:34 +0000198/// Given the list of globals defined in a module, compute the list of imports
199/// as well as the list of "exports", i.e. the list of symbols referenced from
200/// another module (that may require promotion).
201static void ComputeImportForModule(
Mehdi Aminiad5741b2016-04-02 05:07:53 +0000202 const std::map<GlobalValue::GUID, FunctionSummary *> &DefinedFunctions,
Mehdi Amini01e32132016-03-26 05:40:34 +0000203 const ModuleSummaryIndex &Index,
204 FunctionImporter::ImportMapTy &ImportsForModule,
205 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
206 // Worklist contains the list of function imported in this module, for which
207 // we will analyse the callees and may import further down the callgraph.
208 SmallVector<EdgeInfo, 128> Worklist;
209
210 // Populate the worklist with the import for the functions in the current
211 // module
212 for (auto &FuncInfo : DefinedFunctions) {
213 auto *Summary = FuncInfo.second;
214 DEBUG(dbgs() << "Initalize import for " << FuncInfo.first << "\n");
Teresa Johnson3255eec2016-04-10 15:17:26 +0000215 computeImportForFunction(*Summary, Index, ImportInstrLimit,
Mehdi Amini01e32132016-03-26 05:40:34 +0000216 DefinedFunctions, Worklist, ImportsForModule,
217 ExportLists);
218 }
219
Mehdi Amini42418ab2015-11-24 06:07:49 +0000220 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000221 auto FuncInfo = Worklist.pop_back_val();
222 auto *Summary = FuncInfo.first;
223 auto Threshold = FuncInfo.second;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000224
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000225 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini40641742016-02-10 23:31:45 +0000226 // Adjust the threshold
227 Threshold = Threshold * ImportInstrFactor;
Mehdi Amini01e32132016-03-26 05:40:34 +0000228
Teresa Johnson3255eec2016-04-10 15:17:26 +0000229 computeImportForFunction(*Summary, Index, Threshold, DefinedFunctions,
230 Worklist, ImportsForModule, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000231 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000232}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000233
Mehdi Amini01e32132016-03-26 05:40:34 +0000234} // anonymous namespace
235
236/// Compute all the import and export for every module in the Index.
237void llvm::ComputeCrossModuleImport(
238 const ModuleSummaryIndex &Index,
239 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
240 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
241 auto ModuleCount = Index.modulePaths().size();
242
243 // Collect for each module the list of function it defines.
244 // GUID -> Summary
Mehdi Aminiad5741b2016-04-02 05:07:53 +0000245 StringMap<std::map<GlobalValue::GUID, FunctionSummary *>>
246 Module2FunctionInfoMap(ModuleCount);
Mehdi Amini01e32132016-03-26 05:40:34 +0000247
248 for (auto &GlobalList : Index) {
249 auto GUID = GlobalList.first;
250 for (auto &GlobInfo : GlobalList.second) {
251 auto *Summary = dyn_cast_or_null<FunctionSummary>(GlobInfo->summary());
252 if (!Summary)
253 /// Ignore global variable, focus on functions
254 continue;
255 DEBUG(dbgs() << "Adding definition: Module '" << Summary->modulePath()
256 << "' defines '" << GUID << "'\n");
257 Module2FunctionInfoMap[Summary->modulePath()][GUID] = Summary;
258 }
259 }
260
261 // For each module that has function defined, compute the import/export lists.
262 for (auto &DefinedFunctions : Module2FunctionInfoMap) {
263 auto &ImportsForModule = ImportLists[DefinedFunctions.first()];
264 DEBUG(dbgs() << "Computing import for Module '" << DefinedFunctions.first()
265 << "'\n");
Teresa Johnson3255eec2016-04-10 15:17:26 +0000266 ComputeImportForModule(DefinedFunctions.second, Index, ImportsForModule,
267 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000268 }
269
270#ifndef NDEBUG
271 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
272 << " modules:\n");
273 for (auto &ModuleImports : ImportLists) {
274 auto ModName = ModuleImports.first();
275 auto &Exports = ExportLists[ModName];
276 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
277 << " functions. Imports from " << ModuleImports.second.size()
278 << " modules.\n");
279 for (auto &Src : ModuleImports.second) {
280 auto SrcModName = Src.first();
281 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
282 << SrcModName << "\n");
283 }
284 }
285#endif
286}
287
Mehdi Aminic8c55172015-12-03 02:37:33 +0000288// Automatically import functions in Module \p DestModule based on the summaries
289// index.
290//
Mehdi Amini01e32132016-03-26 05:40:34 +0000291bool FunctionImporter::importFunctions(
292 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000293 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000294 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000295 unsigned ImportedCount = 0;
296
Mehdi Aminic8c55172015-12-03 02:37:33 +0000297 // Linker that will be used for importing function
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000298 Linker TheLinker(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000299 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000300 std::set<StringRef> ModuleNameOrderedList;
301 for (auto &FunctionsToImportPerModule : ImportList) {
302 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
303 }
304 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000305 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000306 const auto &FunctionsToImportPerModule = ImportList.find(Name);
307 assert(FunctionsToImportPerModule != ImportList.end());
308 std::unique_ptr<Module> SrcModule = ModuleLoader(Name);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000309 assert(&DestModule.getContext() == &SrcModule->getContext() &&
310 "Context mismatch");
311
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000312 // If modules were created with lazy metadata loading, materialize it
313 // now, before linking it (otherwise this will be a noop).
314 SrcModule->materializeMetadata();
315 UpgradeDebugInfo(*SrcModule);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000316
Mehdi Amini01e32132016-03-26 05:40:34 +0000317 auto &ImportGUIDs = FunctionsToImportPerModule->second;
318 // Find the globals to import
319 DenseSet<const GlobalValue *> GlobalsToImport;
320 for (auto &GV : *SrcModule) {
Teresa Johnson0beb8582016-04-04 18:52:23 +0000321 if (!GV.hasName())
322 continue;
323 auto GUID = GV.getGUID();
324 auto Import = ImportGUIDs.count(GUID);
325 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing " << GUID << " "
326 << GV.getName() << " from " << SrcModule->getSourceFileName()
327 << "\n");
328 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000329 GV.materialize();
330 GlobalsToImport.insert(&GV);
331 }
332 }
333 for (auto &GV : SrcModule->aliases()) {
334 if (!GV.hasName())
335 continue;
336 auto GUID = GV.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000337 auto Import = ImportGUIDs.count(GUID);
338 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing " << GUID << " "
339 << GV.getName() << " from " << SrcModule->getSourceFileName()
340 << "\n");
341 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000342 // Alias can't point to "available_externally". However when we import
Teresa Johnson9aae3952016-03-27 15:01:11 +0000343 // linkOnceODR the linkage does not change. So we import the alias
344 // and aliasee only in this case.
Mehdi Amini01e32132016-03-26 05:40:34 +0000345 const GlobalObject *GO = GV.getBaseObject();
346 if (!GO->hasLinkOnceODRLinkage())
347 continue;
Teresa Johnson9aae3952016-03-27 15:01:11 +0000348 GV.materialize();
349 GlobalsToImport.insert(&GV);
Mehdi Amini01e32132016-03-26 05:40:34 +0000350 GlobalsToImport.insert(GO);
351 }
352 }
353 for (auto &GV : SrcModule->globals()) {
354 if (!GV.hasName())
355 continue;
Teresa Johnsonefeae0e2016-03-29 14:49:26 +0000356 auto GUID = GV.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000357 auto Import = ImportGUIDs.count(GUID);
358 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing " << GUID << " "
359 << GV.getName() << " from " << SrcModule->getSourceFileName()
360 << "\n");
361 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000362 GV.materialize();
363 GlobalsToImport.insert(&GV);
364 }
365 }
366
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000367 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000368 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000369 return true;
370
Teresa Johnsond29478f2016-03-27 15:27:30 +0000371 if (PrintImports) {
372 for (const auto *GV : GlobalsToImport)
373 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
374 << " from " << SrcModule->getSourceFileName() << "\n";
375 }
376
Rafael Espindola434e9562015-12-16 23:16:33 +0000377 if (TheLinker.linkInModule(std::move(SrcModule), Linker::Flags::None,
Mehdi Amini01e32132016-03-26 05:40:34 +0000378 &GlobalsToImport))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000379 report_fatal_error("Function Import: link error");
380
Mehdi Amini01e32132016-03-26 05:40:34 +0000381 ImportedCount += GlobalsToImport.size();
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000382 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000383
Teresa Johnsond29478f2016-03-27 15:27:30 +0000384 NumImported += ImportedCount;
385
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000386 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000387 << DestModule.getModuleIdentifier() << "\n");
388 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000389}
390
391/// Summary file to use for function importing when using -function-import from
392/// the command line.
393static cl::opt<std::string>
394 SummaryFile("summary-file",
395 cl::desc("The summary file to use for function importing."));
396
397static void diagnosticHandler(const DiagnosticInfo &DI) {
398 raw_ostream &OS = errs();
399 DiagnosticPrinterRawOStream DP(OS);
400 DI.print(DP);
401 OS << '\n';
402}
403
Teresa Johnson26ab5772016-03-15 00:04:37 +0000404/// Parse the summary index out of an IR file and return the summary
Mehdi Amini42418ab2015-11-24 06:07:49 +0000405/// index object if found, or nullptr if not.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000406static std::unique_ptr<ModuleSummaryIndex>
407getModuleSummaryIndexForFile(StringRef Path, std::string &Error,
408 DiagnosticHandlerFunction DiagnosticHandler) {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000409 std::unique_ptr<MemoryBuffer> Buffer;
410 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
411 MemoryBuffer::getFile(Path);
412 if (std::error_code EC = BufferOrErr.getError()) {
413 Error = EC.message();
414 return nullptr;
415 }
416 Buffer = std::move(BufferOrErr.get());
Teresa Johnson26ab5772016-03-15 00:04:37 +0000417 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
418 object::ModuleSummaryIndexObjectFile::create(Buffer->getMemBufferRef(),
419 DiagnosticHandler);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000420 if (std::error_code EC = ObjOrErr.getError()) {
421 Error = EC.message();
422 return nullptr;
423 }
424 return (*ObjOrErr)->takeIndex();
425}
426
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000427namespace {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000428/// Pass that performs cross-module function import provided a summary file.
429class FunctionImportPass : public ModulePass {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000430 /// Optional module summary index to use for importing, otherwise
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000431 /// the summary-file option must be specified.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000432 const ModuleSummaryIndex *Index;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000433
434public:
435 /// Pass identification, replacement for typeid
436 static char ID;
437
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000438 /// Specify pass name for debug output
439 const char *getPassName() const override {
440 return "Function Importing";
441 }
442
Teresa Johnson26ab5772016-03-15 00:04:37 +0000443 explicit FunctionImportPass(const ModuleSummaryIndex *Index = nullptr)
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000444 : ModulePass(ID), Index(Index) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000445
446 bool runOnModule(Module &M) override {
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000447 if (SummaryFile.empty() && !Index)
448 report_fatal_error("error: -function-import requires -summary-file or "
449 "file from frontend\n");
Teresa Johnson26ab5772016-03-15 00:04:37 +0000450 std::unique_ptr<ModuleSummaryIndex> IndexPtr;
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000451 if (!SummaryFile.empty()) {
452 if (Index)
453 report_fatal_error("error: -summary-file and index from frontend\n");
454 std::string Error;
Teresa Johnson26ab5772016-03-15 00:04:37 +0000455 IndexPtr =
456 getModuleSummaryIndexForFile(SummaryFile, Error, diagnosticHandler);
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000457 if (!IndexPtr) {
458 errs() << "Error loading file '" << SummaryFile << "': " << Error
459 << "\n";
460 return false;
461 }
462 Index = IndexPtr.get();
Mehdi Amini42418ab2015-11-24 06:07:49 +0000463 }
464
Mehdi Amini01e32132016-03-26 05:40:34 +0000465 // First step is collecting the import/export lists
466 // The export list is not used yet, but could limit the amount of renaming
467 // performed in renameModuleForThinLTO()
468 StringMap<FunctionImporter::ImportMapTy> ImportLists;
469 StringMap<FunctionImporter::ExportSetTy> ExportLists;
470 ComputeCrossModuleImport(*Index, ImportLists, ExportLists);
471 auto &ImportList = ImportLists[M.getModuleIdentifier()];
472
473 // Next we need to promote to global scope and rename any local values that
Teresa Johnson1b00f2d2016-01-08 17:06:29 +0000474 // are potentially exported to other modules.
Mehdi Amini01e32132016-03-26 05:40:34 +0000475 if (renameModuleForThinLTO(M, *Index, nullptr)) {
Teresa Johnson1b00f2d2016-01-08 17:06:29 +0000476 errs() << "Error renaming module\n";
477 return false;
478 }
479
Mehdi Amini42418ab2015-11-24 06:07:49 +0000480 // Perform the import now.
Mehdi Aminid16c8062015-12-08 22:39:40 +0000481 auto ModuleLoader = [&M](StringRef Identifier) {
482 return loadFile(Identifier, M.getContext());
483 };
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000484 FunctionImporter Importer(*Index, ModuleLoader);
Mehdi Amini01e32132016-03-26 05:40:34 +0000485 return Importer.importFunctions(M, ImportList);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000486 }
487};
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000488} // anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000489
490char FunctionImportPass::ID = 0;
491INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
492 "Summary Based Function Import", false, false)
493INITIALIZE_PASS_END(FunctionImportPass, "function-import",
494 "Summary Based Function Import", false, false)
495
496namespace llvm {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000497Pass *createFunctionImportPass(const ModuleSummaryIndex *Index = nullptr) {
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000498 return new FunctionImportPass(Index);
499}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000500}