blob: eef7385dd089d5976a9cd3325d5e5cdc6b664e71 [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]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +000082static const GlobalValueSummary *
Mehdi Amini01e32132016-03-26 05:40:34 +000083selectCallee(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");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +000088 auto *GVSummary = GlobInfo->summary();
89 if (auto *AS = dyn_cast<AliasSummary>(GVSummary))
90 GVSummary = &AS->getAliasee();
91 auto *Summary = cast<FunctionSummary>(GVSummary);
Mehdi Amini40641742016-02-10 23:31:45 +000092
Mehdi Amini01e32132016-03-26 05:40:34 +000093 if (GlobalValue::isWeakAnyLinkage(Summary->linkage()))
94 return false;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000095
Mehdi Amini01e32132016-03-26 05:40:34 +000096 if (Summary->instCount() > Threshold)
97 return false;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000098
Mehdi Amini01e32132016-03-26 05:40:34 +000099 return true;
100 });
101 if (It == CalleeInfoList.end())
102 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000103
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000104 return cast<GlobalValueSummary>((*It)->summary());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000105}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000106
Mehdi Amini01e32132016-03-26 05:40:34 +0000107/// Return the summary for the function \p GUID that fits the \p Threshold, or
108/// null if there's no match.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000109static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID,
110 unsigned Threshold,
111 const ModuleSummaryIndex &Index) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000112 auto CalleeInfoList = Index.findGlobalValueInfoList(GUID);
113 if (CalleeInfoList == Index.end()) {
114 return nullptr; // This function does not have a summary
115 }
116 return selectCallee(CalleeInfoList->second, Threshold);
117}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000118
Mehdi Amini01e32132016-03-26 05:40:34 +0000119/// Return true if the global \p GUID is exported by module \p ExportModulePath.
120static bool isGlobalExported(const ModuleSummaryIndex &Index,
Mehdi Aminiad5741b2016-04-02 05:07:53 +0000121 StringRef ExportModulePath,
122 GlobalValue::GUID GUID) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000123 auto CalleeInfoList = Index.findGlobalValueInfoList(GUID);
124 if (CalleeInfoList == Index.end())
125 // This global does not have a summary, it is not part of the ThinLTO
126 // process
127 return false;
128 auto DefinedInCalleeModule = llvm::find_if(
129 CalleeInfoList->second,
130 [&](const std::unique_ptr<GlobalValueInfo> &GlobInfo) {
131 auto *Summary = GlobInfo->summary();
132 assert(Summary && "Unexpected GlobalValueInfo without summary");
133 return Summary->modulePath() == ExportModulePath;
134 });
135 return (DefinedInCalleeModule != CalleeInfoList->second.end());
136}
Mehdi Amini40641742016-02-10 23:31:45 +0000137
Mehdi Amini01e32132016-03-26 05:40:34 +0000138using EdgeInfo = std::pair<const FunctionSummary *, unsigned /* Threshold */>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000139
Mehdi Amini01e32132016-03-26 05:40:34 +0000140/// Compute the list of functions to import for a given caller. Mark these
141/// imported functions and the symbols they reference in their source module as
142/// exported from their source module.
143static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000144 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
145 unsigned Threshold,
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000146 const std::map<GlobalValue::GUID, GlobalValueSummary *> &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000147 SmallVectorImpl<EdgeInfo> &Worklist,
148 FunctionImporter::ImportMapTy &ImportsForModule,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000149 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000150 for (auto &Edge : Summary.calls()) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000151 auto GUID = Edge.first.getGUID();
Mehdi Amini01e32132016-03-26 05:40:34 +0000152 DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
153
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000154 if (DefinedGVSummaries.count(GUID)) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000155 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
156 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000157 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000158
159 auto *CalleeSummary = selectCallee(GUID, Threshold, Index);
160 if (!CalleeSummary) {
161 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
162 continue;
163 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000164 // "Resolve" the summary, traversing alias,
165 const FunctionSummary *ResolvedCalleeSummary;
Mehdi Amini6968ef72016-04-20 01:04:20 +0000166 if (isa<AliasSummary>(CalleeSummary)) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000167 ResolvedCalleeSummary = cast<FunctionSummary>(
168 &cast<AliasSummary>(CalleeSummary)->getAliasee());
Mehdi Amini6968ef72016-04-20 01:04:20 +0000169 if (!GlobalValue::isLinkOnceODRLinkage(
170 ResolvedCalleeSummary->linkage())) {
171 // Alias can't point to "available_externally". However when we import
172 // linkOnceODR the linkage does not change. So we import the alias
173 // and aliasee only in this case.
174 // FIXME: we should import alias as available_externally *function*, the
175 // destination module does need to know it is an alias.
176 DEBUG(dbgs() << "ignored! Aliasee is not linkonce_odr.\n");
177 continue;
178 }
179 } else
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000180 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
181
182 assert(ResolvedCalleeSummary->instCount() <= Threshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000183 "selectCallee() didn't honor the threshold");
184
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000185 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
186 auto &ProcessedThreshold = ImportsForModule[ExportModulePath][GUID];
Mehdi Amini01e32132016-03-26 05:40:34 +0000187 /// Since the traversal of the call graph is DFS, we can revisit a function
188 /// a second time with a higher threshold. In this case, it is added back to
189 /// the worklist with the new threshold.
190 if (ProcessedThreshold && ProcessedThreshold > Threshold) {
191 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
192 << ProcessedThreshold << "\n");
193 continue;
194 }
195 // Mark this function as imported in this module, with the current Threshold
196 ProcessedThreshold = Threshold;
197
198 // Make exports in the source module.
Teresa Johnsonc86af332016-04-12 21:13:11 +0000199 if (ExportLists) {
Mehdi Aminief7555f2016-04-13 01:52:32 +0000200 auto &ExportList = (*ExportLists)[ExportModulePath];
Teresa Johnsonc86af332016-04-12 21:13:11 +0000201 ExportList.insert(GUID);
202 // Mark all functions and globals referenced by this function as exported
203 // to the outside if they are defined in the same source module.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000204 for (auto &Edge : ResolvedCalleeSummary->calls()) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000205 auto CalleeGUID = Edge.first.getGUID();
206 if (isGlobalExported(Index, ExportModulePath, CalleeGUID))
207 ExportList.insert(CalleeGUID);
208 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000209 for (auto &Ref : ResolvedCalleeSummary->refs()) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000210 auto GUID = Ref.getGUID();
211 if (isGlobalExported(Index, ExportModulePath, GUID))
212 ExportList.insert(GUID);
213 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000214 }
215
216 // Insert the newly imported function to the worklist.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000217 Worklist.push_back(std::make_pair(ResolvedCalleeSummary, Threshold));
Teresa Johnsond450da32015-11-24 21:15:19 +0000218 }
219}
220
Mehdi Amini01e32132016-03-26 05:40:34 +0000221/// Given the list of globals defined in a module, compute the list of imports
222/// as well as the list of "exports", i.e. the list of symbols referenced from
223/// another module (that may require promotion).
224static void ComputeImportForModule(
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000225 const std::map<GlobalValue::GUID, GlobalValueSummary *> &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000226 const ModuleSummaryIndex &Index,
227 FunctionImporter::ImportMapTy &ImportsForModule,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000228 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000229 // Worklist contains the list of function imported in this module, for which
230 // we will analyse the callees and may import further down the callgraph.
231 SmallVector<EdgeInfo, 128> Worklist;
232
233 // Populate the worklist with the import for the functions in the current
234 // module
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000235 for (auto &GVInfo : DefinedGVSummaries) {
236 auto *Summary = GVInfo.second;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000237 if (auto *AS = dyn_cast<AliasSummary>(Summary))
238 Summary = &AS->getAliasee();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000239 auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
240 if (!FuncSummary)
241 // Skip import for global variables
242 continue;
243 DEBUG(dbgs() << "Initalize import for " << GVInfo.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000244 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000245 DefinedGVSummaries, Worklist, ImportsForModule,
Mehdi Amini01e32132016-03-26 05:40:34 +0000246 ExportLists);
247 }
248
Mehdi Amini42418ab2015-11-24 06:07:49 +0000249 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000250 auto FuncInfo = Worklist.pop_back_val();
251 auto *Summary = FuncInfo.first;
252 auto Threshold = FuncInfo.second;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000253
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000254 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini40641742016-02-10 23:31:45 +0000255 // Adjust the threshold
256 Threshold = Threshold * ImportInstrFactor;
Mehdi Amini01e32132016-03-26 05:40:34 +0000257
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000258 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Teresa Johnson3255eec2016-04-10 15:17:26 +0000259 Worklist, ImportsForModule, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000260 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000261}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000262
Mehdi Amini01e32132016-03-26 05:40:34 +0000263} // anonymous namespace
264
Teresa Johnsonc86af332016-04-12 21:13:11 +0000265/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000266void llvm::ComputeCrossModuleImport(
267 const ModuleSummaryIndex &Index,
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000268 const StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>> &
269 ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000270 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
271 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000272 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000273 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
274 auto &ImportsForModule = ImportLists[DefinedGVSummaries.first()];
275 DEBUG(dbgs() << "Computing import for Module '"
276 << DefinedGVSummaries.first() << "'\n");
277 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportsForModule,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000278 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000279 }
280
281#ifndef NDEBUG
282 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
283 << " modules:\n");
284 for (auto &ModuleImports : ImportLists) {
285 auto ModName = ModuleImports.first();
286 auto &Exports = ExportLists[ModName];
287 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
288 << " functions. Imports from " << ModuleImports.second.size()
289 << " modules.\n");
290 for (auto &Src : ModuleImports.second) {
291 auto SrcModName = Src.first();
292 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
293 << SrcModName << "\n");
294 }
295 }
296#endif
297}
298
Teresa Johnsonc86af332016-04-12 21:13:11 +0000299/// Compute all the imports for the given module in the Index.
300void llvm::ComputeCrossModuleImportForModule(
301 StringRef ModulePath, const ModuleSummaryIndex &Index,
302 FunctionImporter::ImportMapTy &ImportList) {
303
304 // Collect the list of functions this module defines.
305 // GUID -> Summary
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000306 std::map<GlobalValue::GUID, GlobalValueSummary *> FunctionInfoMap;
Teresa Johnsonc86af332016-04-12 21:13:11 +0000307 Index.collectDefinedFunctionsForModule(ModulePath, FunctionInfoMap);
308
309 // Compute the import list for this module.
310 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
311 ComputeImportForModule(FunctionInfoMap, Index, ImportList);
312
313#ifndef NDEBUG
314 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
315 << ImportList.size() << " modules.\n");
316 for (auto &Src : ImportList) {
317 auto SrcModName = Src.first();
318 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
319 << SrcModName << "\n");
320 }
321#endif
322}
323
Mehdi Aminic8c55172015-12-03 02:37:33 +0000324// Automatically import functions in Module \p DestModule based on the summaries
325// index.
326//
Mehdi Amini01e32132016-03-26 05:40:34 +0000327bool FunctionImporter::importFunctions(
328 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000329 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000330 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000331 unsigned ImportedCount = 0;
332
Mehdi Aminic8c55172015-12-03 02:37:33 +0000333 // Linker that will be used for importing function
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000334 Linker TheLinker(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000335 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000336 std::set<StringRef> ModuleNameOrderedList;
337 for (auto &FunctionsToImportPerModule : ImportList) {
338 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
339 }
340 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000341 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000342 const auto &FunctionsToImportPerModule = ImportList.find(Name);
343 assert(FunctionsToImportPerModule != ImportList.end());
344 std::unique_ptr<Module> SrcModule = ModuleLoader(Name);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000345 assert(&DestModule.getContext() == &SrcModule->getContext() &&
346 "Context mismatch");
347
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000348 // If modules were created with lazy metadata loading, materialize it
349 // now, before linking it (otherwise this will be a noop).
350 SrcModule->materializeMetadata();
351 UpgradeDebugInfo(*SrcModule);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000352
Mehdi Amini01e32132016-03-26 05:40:34 +0000353 auto &ImportGUIDs = FunctionsToImportPerModule->second;
354 // Find the globals to import
355 DenseSet<const GlobalValue *> GlobalsToImport;
356 for (auto &GV : *SrcModule) {
Teresa Johnson0beb8582016-04-04 18:52:23 +0000357 if (!GV.hasName())
358 continue;
359 auto GUID = GV.getGUID();
360 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000361 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
362 << " " << GV.getName() << " from "
363 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000364 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000365 GV.materialize();
366 GlobalsToImport.insert(&GV);
367 }
368 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000369 for (auto &GV : SrcModule->globals()) {
370 if (!GV.hasName())
371 continue;
372 auto GUID = GV.getGUID();
373 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000374 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
375 << " " << GV.getName() << " from "
376 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000377 if (Import) {
378 GV.materialize();
379 GlobalsToImport.insert(&GV);
380 }
381 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000382 for (auto &GV : SrcModule->aliases()) {
383 if (!GV.hasName())
384 continue;
385 auto GUID = GV.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000386 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000387 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
388 << " " << GV.getName() << " from "
389 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000390 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000391 // Alias can't point to "available_externally". However when we import
Teresa Johnson9aae3952016-03-27 15:01:11 +0000392 // linkOnceODR the linkage does not change. So we import the alias
Mehdi Amini6968ef72016-04-20 01:04:20 +0000393 // and aliasee only in this case. This has been handled by
394 // computeImportForFunction()
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000395 GlobalObject *GO = GV.getBaseObject();
Mehdi Amini6968ef72016-04-20 01:04:20 +0000396 assert(GO->hasLinkOnceODRLinkage() &&
397 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000398#ifndef NDEBUG
399 if (!GlobalsToImport.count(GO))
400 DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
401 << " " << GO->getName() << " from "
402 << SrcModule->getSourceFileName() << "\n");
403#endif
404 GO->materialize();
Mehdi Amini01e32132016-03-26 05:40:34 +0000405 GlobalsToImport.insert(GO);
Mehdi Amini01e32132016-03-26 05:40:34 +0000406 GV.materialize();
407 GlobalsToImport.insert(&GV);
408 }
409 }
410
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000411 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000412 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000413 return true;
414
Teresa Johnsond29478f2016-03-27 15:27:30 +0000415 if (PrintImports) {
416 for (const auto *GV : GlobalsToImport)
417 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
418 << " from " << SrcModule->getSourceFileName() << "\n";
419 }
420
Rafael Espindola434e9562015-12-16 23:16:33 +0000421 if (TheLinker.linkInModule(std::move(SrcModule), Linker::Flags::None,
Mehdi Amini01e32132016-03-26 05:40:34 +0000422 &GlobalsToImport))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000423 report_fatal_error("Function Import: link error");
424
Mehdi Amini01e32132016-03-26 05:40:34 +0000425 ImportedCount += GlobalsToImport.size();
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000426 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000427
Teresa Johnsond29478f2016-03-27 15:27:30 +0000428 NumImported += ImportedCount;
429
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000430 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000431 << DestModule.getModuleIdentifier() << "\n");
432 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000433}
434
435/// Summary file to use for function importing when using -function-import from
436/// the command line.
437static cl::opt<std::string>
438 SummaryFile("summary-file",
439 cl::desc("The summary file to use for function importing."));
440
441static void diagnosticHandler(const DiagnosticInfo &DI) {
442 raw_ostream &OS = errs();
443 DiagnosticPrinterRawOStream DP(OS);
444 DI.print(DP);
445 OS << '\n';
446}
447
Teresa Johnson26ab5772016-03-15 00:04:37 +0000448/// Parse the summary index out of an IR file and return the summary
Mehdi Amini42418ab2015-11-24 06:07:49 +0000449/// index object if found, or nullptr if not.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000450static std::unique_ptr<ModuleSummaryIndex>
451getModuleSummaryIndexForFile(StringRef Path, std::string &Error,
452 DiagnosticHandlerFunction DiagnosticHandler) {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000453 std::unique_ptr<MemoryBuffer> Buffer;
454 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
455 MemoryBuffer::getFile(Path);
456 if (std::error_code EC = BufferOrErr.getError()) {
457 Error = EC.message();
458 return nullptr;
459 }
460 Buffer = std::move(BufferOrErr.get());
Teresa Johnson26ab5772016-03-15 00:04:37 +0000461 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
462 object::ModuleSummaryIndexObjectFile::create(Buffer->getMemBufferRef(),
463 DiagnosticHandler);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000464 if (std::error_code EC = ObjOrErr.getError()) {
465 Error = EC.message();
466 return nullptr;
467 }
468 return (*ObjOrErr)->takeIndex();
469}
470
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000471namespace {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000472/// Pass that performs cross-module function import provided a summary file.
473class FunctionImportPass : public ModulePass {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000474 /// Optional module summary index to use for importing, otherwise
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000475 /// the summary-file option must be specified.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000476 const ModuleSummaryIndex *Index;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000477
478public:
479 /// Pass identification, replacement for typeid
480 static char ID;
481
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000482 /// Specify pass name for debug output
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000483 const char *getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000484
Teresa Johnson26ab5772016-03-15 00:04:37 +0000485 explicit FunctionImportPass(const ModuleSummaryIndex *Index = nullptr)
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000486 : ModulePass(ID), Index(Index) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000487
488 bool runOnModule(Module &M) override {
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000489 if (SummaryFile.empty() && !Index)
490 report_fatal_error("error: -function-import requires -summary-file or "
491 "file from frontend\n");
Teresa Johnson26ab5772016-03-15 00:04:37 +0000492 std::unique_ptr<ModuleSummaryIndex> IndexPtr;
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000493 if (!SummaryFile.empty()) {
494 if (Index)
495 report_fatal_error("error: -summary-file and index from frontend\n");
496 std::string Error;
Teresa Johnson26ab5772016-03-15 00:04:37 +0000497 IndexPtr =
498 getModuleSummaryIndexForFile(SummaryFile, Error, diagnosticHandler);
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000499 if (!IndexPtr) {
500 errs() << "Error loading file '" << SummaryFile << "': " << Error
501 << "\n";
502 return false;
503 }
504 Index = IndexPtr.get();
Mehdi Amini42418ab2015-11-24 06:07:49 +0000505 }
506
Teresa Johnsonc86af332016-04-12 21:13:11 +0000507 // First step is collecting the import list.
508 FunctionImporter::ImportMapTy ImportList;
509 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
510 ImportList);
Mehdi Amini01e32132016-03-26 05:40:34 +0000511
512 // Next we need to promote to global scope and rename any local values that
Teresa Johnson1b00f2d2016-01-08 17:06:29 +0000513 // are potentially exported to other modules.
Mehdi Amini01e32132016-03-26 05:40:34 +0000514 if (renameModuleForThinLTO(M, *Index, nullptr)) {
Teresa Johnson1b00f2d2016-01-08 17:06:29 +0000515 errs() << "Error renaming module\n";
516 return false;
517 }
518
Mehdi Amini42418ab2015-11-24 06:07:49 +0000519 // Perform the import now.
Mehdi Aminid16c8062015-12-08 22:39:40 +0000520 auto ModuleLoader = [&M](StringRef Identifier) {
521 return loadFile(Identifier, M.getContext());
522 };
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000523 FunctionImporter Importer(*Index, ModuleLoader);
Mehdi Amini01e32132016-03-26 05:40:34 +0000524 return Importer.importFunctions(M, ImportList);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000525 }
526};
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000527} // anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000528
529char FunctionImportPass::ID = 0;
530INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
531 "Summary Based Function Import", false, false)
532INITIALIZE_PASS_END(FunctionImportPass, "function-import",
533 "Summary Based Function Import", false, false)
534
535namespace llvm {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000536Pass *createFunctionImportPass(const ModuleSummaryIndex *Index = nullptr) {
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000537 return new FunctionImportPass(Index);
538}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000539}