blob: 6dd95f8dcd55833c311c92980913ad0afad711c0 [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"
Mehdi Aminifc06b832016-12-23 18:04:51 +000024#include "llvm/IR/Verifier.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000025#include "llvm/IRReader/IRReader.h"
26#include "llvm/Linker/Linker.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000027#include "llvm/Object/IRObjectFile.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000028#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000029#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/SourceMgr.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000032#include "llvm/Transforms/IPO/Internalize.h"
Teresa Johnson488a8002016-02-10 18:11:31 +000033#include "llvm/Transforms/Utils/FunctionImportUtils.h"
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000034
Mehdi Amini01e32132016-03-26 05:40:34 +000035#define DEBUG_TYPE "function-import"
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000036
Mehdi Amini42418ab2015-11-24 06:07:49 +000037using namespace llvm;
38
Teresa Johnsond29478f2016-03-27 15:27:30 +000039STATISTIC(NumImported, "Number of functions imported");
40
Teresa Johnson39303612015-11-24 22:55:46 +000041/// Limit on instruction count of imported functions.
42static cl::opt<unsigned> ImportInstrLimit(
43 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
44 cl::desc("Only import functions with less than N instructions"));
45
Mehdi Amini40641742016-02-10 23:31:45 +000046static cl::opt<float>
47 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
48 cl::Hidden, cl::value_desc("x"),
49 cl::desc("As we import functions, multiply the "
50 "`import-instr-limit` threshold by this factor "
51 "before processing newly imported functions"));
Piotr Padlewskiba72b952016-09-29 17:32:07 +000052
Piotr Padlewskid2869472016-09-30 03:01:17 +000053static cl::opt<float> ImportHotInstrFactor(
54 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
55 cl::value_desc("x"),
56 cl::desc("As we import functions called from hot callsite, multiply the "
57 "`import-instr-limit` threshold by this factor "
58 "before processing newly imported functions"));
59
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000060static cl::opt<float> ImportHotMultiplier(
61 "import-hot-multiplier", cl::init(3.0), cl::Hidden, cl::value_desc("x"),
Piotr Padlewskiba72b952016-09-29 17:32:07 +000062 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
63
64// FIXME: This multiplier was not really tuned up.
65static cl::opt<float> ImportColdMultiplier(
66 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
67 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
Mehdi Amini40641742016-02-10 23:31:45 +000068
Teresa Johnsond29478f2016-03-27 15:27:30 +000069static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
70 cl::desc("Print imported functions"));
71
Mehdi Aminibda3c972016-04-21 01:59:39 +000072// Temporary allows the function import pass to disable always linking
73// referenced discardable symbols.
74static cl::opt<bool>
75 DontForceImportReferencedDiscardableSymbols("disable-force-link-odr",
76 cl::init(false), cl::Hidden);
77
Piotr Padlewski3b776122016-07-08 23:01:49 +000078static cl::opt<bool> EnableImportMetadata(
79 "enable-import-metadata", cl::init(
80#if !defined(NDEBUG)
81 true /*Enabled with asserts.*/
82#else
83 false
84#endif
85 ),
86 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
87
Mehdi Amini42418ab2015-11-24 06:07:49 +000088// Load lazily a module from \p FileName in \p Context.
89static std::unique_ptr<Module> loadFile(const std::string &FileName,
90 LLVMContext &Context) {
91 SMDiagnostic Err;
92 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +000093 // Metadata isn't loaded until functions are imported, to minimize
94 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +000095 std::unique_ptr<Module> Result =
96 getLazyIRFileModule(FileName, Err, Context,
97 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +000098 if (!Result) {
99 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +0000100 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000101 }
102
Mehdi Amini42418ab2015-11-24 06:07:49 +0000103 return Result;
104}
105
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000106namespace {
Mehdi Amini40641742016-02-10 23:31:45 +0000107
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000108// Return true if the Summary describes a GlobalValue that can be externally
109// referenced, i.e. it does not need renaming (linkage is not local) or renaming
110// is possible (does not have a section for instance).
111static bool canBeExternallyReferenced(const GlobalValueSummary &Summary) {
112 if (!Summary.needsRenaming())
113 return true;
114
Teresa Johnson58fbc912016-10-28 02:24:59 +0000115 if (Summary.noRename())
116 // Can't externally reference a global that needs renaming if has a section
117 // or is referenced from inline assembly, for example.
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000118 return false;
119
120 return true;
121}
122
123// Return true if \p GUID describes a GlobalValue that can be externally
124// referenced, i.e. it does not need renaming (linkage is not local) or
125// renaming is possible (does not have a section for instance).
126static bool canBeExternallyReferenced(const ModuleSummaryIndex &Index,
127 GlobalValue::GUID GUID) {
128 auto Summaries = Index.findGlobalValueSummaryList(GUID);
129 if (Summaries == Index.end())
130 return true;
131 if (Summaries->second.size() != 1)
132 // If there are multiple globals with this GUID, then we know it is
133 // not a local symbol, and it is necessarily externally referenced.
134 return true;
135
136 // We don't need to check for the module path, because if it can't be
137 // externally referenced and we call it, it is necessarilly in the same
138 // module
139 return canBeExternallyReferenced(**Summaries->second.begin());
140}
141
142// Return true if the global described by \p Summary can be imported in another
143// module.
144static bool eligibleForImport(const ModuleSummaryIndex &Index,
145 const GlobalValueSummary &Summary) {
146 if (!canBeExternallyReferenced(Summary))
147 // Can't import a global that needs renaming if has a section for instance.
148 // FIXME: we may be able to import it by copying it without promotion.
149 return false;
150
Piotr Padlewski332b3b22016-08-11 22:13:57 +0000151 // Don't import functions that are not viable to inline.
152 if (Summary.isNotViableToInline())
153 return false;
154
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000155 // Check references (and potential calls) in the same module. If the current
156 // value references a global that can't be externally referenced it is not
Teresa Johnsond5033a42016-11-14 16:40:19 +0000157 // eligible for import. First check the flag set when we have possible
158 // opaque references (e.g. inline asm calls), then check the call and
159 // reference sets.
160 if (Summary.hasInlineAsmMaybeReferencingInternal())
161 return false;
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000162 bool AllRefsCanBeExternallyReferenced =
163 llvm::all_of(Summary.refs(), [&](const ValueInfo &VI) {
164 return canBeExternallyReferenced(Index, VI.getGUID());
165 });
166 if (!AllRefsCanBeExternallyReferenced)
167 return false;
168
169 if (auto *FuncSummary = dyn_cast<FunctionSummary>(&Summary)) {
170 bool AllCallsCanBeExternallyReferenced = llvm::all_of(
171 FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) {
172 return canBeExternallyReferenced(Index, Edge.first.getGUID());
173 });
174 if (!AllCallsCanBeExternallyReferenced)
175 return false;
176 }
177 return true;
178}
179
Mehdi Amini01e32132016-03-26 05:40:34 +0000180/// Given a list of possible callee implementation for a call site, select one
181/// that fits the \p Threshold.
182///
183/// FIXME: select "best" instead of first that fits. But what is "best"?
184/// - The smallest: more likely to be inlined.
185/// - The one with the least outgoing edges (already well optimized).
186/// - One from a module already being imported from in order to reduce the
187/// number of source modules parsed/linked.
188/// - One that has PGO data attached.
189/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000190static const GlobalValueSummary *
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000191selectCallee(const ModuleSummaryIndex &Index,
192 const GlobalValueSummaryList &CalleeSummaryList,
Teresa Johnson28e457b2016-04-24 14:57:11 +0000193 unsigned Threshold) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000194 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000195 CalleeSummaryList,
196 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
197 auto *GVSummary = SummaryPtr.get();
Rafael Espindolaf329be82016-05-11 01:26:06 +0000198 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000199 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000200 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000201 if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
202 GVSummary = &AS->getAliasee();
203 // Alias can't point to "available_externally". However when we import
204 // linkOnceODR the linkage does not change. So we import the alias
205 // and aliasee only in this case.
206 // FIXME: we should import alias as available_externally *function*,
207 // the destination module does need to know it is an alias.
208 if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
209 return false;
210 }
211
212 auto *Summary = cast<FunctionSummary>(GVSummary);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000213
Mehdi Amini01e32132016-03-26 05:40:34 +0000214 if (Summary->instCount() > Threshold)
215 return false;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000216
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000217 if (!eligibleForImport(Index, *Summary))
218 return false;
219
Mehdi Amini01e32132016-03-26 05:40:34 +0000220 return true;
221 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000222 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000223 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000224
Teresa Johnson28e457b2016-04-24 14:57:11 +0000225 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000226}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000227
Mehdi Amini01e32132016-03-26 05:40:34 +0000228/// Return the summary for the function \p GUID that fits the \p Threshold, or
229/// null if there's no match.
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000230static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID,
231 unsigned Threshold,
232 const ModuleSummaryIndex &Index) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000233 auto CalleeSummaryList = Index.findGlobalValueSummaryList(GUID);
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000234 if (CalleeSummaryList == Index.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000235 return nullptr; // This function does not have a summary
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000236 return selectCallee(Index, CalleeSummaryList->second, Threshold);
Mehdi Amini01e32132016-03-26 05:40:34 +0000237}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000238
Teresa Johnson475b51a2016-12-15 20:48:19 +0000239using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
240 GlobalValue::GUID>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000241
Mehdi Amini01e32132016-03-26 05:40:34 +0000242/// Compute the list of functions to import for a given caller. Mark these
243/// imported functions and the symbols they reference in their source module as
244/// exported from their source module.
245static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000246 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000247 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000248 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000249 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000250 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000251 for (auto &Edge : Summary.calls()) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000252 auto GUID = Edge.first.getGUID();
Mehdi Amini01e32132016-03-26 05:40:34 +0000253 DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
254
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000255 if (DefinedGVSummaries.count(GUID)) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000256 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
257 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000258 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000259
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000260 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
261 if (Hotness == CalleeInfo::HotnessType::Hot)
262 return ImportHotMultiplier;
263 if (Hotness == CalleeInfo::HotnessType::Cold)
264 return ImportColdMultiplier;
265 return 1.0;
266 };
267
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000268 const auto NewThreshold =
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000269 Threshold * GetBonusMultiplier(Edge.second.Hotness);
Piotr Padlewskid2869472016-09-30 03:01:17 +0000270
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000271 auto *CalleeSummary = selectCallee(GUID, NewThreshold, Index);
Mehdi Amini01e32132016-03-26 05:40:34 +0000272 if (!CalleeSummary) {
273 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
274 continue;
275 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000276 // "Resolve" the summary, traversing alias,
277 const FunctionSummary *ResolvedCalleeSummary;
Mehdi Amini6968ef72016-04-20 01:04:20 +0000278 if (isa<AliasSummary>(CalleeSummary)) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000279 ResolvedCalleeSummary = cast<FunctionSummary>(
280 &cast<AliasSummary>(CalleeSummary)->getAliasee());
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000281 assert(
282 GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
283 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini6968ef72016-04-20 01:04:20 +0000284 } else
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000285 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
286
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000287 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000288 "selectCallee() didn't honor the threshold");
289
Piotr Padlewskid2869472016-09-30 03:01:17 +0000290 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
291 // Adjust the threshold for next level of imported functions.
292 // The threshold is different for hot callsites because we can then
293 // inline chains of hot calls.
294 if (IsHotCallsite)
295 return Threshold * ImportHotInstrFactor;
296 return Threshold * ImportInstrFactor;
297 };
298
299 bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000300 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
301
302 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
303 auto &ProcessedThreshold = ImportList[ExportModulePath][GUID];
304 /// Since the traversal of the call graph is DFS, we can revisit a function
305 /// a second time with a higher threshold. In this case, it is added back to
306 /// the worklist with the new threshold.
307 if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
308 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
309 << ProcessedThreshold << "\n");
310 continue;
311 }
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000312 bool PreviouslyImported = ProcessedThreshold != 0;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000313 // Mark this function as imported in this module, with the current Threshold
314 ProcessedThreshold = AdjThreshold;
315
316 // Make exports in the source module.
317 if (ExportLists) {
318 auto &ExportList = (*ExportLists)[ExportModulePath];
319 ExportList.insert(GUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000320 if (!PreviouslyImported) {
321 // This is the first time this function was exported from its source
322 // module, so mark all functions and globals it references as exported
323 // to the outside if they are defined in the same source module.
Teresa Johnsonedddca22016-12-16 04:11:51 +0000324 // For efficiency, we unconditionally add all the referenced GUIDs
325 // to the ExportList for this module, and will prune out any not
326 // defined in the module later in a single pass.
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000327 for (auto &Edge : ResolvedCalleeSummary->calls()) {
328 auto CalleeGUID = Edge.first.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000329 ExportList.insert(CalleeGUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000330 }
331 for (auto &Ref : ResolvedCalleeSummary->refs()) {
332 auto GUID = Ref.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000333 ExportList.insert(GUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000334 }
Teresa Johnson1b859a22016-12-15 18:21:01 +0000335 }
336 }
Piotr Padlewskid2869472016-09-30 03:01:17 +0000337
Mehdi Amini01e32132016-03-26 05:40:34 +0000338 // Insert the newly imported function to the worklist.
Teresa Johnson475b51a2016-12-15 20:48:19 +0000339 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, GUID);
Teresa Johnsond450da32015-11-24 21:15:19 +0000340 }
341}
342
Mehdi Amini01e32132016-03-26 05:40:34 +0000343/// Given the list of globals defined in a module, compute the list of imports
344/// as well as the list of "exports", i.e. the list of symbols referenced from
345/// another module (that may require promotion).
346static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000347 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000348 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000349 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000350 // Worklist contains the list of function imported in this module, for which
351 // we will analyse the callees and may import further down the callgraph.
352 SmallVector<EdgeInfo, 128> Worklist;
353
354 // Populate the worklist with the import for the functions in the current
355 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000356 for (auto &GVSummary : DefinedGVSummaries) {
357 auto *Summary = GVSummary.second;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000358 if (auto *AS = dyn_cast<AliasSummary>(Summary))
359 Summary = &AS->getAliasee();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000360 auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
361 if (!FuncSummary)
362 // Skip import for global variables
363 continue;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000364 DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000365 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000366 DefinedGVSummaries, Worklist, ImportList,
Mehdi Amini01e32132016-03-26 05:40:34 +0000367 ExportLists);
368 }
369
Piotr Padlewskid2869472016-09-30 03:01:17 +0000370 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini42418ab2015-11-24 06:07:49 +0000371 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000372 auto FuncInfo = Worklist.pop_back_val();
Teresa Johnson475b51a2016-12-15 20:48:19 +0000373 auto *Summary = std::get<0>(FuncInfo);
374 auto Threshold = std::get<1>(FuncInfo);
375 auto GUID = std::get<2>(FuncInfo);
376
377 // Check if we later added this summary with a higher threshold.
378 // If so, skip this entry.
379 auto ExportModulePath = Summary->modulePath();
380 auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
381 if (LatestProcessedThreshold > Threshold)
382 continue;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000383
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000384 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000385 Worklist, ImportList, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000386 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000387}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000388
Mehdi Amini01e32132016-03-26 05:40:34 +0000389} // anonymous namespace
390
Teresa Johnsonc86af332016-04-12 21:13:11 +0000391/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000392void llvm::ComputeCrossModuleImport(
393 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000394 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000395 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
396 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000397 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000398 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000399 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000400 DEBUG(dbgs() << "Computing import for Module '"
401 << DefinedGVSummaries.first() << "'\n");
Mehdi Amini9b490f12016-08-16 05:47:12 +0000402 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000403 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000404 }
405
Teresa Johnsonedddca22016-12-16 04:11:51 +0000406 // When computing imports we added all GUIDs referenced by anything
407 // imported from the module to its ExportList. Now we prune each ExportList
408 // of any not defined in that module. This is more efficient than checking
409 // while computing imports because some of the summary lists may be long
410 // due to linkonce (comdat) copies.
411 for (auto &ELI : ExportLists) {
412 const auto &DefinedGVSummaries =
413 ModuleToDefinedGVSummaries.lookup(ELI.first());
414 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
415 if (!DefinedGVSummaries.count(*EI))
416 EI = ELI.second.erase(EI);
417 else
418 ++EI;
419 }
420 }
421
Mehdi Amini01e32132016-03-26 05:40:34 +0000422#ifndef NDEBUG
423 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
424 << " modules:\n");
425 for (auto &ModuleImports : ImportLists) {
426 auto ModName = ModuleImports.first();
427 auto &Exports = ExportLists[ModName];
428 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
429 << " functions. Imports from " << ModuleImports.second.size()
430 << " modules.\n");
431 for (auto &Src : ModuleImports.second) {
432 auto SrcModName = Src.first();
433 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
434 << SrcModName << "\n");
435 }
436 }
437#endif
438}
439
Teresa Johnsonc86af332016-04-12 21:13:11 +0000440/// Compute all the imports for the given module in the Index.
441void llvm::ComputeCrossModuleImportForModule(
442 StringRef ModulePath, const ModuleSummaryIndex &Index,
443 FunctionImporter::ImportMapTy &ImportList) {
444
445 // Collect the list of functions this module defines.
446 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000447 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000448 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000449
450 // Compute the import list for this module.
451 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000452 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000453
454#ifndef NDEBUG
455 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
456 << ImportList.size() << " modules.\n");
457 for (auto &Src : ImportList) {
458 auto SrcModName = Src.first();
459 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
460 << SrcModName << "\n");
461 }
462#endif
463}
464
Teresa Johnson84174c32016-05-10 13:48:23 +0000465/// Compute the set of summaries needed for a ThinLTO backend compilation of
466/// \p ModulePath.
467void llvm::gatherImportedSummariesForModule(
468 StringRef ModulePath,
469 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000470 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000471 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
472 // Include all summaries from the importing module.
473 ModuleToSummariesForIndex[ModulePath] =
474 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000475 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000476 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000477 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
478 const auto &DefinedGVSummaries =
479 ModuleToDefinedGVSummaries.lookup(ILI.first());
480 for (auto &GI : ILI.second) {
481 const auto &DS = DefinedGVSummaries.find(GI.first);
482 assert(DS != DefinedGVSummaries.end() &&
483 "Expected a defined summary for imported global value");
484 SummariesForIndex[GI.first] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000485 }
486 }
487}
488
Teresa Johnson8570fe42016-05-10 15:54:09 +0000489/// Emit the files \p ModulePath will import from into \p OutputFilename.
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000490std::error_code
491llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
492 const FunctionImporter::ImportMapTy &ModuleImports) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000493 std::error_code EC;
494 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
495 if (EC)
496 return EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000497 for (auto &ILI : ModuleImports)
498 ImportsOS << ILI.first() << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000499 return std::error_code();
500}
501
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000502/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
503void llvm::thinLTOResolveWeakForLinkerModule(
504 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
505 auto updateLinkage = [&](GlobalValue &GV) {
506 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
507 return;
508 // See if the global summary analysis computed a new resolved linkage.
509 const auto &GS = DefinedGlobals.find(GV.getGUID());
510 if (GS == DefinedGlobals.end())
511 return;
512 auto NewLinkage = GS->second->linkage();
513 if (NewLinkage == GV.getLinkage())
514 return;
515 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
516 << GV.getLinkage() << " to " << NewLinkage << "\n");
517 GV.setLinkage(NewLinkage);
Teresa Johnson6107a412016-08-15 21:00:04 +0000518 // Remove functions converted to available_externally from comdats,
519 // as this is a declaration for the linker, and will be dropped eventually.
520 // It is illegal for comdats to contain declarations.
521 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
522 if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
523 assert(GO->hasAvailableExternallyLinkage() &&
524 "Expected comdat on definition (possibly available external)");
525 GO->setComdat(nullptr);
526 }
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000527 };
528
529 // Process functions and global now
530 for (auto &GV : TheModule)
531 updateLinkage(GV);
532 for (auto &GV : TheModule.globals())
533 updateLinkage(GV);
534 for (auto &GV : TheModule.aliases())
535 updateLinkage(GV);
536}
537
538/// Run internalization on \p TheModule based on symmary analysis.
539void llvm::thinLTOInternalizeModule(Module &TheModule,
540 const GVSummaryMapTy &DefinedGlobals) {
541 // Parse inline ASM and collect the list of symbols that are not defined in
542 // the current module.
543 StringSet<> AsmUndefinedRefs;
Peter Collingbourne863cbfb2016-12-01 06:51:47 +0000544 ModuleSymbolTable::CollectAsmSymbols(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000545 Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
546 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
547 if (Flags & object::BasicSymbolRef::SF_Undefined)
548 AsmUndefinedRefs.insert(Name);
549 });
550
551 // Declare a callback for the internalize pass that will ask for every
552 // candidate GlobalValue if it can be internalized or not.
553 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
554 // Can't be internalized if referenced in inline asm.
555 if (AsmUndefinedRefs.count(GV.getName()))
556 return true;
557
558 // Lookup the linkage recorded in the summaries during global analysis.
559 const auto &GS = DefinedGlobals.find(GV.getGUID());
560 GlobalValue::LinkageTypes Linkage;
561 if (GS == DefinedGlobals.end()) {
562 // Must have been promoted (possibly conservatively). Find original
563 // name so that we can access the correct summary and see if it can
564 // be internalized again.
565 // FIXME: Eventually we should control promotion instead of promoting
566 // and internalizing again.
567 StringRef OrigName =
568 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
569 std::string OrigId = GlobalValue::getGlobalIdentifier(
570 OrigName, GlobalValue::InternalLinkage,
571 TheModule.getSourceFileName());
572 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000573 if (GS == DefinedGlobals.end()) {
574 // Also check the original non-promoted non-globalized name. In some
575 // cases a preempted weak value is linked in as a local copy because
576 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
577 // In that case, since it was originally not a local value, it was
578 // recorded in the index using the original name.
579 // FIXME: This may not be needed once PR27866 is fixed.
580 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
581 assert(GS != DefinedGlobals.end());
582 Linkage = GS->second->linkage();
583 } else {
584 Linkage = GS->second->linkage();
585 }
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000586 } else
587 Linkage = GS->second->linkage();
588 return !GlobalValue::isLocalLinkage(Linkage);
589 };
590
591 // FIXME: See if we can just internalize directly here via linkage changes
592 // based on the index, rather than invoking internalizeModule.
593 llvm::internalizeModule(TheModule, MustPreserveGV);
594}
595
Mehdi Aminic8c55172015-12-03 02:37:33 +0000596// Automatically import functions in Module \p DestModule based on the summaries
597// index.
598//
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000599Expected<bool> FunctionImporter::importFunctions(
Mehdi Aminibda3c972016-04-21 01:59:39 +0000600 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList,
601 bool ForceImportReferencedDiscardableSymbols) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000602 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000603 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000604 unsigned ImportedCount = 0;
605
Mehdi Aminic8c55172015-12-03 02:37:33 +0000606 // Linker that will be used for importing function
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000607 Linker TheLinker(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000608 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000609 std::set<StringRef> ModuleNameOrderedList;
610 for (auto &FunctionsToImportPerModule : ImportList) {
611 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
612 }
613 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000614 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000615 const auto &FunctionsToImportPerModule = ImportList.find(Name);
616 assert(FunctionsToImportPerModule != ImportList.end());
Peter Collingbourned9445c42016-11-13 07:00:17 +0000617 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
618 if (!SrcModuleOrErr)
619 return SrcModuleOrErr.takeError();
620 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000621 assert(&DestModule.getContext() == &SrcModule->getContext() &&
622 "Context mismatch");
623
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000624 // If modules were created with lazy metadata loading, materialize it
625 // now, before linking it (otherwise this will be a noop).
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000626 if (Error Err = SrcModule->materializeMetadata())
627 return std::move(Err);
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000628 UpgradeDebugInfo(*SrcModule);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000629
Mehdi Amini01e32132016-03-26 05:40:34 +0000630 auto &ImportGUIDs = FunctionsToImportPerModule->second;
631 // Find the globals to import
632 DenseSet<const GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000633 for (Function &F : *SrcModule) {
634 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +0000635 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000636 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000637 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000638 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000639 << " " << F.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000640 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000641 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000642 if (Error Err = F.materialize())
643 return std::move(Err);
Piotr Padlewski3b776122016-07-08 23:01:49 +0000644 if (EnableImportMetadata) {
645 // Add 'thinlto_src_module' metadata for statistics and debugging.
646 F.setMetadata(
647 "thinlto_src_module",
648 llvm::MDNode::get(
649 DestModule.getContext(),
650 {llvm::MDString::get(DestModule.getContext(),
651 SrcModule->getSourceFileName())}));
652 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000653 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +0000654 }
655 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000656 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000657 if (!GV.hasName())
658 continue;
659 auto GUID = GV.getGUID();
660 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000661 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
662 << " " << GV.getName() << " from "
663 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000664 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000665 if (Error Err = GV.materialize())
666 return std::move(Err);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000667 GlobalsToImport.insert(&GV);
668 }
669 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000670 for (GlobalAlias &GA : SrcModule->aliases()) {
671 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +0000672 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000673 auto GUID = GA.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000674 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000675 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000676 << " " << GA.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000677 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000678 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000679 // Alias can't point to "available_externally". However when we import
Teresa Johnson9aae3952016-03-27 15:01:11 +0000680 // linkOnceODR the linkage does not change. So we import the alias
Mehdi Amini6968ef72016-04-20 01:04:20 +0000681 // and aliasee only in this case. This has been handled by
682 // computeImportForFunction()
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000683 GlobalObject *GO = GA.getBaseObject();
Mehdi Amini6968ef72016-04-20 01:04:20 +0000684 assert(GO->hasLinkOnceODRLinkage() &&
685 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000686#ifndef NDEBUG
687 if (!GlobalsToImport.count(GO))
688 DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
689 << " " << GO->getName() << " from "
690 << SrcModule->getSourceFileName() << "\n");
691#endif
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000692 if (Error Err = GO->materialize())
693 return std::move(Err);
Mehdi Amini01e32132016-03-26 05:40:34 +0000694 GlobalsToImport.insert(GO);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000695 if (Error Err = GA.materialize())
696 return std::move(Err);
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000697 GlobalsToImport.insert(&GA);
Mehdi Amini01e32132016-03-26 05:40:34 +0000698 }
699 }
700
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000701 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000702 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000703 return true;
704
Teresa Johnsond29478f2016-03-27 15:27:30 +0000705 if (PrintImports) {
706 for (const auto *GV : GlobalsToImport)
707 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
708 << " from " << SrcModule->getSourceFileName() << "\n";
709 }
710
Mehdi Aminibda3c972016-04-21 01:59:39 +0000711 // Instruct the linker that the client will take care of linkonce resolution
712 unsigned Flags = Linker::Flags::None;
713 if (!ForceImportReferencedDiscardableSymbols)
714 Flags |= Linker::Flags::DontForceLinkLinkonceODR;
715
716 if (TheLinker.linkInModule(std::move(SrcModule), Flags, &GlobalsToImport))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000717 report_fatal_error("Function Import: link error");
718
Mehdi Amini01e32132016-03-26 05:40:34 +0000719 ImportedCount += GlobalsToImport.size();
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000720 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000721
Teresa Johnsond29478f2016-03-27 15:27:30 +0000722 NumImported += ImportedCount;
723
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000724 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000725 << DestModule.getModuleIdentifier() << "\n");
726 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000727}
728
729/// Summary file to use for function importing when using -function-import from
730/// the command line.
731static cl::opt<std::string>
732 SummaryFile("summary-file",
733 cl::desc("The summary file to use for function importing."));
734
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000735static bool doImportingForModule(Module &M) {
736 if (SummaryFile.empty())
737 report_fatal_error("error: -function-import requires -summary-file\n");
738 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
739 getModuleSummaryIndexForFile(SummaryFile);
740 if (!IndexPtrOrErr) {
741 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
742 "Error loading file '" + SummaryFile + "': ");
743 return false;
Teresa Johnson21241572016-07-18 21:22:24 +0000744 }
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000745 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
Teresa Johnson21241572016-07-18 21:22:24 +0000746
747 // First step is collecting the import list.
748 FunctionImporter::ImportMapTy ImportList;
749 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
750 ImportList);
751
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000752 // Conservatively mark all internal values as promoted. This interface is
753 // only used when doing importing via the function importing pass. The pass
754 // is only enabled when testing importing via the 'opt' tool, which does
755 // not do the ThinLink that would normally determine what values to promote.
756 for (auto &I : *Index) {
757 for (auto &S : I.second) {
758 if (GlobalValue::isLocalLinkage(S->linkage()))
759 S->setLinkage(GlobalValue::ExternalLinkage);
760 }
761 }
762
Teresa Johnson21241572016-07-18 21:22:24 +0000763 // Next we need to promote to global scope and rename any local values that
764 // are potentially exported to other modules.
765 if (renameModuleForThinLTO(M, *Index, nullptr)) {
766 errs() << "Error renaming module\n";
767 return false;
768 }
769
770 // Perform the import now.
771 auto ModuleLoader = [&M](StringRef Identifier) {
772 return loadFile(Identifier, M.getContext());
773 };
774 FunctionImporter Importer(*Index, ModuleLoader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000775 Expected<bool> Result = Importer.importFunctions(
776 M, ImportList, !DontForceImportReferencedDiscardableSymbols);
777
778 // FIXME: Probably need to propagate Errors through the pass manager.
779 if (!Result) {
780 logAllUnhandledErrors(Result.takeError(), errs(),
781 "Error importing module: ");
782 return false;
783 }
784
785 return *Result;
Teresa Johnson21241572016-07-18 21:22:24 +0000786}
787
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000788namespace {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000789/// Pass that performs cross-module function import provided a summary file.
Teresa Johnson21241572016-07-18 21:22:24 +0000790class FunctionImportLegacyPass : public ModulePass {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000791public:
792 /// Pass identification, replacement for typeid
793 static char ID;
794
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000795 /// Specify pass name for debug output
Mehdi Amini117296c2016-10-01 02:56:57 +0000796 StringRef getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000797
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000798 explicit FunctionImportLegacyPass() : ModulePass(ID) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000799
800 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000801 if (skipModule(M))
802 return false;
803
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000804 return doImportingForModule(M);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000805 }
806};
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000807} // anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000808
Teresa Johnson21241572016-07-18 21:22:24 +0000809PreservedAnalyses FunctionImportPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000810 ModuleAnalysisManager &AM) {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000811 if (!doImportingForModule(M))
Teresa Johnson21241572016-07-18 21:22:24 +0000812 return PreservedAnalyses::all();
813
814 return PreservedAnalyses::none();
815}
816
817char FunctionImportLegacyPass::ID = 0;
818INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
819 "Summary Based Function Import", false, false)
Mehdi Amini42418ab2015-11-24 06:07:49 +0000820
821namespace llvm {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000822Pass *createFunctionImportPass() {
823 return new FunctionImportLegacyPass();
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000824}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000825}