blob: a1d36de214e9608b824afdc99f99479aecf2e750 [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(
141 StringRef ModulePath, const FunctionSummary &Summary,
142 const ModuleSummaryIndex &Index, 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(
202 StringRef ModulePath,
Mehdi Aminiad5741b2016-04-02 05:07:53 +0000203 const std::map<GlobalValue::GUID, FunctionSummary *> &DefinedFunctions,
Mehdi Amini01e32132016-03-26 05:40:34 +0000204 const ModuleSummaryIndex &Index,
205 FunctionImporter::ImportMapTy &ImportsForModule,
206 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
207 // Worklist contains the list of function imported in this module, for which
208 // we will analyse the callees and may import further down the callgraph.
209 SmallVector<EdgeInfo, 128> Worklist;
210
211 // Populate the worklist with the import for the functions in the current
212 // module
213 for (auto &FuncInfo : DefinedFunctions) {
214 auto *Summary = FuncInfo.second;
215 DEBUG(dbgs() << "Initalize import for " << FuncInfo.first << "\n");
216 computeImportForFunction(ModulePath, *Summary, Index, ImportInstrLimit,
217 DefinedFunctions, Worklist, ImportsForModule,
218 ExportLists);
219 }
220
Mehdi Amini42418ab2015-11-24 06:07:49 +0000221 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000222 auto FuncInfo = Worklist.pop_back_val();
223 auto *Summary = FuncInfo.first;
224 auto Threshold = FuncInfo.second;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000225
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000226 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini40641742016-02-10 23:31:45 +0000227 // Adjust the threshold
228 Threshold = Threshold * ImportInstrFactor;
Mehdi Amini01e32132016-03-26 05:40:34 +0000229
230 computeImportForFunction(ModulePath, *Summary, Index, Threshold,
231 DefinedFunctions, Worklist, ImportsForModule,
232 ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000233 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000234}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000235
Mehdi Amini01e32132016-03-26 05:40:34 +0000236} // anonymous namespace
237
238/// Compute all the import and export for every module in the Index.
239void llvm::ComputeCrossModuleImport(
240 const ModuleSummaryIndex &Index,
241 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
242 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
243 auto ModuleCount = Index.modulePaths().size();
244
245 // Collect for each module the list of function it defines.
246 // GUID -> Summary
Mehdi Aminiad5741b2016-04-02 05:07:53 +0000247 StringMap<std::map<GlobalValue::GUID, FunctionSummary *>>
248 Module2FunctionInfoMap(ModuleCount);
Mehdi Amini01e32132016-03-26 05:40:34 +0000249
250 for (auto &GlobalList : Index) {
251 auto GUID = GlobalList.first;
252 for (auto &GlobInfo : GlobalList.second) {
253 auto *Summary = dyn_cast_or_null<FunctionSummary>(GlobInfo->summary());
254 if (!Summary)
255 /// Ignore global variable, focus on functions
256 continue;
257 DEBUG(dbgs() << "Adding definition: Module '" << Summary->modulePath()
258 << "' defines '" << GUID << "'\n");
259 Module2FunctionInfoMap[Summary->modulePath()][GUID] = Summary;
260 }
261 }
262
263 // For each module that has function defined, compute the import/export lists.
264 for (auto &DefinedFunctions : Module2FunctionInfoMap) {
265 auto &ImportsForModule = ImportLists[DefinedFunctions.first()];
266 DEBUG(dbgs() << "Computing import for Module '" << DefinedFunctions.first()
267 << "'\n");
268 ComputeImportForModule(DefinedFunctions.first(), DefinedFunctions.second,
269 Index, ImportsForModule, ExportLists);
270 }
271
272#ifndef NDEBUG
273 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
274 << " modules:\n");
275 for (auto &ModuleImports : ImportLists) {
276 auto ModName = ModuleImports.first();
277 auto &Exports = ExportLists[ModName];
278 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
279 << " functions. Imports from " << ModuleImports.second.size()
280 << " modules.\n");
281 for (auto &Src : ModuleImports.second) {
282 auto SrcModName = Src.first();
283 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
284 << SrcModName << "\n");
285 }
286 }
287#endif
288}
289
Mehdi Aminic8c55172015-12-03 02:37:33 +0000290// Automatically import functions in Module \p DestModule based on the summaries
291// index.
292//
Mehdi Amini01e32132016-03-26 05:40:34 +0000293bool FunctionImporter::importFunctions(
294 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000295 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000296 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000297 unsigned ImportedCount = 0;
298
Mehdi Aminic8c55172015-12-03 02:37:33 +0000299 // Linker that will be used for importing function
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000300 Linker TheLinker(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000301 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000302 std::set<StringRef> ModuleNameOrderedList;
303 for (auto &FunctionsToImportPerModule : ImportList) {
304 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
305 }
306 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000307 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000308 const auto &FunctionsToImportPerModule = ImportList.find(Name);
309 assert(FunctionsToImportPerModule != ImportList.end());
310 std::unique_ptr<Module> SrcModule = ModuleLoader(Name);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000311 assert(&DestModule.getContext() == &SrcModule->getContext() &&
312 "Context mismatch");
313
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000314 // If modules were created with lazy metadata loading, materialize it
315 // now, before linking it (otherwise this will be a noop).
316 SrcModule->materializeMetadata();
317 UpgradeDebugInfo(*SrcModule);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000318
Mehdi Amini01e32132016-03-26 05:40:34 +0000319 auto &ImportGUIDs = FunctionsToImportPerModule->second;
320 // Find the globals to import
321 DenseSet<const GlobalValue *> GlobalsToImport;
322 for (auto &GV : *SrcModule) {
Teresa Johnson0beb8582016-04-04 18:52:23 +0000323 if (!GV.hasName())
324 continue;
325 auto GUID = GV.getGUID();
326 auto Import = ImportGUIDs.count(GUID);
327 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing " << GUID << " "
328 << GV.getName() << " from " << SrcModule->getSourceFileName()
329 << "\n");
330 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000331 GV.materialize();
332 GlobalsToImport.insert(&GV);
333 }
334 }
335 for (auto &GV : SrcModule->aliases()) {
336 if (!GV.hasName())
337 continue;
338 auto GUID = GV.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000339 auto Import = ImportGUIDs.count(GUID);
340 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing " << GUID << " "
341 << GV.getName() << " from " << SrcModule->getSourceFileName()
342 << "\n");
343 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000344 // Alias can't point to "available_externally". However when we import
Teresa Johnson9aae3952016-03-27 15:01:11 +0000345 // linkOnceODR the linkage does not change. So we import the alias
346 // and aliasee only in this case.
Mehdi Amini01e32132016-03-26 05:40:34 +0000347 const GlobalObject *GO = GV.getBaseObject();
348 if (!GO->hasLinkOnceODRLinkage())
349 continue;
Teresa Johnson9aae3952016-03-27 15:01:11 +0000350 GV.materialize();
351 GlobalsToImport.insert(&GV);
Mehdi Amini01e32132016-03-26 05:40:34 +0000352 GlobalsToImport.insert(GO);
353 }
354 }
355 for (auto &GV : SrcModule->globals()) {
356 if (!GV.hasName())
357 continue;
Teresa Johnsonefeae0e2016-03-29 14:49:26 +0000358 auto GUID = GV.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000359 auto Import = ImportGUIDs.count(GUID);
360 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing " << GUID << " "
361 << GV.getName() << " from " << SrcModule->getSourceFileName()
362 << "\n");
363 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000364 GV.materialize();
365 GlobalsToImport.insert(&GV);
366 }
367 }
368
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000369 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000370 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000371 return true;
372
Teresa Johnsond29478f2016-03-27 15:27:30 +0000373 if (PrintImports) {
374 for (const auto *GV : GlobalsToImport)
375 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
376 << " from " << SrcModule->getSourceFileName() << "\n";
377 }
378
Rafael Espindola434e9562015-12-16 23:16:33 +0000379 if (TheLinker.linkInModule(std::move(SrcModule), Linker::Flags::None,
Mehdi Amini01e32132016-03-26 05:40:34 +0000380 &GlobalsToImport))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000381 report_fatal_error("Function Import: link error");
382
Mehdi Amini01e32132016-03-26 05:40:34 +0000383 ImportedCount += GlobalsToImport.size();
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000384 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000385
Teresa Johnsond29478f2016-03-27 15:27:30 +0000386 NumImported += ImportedCount;
387
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000388 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000389 << DestModule.getModuleIdentifier() << "\n");
390 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000391}
392
393/// Summary file to use for function importing when using -function-import from
394/// the command line.
395static cl::opt<std::string>
396 SummaryFile("summary-file",
397 cl::desc("The summary file to use for function importing."));
398
399static void diagnosticHandler(const DiagnosticInfo &DI) {
400 raw_ostream &OS = errs();
401 DiagnosticPrinterRawOStream DP(OS);
402 DI.print(DP);
403 OS << '\n';
404}
405
Teresa Johnson26ab5772016-03-15 00:04:37 +0000406/// Parse the summary index out of an IR file and return the summary
Mehdi Amini42418ab2015-11-24 06:07:49 +0000407/// index object if found, or nullptr if not.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000408static std::unique_ptr<ModuleSummaryIndex>
409getModuleSummaryIndexForFile(StringRef Path, std::string &Error,
410 DiagnosticHandlerFunction DiagnosticHandler) {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000411 std::unique_ptr<MemoryBuffer> Buffer;
412 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
413 MemoryBuffer::getFile(Path);
414 if (std::error_code EC = BufferOrErr.getError()) {
415 Error = EC.message();
416 return nullptr;
417 }
418 Buffer = std::move(BufferOrErr.get());
Teresa Johnson26ab5772016-03-15 00:04:37 +0000419 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
420 object::ModuleSummaryIndexObjectFile::create(Buffer->getMemBufferRef(),
421 DiagnosticHandler);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000422 if (std::error_code EC = ObjOrErr.getError()) {
423 Error = EC.message();
424 return nullptr;
425 }
426 return (*ObjOrErr)->takeIndex();
427}
428
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000429namespace {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000430/// Pass that performs cross-module function import provided a summary file.
431class FunctionImportPass : public ModulePass {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000432 /// Optional module summary index to use for importing, otherwise
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000433 /// the summary-file option must be specified.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000434 const ModuleSummaryIndex *Index;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000435
436public:
437 /// Pass identification, replacement for typeid
438 static char ID;
439
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000440 /// Specify pass name for debug output
441 const char *getPassName() const override {
442 return "Function Importing";
443 }
444
Teresa Johnson26ab5772016-03-15 00:04:37 +0000445 explicit FunctionImportPass(const ModuleSummaryIndex *Index = nullptr)
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000446 : ModulePass(ID), Index(Index) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000447
448 bool runOnModule(Module &M) override {
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000449 if (SummaryFile.empty() && !Index)
450 report_fatal_error("error: -function-import requires -summary-file or "
451 "file from frontend\n");
Teresa Johnson26ab5772016-03-15 00:04:37 +0000452 std::unique_ptr<ModuleSummaryIndex> IndexPtr;
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000453 if (!SummaryFile.empty()) {
454 if (Index)
455 report_fatal_error("error: -summary-file and index from frontend\n");
456 std::string Error;
Teresa Johnson26ab5772016-03-15 00:04:37 +0000457 IndexPtr =
458 getModuleSummaryIndexForFile(SummaryFile, Error, diagnosticHandler);
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000459 if (!IndexPtr) {
460 errs() << "Error loading file '" << SummaryFile << "': " << Error
461 << "\n";
462 return false;
463 }
464 Index = IndexPtr.get();
Mehdi Amini42418ab2015-11-24 06:07:49 +0000465 }
466
Mehdi Amini01e32132016-03-26 05:40:34 +0000467 // First step is collecting the import/export lists
468 // The export list is not used yet, but could limit the amount of renaming
469 // performed in renameModuleForThinLTO()
470 StringMap<FunctionImporter::ImportMapTy> ImportLists;
471 StringMap<FunctionImporter::ExportSetTy> ExportLists;
472 ComputeCrossModuleImport(*Index, ImportLists, ExportLists);
473 auto &ImportList = ImportLists[M.getModuleIdentifier()];
474
475 // Next we need to promote to global scope and rename any local values that
Teresa Johnson1b00f2d2016-01-08 17:06:29 +0000476 // are potentially exported to other modules.
Mehdi Amini01e32132016-03-26 05:40:34 +0000477 if (renameModuleForThinLTO(M, *Index, nullptr)) {
Teresa Johnson1b00f2d2016-01-08 17:06:29 +0000478 errs() << "Error renaming module\n";
479 return false;
480 }
481
Mehdi Amini42418ab2015-11-24 06:07:49 +0000482 // Perform the import now.
Mehdi Aminid16c8062015-12-08 22:39:40 +0000483 auto ModuleLoader = [&M](StringRef Identifier) {
484 return loadFile(Identifier, M.getContext());
485 };
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000486 FunctionImporter Importer(*Index, ModuleLoader);
Mehdi Amini01e32132016-03-26 05:40:34 +0000487 return Importer.importFunctions(M, ImportList);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000488 }
489};
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000490} // anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000491
492char FunctionImportPass::ID = 0;
493INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
494 "Summary Based Function Import", false, false)
495INITIALIZE_PASS_END(FunctionImportPass, "function-import",
496 "Summary Based Function Import", false, false)
497
498namespace llvm {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000499Pass *createFunctionImportPass(const ModuleSummaryIndex *Index = nullptr) {
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000500 return new FunctionImportPass(Index);
501}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000502}