blob: c20e59fdb94f7b626fd65bfbfde19cba3d851c2c [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
Teresa Johnsond5033a42016-11-14 16:40:19 +0000156 // eligible for import. First check the flag set when we have possible
157 // opaque references (e.g. inline asm calls), then check the call and
158 // reference sets.
159 if (Summary.hasInlineAsmMaybeReferencingInternal())
160 return false;
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000161 bool AllRefsCanBeExternallyReferenced =
162 llvm::all_of(Summary.refs(), [&](const ValueInfo &VI) {
163 return canBeExternallyReferenced(Index, VI.getGUID());
164 });
165 if (!AllRefsCanBeExternallyReferenced)
166 return false;
167
168 if (auto *FuncSummary = dyn_cast<FunctionSummary>(&Summary)) {
169 bool AllCallsCanBeExternallyReferenced = llvm::all_of(
170 FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) {
171 return canBeExternallyReferenced(Index, Edge.first.getGUID());
172 });
173 if (!AllCallsCanBeExternallyReferenced)
174 return false;
175 }
176 return true;
177}
178
Mehdi Amini01e32132016-03-26 05:40:34 +0000179/// Given a list of possible callee implementation for a call site, select one
180/// that fits the \p Threshold.
181///
182/// FIXME: select "best" instead of first that fits. But what is "best"?
183/// - The smallest: more likely to be inlined.
184/// - The one with the least outgoing edges (already well optimized).
185/// - One from a module already being imported from in order to reduce the
186/// number of source modules parsed/linked.
187/// - One that has PGO data attached.
188/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000189static const GlobalValueSummary *
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000190selectCallee(const ModuleSummaryIndex &Index,
191 const GlobalValueSummaryList &CalleeSummaryList,
Teresa Johnson28e457b2016-04-24 14:57:11 +0000192 unsigned Threshold) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000193 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000194 CalleeSummaryList,
195 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
196 auto *GVSummary = SummaryPtr.get();
Rafael Espindolaf329be82016-05-11 01:26:06 +0000197 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000198 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000199 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000200 if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
201 GVSummary = &AS->getAliasee();
202 // Alias can't point to "available_externally". However when we import
203 // linkOnceODR the linkage does not change. So we import the alias
204 // and aliasee only in this case.
205 // FIXME: we should import alias as available_externally *function*,
206 // the destination module does need to know it is an alias.
207 if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
208 return false;
209 }
210
211 auto *Summary = cast<FunctionSummary>(GVSummary);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000212
Mehdi Amini01e32132016-03-26 05:40:34 +0000213 if (Summary->instCount() > Threshold)
214 return false;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000215
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000216 if (!eligibleForImport(Index, *Summary))
217 return false;
218
Mehdi Amini01e32132016-03-26 05:40:34 +0000219 return true;
220 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000221 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000222 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000223
Teresa Johnson28e457b2016-04-24 14:57:11 +0000224 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000225}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000226
Mehdi Amini01e32132016-03-26 05:40:34 +0000227/// Return the summary for the function \p GUID that fits the \p Threshold, or
228/// null if there's no match.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000229static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID,
230 unsigned Threshold,
231 const ModuleSummaryIndex &Index) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000232 auto CalleeSummaryList = Index.findGlobalValueSummaryList(GUID);
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000233 if (CalleeSummaryList == Index.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000234 return nullptr; // This function does not have a summary
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000235 return selectCallee(Index, CalleeSummaryList->second, Threshold);
Mehdi Amini01e32132016-03-26 05:40:34 +0000236}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000237
Mehdi Aminicb874942016-04-23 23:29:24 +0000238/// Mark the global \p GUID as export by module \p ExportModulePath if found in
239/// this module. If it is a GlobalVariable, we also mark any referenced global
240/// in the current module as exported.
241static void exportGlobalInModule(const ModuleSummaryIndex &Index,
242 StringRef ExportModulePath,
243 GlobalValue::GUID GUID,
244 FunctionImporter::ExportSetTy &ExportList) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000245 auto FindGlobalSummaryInModule =
246 [&](GlobalValue::GUID GUID) -> GlobalValueSummary *{
247 auto SummaryList = Index.findGlobalValueSummaryList(GUID);
248 if (SummaryList == Index.end())
Mehdi Aminicb874942016-04-23 23:29:24 +0000249 // This global does not have a summary, it is not part of the ThinLTO
250 // process
251 return nullptr;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000252 auto SummaryIter = llvm::find_if(
253 SummaryList->second,
254 [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
Mehdi Aminicb874942016-04-23 23:29:24 +0000255 return Summary->modulePath() == ExportModulePath;
256 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000257 if (SummaryIter == SummaryList->second.end())
Mehdi Aminicb874942016-04-23 23:29:24 +0000258 return nullptr;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000259 return SummaryIter->get();
Mehdi Aminicb874942016-04-23 23:29:24 +0000260 };
261
Teresa Johnson28e457b2016-04-24 14:57:11 +0000262 auto *Summary = FindGlobalSummaryInModule(GUID);
263 if (!Summary)
Mehdi Aminicb874942016-04-23 23:29:24 +0000264 return;
265 // We found it in the current module, mark as exported
266 ExportList.insert(GUID);
Mehdi Amini01e32132016-03-26 05:40:34 +0000267}
Mehdi Amini40641742016-02-10 23:31:45 +0000268
Mehdi Amini01e32132016-03-26 05:40:34 +0000269using EdgeInfo = std::pair<const FunctionSummary *, unsigned /* Threshold */>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000270
Mehdi Amini01e32132016-03-26 05:40:34 +0000271/// Compute the list of functions to import for a given caller. Mark these
272/// imported functions and the symbols they reference in their source module as
273/// exported from their source module.
274static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000275 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000276 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000277 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000278 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000279 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000280 for (auto &Edge : Summary.calls()) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000281 auto GUID = Edge.first.getGUID();
Mehdi Amini01e32132016-03-26 05:40:34 +0000282 DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
283
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000284 if (DefinedGVSummaries.count(GUID)) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000285 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
286 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000287 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000288
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000289 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
290 if (Hotness == CalleeInfo::HotnessType::Hot)
291 return ImportHotMultiplier;
292 if (Hotness == CalleeInfo::HotnessType::Cold)
293 return ImportColdMultiplier;
294 return 1.0;
295 };
296
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000297 const auto NewThreshold =
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000298 Threshold * GetBonusMultiplier(Edge.second.Hotness);
Piotr Padlewskid2869472016-09-30 03:01:17 +0000299
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000300 auto *CalleeSummary = selectCallee(GUID, NewThreshold, Index);
Mehdi Amini01e32132016-03-26 05:40:34 +0000301 if (!CalleeSummary) {
302 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
303 continue;
304 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000305 // "Resolve" the summary, traversing alias,
306 const FunctionSummary *ResolvedCalleeSummary;
Mehdi Amini6968ef72016-04-20 01:04:20 +0000307 if (isa<AliasSummary>(CalleeSummary)) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000308 ResolvedCalleeSummary = cast<FunctionSummary>(
309 &cast<AliasSummary>(CalleeSummary)->getAliasee());
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000310 assert(
311 GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
312 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini6968ef72016-04-20 01:04:20 +0000313 } else
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000314 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
315
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000316 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000317 "selectCallee() didn't honor the threshold");
318
Piotr Padlewskid2869472016-09-30 03:01:17 +0000319 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
320 // Adjust the threshold for next level of imported functions.
321 // The threshold is different for hot callsites because we can then
322 // inline chains of hot calls.
323 if (IsHotCallsite)
324 return Threshold * ImportHotInstrFactor;
325 return Threshold * ImportInstrFactor;
326 };
327
328 bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000329 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
330
331 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
332 auto &ProcessedThreshold = ImportList[ExportModulePath][GUID];
333 /// 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.
336 if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
337 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
338 << ProcessedThreshold << "\n");
339 continue;
340 }
341 bool PreviouslyImported = ProcessedThreshold != 0;
342 // Mark this function as imported in this module, with the current Threshold
343 ProcessedThreshold = AdjThreshold;
344
345 // Make exports in the source module.
346 if (ExportLists) {
347 auto &ExportList = (*ExportLists)[ExportModulePath];
348 ExportList.insert(GUID);
349 if (!PreviouslyImported) {
350 // This is the first time this function was exported from its source
351 // module, so mark all functions and globals it references as exported
352 // to the outside if they are defined in the same source module.
353 for (auto &Edge : ResolvedCalleeSummary->calls()) {
354 auto CalleeGUID = Edge.first.getGUID();
355 exportGlobalInModule(Index, ExportModulePath, CalleeGUID, ExportList);
356 }
357 for (auto &Ref : ResolvedCalleeSummary->refs()) {
358 auto GUID = Ref.getGUID();
359 exportGlobalInModule(Index, ExportModulePath, GUID, ExportList);
360 }
361 }
362 }
Piotr Padlewskid2869472016-09-30 03:01:17 +0000363
Mehdi Amini01e32132016-03-26 05:40:34 +0000364 // Insert the newly imported function to the worklist.
Teresa Johnson1b859a22016-12-15 18:21:01 +0000365 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold);
Teresa Johnsond450da32015-11-24 21:15:19 +0000366 }
367}
368
Mehdi Amini01e32132016-03-26 05:40:34 +0000369/// Given the list of globals defined in a module, compute the list of imports
370/// as well as the list of "exports", i.e. the list of symbols referenced from
371/// another module (that may require promotion).
372static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000373 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000374 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000375 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000376 // Worklist contains the list of function imported in this module, for which
377 // we will analyse the callees and may import further down the callgraph.
378 SmallVector<EdgeInfo, 128> Worklist;
379
380 // Populate the worklist with the import for the functions in the current
381 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000382 for (auto &GVSummary : DefinedGVSummaries) {
383 auto *Summary = GVSummary.second;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000384 if (auto *AS = dyn_cast<AliasSummary>(Summary))
385 Summary = &AS->getAliasee();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000386 auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
387 if (!FuncSummary)
388 // Skip import for global variables
389 continue;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000390 DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000391 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000392 DefinedGVSummaries, Worklist, ImportList,
Mehdi Amini01e32132016-03-26 05:40:34 +0000393 ExportLists);
394 }
395
Piotr Padlewskid2869472016-09-30 03:01:17 +0000396 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini42418ab2015-11-24 06:07:49 +0000397 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000398 auto FuncInfo = Worklist.pop_back_val();
399 auto *Summary = FuncInfo.first;
400 auto Threshold = FuncInfo.second;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000401
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000402 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000403 Worklist, ImportList, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000404 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000405}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000406
Mehdi Amini01e32132016-03-26 05:40:34 +0000407} // anonymous namespace
408
Teresa Johnsonc86af332016-04-12 21:13:11 +0000409/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000410void llvm::ComputeCrossModuleImport(
411 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000412 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000413 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
414 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000415 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000416 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000417 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000418 DEBUG(dbgs() << "Computing import for Module '"
419 << DefinedGVSummaries.first() << "'\n");
Mehdi Amini9b490f12016-08-16 05:47:12 +0000420 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000421 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000422 }
423
424#ifndef NDEBUG
425 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
426 << " modules:\n");
427 for (auto &ModuleImports : ImportLists) {
428 auto ModName = ModuleImports.first();
429 auto &Exports = ExportLists[ModName];
430 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
431 << " functions. Imports from " << ModuleImports.second.size()
432 << " modules.\n");
433 for (auto &Src : ModuleImports.second) {
434 auto SrcModName = Src.first();
435 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
436 << SrcModName << "\n");
437 }
438 }
439#endif
440}
441
Teresa Johnsonc86af332016-04-12 21:13:11 +0000442/// Compute all the imports for the given module in the Index.
443void llvm::ComputeCrossModuleImportForModule(
444 StringRef ModulePath, const ModuleSummaryIndex &Index,
445 FunctionImporter::ImportMapTy &ImportList) {
446
447 // Collect the list of functions this module defines.
448 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000449 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000450 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000451
452 // Compute the import list for this module.
453 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000454 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000455
456#ifndef NDEBUG
457 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
458 << ImportList.size() << " modules.\n");
459 for (auto &Src : ImportList) {
460 auto SrcModName = Src.first();
461 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
462 << SrcModName << "\n");
463 }
464#endif
465}
466
Teresa Johnson84174c32016-05-10 13:48:23 +0000467/// Compute the set of summaries needed for a ThinLTO backend compilation of
468/// \p ModulePath.
469void llvm::gatherImportedSummariesForModule(
470 StringRef ModulePath,
471 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000472 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000473 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
474 // Include all summaries from the importing module.
475 ModuleToSummariesForIndex[ModulePath] =
476 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000477 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000478 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000479 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
480 const auto &DefinedGVSummaries =
481 ModuleToDefinedGVSummaries.lookup(ILI.first());
482 for (auto &GI : ILI.second) {
483 const auto &DS = DefinedGVSummaries.find(GI.first);
484 assert(DS != DefinedGVSummaries.end() &&
485 "Expected a defined summary for imported global value");
486 SummariesForIndex[GI.first] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000487 }
488 }
489}
490
Teresa Johnson8570fe42016-05-10 15:54:09 +0000491/// Emit the files \p ModulePath will import from into \p OutputFilename.
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000492std::error_code
493llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
494 const FunctionImporter::ImportMapTy &ModuleImports) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000495 std::error_code EC;
496 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
497 if (EC)
498 return EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000499 for (auto &ILI : ModuleImports)
500 ImportsOS << ILI.first() << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000501 return std::error_code();
502}
503
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000504/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
505void llvm::thinLTOResolveWeakForLinkerModule(
506 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
507 auto updateLinkage = [&](GlobalValue &GV) {
508 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
509 return;
510 // See if the global summary analysis computed a new resolved linkage.
511 const auto &GS = DefinedGlobals.find(GV.getGUID());
512 if (GS == DefinedGlobals.end())
513 return;
514 auto NewLinkage = GS->second->linkage();
515 if (NewLinkage == GV.getLinkage())
516 return;
517 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
518 << GV.getLinkage() << " to " << NewLinkage << "\n");
519 GV.setLinkage(NewLinkage);
Teresa Johnson6107a412016-08-15 21:00:04 +0000520 // Remove functions converted to available_externally from comdats,
521 // as this is a declaration for the linker, and will be dropped eventually.
522 // It is illegal for comdats to contain declarations.
523 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
524 if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
525 assert(GO->hasAvailableExternallyLinkage() &&
526 "Expected comdat on definition (possibly available external)");
527 GO->setComdat(nullptr);
528 }
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000529 };
530
531 // Process functions and global now
532 for (auto &GV : TheModule)
533 updateLinkage(GV);
534 for (auto &GV : TheModule.globals())
535 updateLinkage(GV);
536 for (auto &GV : TheModule.aliases())
537 updateLinkage(GV);
538}
539
540/// Run internalization on \p TheModule based on symmary analysis.
541void llvm::thinLTOInternalizeModule(Module &TheModule,
542 const GVSummaryMapTy &DefinedGlobals) {
543 // Parse inline ASM and collect the list of symbols that are not defined in
544 // the current module.
545 StringSet<> AsmUndefinedRefs;
Peter Collingbourne863cbfb2016-12-01 06:51:47 +0000546 ModuleSymbolTable::CollectAsmSymbols(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000547 Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
548 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
549 if (Flags & object::BasicSymbolRef::SF_Undefined)
550 AsmUndefinedRefs.insert(Name);
551 });
552
553 // Declare a callback for the internalize pass that will ask for every
554 // candidate GlobalValue if it can be internalized or not.
555 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
556 // Can't be internalized if referenced in inline asm.
557 if (AsmUndefinedRefs.count(GV.getName()))
558 return true;
559
560 // Lookup the linkage recorded in the summaries during global analysis.
561 const auto &GS = DefinedGlobals.find(GV.getGUID());
562 GlobalValue::LinkageTypes Linkage;
563 if (GS == DefinedGlobals.end()) {
564 // Must have been promoted (possibly conservatively). Find original
565 // name so that we can access the correct summary and see if it can
566 // be internalized again.
567 // FIXME: Eventually we should control promotion instead of promoting
568 // and internalizing again.
569 StringRef OrigName =
570 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
571 std::string OrigId = GlobalValue::getGlobalIdentifier(
572 OrigName, GlobalValue::InternalLinkage,
573 TheModule.getSourceFileName());
574 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000575 if (GS == DefinedGlobals.end()) {
576 // Also check the original non-promoted non-globalized name. In some
577 // cases a preempted weak value is linked in as a local copy because
578 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
579 // In that case, since it was originally not a local value, it was
580 // recorded in the index using the original name.
581 // FIXME: This may not be needed once PR27866 is fixed.
582 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
583 assert(GS != DefinedGlobals.end());
584 Linkage = GS->second->linkage();
585 } else {
586 Linkage = GS->second->linkage();
587 }
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000588 } else
589 Linkage = GS->second->linkage();
590 return !GlobalValue::isLocalLinkage(Linkage);
591 };
592
593 // FIXME: See if we can just internalize directly here via linkage changes
594 // based on the index, rather than invoking internalizeModule.
595 llvm::internalizeModule(TheModule, MustPreserveGV);
596}
597
Mehdi Aminic8c55172015-12-03 02:37:33 +0000598// Automatically import functions in Module \p DestModule based on the summaries
599// index.
600//
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000601Expected<bool> FunctionImporter::importFunctions(
Mehdi Aminibda3c972016-04-21 01:59:39 +0000602 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList,
603 bool ForceImportReferencedDiscardableSymbols) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000604 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000605 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000606 unsigned ImportedCount = 0;
607
Mehdi Aminic8c55172015-12-03 02:37:33 +0000608 // Linker that will be used for importing function
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000609 Linker TheLinker(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000610 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000611 std::set<StringRef> ModuleNameOrderedList;
612 for (auto &FunctionsToImportPerModule : ImportList) {
613 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
614 }
615 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000616 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000617 const auto &FunctionsToImportPerModule = ImportList.find(Name);
618 assert(FunctionsToImportPerModule != ImportList.end());
Peter Collingbourned9445c42016-11-13 07:00:17 +0000619 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
620 if (!SrcModuleOrErr)
621 return SrcModuleOrErr.takeError();
622 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000623 assert(&DestModule.getContext() == &SrcModule->getContext() &&
624 "Context mismatch");
625
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000626 // If modules were created with lazy metadata loading, materialize it
627 // now, before linking it (otherwise this will be a noop).
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000628 if (Error Err = SrcModule->materializeMetadata())
629 return std::move(Err);
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000630 UpgradeDebugInfo(*SrcModule);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000631
Mehdi Amini01e32132016-03-26 05:40:34 +0000632 auto &ImportGUIDs = FunctionsToImportPerModule->second;
633 // Find the globals to import
634 DenseSet<const GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000635 for (Function &F : *SrcModule) {
636 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +0000637 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000638 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000639 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000640 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000641 << " " << F.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000642 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000643 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000644 if (Error Err = F.materialize())
645 return std::move(Err);
Piotr Padlewski3b776122016-07-08 23:01:49 +0000646 if (EnableImportMetadata) {
647 // Add 'thinlto_src_module' metadata for statistics and debugging.
648 F.setMetadata(
649 "thinlto_src_module",
650 llvm::MDNode::get(
651 DestModule.getContext(),
652 {llvm::MDString::get(DestModule.getContext(),
653 SrcModule->getSourceFileName())}));
654 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000655 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +0000656 }
657 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000658 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000659 if (!GV.hasName())
660 continue;
661 auto GUID = GV.getGUID();
662 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000663 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
664 << " " << GV.getName() << " from "
665 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000666 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000667 if (Error Err = GV.materialize())
668 return std::move(Err);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000669 GlobalsToImport.insert(&GV);
670 }
671 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000672 for (GlobalAlias &GA : SrcModule->aliases()) {
673 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +0000674 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000675 auto GUID = GA.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000676 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000677 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000678 << " " << GA.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000679 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000680 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000681 // Alias can't point to "available_externally". However when we import
Teresa Johnson9aae3952016-03-27 15:01:11 +0000682 // linkOnceODR the linkage does not change. So we import the alias
Mehdi Amini6968ef72016-04-20 01:04:20 +0000683 // and aliasee only in this case. This has been handled by
684 // computeImportForFunction()
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000685 GlobalObject *GO = GA.getBaseObject();
Mehdi Amini6968ef72016-04-20 01:04:20 +0000686 assert(GO->hasLinkOnceODRLinkage() &&
687 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000688#ifndef NDEBUG
689 if (!GlobalsToImport.count(GO))
690 DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
691 << " " << GO->getName() << " from "
692 << SrcModule->getSourceFileName() << "\n");
693#endif
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000694 if (Error Err = GO->materialize())
695 return std::move(Err);
Mehdi Amini01e32132016-03-26 05:40:34 +0000696 GlobalsToImport.insert(GO);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000697 if (Error Err = GA.materialize())
698 return std::move(Err);
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000699 GlobalsToImport.insert(&GA);
Mehdi Amini01e32132016-03-26 05:40:34 +0000700 }
701 }
702
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000703 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000704 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000705 return true;
706
Teresa Johnsond29478f2016-03-27 15:27:30 +0000707 if (PrintImports) {
708 for (const auto *GV : GlobalsToImport)
709 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
710 << " from " << SrcModule->getSourceFileName() << "\n";
711 }
712
Mehdi Aminibda3c972016-04-21 01:59:39 +0000713 // Instruct the linker that the client will take care of linkonce resolution
714 unsigned Flags = Linker::Flags::None;
715 if (!ForceImportReferencedDiscardableSymbols)
716 Flags |= Linker::Flags::DontForceLinkLinkonceODR;
717
718 if (TheLinker.linkInModule(std::move(SrcModule), Flags, &GlobalsToImport))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000719 report_fatal_error("Function Import: link error");
720
Mehdi Amini01e32132016-03-26 05:40:34 +0000721 ImportedCount += GlobalsToImport.size();
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000722 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000723
Teresa Johnsond29478f2016-03-27 15:27:30 +0000724 NumImported += ImportedCount;
725
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000726 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000727 << DestModule.getModuleIdentifier() << "\n");
728 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000729}
730
731/// Summary file to use for function importing when using -function-import from
732/// the command line.
733static cl::opt<std::string>
734 SummaryFile("summary-file",
735 cl::desc("The summary file to use for function importing."));
736
Teresa Johnson21241572016-07-18 21:22:24 +0000737static bool doImportingForModule(Module &M, const ModuleSummaryIndex *Index) {
738 if (SummaryFile.empty() && !Index)
739 report_fatal_error("error: -function-import requires -summary-file or "
740 "file from frontend\n");
741 std::unique_ptr<ModuleSummaryIndex> IndexPtr;
742 if (!SummaryFile.empty()) {
743 if (Index)
744 report_fatal_error("error: -summary-file and index from frontend\n");
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000745 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
746 getModuleSummaryIndexForFile(SummaryFile);
747 if (!IndexPtrOrErr) {
748 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
749 "Error loading file '" + SummaryFile + "': ");
Teresa Johnson21241572016-07-18 21:22:24 +0000750 return false;
751 }
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000752 IndexPtr = std::move(*IndexPtrOrErr);
Teresa Johnson21241572016-07-18 21:22:24 +0000753 Index = IndexPtr.get();
754 }
755
756 // First step is collecting the import list.
757 FunctionImporter::ImportMapTy ImportList;
758 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
759 ImportList);
760
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000761 // Conservatively mark all internal values as promoted. This interface is
762 // only used when doing importing via the function importing pass. The pass
763 // is only enabled when testing importing via the 'opt' tool, which does
764 // not do the ThinLink that would normally determine what values to promote.
765 for (auto &I : *Index) {
766 for (auto &S : I.second) {
767 if (GlobalValue::isLocalLinkage(S->linkage()))
768 S->setLinkage(GlobalValue::ExternalLinkage);
769 }
770 }
771
Teresa Johnson21241572016-07-18 21:22:24 +0000772 // Next we need to promote to global scope and rename any local values that
773 // are potentially exported to other modules.
774 if (renameModuleForThinLTO(M, *Index, nullptr)) {
775 errs() << "Error renaming module\n";
776 return false;
777 }
778
779 // Perform the import now.
780 auto ModuleLoader = [&M](StringRef Identifier) {
781 return loadFile(Identifier, M.getContext());
782 };
783 FunctionImporter Importer(*Index, ModuleLoader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000784 Expected<bool> Result = Importer.importFunctions(
785 M, ImportList, !DontForceImportReferencedDiscardableSymbols);
786
787 // FIXME: Probably need to propagate Errors through the pass manager.
788 if (!Result) {
789 logAllUnhandledErrors(Result.takeError(), errs(),
790 "Error importing module: ");
791 return false;
792 }
793
794 return *Result;
Teresa Johnson21241572016-07-18 21:22:24 +0000795}
796
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000797namespace {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000798/// Pass that performs cross-module function import provided a summary file.
Teresa Johnson21241572016-07-18 21:22:24 +0000799class FunctionImportLegacyPass : public ModulePass {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000800 /// Optional module summary index to use for importing, otherwise
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000801 /// the summary-file option must be specified.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000802 const ModuleSummaryIndex *Index;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000803
804public:
805 /// Pass identification, replacement for typeid
806 static char ID;
807
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000808 /// Specify pass name for debug output
Mehdi Amini117296c2016-10-01 02:56:57 +0000809 StringRef getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000810
Teresa Johnson21241572016-07-18 21:22:24 +0000811 explicit FunctionImportLegacyPass(const ModuleSummaryIndex *Index = nullptr)
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000812 : ModulePass(ID), Index(Index) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000813
814 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000815 if (skipModule(M))
816 return false;
817
Teresa Johnson21241572016-07-18 21:22:24 +0000818 return doImportingForModule(M, Index);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000819 }
820};
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000821} // anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000822
Teresa Johnson21241572016-07-18 21:22:24 +0000823PreservedAnalyses FunctionImportPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000824 ModuleAnalysisManager &AM) {
Teresa Johnson21241572016-07-18 21:22:24 +0000825 if (!doImportingForModule(M, Index))
826 return PreservedAnalyses::all();
827
828 return PreservedAnalyses::none();
829}
830
831char FunctionImportLegacyPass::ID = 0;
832INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
833 "Summary Based Function Import", false, false)
Mehdi Amini42418ab2015-11-24 06:07:49 +0000834
835namespace llvm {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000836Pass *createFunctionImportPass(const ModuleSummaryIndex *Index = nullptr) {
Teresa Johnson21241572016-07-18 21:22:24 +0000837 return new FunctionImportLegacyPass(Index);
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000838}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000839}