blob: 2a351b301190039ea3c429fe12f3fa975c60496a [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"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000019#include "llvm/ADT/Triple.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000020#include "llvm/IR/AutoUpgrade.h"
21#include "llvm/IR/DiagnosticPrinter.h"
22#include "llvm/IR/IntrinsicInst.h"
23#include "llvm/IR/Module.h"
24#include "llvm/IRReader/IRReader.h"
25#include "llvm/Linker/Linker.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000026#include "llvm/Object/IRObjectFile.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000027#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000028#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/SourceMgr.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000031#include "llvm/Transforms/IPO/Internalize.h"
Teresa Johnson488a8002016-02-10 18:11:31 +000032#include "llvm/Transforms/Utils/FunctionImportUtils.h"
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000033
Mehdi Amini01e32132016-03-26 05:40:34 +000034#define DEBUG_TYPE "function-import"
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000035
Mehdi Amini42418ab2015-11-24 06:07:49 +000036using namespace llvm;
37
Teresa Johnsond29478f2016-03-27 15:27:30 +000038STATISTIC(NumImported, "Number of functions imported");
39
Teresa Johnson39303612015-11-24 22:55:46 +000040/// Limit on instruction count of imported functions.
41static cl::opt<unsigned> ImportInstrLimit(
42 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
43 cl::desc("Only import functions with less than N instructions"));
44
Mehdi Amini40641742016-02-10 23:31:45 +000045static cl::opt<float>
46 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
47 cl::Hidden, cl::value_desc("x"),
48 cl::desc("As we import functions, multiply the "
49 "`import-instr-limit` threshold by this factor "
50 "before processing newly imported functions"));
Piotr Padlewskiba72b952016-09-29 17:32:07 +000051
Piotr Padlewskid2869472016-09-30 03:01:17 +000052static cl::opt<float> ImportHotInstrFactor(
53 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
54 cl::value_desc("x"),
55 cl::desc("As we import functions called from hot callsite, multiply the "
56 "`import-instr-limit` threshold by this factor "
57 "before processing newly imported functions"));
58
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000059static cl::opt<float> ImportHotMultiplier(
60 "import-hot-multiplier", cl::init(3.0), cl::Hidden, cl::value_desc("x"),
Piotr Padlewskiba72b952016-09-29 17:32:07 +000061 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
62
63// FIXME: This multiplier was not really tuned up.
64static cl::opt<float> ImportColdMultiplier(
65 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
66 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
Mehdi Amini40641742016-02-10 23:31:45 +000067
Teresa Johnsond29478f2016-03-27 15:27:30 +000068static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
69 cl::desc("Print imported functions"));
70
Mehdi Aminibda3c972016-04-21 01:59:39 +000071// Temporary allows the function import pass to disable always linking
72// referenced discardable symbols.
73static cl::opt<bool>
74 DontForceImportReferencedDiscardableSymbols("disable-force-link-odr",
75 cl::init(false), cl::Hidden);
76
Piotr Padlewski3b776122016-07-08 23:01:49 +000077static cl::opt<bool> EnableImportMetadata(
78 "enable-import-metadata", cl::init(
79#if !defined(NDEBUG)
80 true /*Enabled with asserts.*/
81#else
82 false
83#endif
84 ),
85 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
86
Mehdi Amini42418ab2015-11-24 06:07:49 +000087// Load lazily a module from \p FileName in \p Context.
88static std::unique_ptr<Module> loadFile(const std::string &FileName,
89 LLVMContext &Context) {
90 SMDiagnostic Err;
91 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +000092 // Metadata isn't loaded until functions are imported, to minimize
93 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +000094 std::unique_ptr<Module> Result =
95 getLazyIRFileModule(FileName, Err, Context,
96 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +000097 if (!Result) {
98 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +000099 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000100 }
101
Mehdi Amini42418ab2015-11-24 06:07:49 +0000102 return Result;
103}
104
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000105namespace {
Mehdi Amini40641742016-02-10 23:31:45 +0000106
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000107// Return true if the Summary describes a GlobalValue that can be externally
108// referenced, i.e. it does not need renaming (linkage is not local) or renaming
109// is possible (does not have a section for instance).
110static bool canBeExternallyReferenced(const GlobalValueSummary &Summary) {
111 if (!Summary.needsRenaming())
112 return true;
113
Teresa Johnson58fbc912016-10-28 02:24:59 +0000114 if (Summary.noRename())
115 // Can't externally reference a global that needs renaming if has a section
116 // or is referenced from inline assembly, for example.
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000117 return false;
118
119 return true;
120}
121
122// Return true if \p GUID describes a GlobalValue that can be externally
123// referenced, i.e. it does not need renaming (linkage is not local) or
124// renaming is possible (does not have a section for instance).
125static bool canBeExternallyReferenced(const ModuleSummaryIndex &Index,
126 GlobalValue::GUID GUID) {
127 auto Summaries = Index.findGlobalValueSummaryList(GUID);
128 if (Summaries == Index.end())
129 return true;
130 if (Summaries->second.size() != 1)
131 // If there are multiple globals with this GUID, then we know it is
132 // not a local symbol, and it is necessarily externally referenced.
133 return true;
134
135 // We don't need to check for the module path, because if it can't be
136 // externally referenced and we call it, it is necessarilly in the same
137 // module
138 return canBeExternallyReferenced(**Summaries->second.begin());
139}
140
141// Return true if the global described by \p Summary can be imported in another
142// module.
143static bool eligibleForImport(const ModuleSummaryIndex &Index,
144 const GlobalValueSummary &Summary) {
145 if (!canBeExternallyReferenced(Summary))
146 // Can't import a global that needs renaming if has a section for instance.
147 // FIXME: we may be able to import it by copying it without promotion.
148 return false;
149
Piotr Padlewski332b3b22016-08-11 22:13:57 +0000150 // Don't import functions that are not viable to inline.
151 if (Summary.isNotViableToInline())
152 return false;
153
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000154 // Check references (and potential calls) in the same module. If the current
155 // value references a global that can't be externally referenced it is not
156 // eligible for import.
157 bool AllRefsCanBeExternallyReferenced =
158 llvm::all_of(Summary.refs(), [&](const ValueInfo &VI) {
159 return canBeExternallyReferenced(Index, VI.getGUID());
160 });
161 if (!AllRefsCanBeExternallyReferenced)
162 return false;
163
164 if (auto *FuncSummary = dyn_cast<FunctionSummary>(&Summary)) {
165 bool AllCallsCanBeExternallyReferenced = llvm::all_of(
166 FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) {
167 return canBeExternallyReferenced(Index, Edge.first.getGUID());
168 });
169 if (!AllCallsCanBeExternallyReferenced)
170 return false;
171 }
172 return true;
173}
174
Mehdi Amini01e32132016-03-26 05:40:34 +0000175/// Given a list of possible callee implementation for a call site, select one
176/// that fits the \p Threshold.
177///
178/// FIXME: select "best" instead of first that fits. But what is "best"?
179/// - The smallest: more likely to be inlined.
180/// - The one with the least outgoing edges (already well optimized).
181/// - One from a module already being imported from in order to reduce the
182/// number of source modules parsed/linked.
183/// - One that has PGO data attached.
184/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000185static const GlobalValueSummary *
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000186selectCallee(const ModuleSummaryIndex &Index,
187 const GlobalValueSummaryList &CalleeSummaryList,
Teresa Johnson28e457b2016-04-24 14:57:11 +0000188 unsigned Threshold) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000189 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000190 CalleeSummaryList,
191 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
192 auto *GVSummary = SummaryPtr.get();
Rafael Espindolaf329be82016-05-11 01:26:06 +0000193 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000194 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000195 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000196 if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
197 GVSummary = &AS->getAliasee();
198 // Alias can't point to "available_externally". However when we import
199 // linkOnceODR the linkage does not change. So we import the alias
200 // and aliasee only in this case.
201 // FIXME: we should import alias as available_externally *function*,
202 // the destination module does need to know it is an alias.
203 if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
204 return false;
205 }
206
207 auto *Summary = cast<FunctionSummary>(GVSummary);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000208
Mehdi Amini01e32132016-03-26 05:40:34 +0000209 if (Summary->instCount() > Threshold)
210 return false;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000211
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000212 if (!eligibleForImport(Index, *Summary))
213 return false;
214
Mehdi Amini01e32132016-03-26 05:40:34 +0000215 return true;
216 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000217 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000218 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000219
Teresa Johnson28e457b2016-04-24 14:57:11 +0000220 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000221}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000222
Mehdi Amini01e32132016-03-26 05:40:34 +0000223/// Return the summary for the function \p GUID that fits the \p Threshold, or
224/// null if there's no match.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000225static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID,
226 unsigned Threshold,
227 const ModuleSummaryIndex &Index) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000228 auto CalleeSummaryList = Index.findGlobalValueSummaryList(GUID);
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000229 if (CalleeSummaryList == Index.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000230 return nullptr; // This function does not have a summary
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000231 return selectCallee(Index, CalleeSummaryList->second, Threshold);
Mehdi Amini01e32132016-03-26 05:40:34 +0000232}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000233
Mehdi Aminicb874942016-04-23 23:29:24 +0000234/// Mark the global \p GUID as export by module \p ExportModulePath if found in
235/// this module. If it is a GlobalVariable, we also mark any referenced global
236/// in the current module as exported.
237static void exportGlobalInModule(const ModuleSummaryIndex &Index,
238 StringRef ExportModulePath,
239 GlobalValue::GUID GUID,
240 FunctionImporter::ExportSetTy &ExportList) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000241 auto FindGlobalSummaryInModule =
242 [&](GlobalValue::GUID GUID) -> GlobalValueSummary *{
243 auto SummaryList = Index.findGlobalValueSummaryList(GUID);
244 if (SummaryList == Index.end())
Mehdi Aminicb874942016-04-23 23:29:24 +0000245 // This global does not have a summary, it is not part of the ThinLTO
246 // process
247 return nullptr;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000248 auto SummaryIter = llvm::find_if(
249 SummaryList->second,
250 [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
Mehdi Aminicb874942016-04-23 23:29:24 +0000251 return Summary->modulePath() == ExportModulePath;
252 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000253 if (SummaryIter == SummaryList->second.end())
Mehdi Aminicb874942016-04-23 23:29:24 +0000254 return nullptr;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000255 return SummaryIter->get();
Mehdi Aminicb874942016-04-23 23:29:24 +0000256 };
257
Teresa Johnson28e457b2016-04-24 14:57:11 +0000258 auto *Summary = FindGlobalSummaryInModule(GUID);
259 if (!Summary)
Mehdi Aminicb874942016-04-23 23:29:24 +0000260 return;
261 // We found it in the current module, mark as exported
262 ExportList.insert(GUID);
263
Mehdi Aminicb874942016-04-23 23:29:24 +0000264 auto GVS = dyn_cast<GlobalVarSummary>(Summary);
265 if (!GVS)
266 return;
267 // FunctionImportGlobalProcessing::doPromoteLocalToGlobal() will always
268 // trigger importing the initializer for `constant unnamed addr` globals that
269 // are referenced. We conservatively export all the referenced symbols for
270 // every global to workaround this, so that the ExportList is accurate.
271 // FIXME: with a "isConstant" flag in the summary we could be more targetted.
272 for (auto &Ref : GVS->refs()) {
273 auto GUID = Ref.getGUID();
Teresa Johnson28e457b2016-04-24 14:57:11 +0000274 auto *RefSummary = FindGlobalSummaryInModule(GUID);
275 if (RefSummary)
Mehdi Aminicb874942016-04-23 23:29:24 +0000276 // Found a ref in the current module, mark it as exported
277 ExportList.insert(GUID);
278 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000279}
Mehdi Amini40641742016-02-10 23:31:45 +0000280
Mehdi Amini01e32132016-03-26 05:40:34 +0000281using EdgeInfo = std::pair<const FunctionSummary *, unsigned /* Threshold */>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000282
Mehdi Amini01e32132016-03-26 05:40:34 +0000283/// Compute the list of functions to import for a given caller. Mark these
284/// imported functions and the symbols they reference in their source module as
285/// exported from their source module.
286static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000287 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000288 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000289 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000290 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000291 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000292 for (auto &Edge : Summary.calls()) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000293 auto GUID = Edge.first.getGUID();
Mehdi Amini01e32132016-03-26 05:40:34 +0000294 DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
295
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000296 if (DefinedGVSummaries.count(GUID)) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000297 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
298 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000299 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000300
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000301 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
302 if (Hotness == CalleeInfo::HotnessType::Hot)
303 return ImportHotMultiplier;
304 if (Hotness == CalleeInfo::HotnessType::Cold)
305 return ImportColdMultiplier;
306 return 1.0;
307 };
308
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000309 const auto NewThreshold =
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000310 Threshold * GetBonusMultiplier(Edge.second.Hotness);
Piotr Padlewskid2869472016-09-30 03:01:17 +0000311
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000312 auto *CalleeSummary = selectCallee(GUID, NewThreshold, Index);
Mehdi Amini01e32132016-03-26 05:40:34 +0000313 if (!CalleeSummary) {
314 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
315 continue;
316 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000317 // "Resolve" the summary, traversing alias,
318 const FunctionSummary *ResolvedCalleeSummary;
Mehdi Amini6968ef72016-04-20 01:04:20 +0000319 if (isa<AliasSummary>(CalleeSummary)) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000320 ResolvedCalleeSummary = cast<FunctionSummary>(
321 &cast<AliasSummary>(CalleeSummary)->getAliasee());
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000322 assert(
323 GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
324 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini6968ef72016-04-20 01:04:20 +0000325 } else
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000326 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
327
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000328 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000329 "selectCallee() didn't honor the threshold");
330
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000331 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
Mehdi Amini9b490f12016-08-16 05:47:12 +0000332 auto &ProcessedThreshold = ImportList[ExportModulePath][GUID];
Mehdi Amini01e32132016-03-26 05:40:34 +0000333 /// Since the traversal of the call graph is DFS, we can revisit a function
334 /// a second time with a higher threshold. In this case, it is added back to
335 /// the worklist with the new threshold.
Teresa Johnson2e030942016-05-11 22:56:19 +0000336 if (ProcessedThreshold && ProcessedThreshold >= Threshold) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000337 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
338 << ProcessedThreshold << "\n");
339 continue;
340 }
341 // Mark this function as imported in this module, with the current Threshold
342 ProcessedThreshold = Threshold;
343
344 // Make exports in the source module.
Teresa Johnsonc86af332016-04-12 21:13:11 +0000345 if (ExportLists) {
Mehdi Aminief7555f2016-04-13 01:52:32 +0000346 auto &ExportList = (*ExportLists)[ExportModulePath];
Teresa Johnsonc86af332016-04-12 21:13:11 +0000347 ExportList.insert(GUID);
348 // Mark all functions and globals referenced by this function as exported
349 // to the outside if they are defined in the same source module.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000350 for (auto &Edge : ResolvedCalleeSummary->calls()) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000351 auto CalleeGUID = Edge.first.getGUID();
Mehdi Aminicb874942016-04-23 23:29:24 +0000352 exportGlobalInModule(Index, ExportModulePath, CalleeGUID, ExportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000353 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000354 for (auto &Ref : ResolvedCalleeSummary->refs()) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000355 auto GUID = Ref.getGUID();
Mehdi Aminicb874942016-04-23 23:29:24 +0000356 exportGlobalInModule(Index, ExportModulePath, GUID, ExportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000357 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000358 }
359
Piotr Padlewskid2869472016-09-30 03:01:17 +0000360 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
361 // Adjust the threshold for next level of imported functions.
362 // The threshold is different for hot callsites because we can then
363 // inline chains of hot calls.
364 if (IsHotCallsite)
365 return Threshold * ImportHotInstrFactor;
366 return Threshold * ImportInstrFactor;
367 };
368
369 bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
370
Mehdi Amini01e32132016-03-26 05:40:34 +0000371 // Insert the newly imported function to the worklist.
Piotr Padlewskid2869472016-09-30 03:01:17 +0000372 Worklist.emplace_back(ResolvedCalleeSummary,
373 GetAdjustedThreshold(Threshold, IsHotCallsite));
Teresa Johnsond450da32015-11-24 21:15:19 +0000374 }
375}
376
Mehdi Amini01e32132016-03-26 05:40:34 +0000377/// Given the list of globals defined in a module, compute the list of imports
378/// as well as the list of "exports", i.e. the list of symbols referenced from
379/// another module (that may require promotion).
380static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000381 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000382 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000383 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000384 // Worklist contains the list of function imported in this module, for which
385 // we will analyse the callees and may import further down the callgraph.
386 SmallVector<EdgeInfo, 128> Worklist;
387
388 // Populate the worklist with the import for the functions in the current
389 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000390 for (auto &GVSummary : DefinedGVSummaries) {
391 auto *Summary = GVSummary.second;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000392 if (auto *AS = dyn_cast<AliasSummary>(Summary))
393 Summary = &AS->getAliasee();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000394 auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
395 if (!FuncSummary)
396 // Skip import for global variables
397 continue;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000398 DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000399 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000400 DefinedGVSummaries, Worklist, ImportList,
Mehdi Amini01e32132016-03-26 05:40:34 +0000401 ExportLists);
402 }
403
Piotr Padlewskid2869472016-09-30 03:01:17 +0000404 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini42418ab2015-11-24 06:07:49 +0000405 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000406 auto FuncInfo = Worklist.pop_back_val();
407 auto *Summary = FuncInfo.first;
408 auto Threshold = FuncInfo.second;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000409
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000410 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000411 Worklist, ImportList, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000412 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000413}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000414
Mehdi Amini01e32132016-03-26 05:40:34 +0000415} // anonymous namespace
416
Teresa Johnsonc86af332016-04-12 21:13:11 +0000417/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000418void llvm::ComputeCrossModuleImport(
419 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000420 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000421 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
422 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000423 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000424 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000425 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000426 DEBUG(dbgs() << "Computing import for Module '"
427 << DefinedGVSummaries.first() << "'\n");
Mehdi Amini9b490f12016-08-16 05:47:12 +0000428 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000429 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000430 }
431
432#ifndef NDEBUG
433 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
434 << " modules:\n");
435 for (auto &ModuleImports : ImportLists) {
436 auto ModName = ModuleImports.first();
437 auto &Exports = ExportLists[ModName];
438 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
439 << " functions. Imports from " << ModuleImports.second.size()
440 << " modules.\n");
441 for (auto &Src : ModuleImports.second) {
442 auto SrcModName = Src.first();
443 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
444 << SrcModName << "\n");
445 }
446 }
447#endif
448}
449
Teresa Johnsonc86af332016-04-12 21:13:11 +0000450/// Compute all the imports for the given module in the Index.
451void llvm::ComputeCrossModuleImportForModule(
452 StringRef ModulePath, const ModuleSummaryIndex &Index,
453 FunctionImporter::ImportMapTy &ImportList) {
454
455 // Collect the list of functions this module defines.
456 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000457 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000458 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000459
460 // Compute the import list for this module.
461 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000462 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000463
464#ifndef NDEBUG
465 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
466 << ImportList.size() << " modules.\n");
467 for (auto &Src : ImportList) {
468 auto SrcModName = Src.first();
469 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
470 << SrcModName << "\n");
471 }
472#endif
473}
474
Teresa Johnson84174c32016-05-10 13:48:23 +0000475/// Compute the set of summaries needed for a ThinLTO backend compilation of
476/// \p ModulePath.
477void llvm::gatherImportedSummariesForModule(
478 StringRef ModulePath,
479 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000480 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000481 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
482 // Include all summaries from the importing module.
483 ModuleToSummariesForIndex[ModulePath] =
484 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000485 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000486 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000487 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
488 const auto &DefinedGVSummaries =
489 ModuleToDefinedGVSummaries.lookup(ILI.first());
490 for (auto &GI : ILI.second) {
491 const auto &DS = DefinedGVSummaries.find(GI.first);
492 assert(DS != DefinedGVSummaries.end() &&
493 "Expected a defined summary for imported global value");
494 SummariesForIndex[GI.first] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000495 }
496 }
497}
498
Teresa Johnson8570fe42016-05-10 15:54:09 +0000499/// Emit the files \p ModulePath will import from into \p OutputFilename.
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000500std::error_code
501llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
502 const FunctionImporter::ImportMapTy &ModuleImports) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000503 std::error_code EC;
504 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
505 if (EC)
506 return EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000507 for (auto &ILI : ModuleImports)
508 ImportsOS << ILI.first() << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000509 return std::error_code();
510}
511
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000512/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
513void llvm::thinLTOResolveWeakForLinkerModule(
514 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
515 auto updateLinkage = [&](GlobalValue &GV) {
516 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
517 return;
518 // See if the global summary analysis computed a new resolved linkage.
519 const auto &GS = DefinedGlobals.find(GV.getGUID());
520 if (GS == DefinedGlobals.end())
521 return;
522 auto NewLinkage = GS->second->linkage();
523 if (NewLinkage == GV.getLinkage())
524 return;
525 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
526 << GV.getLinkage() << " to " << NewLinkage << "\n");
527 GV.setLinkage(NewLinkage);
Teresa Johnson6107a412016-08-15 21:00:04 +0000528 // Remove functions converted to available_externally from comdats,
529 // as this is a declaration for the linker, and will be dropped eventually.
530 // It is illegal for comdats to contain declarations.
531 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
532 if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
533 assert(GO->hasAvailableExternallyLinkage() &&
534 "Expected comdat on definition (possibly available external)");
535 GO->setComdat(nullptr);
536 }
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000537 };
538
539 // Process functions and global now
540 for (auto &GV : TheModule)
541 updateLinkage(GV);
542 for (auto &GV : TheModule.globals())
543 updateLinkage(GV);
544 for (auto &GV : TheModule.aliases())
545 updateLinkage(GV);
546}
547
548/// Run internalization on \p TheModule based on symmary analysis.
549void llvm::thinLTOInternalizeModule(Module &TheModule,
550 const GVSummaryMapTy &DefinedGlobals) {
551 // Parse inline ASM and collect the list of symbols that are not defined in
552 // the current module.
553 StringSet<> AsmUndefinedRefs;
554 object::IRObjectFile::CollectAsmUndefinedRefs(
555 Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
556 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
557 if (Flags & object::BasicSymbolRef::SF_Undefined)
558 AsmUndefinedRefs.insert(Name);
559 });
560
561 // Declare a callback for the internalize pass that will ask for every
562 // candidate GlobalValue if it can be internalized or not.
563 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
564 // Can't be internalized if referenced in inline asm.
565 if (AsmUndefinedRefs.count(GV.getName()))
566 return true;
567
568 // Lookup the linkage recorded in the summaries during global analysis.
569 const auto &GS = DefinedGlobals.find(GV.getGUID());
570 GlobalValue::LinkageTypes Linkage;
571 if (GS == DefinedGlobals.end()) {
572 // Must have been promoted (possibly conservatively). Find original
573 // name so that we can access the correct summary and see if it can
574 // be internalized again.
575 // FIXME: Eventually we should control promotion instead of promoting
576 // and internalizing again.
577 StringRef OrigName =
578 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
579 std::string OrigId = GlobalValue::getGlobalIdentifier(
580 OrigName, GlobalValue::InternalLinkage,
581 TheModule.getSourceFileName());
582 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000583 if (GS == DefinedGlobals.end()) {
584 // Also check the original non-promoted non-globalized name. In some
585 // cases a preempted weak value is linked in as a local copy because
586 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
587 // In that case, since it was originally not a local value, it was
588 // recorded in the index using the original name.
589 // FIXME: This may not be needed once PR27866 is fixed.
590 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
591 assert(GS != DefinedGlobals.end());
592 Linkage = GS->second->linkage();
593 } else {
594 Linkage = GS->second->linkage();
595 }
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000596 } else
597 Linkage = GS->second->linkage();
598 return !GlobalValue::isLocalLinkage(Linkage);
599 };
600
601 // FIXME: See if we can just internalize directly here via linkage changes
602 // based on the index, rather than invoking internalizeModule.
603 llvm::internalizeModule(TheModule, MustPreserveGV);
604}
605
Mehdi Aminic8c55172015-12-03 02:37:33 +0000606// Automatically import functions in Module \p DestModule based on the summaries
607// index.
608//
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000609Expected<bool> FunctionImporter::importFunctions(
Mehdi Aminibda3c972016-04-21 01:59:39 +0000610 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList,
611 bool ForceImportReferencedDiscardableSymbols) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000612 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000613 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000614 unsigned ImportedCount = 0;
615
Mehdi Aminic8c55172015-12-03 02:37:33 +0000616 // Linker that will be used for importing function
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000617 Linker TheLinker(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000618 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000619 std::set<StringRef> ModuleNameOrderedList;
620 for (auto &FunctionsToImportPerModule : ImportList) {
621 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
622 }
623 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000624 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000625 const auto &FunctionsToImportPerModule = ImportList.find(Name);
626 assert(FunctionsToImportPerModule != ImportList.end());
627 std::unique_ptr<Module> SrcModule = ModuleLoader(Name);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000628 assert(&DestModule.getContext() == &SrcModule->getContext() &&
629 "Context mismatch");
630
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000631 // If modules were created with lazy metadata loading, materialize it
632 // now, before linking it (otherwise this will be a noop).
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000633 if (Error Err = SrcModule->materializeMetadata())
634 return std::move(Err);
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000635 UpgradeDebugInfo(*SrcModule);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000636
Mehdi Amini01e32132016-03-26 05:40:34 +0000637 auto &ImportGUIDs = FunctionsToImportPerModule->second;
638 // Find the globals to import
639 DenseSet<const GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000640 for (Function &F : *SrcModule) {
641 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +0000642 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000643 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000644 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000645 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000646 << " " << F.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000647 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000648 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000649 if (Error Err = F.materialize())
650 return std::move(Err);
Piotr Padlewski3b776122016-07-08 23:01:49 +0000651 if (EnableImportMetadata) {
652 // Add 'thinlto_src_module' metadata for statistics and debugging.
653 F.setMetadata(
654 "thinlto_src_module",
655 llvm::MDNode::get(
656 DestModule.getContext(),
657 {llvm::MDString::get(DestModule.getContext(),
658 SrcModule->getSourceFileName())}));
659 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000660 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +0000661 }
662 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000663 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000664 if (!GV.hasName())
665 continue;
666 auto GUID = GV.getGUID();
667 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000668 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
669 << " " << GV.getName() << " from "
670 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000671 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000672 if (Error Err = GV.materialize())
673 return std::move(Err);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000674 GlobalsToImport.insert(&GV);
675 }
676 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000677 for (GlobalAlias &GA : SrcModule->aliases()) {
678 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +0000679 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000680 auto GUID = GA.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000681 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000682 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000683 << " " << GA.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000684 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000685 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000686 // Alias can't point to "available_externally". However when we import
Teresa Johnson9aae3952016-03-27 15:01:11 +0000687 // linkOnceODR the linkage does not change. So we import the alias
Mehdi Amini6968ef72016-04-20 01:04:20 +0000688 // and aliasee only in this case. This has been handled by
689 // computeImportForFunction()
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000690 GlobalObject *GO = GA.getBaseObject();
Mehdi Amini6968ef72016-04-20 01:04:20 +0000691 assert(GO->hasLinkOnceODRLinkage() &&
692 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000693#ifndef NDEBUG
694 if (!GlobalsToImport.count(GO))
695 DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
696 << " " << GO->getName() << " from "
697 << SrcModule->getSourceFileName() << "\n");
698#endif
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000699 if (Error Err = GO->materialize())
700 return std::move(Err);
Mehdi Amini01e32132016-03-26 05:40:34 +0000701 GlobalsToImport.insert(GO);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000702 if (Error Err = GA.materialize())
703 return std::move(Err);
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000704 GlobalsToImport.insert(&GA);
Mehdi Amini01e32132016-03-26 05:40:34 +0000705 }
706 }
707
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000708 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000709 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000710 return true;
711
Teresa Johnsond29478f2016-03-27 15:27:30 +0000712 if (PrintImports) {
713 for (const auto *GV : GlobalsToImport)
714 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
715 << " from " << SrcModule->getSourceFileName() << "\n";
716 }
717
Mehdi Aminibda3c972016-04-21 01:59:39 +0000718 // Instruct the linker that the client will take care of linkonce resolution
719 unsigned Flags = Linker::Flags::None;
720 if (!ForceImportReferencedDiscardableSymbols)
721 Flags |= Linker::Flags::DontForceLinkLinkonceODR;
722
723 if (TheLinker.linkInModule(std::move(SrcModule), Flags, &GlobalsToImport))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000724 report_fatal_error("Function Import: link error");
725
Mehdi Amini01e32132016-03-26 05:40:34 +0000726 ImportedCount += GlobalsToImport.size();
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000727 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000728
Teresa Johnsond29478f2016-03-27 15:27:30 +0000729 NumImported += ImportedCount;
730
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000731 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000732 << DestModule.getModuleIdentifier() << "\n");
733 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000734}
735
736/// Summary file to use for function importing when using -function-import from
737/// the command line.
738static cl::opt<std::string>
739 SummaryFile("summary-file",
740 cl::desc("The summary file to use for function importing."));
741
Teresa Johnson21241572016-07-18 21:22:24 +0000742static bool doImportingForModule(Module &M, const ModuleSummaryIndex *Index) {
743 if (SummaryFile.empty() && !Index)
744 report_fatal_error("error: -function-import requires -summary-file or "
745 "file from frontend\n");
746 std::unique_ptr<ModuleSummaryIndex> IndexPtr;
747 if (!SummaryFile.empty()) {
748 if (Index)
749 report_fatal_error("error: -summary-file and index from frontend\n");
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000750 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
751 getModuleSummaryIndexForFile(SummaryFile);
752 if (!IndexPtrOrErr) {
753 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
754 "Error loading file '" + SummaryFile + "': ");
Teresa Johnson21241572016-07-18 21:22:24 +0000755 return false;
756 }
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000757 IndexPtr = std::move(*IndexPtrOrErr);
Teresa Johnson21241572016-07-18 21:22:24 +0000758 Index = IndexPtr.get();
759 }
760
761 // First step is collecting the import list.
762 FunctionImporter::ImportMapTy ImportList;
763 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
764 ImportList);
765
766 // Next we need to promote to global scope and rename any local values that
767 // are potentially exported to other modules.
768 if (renameModuleForThinLTO(M, *Index, nullptr)) {
769 errs() << "Error renaming module\n";
770 return false;
771 }
772
773 // Perform the import now.
774 auto ModuleLoader = [&M](StringRef Identifier) {
775 return loadFile(Identifier, M.getContext());
776 };
777 FunctionImporter Importer(*Index, ModuleLoader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000778 Expected<bool> Result = Importer.importFunctions(
779 M, ImportList, !DontForceImportReferencedDiscardableSymbols);
780
781 // FIXME: Probably need to propagate Errors through the pass manager.
782 if (!Result) {
783 logAllUnhandledErrors(Result.takeError(), errs(),
784 "Error importing module: ");
785 return false;
786 }
787
788 return *Result;
Teresa Johnson21241572016-07-18 21:22:24 +0000789}
790
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000791namespace {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000792/// Pass that performs cross-module function import provided a summary file.
Teresa Johnson21241572016-07-18 21:22:24 +0000793class FunctionImportLegacyPass : public ModulePass {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000794 /// Optional module summary index to use for importing, otherwise
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000795 /// the summary-file option must be specified.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000796 const ModuleSummaryIndex *Index;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000797
798public:
799 /// Pass identification, replacement for typeid
800 static char ID;
801
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000802 /// Specify pass name for debug output
Mehdi Amini117296c2016-10-01 02:56:57 +0000803 StringRef getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000804
Teresa Johnson21241572016-07-18 21:22:24 +0000805 explicit FunctionImportLegacyPass(const ModuleSummaryIndex *Index = nullptr)
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000806 : ModulePass(ID), Index(Index) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000807
808 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000809 if (skipModule(M))
810 return false;
811
Teresa Johnson21241572016-07-18 21:22:24 +0000812 return doImportingForModule(M, Index);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000813 }
814};
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000815} // anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000816
Teresa Johnson21241572016-07-18 21:22:24 +0000817PreservedAnalyses FunctionImportPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000818 ModuleAnalysisManager &AM) {
Teresa Johnson21241572016-07-18 21:22:24 +0000819 if (!doImportingForModule(M, Index))
820 return PreservedAnalyses::all();
821
822 return PreservedAnalyses::none();
823}
824
825char FunctionImportLegacyPass::ID = 0;
826INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
827 "Summary Based Function Import", false, false)
Mehdi Amini42418ab2015-11-24 06:07:49 +0000828
829namespace llvm {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000830Pass *createFunctionImportPass(const ModuleSummaryIndex *Index = nullptr) {
Teresa Johnson21241572016-07-18 21:22:24 +0000831 return new FunctionImportLegacyPass(Index);
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000832}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000833}