blob: 63cfca424c5fa1aa6230f9136c979d7f524c4d2b [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,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000146 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000147 for (auto &Edge : Summary.calls()) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000148 auto GUID = Edge.first.getGUID();
Mehdi Amini01e32132016-03-26 05:40:34 +0000149 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();
Teresa Johnsonc86af332016-04-12 21:13:11 +0000179 if (ExportLists) {
180 auto ExportList = (*ExportLists)[ExportModulePath];
181 ExportList.insert(GUID);
182 // Mark all functions and globals referenced by this function as exported
183 // to the outside if they are defined in the same source module.
184 for (auto &Edge : CalleeSummary->calls()) {
185 auto CalleeGUID = Edge.first.getGUID();
186 if (isGlobalExported(Index, ExportModulePath, CalleeGUID))
187 ExportList.insert(CalleeGUID);
188 }
189 for (auto &Ref : CalleeSummary->refs()) {
190 auto GUID = Ref.getGUID();
191 if (isGlobalExported(Index, ExportModulePath, GUID))
192 ExportList.insert(GUID);
193 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000194 }
195
196 // Insert the newly imported function to the worklist.
197 Worklist.push_back(std::make_pair(CalleeSummary, Threshold));
Teresa Johnsond450da32015-11-24 21:15:19 +0000198 }
199}
200
Mehdi Amini01e32132016-03-26 05:40:34 +0000201/// Given the list of globals defined in a module, compute the list of imports
202/// as well as the list of "exports", i.e. the list of symbols referenced from
203/// another module (that may require promotion).
204static void ComputeImportForModule(
Mehdi Aminiad5741b2016-04-02 05:07:53 +0000205 const std::map<GlobalValue::GUID, FunctionSummary *> &DefinedFunctions,
Mehdi Amini01e32132016-03-26 05:40:34 +0000206 const ModuleSummaryIndex &Index,
207 FunctionImporter::ImportMapTy &ImportsForModule,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000208 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000209 // Worklist contains the list of function imported in this module, for which
210 // we will analyse the callees and may import further down the callgraph.
211 SmallVector<EdgeInfo, 128> Worklist;
212
213 // Populate the worklist with the import for the functions in the current
214 // module
215 for (auto &FuncInfo : DefinedFunctions) {
216 auto *Summary = FuncInfo.second;
217 DEBUG(dbgs() << "Initalize import for " << FuncInfo.first << "\n");
Teresa Johnson3255eec2016-04-10 15:17:26 +0000218 computeImportForFunction(*Summary, Index, ImportInstrLimit,
Mehdi Amini01e32132016-03-26 05:40:34 +0000219 DefinedFunctions, Worklist, ImportsForModule,
220 ExportLists);
221 }
222
Mehdi Amini42418ab2015-11-24 06:07:49 +0000223 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000224 auto FuncInfo = Worklist.pop_back_val();
225 auto *Summary = FuncInfo.first;
226 auto Threshold = FuncInfo.second;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000227
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000228 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini40641742016-02-10 23:31:45 +0000229 // Adjust the threshold
230 Threshold = Threshold * ImportInstrFactor;
Mehdi Amini01e32132016-03-26 05:40:34 +0000231
Teresa Johnson3255eec2016-04-10 15:17:26 +0000232 computeImportForFunction(*Summary, Index, Threshold, DefinedFunctions,
233 Worklist, ImportsForModule, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000234 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000235}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000236
Mehdi Amini01e32132016-03-26 05:40:34 +0000237} // anonymous namespace
238
Teresa Johnsonc86af332016-04-12 21:13:11 +0000239/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000240void llvm::ComputeCrossModuleImport(
241 const ModuleSummaryIndex &Index,
242 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
243 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
244 auto ModuleCount = Index.modulePaths().size();
245
246 // Collect for each module the list of function it defines.
247 // GUID -> Summary
Mehdi Aminiad5741b2016-04-02 05:07:53 +0000248 StringMap<std::map<GlobalValue::GUID, FunctionSummary *>>
249 Module2FunctionInfoMap(ModuleCount);
Mehdi Amini01e32132016-03-26 05:40:34 +0000250
251 for (auto &GlobalList : Index) {
252 auto GUID = GlobalList.first;
253 for (auto &GlobInfo : GlobalList.second) {
254 auto *Summary = dyn_cast_or_null<FunctionSummary>(GlobInfo->summary());
255 if (!Summary)
256 /// Ignore global variable, focus on functions
257 continue;
258 DEBUG(dbgs() << "Adding definition: Module '" << Summary->modulePath()
259 << "' defines '" << GUID << "'\n");
260 Module2FunctionInfoMap[Summary->modulePath()][GUID] = Summary;
261 }
262 }
263
264 // For each module that has function defined, compute the import/export lists.
265 for (auto &DefinedFunctions : Module2FunctionInfoMap) {
266 auto &ImportsForModule = ImportLists[DefinedFunctions.first()];
267 DEBUG(dbgs() << "Computing import for Module '" << DefinedFunctions.first()
268 << "'\n");
Teresa Johnson3255eec2016-04-10 15:17:26 +0000269 ComputeImportForModule(DefinedFunctions.second, Index, ImportsForModule,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000270 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000271 }
272
273#ifndef NDEBUG
274 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
275 << " modules:\n");
276 for (auto &ModuleImports : ImportLists) {
277 auto ModName = ModuleImports.first();
278 auto &Exports = ExportLists[ModName];
279 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
280 << " functions. Imports from " << ModuleImports.second.size()
281 << " modules.\n");
282 for (auto &Src : ModuleImports.second) {
283 auto SrcModName = Src.first();
284 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
285 << SrcModName << "\n");
286 }
287 }
288#endif
289}
290
Teresa Johnsonc86af332016-04-12 21:13:11 +0000291/// Compute all the imports for the given module in the Index.
292void llvm::ComputeCrossModuleImportForModule(
293 StringRef ModulePath, const ModuleSummaryIndex &Index,
294 FunctionImporter::ImportMapTy &ImportList) {
295
296 // Collect the list of functions this module defines.
297 // GUID -> Summary
298 std::map<GlobalValue::GUID, FunctionSummary *> FunctionInfoMap;
299 Index.collectDefinedFunctionsForModule(ModulePath, FunctionInfoMap);
300
301 // Compute the import list for this module.
302 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
303 ComputeImportForModule(FunctionInfoMap, Index, ImportList);
304
305#ifndef NDEBUG
306 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
307 << ImportList.size() << " modules.\n");
308 for (auto &Src : ImportList) {
309 auto SrcModName = Src.first();
310 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
311 << SrcModName << "\n");
312 }
313#endif
314}
315
Mehdi Aminic8c55172015-12-03 02:37:33 +0000316// Automatically import functions in Module \p DestModule based on the summaries
317// index.
318//
Mehdi Amini01e32132016-03-26 05:40:34 +0000319bool FunctionImporter::importFunctions(
320 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000321 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000322 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000323 unsigned ImportedCount = 0;
324
Mehdi Aminic8c55172015-12-03 02:37:33 +0000325 // Linker that will be used for importing function
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000326 Linker TheLinker(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000327 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000328 std::set<StringRef> ModuleNameOrderedList;
329 for (auto &FunctionsToImportPerModule : ImportList) {
330 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
331 }
332 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000333 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000334 const auto &FunctionsToImportPerModule = ImportList.find(Name);
335 assert(FunctionsToImportPerModule != ImportList.end());
336 std::unique_ptr<Module> SrcModule = ModuleLoader(Name);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000337 assert(&DestModule.getContext() == &SrcModule->getContext() &&
338 "Context mismatch");
339
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000340 // If modules were created with lazy metadata loading, materialize it
341 // now, before linking it (otherwise this will be a noop).
342 SrcModule->materializeMetadata();
343 UpgradeDebugInfo(*SrcModule);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000344
Mehdi Amini01e32132016-03-26 05:40:34 +0000345 auto &ImportGUIDs = FunctionsToImportPerModule->second;
346 // Find the globals to import
347 DenseSet<const GlobalValue *> GlobalsToImport;
348 for (auto &GV : *SrcModule) {
Teresa Johnson0beb8582016-04-04 18:52:23 +0000349 if (!GV.hasName())
350 continue;
351 auto GUID = GV.getGUID();
352 auto Import = ImportGUIDs.count(GUID);
353 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing " << GUID << " "
354 << GV.getName() << " from " << SrcModule->getSourceFileName()
355 << "\n");
356 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000357 GV.materialize();
358 GlobalsToImport.insert(&GV);
359 }
360 }
361 for (auto &GV : SrcModule->aliases()) {
362 if (!GV.hasName())
363 continue;
364 auto GUID = GV.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000365 auto Import = ImportGUIDs.count(GUID);
366 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing " << GUID << " "
367 << GV.getName() << " from " << SrcModule->getSourceFileName()
368 << "\n");
369 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000370 // Alias can't point to "available_externally". However when we import
Teresa Johnson9aae3952016-03-27 15:01:11 +0000371 // linkOnceODR the linkage does not change. So we import the alias
372 // and aliasee only in this case.
Mehdi Amini01e32132016-03-26 05:40:34 +0000373 const GlobalObject *GO = GV.getBaseObject();
374 if (!GO->hasLinkOnceODRLinkage())
375 continue;
Teresa Johnson9aae3952016-03-27 15:01:11 +0000376 GV.materialize();
377 GlobalsToImport.insert(&GV);
Mehdi Amini01e32132016-03-26 05:40:34 +0000378 GlobalsToImport.insert(GO);
379 }
380 }
381 for (auto &GV : SrcModule->globals()) {
382 if (!GV.hasName())
383 continue;
Teresa Johnsonefeae0e2016-03-29 14:49:26 +0000384 auto GUID = GV.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000385 auto Import = ImportGUIDs.count(GUID);
386 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing " << GUID << " "
387 << GV.getName() << " from " << SrcModule->getSourceFileName()
388 << "\n");
389 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000390 GV.materialize();
391 GlobalsToImport.insert(&GV);
392 }
393 }
394
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000395 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000396 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000397 return true;
398
Teresa Johnsond29478f2016-03-27 15:27:30 +0000399 if (PrintImports) {
400 for (const auto *GV : GlobalsToImport)
401 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
402 << " from " << SrcModule->getSourceFileName() << "\n";
403 }
404
Rafael Espindola434e9562015-12-16 23:16:33 +0000405 if (TheLinker.linkInModule(std::move(SrcModule), Linker::Flags::None,
Mehdi Amini01e32132016-03-26 05:40:34 +0000406 &GlobalsToImport))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000407 report_fatal_error("Function Import: link error");
408
Mehdi Amini01e32132016-03-26 05:40:34 +0000409 ImportedCount += GlobalsToImport.size();
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000410 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000411
Teresa Johnsond29478f2016-03-27 15:27:30 +0000412 NumImported += ImportedCount;
413
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000414 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000415 << DestModule.getModuleIdentifier() << "\n");
416 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000417}
418
419/// Summary file to use for function importing when using -function-import from
420/// the command line.
421static cl::opt<std::string>
422 SummaryFile("summary-file",
423 cl::desc("The summary file to use for function importing."));
424
425static void diagnosticHandler(const DiagnosticInfo &DI) {
426 raw_ostream &OS = errs();
427 DiagnosticPrinterRawOStream DP(OS);
428 DI.print(DP);
429 OS << '\n';
430}
431
Teresa Johnson26ab5772016-03-15 00:04:37 +0000432/// Parse the summary index out of an IR file and return the summary
Mehdi Amini42418ab2015-11-24 06:07:49 +0000433/// index object if found, or nullptr if not.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000434static std::unique_ptr<ModuleSummaryIndex>
435getModuleSummaryIndexForFile(StringRef Path, std::string &Error,
436 DiagnosticHandlerFunction DiagnosticHandler) {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000437 std::unique_ptr<MemoryBuffer> Buffer;
438 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
439 MemoryBuffer::getFile(Path);
440 if (std::error_code EC = BufferOrErr.getError()) {
441 Error = EC.message();
442 return nullptr;
443 }
444 Buffer = std::move(BufferOrErr.get());
Teresa Johnson26ab5772016-03-15 00:04:37 +0000445 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
446 object::ModuleSummaryIndexObjectFile::create(Buffer->getMemBufferRef(),
447 DiagnosticHandler);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000448 if (std::error_code EC = ObjOrErr.getError()) {
449 Error = EC.message();
450 return nullptr;
451 }
452 return (*ObjOrErr)->takeIndex();
453}
454
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000455namespace {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000456/// Pass that performs cross-module function import provided a summary file.
457class FunctionImportPass : public ModulePass {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000458 /// Optional module summary index to use for importing, otherwise
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000459 /// the summary-file option must be specified.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000460 const ModuleSummaryIndex *Index;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000461
462public:
463 /// Pass identification, replacement for typeid
464 static char ID;
465
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000466 /// Specify pass name for debug output
467 const char *getPassName() const override {
468 return "Function Importing";
469 }
470
Teresa Johnson26ab5772016-03-15 00:04:37 +0000471 explicit FunctionImportPass(const ModuleSummaryIndex *Index = nullptr)
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000472 : ModulePass(ID), Index(Index) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000473
474 bool runOnModule(Module &M) override {
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000475 if (SummaryFile.empty() && !Index)
476 report_fatal_error("error: -function-import requires -summary-file or "
477 "file from frontend\n");
Teresa Johnson26ab5772016-03-15 00:04:37 +0000478 std::unique_ptr<ModuleSummaryIndex> IndexPtr;
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000479 if (!SummaryFile.empty()) {
480 if (Index)
481 report_fatal_error("error: -summary-file and index from frontend\n");
482 std::string Error;
Teresa Johnson26ab5772016-03-15 00:04:37 +0000483 IndexPtr =
484 getModuleSummaryIndexForFile(SummaryFile, Error, diagnosticHandler);
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000485 if (!IndexPtr) {
486 errs() << "Error loading file '" << SummaryFile << "': " << Error
487 << "\n";
488 return false;
489 }
490 Index = IndexPtr.get();
Mehdi Amini42418ab2015-11-24 06:07:49 +0000491 }
492
Teresa Johnsonc86af332016-04-12 21:13:11 +0000493 // First step is collecting the import list.
494 FunctionImporter::ImportMapTy ImportList;
495 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
496 ImportList);
Mehdi Amini01e32132016-03-26 05:40:34 +0000497
498 // Next we need to promote to global scope and rename any local values that
Teresa Johnson1b00f2d2016-01-08 17:06:29 +0000499 // are potentially exported to other modules.
Mehdi Amini01e32132016-03-26 05:40:34 +0000500 if (renameModuleForThinLTO(M, *Index, nullptr)) {
Teresa Johnson1b00f2d2016-01-08 17:06:29 +0000501 errs() << "Error renaming module\n";
502 return false;
503 }
504
Mehdi Amini42418ab2015-11-24 06:07:49 +0000505 // Perform the import now.
Mehdi Aminid16c8062015-12-08 22:39:40 +0000506 auto ModuleLoader = [&M](StringRef Identifier) {
507 return loadFile(Identifier, M.getContext());
508 };
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000509 FunctionImporter Importer(*Index, ModuleLoader);
Mehdi Amini01e32132016-03-26 05:40:34 +0000510 return Importer.importFunctions(M, ImportList);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000511 }
512};
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000513} // anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000514
515char FunctionImportPass::ID = 0;
516INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
517 "Summary Based Function Import", false, false)
518INITIALIZE_PASS_END(FunctionImportPass, "function-import",
519 "Summary Based Function Import", false, false)
520
521namespace llvm {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000522Pass *createFunctionImportPass(const ModuleSummaryIndex *Index = nullptr) {
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000523 return new FunctionImportPass(Index);
524}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000525}