blob: b6c8993a6f0daa87e40cd310bf46026492b26695 [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 Aminibda3c972016-04-21 01:59:39 +000052// Temporary allows the function import pass to disable always linking
53// referenced discardable symbols.
54static cl::opt<bool>
55 DontForceImportReferencedDiscardableSymbols("disable-force-link-odr",
56 cl::init(false), cl::Hidden);
57
Mehdi Amini42418ab2015-11-24 06:07:49 +000058// Load lazily a module from \p FileName in \p Context.
59static std::unique_ptr<Module> loadFile(const std::string &FileName,
60 LLVMContext &Context) {
61 SMDiagnostic Err;
62 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +000063 // Metadata isn't loaded until functions are imported, to minimize
64 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +000065 std::unique_ptr<Module> Result =
66 getLazyIRFileModule(FileName, Err, Context,
67 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +000068 if (!Result) {
69 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +000070 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +000071 }
72
Mehdi Amini42418ab2015-11-24 06:07:49 +000073 return Result;
74}
75
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000076namespace {
Mehdi Amini40641742016-02-10 23:31:45 +000077
Mehdi Amini01e32132016-03-26 05:40:34 +000078/// Given a list of possible callee implementation for a call site, select one
79/// that fits the \p Threshold.
80///
81/// FIXME: select "best" instead of first that fits. But what is "best"?
82/// - The smallest: more likely to be inlined.
83/// - The one with the least outgoing edges (already well optimized).
84/// - One from a module already being imported from in order to reduce the
85/// number of source modules parsed/linked.
86/// - One that has PGO data attached.
87/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +000088static const GlobalValueSummary *
Teresa Johnson28e457b2016-04-24 14:57:11 +000089selectCallee(const GlobalValueSummaryList &CalleeSummaryList,
90 unsigned Threshold) {
Mehdi Amini01e32132016-03-26 05:40:34 +000091 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +000092 CalleeSummaryList,
93 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
94 auto *GVSummary = SummaryPtr.get();
Mehdi Amini2c719cc2016-04-20 04:17:36 +000095 if (GlobalValue::isWeakAnyLinkage(GVSummary->linkage()))
96 // There is no point in importing weak symbols, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +000097 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +000098 if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
99 GVSummary = &AS->getAliasee();
100 // Alias can't point to "available_externally". However when we import
101 // linkOnceODR the linkage does not change. So we import the alias
102 // and aliasee only in this case.
103 // FIXME: we should import alias as available_externally *function*,
104 // the destination module does need to know it is an alias.
105 if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
106 return false;
107 }
108
109 auto *Summary = cast<FunctionSummary>(GVSummary);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000110
Mehdi Amini01e32132016-03-26 05:40:34 +0000111 if (Summary->instCount() > Threshold)
112 return false;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000113
Mehdi Amini01e32132016-03-26 05:40:34 +0000114 return true;
115 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000116 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000117 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000118
Teresa Johnson28e457b2016-04-24 14:57:11 +0000119 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000120}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000121
Mehdi Amini01e32132016-03-26 05:40:34 +0000122/// Return the summary for the function \p GUID that fits the \p Threshold, or
123/// null if there's no match.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000124static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID,
125 unsigned Threshold,
126 const ModuleSummaryIndex &Index) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000127 auto CalleeSummaryList = Index.findGlobalValueSummaryList(GUID);
128 if (CalleeSummaryList == Index.end()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000129 return nullptr; // This function does not have a summary
130 }
Teresa Johnson28e457b2016-04-24 14:57:11 +0000131 return selectCallee(CalleeSummaryList->second, Threshold);
Mehdi Amini01e32132016-03-26 05:40:34 +0000132}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000133
Mehdi Aminicb874942016-04-23 23:29:24 +0000134/// Mark the global \p GUID as export by module \p ExportModulePath if found in
135/// this module. If it is a GlobalVariable, we also mark any referenced global
136/// in the current module as exported.
137static void exportGlobalInModule(const ModuleSummaryIndex &Index,
138 StringRef ExportModulePath,
139 GlobalValue::GUID GUID,
140 FunctionImporter::ExportSetTy &ExportList) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000141 auto FindGlobalSummaryInModule =
142 [&](GlobalValue::GUID GUID) -> GlobalValueSummary *{
143 auto SummaryList = Index.findGlobalValueSummaryList(GUID);
144 if (SummaryList == Index.end())
Mehdi Aminicb874942016-04-23 23:29:24 +0000145 // This global does not have a summary, it is not part of the ThinLTO
146 // process
147 return nullptr;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000148 auto SummaryIter = llvm::find_if(
149 SummaryList->second,
150 [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
Mehdi Aminicb874942016-04-23 23:29:24 +0000151 return Summary->modulePath() == ExportModulePath;
152 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000153 if (SummaryIter == SummaryList->second.end())
Mehdi Aminicb874942016-04-23 23:29:24 +0000154 return nullptr;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000155 return SummaryIter->get();
Mehdi Aminicb874942016-04-23 23:29:24 +0000156 };
157
Teresa Johnson28e457b2016-04-24 14:57:11 +0000158 auto *Summary = FindGlobalSummaryInModule(GUID);
159 if (!Summary)
Mehdi Aminicb874942016-04-23 23:29:24 +0000160 return;
161 // We found it in the current module, mark as exported
162 ExportList.insert(GUID);
163
Mehdi Aminicb874942016-04-23 23:29:24 +0000164 auto GVS = dyn_cast<GlobalVarSummary>(Summary);
165 if (!GVS)
166 return;
167 // FunctionImportGlobalProcessing::doPromoteLocalToGlobal() will always
168 // trigger importing the initializer for `constant unnamed addr` globals that
169 // are referenced. We conservatively export all the referenced symbols for
170 // every global to workaround this, so that the ExportList is accurate.
171 // FIXME: with a "isConstant" flag in the summary we could be more targetted.
172 for (auto &Ref : GVS->refs()) {
173 auto GUID = Ref.getGUID();
Teresa Johnson28e457b2016-04-24 14:57:11 +0000174 auto *RefSummary = FindGlobalSummaryInModule(GUID);
175 if (RefSummary)
Mehdi Aminicb874942016-04-23 23:29:24 +0000176 // Found a ref in the current module, mark it as exported
177 ExportList.insert(GUID);
178 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000179}
Mehdi Amini40641742016-02-10 23:31:45 +0000180
Mehdi Amini01e32132016-03-26 05:40:34 +0000181using EdgeInfo = std::pair<const FunctionSummary *, unsigned /* Threshold */>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000182
Mehdi Amini01e32132016-03-26 05:40:34 +0000183/// Compute the list of functions to import for a given caller. Mark these
184/// imported functions and the symbols they reference in their source module as
185/// exported from their source module.
186static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000187 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
188 unsigned Threshold,
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000189 const std::map<GlobalValue::GUID, GlobalValueSummary *> &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000190 SmallVectorImpl<EdgeInfo> &Worklist,
191 FunctionImporter::ImportMapTy &ImportsForModule,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000192 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000193 for (auto &Edge : Summary.calls()) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000194 auto GUID = Edge.first.getGUID();
Mehdi Amini01e32132016-03-26 05:40:34 +0000195 DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
196
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000197 if (DefinedGVSummaries.count(GUID)) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000198 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
199 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000200 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000201
202 auto *CalleeSummary = selectCallee(GUID, Threshold, Index);
203 if (!CalleeSummary) {
204 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
205 continue;
206 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000207 // "Resolve" the summary, traversing alias,
208 const FunctionSummary *ResolvedCalleeSummary;
Mehdi Amini6968ef72016-04-20 01:04:20 +0000209 if (isa<AliasSummary>(CalleeSummary)) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000210 ResolvedCalleeSummary = cast<FunctionSummary>(
211 &cast<AliasSummary>(CalleeSummary)->getAliasee());
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000212 assert(
213 GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
214 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini6968ef72016-04-20 01:04:20 +0000215 } else
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000216 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
217
218 assert(ResolvedCalleeSummary->instCount() <= Threshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000219 "selectCallee() didn't honor the threshold");
220
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000221 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
222 auto &ProcessedThreshold = ImportsForModule[ExportModulePath][GUID];
Mehdi Amini01e32132016-03-26 05:40:34 +0000223 /// Since the traversal of the call graph is DFS, we can revisit a function
224 /// a second time with a higher threshold. In this case, it is added back to
225 /// the worklist with the new threshold.
226 if (ProcessedThreshold && ProcessedThreshold > Threshold) {
227 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
228 << ProcessedThreshold << "\n");
229 continue;
230 }
231 // Mark this function as imported in this module, with the current Threshold
232 ProcessedThreshold = Threshold;
233
234 // Make exports in the source module.
Teresa Johnsonc86af332016-04-12 21:13:11 +0000235 if (ExportLists) {
Mehdi Aminief7555f2016-04-13 01:52:32 +0000236 auto &ExportList = (*ExportLists)[ExportModulePath];
Teresa Johnsonc86af332016-04-12 21:13:11 +0000237 ExportList.insert(GUID);
238 // Mark all functions and globals referenced by this function as exported
239 // to the outside if they are defined in the same source module.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000240 for (auto &Edge : ResolvedCalleeSummary->calls()) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000241 auto CalleeGUID = Edge.first.getGUID();
Mehdi Aminicb874942016-04-23 23:29:24 +0000242 exportGlobalInModule(Index, ExportModulePath, CalleeGUID, ExportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000243 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000244 for (auto &Ref : ResolvedCalleeSummary->refs()) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000245 auto GUID = Ref.getGUID();
Mehdi Aminicb874942016-04-23 23:29:24 +0000246 exportGlobalInModule(Index, ExportModulePath, GUID, ExportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000247 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000248 }
249
250 // Insert the newly imported function to the worklist.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000251 Worklist.push_back(std::make_pair(ResolvedCalleeSummary, Threshold));
Teresa Johnsond450da32015-11-24 21:15:19 +0000252 }
253}
254
Mehdi Amini01e32132016-03-26 05:40:34 +0000255/// Given the list of globals defined in a module, compute the list of imports
256/// as well as the list of "exports", i.e. the list of symbols referenced from
257/// another module (that may require promotion).
258static void ComputeImportForModule(
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000259 const std::map<GlobalValue::GUID, GlobalValueSummary *> &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000260 const ModuleSummaryIndex &Index,
261 FunctionImporter::ImportMapTy &ImportsForModule,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000262 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000263 // Worklist contains the list of function imported in this module, for which
264 // we will analyse the callees and may import further down the callgraph.
265 SmallVector<EdgeInfo, 128> Worklist;
266
267 // Populate the worklist with the import for the functions in the current
268 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000269 for (auto &GVSummary : DefinedGVSummaries) {
270 auto *Summary = GVSummary.second;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000271 if (auto *AS = dyn_cast<AliasSummary>(Summary))
272 Summary = &AS->getAliasee();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000273 auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
274 if (!FuncSummary)
275 // Skip import for global variables
276 continue;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000277 DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000278 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000279 DefinedGVSummaries, Worklist, ImportsForModule,
Mehdi Amini01e32132016-03-26 05:40:34 +0000280 ExportLists);
281 }
282
Mehdi Amini42418ab2015-11-24 06:07:49 +0000283 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000284 auto FuncInfo = Worklist.pop_back_val();
285 auto *Summary = FuncInfo.first;
286 auto Threshold = FuncInfo.second;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000287
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000288 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini40641742016-02-10 23:31:45 +0000289 // Adjust the threshold
290 Threshold = Threshold * ImportInstrFactor;
Mehdi Amini01e32132016-03-26 05:40:34 +0000291
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000292 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Teresa Johnson3255eec2016-04-10 15:17:26 +0000293 Worklist, ImportsForModule, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000294 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000295}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000296
Mehdi Amini01e32132016-03-26 05:40:34 +0000297} // anonymous namespace
298
Teresa Johnsonc86af332016-04-12 21:13:11 +0000299/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000300void llvm::ComputeCrossModuleImport(
301 const ModuleSummaryIndex &Index,
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000302 const StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>> &
303 ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000304 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
305 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000306 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000307 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
308 auto &ImportsForModule = ImportLists[DefinedGVSummaries.first()];
309 DEBUG(dbgs() << "Computing import for Module '"
310 << DefinedGVSummaries.first() << "'\n");
311 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportsForModule,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000312 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000313 }
314
315#ifndef NDEBUG
316 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
317 << " modules:\n");
318 for (auto &ModuleImports : ImportLists) {
319 auto ModName = ModuleImports.first();
320 auto &Exports = ExportLists[ModName];
321 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
322 << " functions. Imports from " << ModuleImports.second.size()
323 << " modules.\n");
324 for (auto &Src : ModuleImports.second) {
325 auto SrcModName = Src.first();
326 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
327 << SrcModName << "\n");
328 }
329 }
330#endif
331}
332
Teresa Johnsonc86af332016-04-12 21:13:11 +0000333/// Compute all the imports for the given module in the Index.
334void llvm::ComputeCrossModuleImportForModule(
335 StringRef ModulePath, const ModuleSummaryIndex &Index,
336 FunctionImporter::ImportMapTy &ImportList) {
337
338 // Collect the list of functions this module defines.
339 // GUID -> Summary
Teresa Johnson28e457b2016-04-24 14:57:11 +0000340 std::map<GlobalValue::GUID, GlobalValueSummary *> FunctionSummaryMap;
341 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000342
343 // Compute the import list for this module.
344 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000345 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000346
347#ifndef NDEBUG
348 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
349 << ImportList.size() << " modules.\n");
350 for (auto &Src : ImportList) {
351 auto SrcModName = Src.first();
352 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
353 << SrcModName << "\n");
354 }
355#endif
356}
357
Mehdi Aminic8c55172015-12-03 02:37:33 +0000358// Automatically import functions in Module \p DestModule based on the summaries
359// index.
360//
Mehdi Amini01e32132016-03-26 05:40:34 +0000361bool FunctionImporter::importFunctions(
Mehdi Aminibda3c972016-04-21 01:59:39 +0000362 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList,
363 bool ForceImportReferencedDiscardableSymbols) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000364 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000365 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000366 unsigned ImportedCount = 0;
367
Mehdi Aminic8c55172015-12-03 02:37:33 +0000368 // Linker that will be used for importing function
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000369 Linker TheLinker(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000370 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000371 std::set<StringRef> ModuleNameOrderedList;
372 for (auto &FunctionsToImportPerModule : ImportList) {
373 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
374 }
375 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000376 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000377 const auto &FunctionsToImportPerModule = ImportList.find(Name);
378 assert(FunctionsToImportPerModule != ImportList.end());
379 std::unique_ptr<Module> SrcModule = ModuleLoader(Name);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000380 assert(&DestModule.getContext() == &SrcModule->getContext() &&
381 "Context mismatch");
382
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000383 // If modules were created with lazy metadata loading, materialize it
384 // now, before linking it (otherwise this will be a noop).
385 SrcModule->materializeMetadata();
386 UpgradeDebugInfo(*SrcModule);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000387
Mehdi Amini01e32132016-03-26 05:40:34 +0000388 auto &ImportGUIDs = FunctionsToImportPerModule->second;
389 // Find the globals to import
390 DenseSet<const GlobalValue *> GlobalsToImport;
391 for (auto &GV : *SrcModule) {
Teresa Johnson0beb8582016-04-04 18:52:23 +0000392 if (!GV.hasName())
393 continue;
394 auto GUID = GV.getGUID();
395 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000396 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
397 << " " << GV.getName() << " from "
398 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000399 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000400 GV.materialize();
401 GlobalsToImport.insert(&GV);
402 }
403 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000404 for (auto &GV : SrcModule->globals()) {
405 if (!GV.hasName())
406 continue;
407 auto GUID = GV.getGUID();
408 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000409 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
410 << " " << GV.getName() << " from "
411 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000412 if (Import) {
413 GV.materialize();
414 GlobalsToImport.insert(&GV);
415 }
416 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000417 for (auto &GV : SrcModule->aliases()) {
418 if (!GV.hasName())
419 continue;
420 auto GUID = GV.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000421 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000422 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
423 << " " << GV.getName() << " from "
424 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000425 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000426 // Alias can't point to "available_externally". However when we import
Teresa Johnson9aae3952016-03-27 15:01:11 +0000427 // linkOnceODR the linkage does not change. So we import the alias
Mehdi Amini6968ef72016-04-20 01:04:20 +0000428 // and aliasee only in this case. This has been handled by
429 // computeImportForFunction()
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000430 GlobalObject *GO = GV.getBaseObject();
Mehdi Amini6968ef72016-04-20 01:04:20 +0000431 assert(GO->hasLinkOnceODRLinkage() &&
432 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000433#ifndef NDEBUG
434 if (!GlobalsToImport.count(GO))
435 DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
436 << " " << GO->getName() << " from "
437 << SrcModule->getSourceFileName() << "\n");
438#endif
439 GO->materialize();
Mehdi Amini01e32132016-03-26 05:40:34 +0000440 GlobalsToImport.insert(GO);
Mehdi Amini01e32132016-03-26 05:40:34 +0000441 GV.materialize();
442 GlobalsToImport.insert(&GV);
443 }
444 }
445
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000446 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000447 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000448 return true;
449
Teresa Johnsond29478f2016-03-27 15:27:30 +0000450 if (PrintImports) {
451 for (const auto *GV : GlobalsToImport)
452 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
453 << " from " << SrcModule->getSourceFileName() << "\n";
454 }
455
Mehdi Aminibda3c972016-04-21 01:59:39 +0000456 // Instruct the linker that the client will take care of linkonce resolution
457 unsigned Flags = Linker::Flags::None;
458 if (!ForceImportReferencedDiscardableSymbols)
459 Flags |= Linker::Flags::DontForceLinkLinkonceODR;
460
461 if (TheLinker.linkInModule(std::move(SrcModule), Flags, &GlobalsToImport))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000462 report_fatal_error("Function Import: link error");
463
Mehdi Amini01e32132016-03-26 05:40:34 +0000464 ImportedCount += GlobalsToImport.size();
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000465 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000466
Teresa Johnsond29478f2016-03-27 15:27:30 +0000467 NumImported += ImportedCount;
468
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000469 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000470 << DestModule.getModuleIdentifier() << "\n");
471 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000472}
473
474/// Summary file to use for function importing when using -function-import from
475/// the command line.
476static cl::opt<std::string>
477 SummaryFile("summary-file",
478 cl::desc("The summary file to use for function importing."));
479
480static void diagnosticHandler(const DiagnosticInfo &DI) {
481 raw_ostream &OS = errs();
482 DiagnosticPrinterRawOStream DP(OS);
483 DI.print(DP);
484 OS << '\n';
485}
486
Teresa Johnson26ab5772016-03-15 00:04:37 +0000487/// Parse the summary index out of an IR file and return the summary
Mehdi Amini42418ab2015-11-24 06:07:49 +0000488/// index object if found, or nullptr if not.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000489static std::unique_ptr<ModuleSummaryIndex>
490getModuleSummaryIndexForFile(StringRef Path, std::string &Error,
491 DiagnosticHandlerFunction DiagnosticHandler) {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000492 std::unique_ptr<MemoryBuffer> Buffer;
493 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
494 MemoryBuffer::getFile(Path);
495 if (std::error_code EC = BufferOrErr.getError()) {
496 Error = EC.message();
497 return nullptr;
498 }
499 Buffer = std::move(BufferOrErr.get());
Teresa Johnson26ab5772016-03-15 00:04:37 +0000500 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
501 object::ModuleSummaryIndexObjectFile::create(Buffer->getMemBufferRef(),
502 DiagnosticHandler);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000503 if (std::error_code EC = ObjOrErr.getError()) {
504 Error = EC.message();
505 return nullptr;
506 }
507 return (*ObjOrErr)->takeIndex();
508}
509
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000510namespace {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000511/// Pass that performs cross-module function import provided a summary file.
512class FunctionImportPass : public ModulePass {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000513 /// Optional module summary index to use for importing, otherwise
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000514 /// the summary-file option must be specified.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000515 const ModuleSummaryIndex *Index;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000516
517public:
518 /// Pass identification, replacement for typeid
519 static char ID;
520
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000521 /// Specify pass name for debug output
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000522 const char *getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000523
Teresa Johnson26ab5772016-03-15 00:04:37 +0000524 explicit FunctionImportPass(const ModuleSummaryIndex *Index = nullptr)
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000525 : ModulePass(ID), Index(Index) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000526
527 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000528 if (skipModule(M))
529 return false;
530
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000531 if (SummaryFile.empty() && !Index)
532 report_fatal_error("error: -function-import requires -summary-file or "
533 "file from frontend\n");
Teresa Johnson26ab5772016-03-15 00:04:37 +0000534 std::unique_ptr<ModuleSummaryIndex> IndexPtr;
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000535 if (!SummaryFile.empty()) {
536 if (Index)
537 report_fatal_error("error: -summary-file and index from frontend\n");
538 std::string Error;
Teresa Johnson26ab5772016-03-15 00:04:37 +0000539 IndexPtr =
540 getModuleSummaryIndexForFile(SummaryFile, Error, diagnosticHandler);
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000541 if (!IndexPtr) {
542 errs() << "Error loading file '" << SummaryFile << "': " << Error
543 << "\n";
544 return false;
545 }
546 Index = IndexPtr.get();
Mehdi Amini42418ab2015-11-24 06:07:49 +0000547 }
548
Teresa Johnsonc86af332016-04-12 21:13:11 +0000549 // First step is collecting the import list.
550 FunctionImporter::ImportMapTy ImportList;
551 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
552 ImportList);
Mehdi Amini01e32132016-03-26 05:40:34 +0000553
554 // Next we need to promote to global scope and rename any local values that
Teresa Johnson1b00f2d2016-01-08 17:06:29 +0000555 // are potentially exported to other modules.
Mehdi Amini01e32132016-03-26 05:40:34 +0000556 if (renameModuleForThinLTO(M, *Index, nullptr)) {
Teresa Johnson1b00f2d2016-01-08 17:06:29 +0000557 errs() << "Error renaming module\n";
558 return false;
559 }
560
Mehdi Amini42418ab2015-11-24 06:07:49 +0000561 // Perform the import now.
Mehdi Aminid16c8062015-12-08 22:39:40 +0000562 auto ModuleLoader = [&M](StringRef Identifier) {
563 return loadFile(Identifier, M.getContext());
564 };
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000565 FunctionImporter Importer(*Index, ModuleLoader);
Mehdi Aminibda3c972016-04-21 01:59:39 +0000566 return Importer.importFunctions(
567 M, ImportList, !DontForceImportReferencedDiscardableSymbols);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000568 }
569};
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000570} // anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000571
572char FunctionImportPass::ID = 0;
573INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
574 "Summary Based Function Import", false, false)
575INITIALIZE_PASS_END(FunctionImportPass, "function-import",
576 "Summary Based Function Import", false, false)
577
578namespace llvm {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000579Pass *createFunctionImportPass(const ModuleSummaryIndex *Index = nullptr) {
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000580 return new FunctionImportPass(Index);
581}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000582}