blob: f3460c49422330c5872e2a1fdf9383bdc0856700 [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"
Peter Collingbournec15d60b2017-05-01 20:42:32 +000020#include "llvm/Bitcode/BitcodeReader.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000021#include "llvm/IR/AutoUpgrade.h"
22#include "llvm/IR/DiagnosticPrinter.h"
23#include "llvm/IR/IntrinsicInst.h"
24#include "llvm/IR/Module.h"
Mehdi Aminifc06b832016-12-23 18:04:51 +000025#include "llvm/IR/Verifier.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000026#include "llvm/IRReader/IRReader.h"
27#include "llvm/Linker/Linker.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000028#include "llvm/Object/IRObjectFile.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 Johnson6c475a72017-01-05 21:34:18 +000039STATISTIC(NumImportedFunctions, "Number of functions imported");
40STATISTIC(NumImportedModules, "Number of modules imported from");
41STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
42STATISTIC(NumLiveSymbols, "Number of live symbols in index");
Teresa Johnsond29478f2016-03-27 15:27:30 +000043
Teresa Johnson39303612015-11-24 22:55:46 +000044/// Limit on instruction count of imported functions.
45static cl::opt<unsigned> ImportInstrLimit(
46 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
47 cl::desc("Only import functions with less than N instructions"));
48
Mehdi Amini40641742016-02-10 23:31:45 +000049static cl::opt<float>
50 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
51 cl::Hidden, cl::value_desc("x"),
52 cl::desc("As we import functions, multiply the "
53 "`import-instr-limit` threshold by this factor "
54 "before processing newly imported functions"));
Piotr Padlewskiba72b952016-09-29 17:32:07 +000055
Piotr Padlewskid2869472016-09-30 03:01:17 +000056static cl::opt<float> ImportHotInstrFactor(
57 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
58 cl::value_desc("x"),
59 cl::desc("As we import functions called from hot callsite, multiply the "
60 "`import-instr-limit` threshold by this factor "
61 "before processing newly imported functions"));
62
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000063static cl::opt<float> ImportHotMultiplier(
64 "import-hot-multiplier", cl::init(3.0), cl::Hidden, cl::value_desc("x"),
Piotr Padlewskiba72b952016-09-29 17:32:07 +000065 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
66
Dehao Chen64c46572017-07-07 21:01:00 +000067static cl::opt<float> ImportCriticalMultiplier(
68 "import-critical-multiplier", cl::init(100.0), cl::Hidden,
69 cl::value_desc("x"),
70 cl::desc(
71 "Multiply the `import-instr-limit` threshold for critical callsites"));
72
Piotr Padlewskiba72b952016-09-29 17:32:07 +000073// FIXME: This multiplier was not really tuned up.
74static cl::opt<float> ImportColdMultiplier(
75 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
76 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
Mehdi Amini40641742016-02-10 23:31:45 +000077
Teresa Johnsond29478f2016-03-27 15:27:30 +000078static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
79 cl::desc("Print imported functions"));
80
Teresa Johnson6c475a72017-01-05 21:34:18 +000081static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
82 cl::desc("Compute dead symbols"));
83
Piotr Padlewski3b776122016-07-08 23:01:49 +000084static cl::opt<bool> EnableImportMetadata(
85 "enable-import-metadata", cl::init(
86#if !defined(NDEBUG)
87 true /*Enabled with asserts.*/
88#else
89 false
90#endif
91 ),
92 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
93
Mehdi Amini42418ab2015-11-24 06:07:49 +000094// Load lazily a module from \p FileName in \p Context.
95static std::unique_ptr<Module> loadFile(const std::string &FileName,
96 LLVMContext &Context) {
97 SMDiagnostic Err;
98 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +000099 // Metadata isn't loaded until functions are imported, to minimize
100 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +0000101 std::unique_ptr<Module> Result =
102 getLazyIRFileModule(FileName, Err, Context,
103 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000104 if (!Result) {
105 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +0000106 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000107 }
108
Mehdi Amini42418ab2015-11-24 06:07:49 +0000109 return Result;
110}
111
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000112namespace {
Mehdi Amini40641742016-02-10 23:31:45 +0000113
Mehdi Amini01e32132016-03-26 05:40:34 +0000114/// Given a list of possible callee implementation for a call site, select one
115/// that fits the \p Threshold.
116///
117/// FIXME: select "best" instead of first that fits. But what is "best"?
118/// - The smallest: more likely to be inlined.
119/// - The one with the least outgoing edges (already well optimized).
120/// - One from a module already being imported from in order to reduce the
121/// number of source modules parsed/linked.
122/// - One that has PGO data attached.
123/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000124static const GlobalValueSummary *
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000125selectCallee(const ModuleSummaryIndex &Index,
Peter Collingbourne9667b912017-05-04 18:03:25 +0000126 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
Teresa Johnson83aaf352017-01-12 22:04:45 +0000127 unsigned Threshold, StringRef CallerModulePath) {
Teresa Johnsona7660b02017-07-15 22:58:06 +0000128 // Find the first eligible callee (e.g. legality checks).
Mehdi Amini01e32132016-03-26 05:40:34 +0000129 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000130 CalleeSummaryList,
131 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
132 auto *GVSummary = SummaryPtr.get();
Rafael Espindolaf329be82016-05-11 01:26:06 +0000133 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000134 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000135 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000136 if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
137 GVSummary = &AS->getAliasee();
138 // Alias can't point to "available_externally". However when we import
139 // linkOnceODR the linkage does not change. So we import the alias
140 // and aliasee only in this case.
141 // FIXME: we should import alias as available_externally *function*,
142 // the destination module does need to know it is an alias.
143 if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
144 return false;
145 }
146
147 auto *Summary = cast<FunctionSummary>(GVSummary);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000148
Teresa Johnson83aaf352017-01-12 22:04:45 +0000149 // If this is a local function, make sure we import the copy
150 // in the caller's module. The only time a local function can
151 // share an entry in the index is if there is a local with the same name
152 // in another module that had the same source file name (in a different
153 // directory), where each was compiled in their own directory so there
154 // was not distinguishing path.
155 // However, do the import from another module if there is only one
156 // entry in the list - in that case this must be a reference due
157 // to indirect call profile data, since a function pointer can point to
158 // a local in another module.
159 if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
160 CalleeSummaryList.size() > 1 &&
161 Summary->modulePath() != CallerModulePath)
162 return false;
163
Teresa Johnson519465b2017-01-05 14:32:16 +0000164 if (Summary->notEligibleToImport())
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000165 return false;
166
Mehdi Amini01e32132016-03-26 05:40:34 +0000167 return true;
168 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000169 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000170 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000171
Teresa Johnsona7660b02017-07-15 22:58:06 +0000172 // Now check if the first eligible callee is under the instruction
173 // threshold. Checking this on the first eligible callee ensures that
174 // we don't end up selecting different callees to import when we invoke
175 // this routine with different thresholds (when there are multiple copies,
176 // i.e. with weak or linkonce linkage).
177 auto *Summary = dyn_cast<FunctionSummary>(It->get());
178 if (auto *AS = dyn_cast<AliasSummary>(It->get()))
179 Summary = cast<FunctionSummary>(&AS->getAliasee());
180 assert(Summary && "Expected FunctionSummary, or alias to one");
181 if (Summary->instCount() > Threshold)
182 return nullptr;
183
184 return Summary;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000185}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000186
Teresa Johnson475b51a2016-12-15 20:48:19 +0000187using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
188 GlobalValue::GUID>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000189
Mehdi Amini01e32132016-03-26 05:40:34 +0000190/// Compute the list of functions to import for a given caller. Mark these
191/// imported functions and the symbols they reference in their source module as
192/// exported from their source module.
193static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000194 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000195 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000196 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000197 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000198 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000199 for (auto &Edge : Summary.calls()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000200 ValueInfo VI = Edge.first;
201 DEBUG(dbgs() << " edge -> " << VI.getGUID() << " Threshold:" << Threshold
202 << "\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000203
Peter Collingbourne9667b912017-05-04 18:03:25 +0000204 if (VI.getSummaryList().empty()) {
Dehao Chen4a435e02017-03-14 17:33:01 +0000205 // For SamplePGO, the indirect call targets for local functions will
206 // have its original name annotated in profile. We try to find the
207 // corresponding PGOFuncName as the GUID.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000208 auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
Dehao Chen4a435e02017-03-14 17:33:01 +0000209 if (GUID == 0)
210 continue;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000211 VI = Index.getValueInfo(GUID);
212 if (!VI)
213 continue;
Dehao Chen4a435e02017-03-14 17:33:01 +0000214 }
215
Peter Collingbourne9667b912017-05-04 18:03:25 +0000216 if (DefinedGVSummaries.count(VI.getGUID())) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000217 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
218 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000219 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000220
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000221 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
222 if (Hotness == CalleeInfo::HotnessType::Hot)
223 return ImportHotMultiplier;
224 if (Hotness == CalleeInfo::HotnessType::Cold)
225 return ImportColdMultiplier;
Dehao Chen64c46572017-07-07 21:01:00 +0000226 if (Hotness == CalleeInfo::HotnessType::Critical)
227 return ImportCriticalMultiplier;
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000228 return 1.0;
229 };
230
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000231 const auto NewThreshold =
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000232 Threshold * GetBonusMultiplier(Edge.second.Hotness);
Piotr Padlewskid2869472016-09-30 03:01:17 +0000233
Peter Collingbourne9667b912017-05-04 18:03:25 +0000234 auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
235 Summary.modulePath());
Mehdi Amini01e32132016-03-26 05:40:34 +0000236 if (!CalleeSummary) {
237 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
238 continue;
239 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000240 // "Resolve" the summary, traversing alias,
241 const FunctionSummary *ResolvedCalleeSummary;
Mehdi Amini6968ef72016-04-20 01:04:20 +0000242 if (isa<AliasSummary>(CalleeSummary)) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000243 ResolvedCalleeSummary = cast<FunctionSummary>(
244 &cast<AliasSummary>(CalleeSummary)->getAliasee());
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000245 assert(
246 GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
247 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini6968ef72016-04-20 01:04:20 +0000248 } else
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000249 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
250
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000251 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000252 "selectCallee() didn't honor the threshold");
253
Piotr Padlewskid2869472016-09-30 03:01:17 +0000254 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
255 // Adjust the threshold for next level of imported functions.
256 // The threshold is different for hot callsites because we can then
257 // inline chains of hot calls.
258 if (IsHotCallsite)
259 return Threshold * ImportHotInstrFactor;
260 return Threshold * ImportInstrFactor;
261 };
262
263 bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000264 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
265
266 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000267 auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()];
Teresa Johnson1b859a22016-12-15 18:21:01 +0000268 /// Since the traversal of the call graph is DFS, we can revisit a function
269 /// a second time with a higher threshold. In this case, it is added back to
270 /// the worklist with the new threshold.
271 if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
272 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
273 << ProcessedThreshold << "\n");
274 continue;
275 }
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000276 bool PreviouslyImported = ProcessedThreshold != 0;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000277 // Mark this function as imported in this module, with the current Threshold
278 ProcessedThreshold = AdjThreshold;
279
280 // Make exports in the source module.
281 if (ExportLists) {
282 auto &ExportList = (*ExportLists)[ExportModulePath];
Peter Collingbourne9667b912017-05-04 18:03:25 +0000283 ExportList.insert(VI.getGUID());
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000284 if (!PreviouslyImported) {
285 // This is the first time this function was exported from its source
286 // module, so mark all functions and globals it references as exported
287 // to the outside if they are defined in the same source module.
Teresa Johnsonedddca22016-12-16 04:11:51 +0000288 // For efficiency, we unconditionally add all the referenced GUIDs
289 // to the ExportList for this module, and will prune out any not
290 // defined in the module later in a single pass.
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000291 for (auto &Edge : ResolvedCalleeSummary->calls()) {
292 auto CalleeGUID = Edge.first.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000293 ExportList.insert(CalleeGUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000294 }
295 for (auto &Ref : ResolvedCalleeSummary->refs()) {
296 auto GUID = Ref.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000297 ExportList.insert(GUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000298 }
Teresa Johnson1b859a22016-12-15 18:21:01 +0000299 }
300 }
Piotr Padlewskid2869472016-09-30 03:01:17 +0000301
Mehdi Amini01e32132016-03-26 05:40:34 +0000302 // Insert the newly imported function to the worklist.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000303 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
Teresa Johnsond450da32015-11-24 21:15:19 +0000304 }
305}
306
Mehdi Amini01e32132016-03-26 05:40:34 +0000307/// Given the list of globals defined in a module, compute the list of imports
308/// as well as the list of "exports", i.e. the list of symbols referenced from
309/// another module (that may require promotion).
310static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000311 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000312 FunctionImporter::ImportMapTy &ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000313 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000314 // Worklist contains the list of function imported in this module, for which
315 // we will analyse the callees and may import further down the callgraph.
316 SmallVector<EdgeInfo, 128> Worklist;
317
318 // Populate the worklist with the import for the functions in the current
319 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000320 for (auto &GVSummary : DefinedGVSummaries) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000321 if (!Index.isGlobalValueLive(GVSummary.second)) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000322 DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
323 continue;
324 }
Teresa Johnson28e457b2016-04-24 14:57:11 +0000325 auto *Summary = GVSummary.second;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000326 if (auto *AS = dyn_cast<AliasSummary>(Summary))
327 Summary = &AS->getAliasee();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000328 auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
329 if (!FuncSummary)
330 // Skip import for global variables
331 continue;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000332 DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000333 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000334 DefinedGVSummaries, Worklist, ImportList,
Mehdi Amini01e32132016-03-26 05:40:34 +0000335 ExportLists);
336 }
337
Piotr Padlewskid2869472016-09-30 03:01:17 +0000338 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini42418ab2015-11-24 06:07:49 +0000339 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000340 auto FuncInfo = Worklist.pop_back_val();
Teresa Johnson475b51a2016-12-15 20:48:19 +0000341 auto *Summary = std::get<0>(FuncInfo);
342 auto Threshold = std::get<1>(FuncInfo);
343 auto GUID = std::get<2>(FuncInfo);
344
345 // Check if we later added this summary with a higher threshold.
346 // If so, skip this entry.
347 auto ExportModulePath = Summary->modulePath();
348 auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
349 if (LatestProcessedThreshold > Threshold)
350 continue;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000351
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000352 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000353 Worklist, ImportList, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000354 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000355}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000356
Mehdi Amini01e32132016-03-26 05:40:34 +0000357} // anonymous namespace
358
Teresa Johnsonc86af332016-04-12 21:13:11 +0000359/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000360void llvm::ComputeCrossModuleImport(
361 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000362 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000363 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000364 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000365 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000366 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000367 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000368 DEBUG(dbgs() << "Computing import for Module '"
369 << DefinedGVSummaries.first() << "'\n");
Mehdi Amini9b490f12016-08-16 05:47:12 +0000370 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000371 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000372 }
373
Teresa Johnsonedddca22016-12-16 04:11:51 +0000374 // When computing imports we added all GUIDs referenced by anything
375 // imported from the module to its ExportList. Now we prune each ExportList
376 // of any not defined in that module. This is more efficient than checking
377 // while computing imports because some of the summary lists may be long
378 // due to linkonce (comdat) copies.
379 for (auto &ELI : ExportLists) {
380 const auto &DefinedGVSummaries =
381 ModuleToDefinedGVSummaries.lookup(ELI.first());
382 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
383 if (!DefinedGVSummaries.count(*EI))
384 EI = ELI.second.erase(EI);
385 else
386 ++EI;
387 }
388 }
389
Mehdi Amini01e32132016-03-26 05:40:34 +0000390#ifndef NDEBUG
391 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
392 << " modules:\n");
393 for (auto &ModuleImports : ImportLists) {
394 auto ModName = ModuleImports.first();
395 auto &Exports = ExportLists[ModName];
396 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
397 << " functions. Imports from " << ModuleImports.second.size()
398 << " modules.\n");
399 for (auto &Src : ModuleImports.second) {
400 auto SrcModName = Src.first();
401 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
402 << SrcModName << "\n");
403 }
404 }
405#endif
406}
407
Teresa Johnsonc86af332016-04-12 21:13:11 +0000408/// Compute all the imports for the given module in the Index.
409void llvm::ComputeCrossModuleImportForModule(
410 StringRef ModulePath, const ModuleSummaryIndex &Index,
411 FunctionImporter::ImportMapTy &ImportList) {
412
413 // Collect the list of functions this module defines.
414 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000415 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000416 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000417
418 // Compute the import list for this module.
419 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000420 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000421
422#ifndef NDEBUG
423 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
424 << ImportList.size() << " modules.\n");
425 for (auto &Src : ImportList) {
426 auto SrcModName = Src.first();
427 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
428 << SrcModName << "\n");
429 }
430#endif
431}
432
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000433void llvm::computeDeadSymbols(
434 ModuleSummaryIndex &Index,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000435 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000436 assert(!Index.withGlobalValueDeadStripping());
Teresa Johnson6c475a72017-01-05 21:34:18 +0000437 if (!ComputeDead)
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000438 return;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000439 if (GUIDPreservedSymbols.empty())
440 // Don't do anything when nothing is live, this is friendly with tests.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000441 return;
442 unsigned LiveSymbols = 0;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000443 SmallVector<ValueInfo, 128> Worklist;
444 Worklist.reserve(GUIDPreservedSymbols.size() * 2);
445 for (auto GUID : GUIDPreservedSymbols) {
446 ValueInfo VI = Index.getValueInfo(GUID);
447 if (!VI)
448 continue;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000449 for (auto &S : VI.getSummaryList())
450 S->setLive(true);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000451 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000452
Teresa Johnson6c475a72017-01-05 21:34:18 +0000453 // Add values flagged in the index as live roots to the worklist.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000454 for (const auto &Entry : Index)
455 for (auto &S : Entry.second.SummaryList)
456 if (S->isLive()) {
457 DEBUG(dbgs() << "Live root: " << Entry.first << "\n");
458 Worklist.push_back(ValueInfo(&Entry));
459 ++LiveSymbols;
460 break;
461 }
462
463 // Make value live and add it to the worklist if it was not live before.
464 // FIXME: we should only make the prevailing copy live here
465 auto visit = [&](ValueInfo VI) {
466 for (auto &S : VI.getSummaryList())
467 if (S->isLive())
468 return;
469 for (auto &S : VI.getSummaryList())
470 S->setLive(true);
471 ++LiveSymbols;
472 Worklist.push_back(VI);
473 };
Teresa Johnson6c475a72017-01-05 21:34:18 +0000474
475 while (!Worklist.empty()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000476 auto VI = Worklist.pop_back_val();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000477 for (auto &Summary : VI.getSummaryList()) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000478 for (auto Ref : Summary->refs())
479 visit(Ref);
480 if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
481 for (auto Call : FS->calls())
482 visit(Call.first);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000483 if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
484 auto AliaseeGUID = AS->getAliasee().getOriginalName();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000485 ValueInfo AliaseeVI = Index.getValueInfo(AliaseeGUID);
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000486 if (AliaseeVI)
487 visit(AliaseeVI);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000488 }
489 }
490 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000491 Index.setWithGlobalValueDeadStripping();
492
493 unsigned DeadSymbols = Index.size() - LiveSymbols;
494 DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
495 << " symbols Dead \n");
496 NumDeadSymbols += DeadSymbols;
497 NumLiveSymbols += LiveSymbols;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000498}
499
Teresa Johnson84174c32016-05-10 13:48:23 +0000500/// Compute the set of summaries needed for a ThinLTO backend compilation of
501/// \p ModulePath.
502void llvm::gatherImportedSummariesForModule(
503 StringRef ModulePath,
504 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000505 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000506 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
507 // Include all summaries from the importing module.
508 ModuleToSummariesForIndex[ModulePath] =
509 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000510 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000511 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000512 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
513 const auto &DefinedGVSummaries =
514 ModuleToDefinedGVSummaries.lookup(ILI.first());
515 for (auto &GI : ILI.second) {
516 const auto &DS = DefinedGVSummaries.find(GI.first);
517 assert(DS != DefinedGVSummaries.end() &&
518 "Expected a defined summary for imported global value");
519 SummariesForIndex[GI.first] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000520 }
521 }
522}
523
Teresa Johnson8570fe42016-05-10 15:54:09 +0000524/// Emit the files \p ModulePath will import from into \p OutputFilename.
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000525std::error_code
526llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
527 const FunctionImporter::ImportMapTy &ModuleImports) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000528 std::error_code EC;
529 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
530 if (EC)
531 return EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000532 for (auto &ILI : ModuleImports)
533 ImportsOS << ILI.first() << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000534 return std::error_code();
535}
536
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000537/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
538void llvm::thinLTOResolveWeakForLinkerModule(
539 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000540 auto ConvertToDeclaration = [](GlobalValue &GV) {
541 DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n");
542 if (Function *F = dyn_cast<Function>(&GV)) {
543 F->deleteBody();
544 F->clearMetadata();
545 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
546 V->setInitializer(nullptr);
547 V->setLinkage(GlobalValue::ExternalLinkage);
548 V->clearMetadata();
549 } else
550 // For now we don't resolve or drop aliases. Once we do we'll
551 // need to add support here for creating either a function or
552 // variable declaration, and return the new GlobalValue* for
553 // the caller to use.
Davide Italiano91239082017-04-14 17:22:02 +0000554 llvm_unreachable("Expected function or variable");
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000555 };
556
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000557 auto updateLinkage = [&](GlobalValue &GV) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000558 // See if the global summary analysis computed a new resolved linkage.
559 const auto &GS = DefinedGlobals.find(GV.getGUID());
560 if (GS == DefinedGlobals.end())
561 return;
562 auto NewLinkage = GS->second->linkage();
563 if (NewLinkage == GV.getLinkage())
564 return;
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000565
566 // Switch the linkage to weakany if asked for, e.g. we do this for
567 // linker redefined symbols (via --wrap or --defsym).
Davide Italianof4891d22017-07-06 20:04:20 +0000568 // We record that the visibility should be changed here in `addThinLTO`
569 // as we need access to the resolution vectors for each input file in
570 // order to find which symbols have been redefined.
571 // We may consider reorganizing this code and moving the linkage recording
572 // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex.
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000573 if (NewLinkage == GlobalValue::WeakAnyLinkage) {
574 GV.setLinkage(NewLinkage);
575 return;
576 }
577
578 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
579 return;
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000580 // Check for a non-prevailing def that has interposable linkage
581 // (e.g. non-odr weak or linkonce). In that case we can't simply
582 // convert to available_externally, since it would lose the
583 // interposable property and possibly get inlined. Simply drop
584 // the definition in that case.
585 if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
586 GlobalValue::isInterposableLinkage(GV.getLinkage()))
587 ConvertToDeclaration(GV);
588 else {
589 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
590 << GV.getLinkage() << " to " << NewLinkage << "\n");
591 GV.setLinkage(NewLinkage);
592 }
593 // Remove declarations from comdats, including available_externally
Teresa Johnson6107a412016-08-15 21:00:04 +0000594 // as this is a declaration for the linker, and will be dropped eventually.
595 // It is illegal for comdats to contain declarations.
596 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000597 if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
Teresa Johnson6107a412016-08-15 21:00:04 +0000598 GO->setComdat(nullptr);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000599 };
600
601 // Process functions and global now
602 for (auto &GV : TheModule)
603 updateLinkage(GV);
604 for (auto &GV : TheModule.globals())
605 updateLinkage(GV);
606 for (auto &GV : TheModule.aliases())
607 updateLinkage(GV);
608}
609
610/// Run internalization on \p TheModule based on symmary analysis.
611void llvm::thinLTOInternalizeModule(Module &TheModule,
612 const GVSummaryMapTy &DefinedGlobals) {
613 // Parse inline ASM and collect the list of symbols that are not defined in
614 // the current module.
615 StringSet<> AsmUndefinedRefs;
Peter Collingbourne863cbfb2016-12-01 06:51:47 +0000616 ModuleSymbolTable::CollectAsmSymbols(
Teresa Johnsond8204472017-03-09 00:19:49 +0000617 TheModule,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000618 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
619 if (Flags & object::BasicSymbolRef::SF_Undefined)
620 AsmUndefinedRefs.insert(Name);
621 });
622
623 // Declare a callback for the internalize pass that will ask for every
624 // candidate GlobalValue if it can be internalized or not.
625 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
626 // Can't be internalized if referenced in inline asm.
627 if (AsmUndefinedRefs.count(GV.getName()))
628 return true;
629
630 // Lookup the linkage recorded in the summaries during global analysis.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000631 auto GS = DefinedGlobals.find(GV.getGUID());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000632 if (GS == DefinedGlobals.end()) {
633 // Must have been promoted (possibly conservatively). Find original
634 // name so that we can access the correct summary and see if it can
635 // be internalized again.
636 // FIXME: Eventually we should control promotion instead of promoting
637 // and internalizing again.
638 StringRef OrigName =
639 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
640 std::string OrigId = GlobalValue::getGlobalIdentifier(
641 OrigName, GlobalValue::InternalLinkage,
642 TheModule.getSourceFileName());
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000643 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000644 if (GS == DefinedGlobals.end()) {
645 // Also check the original non-promoted non-globalized name. In some
646 // cases a preempted weak value is linked in as a local copy because
647 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
648 // In that case, since it was originally not a local value, it was
649 // recorded in the index using the original name.
650 // FIXME: This may not be needed once PR27866 is fixed.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000651 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000652 assert(GS != DefinedGlobals.end());
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000653 }
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000654 }
655 return !GlobalValue::isLocalLinkage(GS->second->linkage());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000656 };
657
658 // FIXME: See if we can just internalize directly here via linkage changes
659 // based on the index, rather than invoking internalizeModule.
660 llvm::internalizeModule(TheModule, MustPreserveGV);
661}
662
Mehdi Aminic8c55172015-12-03 02:37:33 +0000663// Automatically import functions in Module \p DestModule based on the summaries
664// index.
665//
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000666Expected<bool> FunctionImporter::importFunctions(
Adrian Prantl66043792017-05-19 23:32:21 +0000667 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000668 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000669 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000670 unsigned ImportedCount = 0;
671
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000672 IRMover Mover(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000673 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000674 std::set<StringRef> ModuleNameOrderedList;
675 for (auto &FunctionsToImportPerModule : ImportList) {
676 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
677 }
678 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000679 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000680 const auto &FunctionsToImportPerModule = ImportList.find(Name);
681 assert(FunctionsToImportPerModule != ImportList.end());
Peter Collingbourned9445c42016-11-13 07:00:17 +0000682 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
683 if (!SrcModuleOrErr)
684 return SrcModuleOrErr.takeError();
685 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000686 assert(&DestModule.getContext() == &SrcModule->getContext() &&
687 "Context mismatch");
688
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000689 // If modules were created with lazy metadata loading, materialize it
690 // now, before linking it (otherwise this will be a noop).
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000691 if (Error Err = SrcModule->materializeMetadata())
692 return std::move(Err);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000693
Mehdi Amini01e32132016-03-26 05:40:34 +0000694 auto &ImportGUIDs = FunctionsToImportPerModule->second;
695 // Find the globals to import
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000696 SetVector<GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000697 for (Function &F : *SrcModule) {
698 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +0000699 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000700 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000701 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000702 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000703 << " " << F.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000704 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000705 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000706 if (Error Err = F.materialize())
707 return std::move(Err);
Piotr Padlewski3b776122016-07-08 23:01:49 +0000708 if (EnableImportMetadata) {
709 // Add 'thinlto_src_module' metadata for statistics and debugging.
710 F.setMetadata(
711 "thinlto_src_module",
712 llvm::MDNode::get(
713 DestModule.getContext(),
714 {llvm::MDString::get(DestModule.getContext(),
715 SrcModule->getSourceFileName())}));
716 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000717 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +0000718 }
719 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000720 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000721 if (!GV.hasName())
722 continue;
723 auto GUID = GV.getGUID();
724 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000725 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
726 << " " << GV.getName() << " from "
727 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000728 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000729 if (Error Err = GV.materialize())
730 return std::move(Err);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000731 GlobalsToImport.insert(&GV);
732 }
733 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000734 for (GlobalAlias &GA : SrcModule->aliases()) {
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000735 // FIXME: This should eventually be controlled entirely by the summary.
736 if (FunctionImportGlobalProcessing::doImportAsDefinition(
737 &GA, &GlobalsToImport)) {
738 GlobalsToImport.insert(&GA);
739 continue;
740 }
741
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000742 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +0000743 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000744 auto GUID = GA.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000745 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000746 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000747 << " " << GA.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000748 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000749 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000750 // Alias can't point to "available_externally". However when we import
Teresa Johnson9aae3952016-03-27 15:01:11 +0000751 // linkOnceODR the linkage does not change. So we import the alias
Mehdi Amini6968ef72016-04-20 01:04:20 +0000752 // and aliasee only in this case. This has been handled by
753 // computeImportForFunction()
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000754 GlobalObject *GO = GA.getBaseObject();
Mehdi Amini6968ef72016-04-20 01:04:20 +0000755 assert(GO->hasLinkOnceODRLinkage() &&
756 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000757#ifndef NDEBUG
758 if (!GlobalsToImport.count(GO))
759 DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
760 << " " << GO->getName() << " from "
761 << SrcModule->getSourceFileName() << "\n");
762#endif
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000763 if (Error Err = GO->materialize())
764 return std::move(Err);
Mehdi Amini01e32132016-03-26 05:40:34 +0000765 GlobalsToImport.insert(GO);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000766 if (Error Err = GA.materialize())
767 return std::move(Err);
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000768 GlobalsToImport.insert(&GA);
Mehdi Amini01e32132016-03-26 05:40:34 +0000769 }
770 }
771
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000772 // Upgrade debug info after we're done materializing all the globals and we
773 // have loaded all the required metadata!
774 UpgradeDebugInfo(*SrcModule);
775
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000776 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000777 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000778 return true;
779
Teresa Johnsond29478f2016-03-27 15:27:30 +0000780 if (PrintImports) {
781 for (const auto *GV : GlobalsToImport)
782 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
783 << " from " << SrcModule->getSourceFileName() << "\n";
784 }
785
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000786 if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
787 [](GlobalValue &, IRMover::ValueAdder) {},
Peter Collingbournee6fd9ff2017-02-03 17:01:14 +0000788 /*IsPerformingImport=*/true))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000789 report_fatal_error("Function Import: link error");
790
Mehdi Amini01e32132016-03-26 05:40:34 +0000791 ImportedCount += GlobalsToImport.size();
Teresa Johnson6c475a72017-01-05 21:34:18 +0000792 NumImportedModules++;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000793 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000794
Teresa Johnson6c475a72017-01-05 21:34:18 +0000795 NumImportedFunctions += ImportedCount;
Teresa Johnsond29478f2016-03-27 15:27:30 +0000796
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000797 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000798 << DestModule.getModuleIdentifier() << "\n");
799 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000800}
801
802/// Summary file to use for function importing when using -function-import from
803/// the command line.
804static cl::opt<std::string>
805 SummaryFile("summary-file",
806 cl::desc("The summary file to use for function importing."));
807
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000808static bool doImportingForModule(Module &M) {
809 if (SummaryFile.empty())
810 report_fatal_error("error: -function-import requires -summary-file\n");
811 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
812 getModuleSummaryIndexForFile(SummaryFile);
813 if (!IndexPtrOrErr) {
814 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
815 "Error loading file '" + SummaryFile + "': ");
816 return false;
Teresa Johnson21241572016-07-18 21:22:24 +0000817 }
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000818 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
Teresa Johnson21241572016-07-18 21:22:24 +0000819
820 // First step is collecting the import list.
821 FunctionImporter::ImportMapTy ImportList;
822 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
823 ImportList);
824
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000825 // Conservatively mark all internal values as promoted. This interface is
826 // only used when doing importing via the function importing pass. The pass
827 // is only enabled when testing importing via the 'opt' tool, which does
828 // not do the ThinLink that would normally determine what values to promote.
829 for (auto &I : *Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000830 for (auto &S : I.second.SummaryList) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000831 if (GlobalValue::isLocalLinkage(S->linkage()))
832 S->setLinkage(GlobalValue::ExternalLinkage);
833 }
834 }
835
Teresa Johnson21241572016-07-18 21:22:24 +0000836 // Next we need to promote to global scope and rename any local values that
837 // are potentially exported to other modules.
838 if (renameModuleForThinLTO(M, *Index, nullptr)) {
839 errs() << "Error renaming module\n";
840 return false;
841 }
842
843 // Perform the import now.
844 auto ModuleLoader = [&M](StringRef Identifier) {
845 return loadFile(Identifier, M.getContext());
846 };
847 FunctionImporter Importer(*Index, ModuleLoader);
Peter Collingbourne37e24592017-02-02 18:42:25 +0000848 Expected<bool> Result = Importer.importFunctions(M, ImportList);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000849
850 // FIXME: Probably need to propagate Errors through the pass manager.
851 if (!Result) {
852 logAllUnhandledErrors(Result.takeError(), errs(),
853 "Error importing module: ");
854 return false;
855 }
856
857 return *Result;
Teresa Johnson21241572016-07-18 21:22:24 +0000858}
859
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000860namespace {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000861/// Pass that performs cross-module function import provided a summary file.
Teresa Johnson21241572016-07-18 21:22:24 +0000862class FunctionImportLegacyPass : public ModulePass {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000863public:
864 /// Pass identification, replacement for typeid
865 static char ID;
866
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000867 /// Specify pass name for debug output
Mehdi Amini117296c2016-10-01 02:56:57 +0000868 StringRef getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000869
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000870 explicit FunctionImportLegacyPass() : ModulePass(ID) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000871
872 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000873 if (skipModule(M))
874 return false;
875
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000876 return doImportingForModule(M);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000877 }
878};
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000879} // anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000880
Teresa Johnson21241572016-07-18 21:22:24 +0000881PreservedAnalyses FunctionImportPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000882 ModuleAnalysisManager &AM) {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000883 if (!doImportingForModule(M))
Teresa Johnson21241572016-07-18 21:22:24 +0000884 return PreservedAnalyses::all();
885
886 return PreservedAnalyses::none();
887}
888
889char FunctionImportLegacyPass::ID = 0;
890INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
891 "Summary Based Function Import", false, false)
Mehdi Amini42418ab2015-11-24 06:07:49 +0000892
893namespace llvm {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000894Pass *createFunctionImportPass() {
895 return new FunctionImportLegacyPass();
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000896}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000897}