blob: ed85c20051ee347c19eadf2c9163310edf9d8831 [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"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000015#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SetVector.h"
Mehdi Amini01e32132016-03-26 05:40:34 +000018#include "llvm/ADT/SmallVector.h"
Teresa Johnsond29478f2016-03-27 15:27:30 +000019#include "llvm/ADT/Statistic.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000020#include "llvm/ADT/StringMap.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000021#include "llvm/ADT/StringSet.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000022#include "llvm/ADT/StringRef.h"
Peter Collingbournec15d60b2017-05-01 20:42:32 +000023#include "llvm/Bitcode/BitcodeReader.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000024#include "llvm/IR/AutoUpgrade.h"
Teresa Johnson81bbf742017-12-16 00:18:12 +000025#include "llvm/IR/Constants.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000026#include "llvm/IR/Function.h"
27#include "llvm/IR/GlobalAlias.h"
28#include "llvm/IR/GlobalObject.h"
29#include "llvm/IR/GlobalValue.h"
30#include "llvm/IR/GlobalVariable.h"
31#include "llvm/IR/Metadata.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000032#include "llvm/IR/Module.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000033#include "llvm/IR/ModuleSummaryIndex.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000034#include "llvm/IRReader/IRReader.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000035#include "llvm/Linker/IRMover.h"
36#include "llvm/Object/ModuleSymbolTable.h"
37#include "llvm/Object/SymbolicFile.h"
38#include "llvm/Pass.h"
39#include "llvm/Support/Casting.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000040#include "llvm/Support/CommandLine.h"
41#include "llvm/Support/Debug.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000042#include "llvm/Support/Error.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/FileSystem.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000045#include "llvm/Support/SourceMgr.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000046#include "llvm/Support/raw_ostream.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000047#include "llvm/Transforms/IPO/Internalize.h"
Teresa Johnson81bbf742017-12-16 00:18:12 +000048#include "llvm/Transforms/Utils/Cloning.h"
Teresa Johnson488a8002016-02-10 18:11:31 +000049#include "llvm/Transforms/Utils/FunctionImportUtils.h"
Teresa Johnson81bbf742017-12-16 00:18:12 +000050#include "llvm/Transforms/Utils/ValueMapper.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000051#include <cassert>
52#include <memory>
53#include <set>
54#include <string>
55#include <system_error>
56#include <tuple>
57#include <utility>
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000058
Mehdi Amini42418ab2015-11-24 06:07:49 +000059using namespace llvm;
60
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000061#define DEBUG_TYPE "function-import"
62
Teresa Johnson6c475a72017-01-05 21:34:18 +000063STATISTIC(NumImportedFunctions, "Number of functions imported");
64STATISTIC(NumImportedModules, "Number of modules imported from");
65STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
66STATISTIC(NumLiveSymbols, "Number of live symbols in index");
Teresa Johnsond29478f2016-03-27 15:27:30 +000067
Teresa Johnson39303612015-11-24 22:55:46 +000068/// Limit on instruction count of imported functions.
69static cl::opt<unsigned> ImportInstrLimit(
70 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
71 cl::desc("Only import functions with less than N instructions"));
72
Mehdi Amini40641742016-02-10 23:31:45 +000073static cl::opt<float>
74 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
75 cl::Hidden, cl::value_desc("x"),
76 cl::desc("As we import functions, multiply the "
77 "`import-instr-limit` threshold by this factor "
78 "before processing newly imported functions"));
Piotr Padlewskiba72b952016-09-29 17:32:07 +000079
Piotr Padlewskid2869472016-09-30 03:01:17 +000080static cl::opt<float> ImportHotInstrFactor(
81 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
82 cl::value_desc("x"),
83 cl::desc("As we import functions called from hot callsite, multiply the "
84 "`import-instr-limit` threshold by this factor "
85 "before processing newly imported functions"));
86
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000087static cl::opt<float> ImportHotMultiplier(
Dehao Chen8260d662017-07-28 01:02:34 +000088 "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
Piotr Padlewskiba72b952016-09-29 17:32:07 +000089 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
90
Dehao Chen64c46572017-07-07 21:01:00 +000091static cl::opt<float> ImportCriticalMultiplier(
92 "import-critical-multiplier", cl::init(100.0), cl::Hidden,
93 cl::value_desc("x"),
94 cl::desc(
95 "Multiply the `import-instr-limit` threshold for critical callsites"));
96
Piotr Padlewskiba72b952016-09-29 17:32:07 +000097// FIXME: This multiplier was not really tuned up.
98static cl::opt<float> ImportColdMultiplier(
99 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
100 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
Mehdi Amini40641742016-02-10 23:31:45 +0000101
Teresa Johnsond29478f2016-03-27 15:27:30 +0000102static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
103 cl::desc("Print imported functions"));
104
Teresa Johnson6c475a72017-01-05 21:34:18 +0000105static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
106 cl::desc("Compute dead symbols"));
107
Piotr Padlewski3b776122016-07-08 23:01:49 +0000108static cl::opt<bool> EnableImportMetadata(
109 "enable-import-metadata", cl::init(
110#if !defined(NDEBUG)
111 true /*Enabled with asserts.*/
112#else
113 false
114#endif
115 ),
116 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
117
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000118/// Summary file to use for function importing when using -function-import from
119/// the command line.
120static cl::opt<std::string>
121 SummaryFile("summary-file",
122 cl::desc("The summary file to use for function importing."));
123
Teresa Johnson81bbf742017-12-16 00:18:12 +0000124/// Used when testing importing from distributed indexes via opt
125// -function-import.
126static cl::opt<bool>
127 ImportAllIndex("import-all-index",
128 cl::desc("Import all external functions in index."));
129
Mehdi Amini42418ab2015-11-24 06:07:49 +0000130// Load lazily a module from \p FileName in \p Context.
131static std::unique_ptr<Module> loadFile(const std::string &FileName,
132 LLVMContext &Context) {
133 SMDiagnostic Err;
134 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000135 // Metadata isn't loaded until functions are imported, to minimize
136 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +0000137 std::unique_ptr<Module> Result =
138 getLazyIRFileModule(FileName, Err, Context,
139 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000140 if (!Result) {
141 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +0000142 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000143 }
144
Mehdi Amini42418ab2015-11-24 06:07:49 +0000145 return Result;
146}
147
Mehdi Amini01e32132016-03-26 05:40:34 +0000148/// Given a list of possible callee implementation for a call site, select one
149/// that fits the \p Threshold.
150///
151/// FIXME: select "best" instead of first that fits. But what is "best"?
152/// - The smallest: more likely to be inlined.
153/// - The one with the least outgoing edges (already well optimized).
154/// - One from a module already being imported from in order to reduce the
155/// number of source modules parsed/linked.
156/// - One that has PGO data attached.
157/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000158static const GlobalValueSummary *
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000159selectCallee(const ModuleSummaryIndex &Index,
Peter Collingbourne9667b912017-05-04 18:03:25 +0000160 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
Teresa Johnson83aaf352017-01-12 22:04:45 +0000161 unsigned Threshold, StringRef CallerModulePath) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000162 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000163 CalleeSummaryList,
164 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
165 auto *GVSummary = SummaryPtr.get();
Teresa Johnson73305f82017-08-19 18:04:25 +0000166 // For SamplePGO, in computeImportForFunction the OriginalId
167 // may have been used to locate the callee summary list (See
168 // comment there).
169 // The mapping from OriginalId to GUID may return a GUID
170 // that corresponds to a static variable. Filter it out here.
171 // This can happen when
172 // 1) There is a call to a library function which is not defined
173 // in the index.
174 // 2) There is a static variable with the OriginalGUID identical
175 // to the GUID of the library function in 1);
176 // When this happens, the logic for SamplePGO kicks in and
177 // the static variable in 2) will be found, which needs to be
178 // filtered out.
179 if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
180 return false;
Rafael Espindolaf329be82016-05-11 01:26:06 +0000181 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000182 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000183 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000184
Teresa Johnson81bbf742017-12-16 00:18:12 +0000185 auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000186
Teresa Johnson83aaf352017-01-12 22:04:45 +0000187 // If this is a local function, make sure we import the copy
188 // in the caller's module. The only time a local function can
189 // share an entry in the index is if there is a local with the same name
190 // in another module that had the same source file name (in a different
191 // directory), where each was compiled in their own directory so there
192 // was not distinguishing path.
193 // However, do the import from another module if there is only one
194 // entry in the list - in that case this must be a reference due
195 // to indirect call profile data, since a function pointer can point to
196 // a local in another module.
197 if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
198 CalleeSummaryList.size() > 1 &&
199 Summary->modulePath() != CallerModulePath)
200 return false;
201
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000202 if (Summary->instCount() > Threshold)
203 return false;
204
Teresa Johnson519465b2017-01-05 14:32:16 +0000205 if (Summary->notEligibleToImport())
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000206 return false;
207
Mehdi Amini01e32132016-03-26 05:40:34 +0000208 return true;
209 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000210 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000211 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000212
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000213 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000214}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000215
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000216namespace {
217
Teresa Johnson475b51a2016-12-15 20:48:19 +0000218using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
219 GlobalValue::GUID>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000220
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000221} // anonymous namespace
222
Teresa Johnson19580832017-09-13 15:16:38 +0000223static ValueInfo
224updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) {
225 if (!VI.getSummaryList().empty())
226 return VI;
227 // For SamplePGO, the indirect call targets for local functions will
228 // have its original name annotated in profile. We try to find the
229 // corresponding PGOFuncName as the GUID.
230 // FIXME: Consider updating the edges in the graph after building
231 // it, rather than needing to perform this mapping on each walk.
232 auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
233 if (GUID == 0)
Eugene Leviant28d8a492018-01-22 13:35:40 +0000234 return ValueInfo();
Teresa Johnson19580832017-09-13 15:16:38 +0000235 return Index.getValueInfo(GUID);
236}
237
Mehdi Amini01e32132016-03-26 05:40:34 +0000238/// Compute the list of functions to import for a given caller. Mark these
239/// imported functions and the symbols they reference in their source module as
240/// exported from their source module.
241static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000242 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000243 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000244 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000245 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000246 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000247 for (auto &Edge : Summary.calls()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000248 ValueInfo VI = Edge.first;
249 DEBUG(dbgs() << " edge -> " << VI.getGUID() << " Threshold:" << Threshold
250 << "\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000251
Teresa Johnson19580832017-09-13 15:16:38 +0000252 VI = updateValueInfoForIndirectCalls(Index, VI);
253 if (!VI)
254 continue;
Dehao Chen4a435e02017-03-14 17:33:01 +0000255
Peter Collingbourne9667b912017-05-04 18:03:25 +0000256 if (DefinedGVSummaries.count(VI.getGUID())) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000257 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
258 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000259 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000260
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000261 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
262 if (Hotness == CalleeInfo::HotnessType::Hot)
263 return ImportHotMultiplier;
264 if (Hotness == CalleeInfo::HotnessType::Cold)
265 return ImportColdMultiplier;
Dehao Chen64c46572017-07-07 21:01:00 +0000266 if (Hotness == CalleeInfo::HotnessType::Critical)
267 return ImportCriticalMultiplier;
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000268 return 1.0;
269 };
270
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000271 const auto NewThreshold =
Easwaran Ramanc73cec82018-01-25 19:27:17 +0000272 Threshold * GetBonusMultiplier(Edge.second.getHotness());
Piotr Padlewskid2869472016-09-30 03:01:17 +0000273
Peter Collingbourne9667b912017-05-04 18:03:25 +0000274 auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
275 Summary.modulePath());
Mehdi Amini01e32132016-03-26 05:40:34 +0000276 if (!CalleeSummary) {
277 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
278 continue;
279 }
David Blaikie2f0cc472017-07-27 15:09:06 +0000280
281 // "Resolve" the summary
Teresa Johnson81bbf742017-12-16 00:18:12 +0000282 const auto *ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary->getBaseObject());
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000283
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000284 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000285 "selectCallee() didn't honor the threshold");
286
Piotr Padlewskid2869472016-09-30 03:01:17 +0000287 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
288 // Adjust the threshold for next level of imported functions.
289 // The threshold is different for hot callsites because we can then
290 // inline chains of hot calls.
291 if (IsHotCallsite)
292 return Threshold * ImportHotInstrFactor;
293 return Threshold * ImportInstrFactor;
294 };
295
Easwaran Ramanc73cec82018-01-25 19:27:17 +0000296 bool IsHotCallsite =
297 Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000298 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
299
300 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000301 auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()];
Teresa Johnson1b859a22016-12-15 18:21:01 +0000302 /// Since the traversal of the call graph is DFS, we can revisit a function
303 /// a second time with a higher threshold. In this case, it is added back to
304 /// the worklist with the new threshold.
305 if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
306 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
307 << ProcessedThreshold << "\n");
308 continue;
309 }
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000310 bool PreviouslyImported = ProcessedThreshold != 0;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000311 // Mark this function as imported in this module, with the current Threshold
312 ProcessedThreshold = AdjThreshold;
313
314 // Make exports in the source module.
315 if (ExportLists) {
316 auto &ExportList = (*ExportLists)[ExportModulePath];
Peter Collingbourne9667b912017-05-04 18:03:25 +0000317 ExportList.insert(VI.getGUID());
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000318 if (!PreviouslyImported) {
319 // This is the first time this function was exported from its source
320 // module, so mark all functions and globals it references as exported
321 // to the outside if they are defined in the same source module.
Teresa Johnsonedddca22016-12-16 04:11:51 +0000322 // For efficiency, we unconditionally add all the referenced GUIDs
323 // to the ExportList for this module, and will prune out any not
324 // defined in the module later in a single pass.
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000325 for (auto &Edge : ResolvedCalleeSummary->calls()) {
326 auto CalleeGUID = Edge.first.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000327 ExportList.insert(CalleeGUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000328 }
329 for (auto &Ref : ResolvedCalleeSummary->refs()) {
330 auto GUID = Ref.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000331 ExportList.insert(GUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000332 }
Teresa Johnson1b859a22016-12-15 18:21:01 +0000333 }
334 }
Piotr Padlewskid2869472016-09-30 03:01:17 +0000335
Mehdi Amini01e32132016-03-26 05:40:34 +0000336 // Insert the newly imported function to the worklist.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000337 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
Teresa Johnsond450da32015-11-24 21:15:19 +0000338 }
339}
340
Mehdi Amini01e32132016-03-26 05:40:34 +0000341/// Given the list of globals defined in a module, compute the list of imports
342/// as well as the list of "exports", i.e. the list of symbols referenced from
343/// another module (that may require promotion).
344static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000345 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000346 FunctionImporter::ImportMapTy &ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000347 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000348 // Worklist contains the list of function imported in this module, for which
349 // we will analyse the callees and may import further down the callgraph.
350 SmallVector<EdgeInfo, 128> Worklist;
351
352 // Populate the worklist with the import for the functions in the current
353 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000354 for (auto &GVSummary : DefinedGVSummaries) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000355 if (!Index.isGlobalValueLive(GVSummary.second)) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000356 DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
357 continue;
358 }
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000359 auto *FuncSummary =
360 dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000361 if (!FuncSummary)
362 // Skip import for global variables
363 continue;
Xinliang David Li24524f32017-08-11 17:49:20 +0000364 DEBUG(dbgs() << "Initialize 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
Teresa Johnsonc86af332016-04-12 21:13:11 +0000389/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000390void llvm::ComputeCrossModuleImport(
391 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000392 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000393 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000394 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000395 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000396 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000397 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000398 DEBUG(dbgs() << "Computing import for Module '"
399 << DefinedGVSummaries.first() << "'\n");
Mehdi Amini9b490f12016-08-16 05:47:12 +0000400 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000401 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000402 }
403
Teresa Johnsonedddca22016-12-16 04:11:51 +0000404 // When computing imports we added all GUIDs referenced by anything
405 // imported from the module to its ExportList. Now we prune each ExportList
406 // of any not defined in that module. This is more efficient than checking
407 // while computing imports because some of the summary lists may be long
408 // due to linkonce (comdat) copies.
409 for (auto &ELI : ExportLists) {
410 const auto &DefinedGVSummaries =
411 ModuleToDefinedGVSummaries.lookup(ELI.first());
412 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
413 if (!DefinedGVSummaries.count(*EI))
414 EI = ELI.second.erase(EI);
415 else
416 ++EI;
417 }
418 }
419
Mehdi Amini01e32132016-03-26 05:40:34 +0000420#ifndef NDEBUG
421 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
422 << " modules:\n");
423 for (auto &ModuleImports : ImportLists) {
424 auto ModName = ModuleImports.first();
425 auto &Exports = ExportLists[ModName];
426 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
427 << " functions. Imports from " << ModuleImports.second.size()
428 << " modules.\n");
429 for (auto &Src : ModuleImports.second) {
430 auto SrcModName = Src.first();
431 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
432 << SrcModName << "\n");
433 }
434 }
435#endif
436}
437
Teresa Johnson81bbf742017-12-16 00:18:12 +0000438#ifndef NDEBUG
439static void dumpImportListForModule(StringRef ModulePath,
440 FunctionImporter::ImportMapTy &ImportList) {
441 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
442 << ImportList.size() << " modules.\n");
443 for (auto &Src : ImportList) {
444 auto SrcModName = Src.first();
445 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
446 << SrcModName << "\n");
447 }
Teresa Johnson81bbf742017-12-16 00:18:12 +0000448}
Teresa Johnson69b2de82017-12-16 00:29:31 +0000449#endif
Teresa Johnson81bbf742017-12-16 00:18:12 +0000450
Teresa Johnsonc86af332016-04-12 21:13:11 +0000451/// Compute all the imports for the given module in the Index.
452void llvm::ComputeCrossModuleImportForModule(
453 StringRef ModulePath, const ModuleSummaryIndex &Index,
454 FunctionImporter::ImportMapTy &ImportList) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000455 // Collect the list of functions this module defines.
456 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000457 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000458 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000459
460 // Compute the import list for this module.
461 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000462 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000463
464#ifndef NDEBUG
Teresa Johnson81bbf742017-12-16 00:18:12 +0000465 dumpImportListForModule(ModulePath, ImportList);
466#endif
467}
468
469// Mark all external summaries in Index for import into the given module.
470// Used for distributed builds using a distributed index.
471void llvm::ComputeCrossModuleImportForModuleFromIndex(
472 StringRef ModulePath, const ModuleSummaryIndex &Index,
473 FunctionImporter::ImportMapTy &ImportList) {
474 for (auto &GlobalList : Index) {
475 // Ignore entries for undefined references.
476 if (GlobalList.second.SummaryList.empty())
477 continue;
478
479 auto GUID = GlobalList.first;
480 assert(GlobalList.second.SummaryList.size() == 1 &&
481 "Expected individual combined index to have one summary per GUID");
482 auto &Summary = GlobalList.second.SummaryList[0];
483 // Skip the summaries for the importing module. These are included to
484 // e.g. record required linkage changes.
485 if (Summary->modulePath() == ModulePath)
486 continue;
487 // Doesn't matter what value we plug in to the map, just needs an entry
488 // to provoke importing by thinBackend.
489 ImportList[Summary->modulePath()][GUID] = 1;
Teresa Johnsonc86af332016-04-12 21:13:11 +0000490 }
Teresa Johnson81bbf742017-12-16 00:18:12 +0000491#ifndef NDEBUG
492 dumpImportListForModule(ModulePath, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000493#endif
494}
495
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000496void llvm::computeDeadSymbols(
497 ModuleSummaryIndex &Index,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000498 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000499 assert(!Index.withGlobalValueDeadStripping());
Teresa Johnson6c475a72017-01-05 21:34:18 +0000500 if (!ComputeDead)
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000501 return;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000502 if (GUIDPreservedSymbols.empty())
503 // Don't do anything when nothing is live, this is friendly with tests.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000504 return;
505 unsigned LiveSymbols = 0;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000506 SmallVector<ValueInfo, 128> Worklist;
507 Worklist.reserve(GUIDPreservedSymbols.size() * 2);
508 for (auto GUID : GUIDPreservedSymbols) {
509 ValueInfo VI = Index.getValueInfo(GUID);
510 if (!VI)
511 continue;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000512 for (auto &S : VI.getSummaryList())
513 S->setLive(true);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000514 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000515
Teresa Johnson6c475a72017-01-05 21:34:18 +0000516 // Add values flagged in the index as live roots to the worklist.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000517 for (const auto &Entry : Index)
518 for (auto &S : Entry.second.SummaryList)
519 if (S->isLive()) {
520 DEBUG(dbgs() << "Live root: " << Entry.first << "\n");
Eugene Leviant28d8a492018-01-22 13:35:40 +0000521 Worklist.push_back(ValueInfo(/*IsAnalysis=*/false, &Entry));
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000522 ++LiveSymbols;
523 break;
524 }
525
526 // Make value live and add it to the worklist if it was not live before.
527 // FIXME: we should only make the prevailing copy live here
528 auto visit = [&](ValueInfo VI) {
Teresa Johnson19580832017-09-13 15:16:38 +0000529 // FIXME: If we knew which edges were created for indirect call profiles,
530 // we could skip them here. Any that are live should be reached via
531 // other edges, e.g. reference edges. Otherwise, using a profile collected
532 // on a slightly different binary might provoke preserving, importing
533 // and ultimately promoting calls to functions not linked into this
534 // binary, which increases the binary size unnecessarily. Note that
535 // if this code changes, the importer needs to change so that edges
536 // to functions marked dead are skipped.
537 VI = updateValueInfoForIndirectCalls(Index, VI);
538 if (!VI)
539 return;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000540 for (auto &S : VI.getSummaryList())
Teresa Johnsonf6251182017-09-20 17:09:47 +0000541 if (S->isLive())
542 return;
543 for (auto &S : VI.getSummaryList())
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000544 S->setLive(true);
545 ++LiveSymbols;
546 Worklist.push_back(VI);
547 };
Teresa Johnson6c475a72017-01-05 21:34:18 +0000548
549 while (!Worklist.empty()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000550 auto VI = Worklist.pop_back_val();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000551 for (auto &Summary : VI.getSummaryList()) {
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000552 GlobalValueSummary *Base = Summary->getBaseObject();
553 for (auto Ref : Base->refs())
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000554 visit(Ref);
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000555 if (auto *FS = dyn_cast<FunctionSummary>(Base))
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000556 for (auto Call : FS->calls())
557 visit(Call.first);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000558 }
559 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000560 Index.setWithGlobalValueDeadStripping();
561
562 unsigned DeadSymbols = Index.size() - LiveSymbols;
563 DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
564 << " symbols Dead \n");
565 NumDeadSymbols += DeadSymbols;
566 NumLiveSymbols += LiveSymbols;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000567}
568
Teresa Johnson84174c32016-05-10 13:48:23 +0000569/// Compute the set of summaries needed for a ThinLTO backend compilation of
570/// \p ModulePath.
571void llvm::gatherImportedSummariesForModule(
572 StringRef ModulePath,
573 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000574 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000575 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
576 // Include all summaries from the importing module.
577 ModuleToSummariesForIndex[ModulePath] =
578 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000579 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000580 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000581 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
582 const auto &DefinedGVSummaries =
583 ModuleToDefinedGVSummaries.lookup(ILI.first());
584 for (auto &GI : ILI.second) {
585 const auto &DS = DefinedGVSummaries.find(GI.first);
586 assert(DS != DefinedGVSummaries.end() &&
587 "Expected a defined summary for imported global value");
588 SummariesForIndex[GI.first] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000589 }
590 }
591}
592
Teresa Johnson8570fe42016-05-10 15:54:09 +0000593/// Emit the files \p ModulePath will import from into \p OutputFilename.
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000594std::error_code
595llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
596 const FunctionImporter::ImportMapTy &ModuleImports) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000597 std::error_code EC;
598 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
599 if (EC)
600 return EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000601 for (auto &ILI : ModuleImports)
602 ImportsOS << ILI.first() << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000603 return std::error_code();
604}
605
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000606/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
607void llvm::thinLTOResolveWeakForLinkerModule(
608 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000609 auto ConvertToDeclaration = [](GlobalValue &GV) {
610 DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n");
611 if (Function *F = dyn_cast<Function>(&GV)) {
612 F->deleteBody();
613 F->clearMetadata();
614 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
615 V->setInitializer(nullptr);
616 V->setLinkage(GlobalValue::ExternalLinkage);
617 V->clearMetadata();
618 } else
619 // For now we don't resolve or drop aliases. Once we do we'll
620 // need to add support here for creating either a function or
621 // variable declaration, and return the new GlobalValue* for
622 // the caller to use.
Davide Italiano91239082017-04-14 17:22:02 +0000623 llvm_unreachable("Expected function or variable");
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000624 };
625
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000626 auto updateLinkage = [&](GlobalValue &GV) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000627 // See if the global summary analysis computed a new resolved linkage.
628 const auto &GS = DefinedGlobals.find(GV.getGUID());
629 if (GS == DefinedGlobals.end())
630 return;
631 auto NewLinkage = GS->second->linkage();
632 if (NewLinkage == GV.getLinkage())
633 return;
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000634
635 // Switch the linkage to weakany if asked for, e.g. we do this for
636 // linker redefined symbols (via --wrap or --defsym).
Davide Italianof4891d22017-07-06 20:04:20 +0000637 // We record that the visibility should be changed here in `addThinLTO`
638 // as we need access to the resolution vectors for each input file in
639 // order to find which symbols have been redefined.
640 // We may consider reorganizing this code and moving the linkage recording
641 // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex.
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000642 if (NewLinkage == GlobalValue::WeakAnyLinkage) {
643 GV.setLinkage(NewLinkage);
644 return;
645 }
646
647 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
648 return;
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000649 // Check for a non-prevailing def that has interposable linkage
650 // (e.g. non-odr weak or linkonce). In that case we can't simply
651 // convert to available_externally, since it would lose the
652 // interposable property and possibly get inlined. Simply drop
653 // the definition in that case.
654 if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
655 GlobalValue::isInterposableLinkage(GV.getLinkage()))
656 ConvertToDeclaration(GV);
657 else {
658 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
659 << GV.getLinkage() << " to " << NewLinkage << "\n");
660 GV.setLinkage(NewLinkage);
661 }
662 // Remove declarations from comdats, including available_externally
Teresa Johnson6107a412016-08-15 21:00:04 +0000663 // as this is a declaration for the linker, and will be dropped eventually.
664 // It is illegal for comdats to contain declarations.
665 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000666 if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
Teresa Johnson6107a412016-08-15 21:00:04 +0000667 GO->setComdat(nullptr);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000668 };
669
670 // Process functions and global now
671 for (auto &GV : TheModule)
672 updateLinkage(GV);
673 for (auto &GV : TheModule.globals())
674 updateLinkage(GV);
675 for (auto &GV : TheModule.aliases())
676 updateLinkage(GV);
677}
678
679/// Run internalization on \p TheModule based on symmary analysis.
680void llvm::thinLTOInternalizeModule(Module &TheModule,
681 const GVSummaryMapTy &DefinedGlobals) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000682 // Declare a callback for the internalize pass that will ask for every
683 // candidate GlobalValue if it can be internalized or not.
684 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000685 // Lookup the linkage recorded in the summaries during global analysis.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000686 auto GS = DefinedGlobals.find(GV.getGUID());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000687 if (GS == DefinedGlobals.end()) {
688 // Must have been promoted (possibly conservatively). Find original
689 // name so that we can access the correct summary and see if it can
690 // be internalized again.
691 // FIXME: Eventually we should control promotion instead of promoting
692 // and internalizing again.
693 StringRef OrigName =
694 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
695 std::string OrigId = GlobalValue::getGlobalIdentifier(
696 OrigName, GlobalValue::InternalLinkage,
697 TheModule.getSourceFileName());
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000698 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000699 if (GS == DefinedGlobals.end()) {
700 // Also check the original non-promoted non-globalized name. In some
701 // cases a preempted weak value is linked in as a local copy because
702 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
703 // In that case, since it was originally not a local value, it was
704 // recorded in the index using the original name.
705 // FIXME: This may not be needed once PR27866 is fixed.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000706 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000707 assert(GS != DefinedGlobals.end());
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000708 }
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000709 }
710 return !GlobalValue::isLocalLinkage(GS->second->linkage());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000711 };
712
713 // FIXME: See if we can just internalize directly here via linkage changes
714 // based on the index, rather than invoking internalizeModule.
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000715 internalizeModule(TheModule, MustPreserveGV);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000716}
717
Teresa Johnson81bbf742017-12-16 00:18:12 +0000718/// Make alias a clone of its aliasee.
719static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
720 Function *Fn = cast<Function>(GA->getBaseObject());
721
722 ValueToValueMapTy VMap;
723 Function *NewFn = CloneFunction(Fn, VMap);
724 // Clone should use the original alias's linkage and name, and we ensure
725 // all uses of alias instead use the new clone (casted if necessary).
726 NewFn->setLinkage(GA->getLinkage());
727 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType()));
728 NewFn->takeName(GA);
729 return NewFn;
730}
731
Mehdi Aminic8c55172015-12-03 02:37:33 +0000732// Automatically import functions in Module \p DestModule based on the summaries
733// index.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000734Expected<bool> FunctionImporter::importFunctions(
Adrian Prantl66043792017-05-19 23:32:21 +0000735 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000736 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000737 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000738 unsigned ImportedCount = 0;
739
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000740 IRMover Mover(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000741 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000742 std::set<StringRef> ModuleNameOrderedList;
743 for (auto &FunctionsToImportPerModule : ImportList) {
744 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
745 }
746 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000747 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000748 const auto &FunctionsToImportPerModule = ImportList.find(Name);
749 assert(FunctionsToImportPerModule != ImportList.end());
Peter Collingbourned9445c42016-11-13 07:00:17 +0000750 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
751 if (!SrcModuleOrErr)
752 return SrcModuleOrErr.takeError();
753 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000754 assert(&DestModule.getContext() == &SrcModule->getContext() &&
755 "Context mismatch");
756
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000757 // If modules were created with lazy metadata loading, materialize it
758 // now, before linking it (otherwise this will be a noop).
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000759 if (Error Err = SrcModule->materializeMetadata())
760 return std::move(Err);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000761
Mehdi Amini01e32132016-03-26 05:40:34 +0000762 auto &ImportGUIDs = FunctionsToImportPerModule->second;
763 // Find the globals to import
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000764 SetVector<GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000765 for (Function &F : *SrcModule) {
766 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +0000767 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000768 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000769 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000770 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000771 << " " << F.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000772 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000773 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000774 if (Error Err = F.materialize())
775 return std::move(Err);
Piotr Padlewski3b776122016-07-08 23:01:49 +0000776 if (EnableImportMetadata) {
777 // Add 'thinlto_src_module' metadata for statistics and debugging.
778 F.setMetadata(
779 "thinlto_src_module",
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000780 MDNode::get(DestModule.getContext(),
781 {MDString::get(DestModule.getContext(),
782 SrcModule->getSourceFileName())}));
Piotr Padlewski3b776122016-07-08 23:01:49 +0000783 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000784 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +0000785 }
786 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000787 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000788 if (!GV.hasName())
789 continue;
790 auto GUID = GV.getGUID();
791 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000792 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
793 << " " << GV.getName() << " from "
794 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000795 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000796 if (Error Err = GV.materialize())
797 return std::move(Err);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000798 GlobalsToImport.insert(&GV);
799 }
800 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000801 for (GlobalAlias &GA : SrcModule->aliases()) {
802 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +0000803 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000804 auto GUID = GA.getGUID();
Teresa Johnson81bbf742017-12-16 00:18:12 +0000805 auto Import = ImportGUIDs.count(GUID);
806 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000807 << " " << GA.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000808 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson81bbf742017-12-16 00:18:12 +0000809 if (Import) {
810 if (Error Err = GA.materialize())
811 return std::move(Err);
812 // Import alias as a copy of its aliasee.
813 GlobalObject *Base = GA.getBaseObject();
814 if (Error Err = Base->materialize())
815 return std::move(Err);
816 auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
817 DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID()
818 << " " << Base->getName() << " from "
819 << SrcModule->getSourceFileName() << "\n");
820 if (EnableImportMetadata) {
821 // Add 'thinlto_src_module' metadata for statistics and debugging.
822 Fn->setMetadata(
823 "thinlto_src_module",
824 MDNode::get(DestModule.getContext(),
825 {MDString::get(DestModule.getContext(),
826 SrcModule->getSourceFileName())}));
827 }
828 GlobalsToImport.insert(Fn);
829 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000830 }
831
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000832 // Upgrade debug info after we're done materializing all the globals and we
833 // have loaded all the required metadata!
834 UpgradeDebugInfo(*SrcModule);
835
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000836 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000837 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000838 return true;
839
Teresa Johnsond29478f2016-03-27 15:27:30 +0000840 if (PrintImports) {
841 for (const auto *GV : GlobalsToImport)
842 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
843 << " from " << SrcModule->getSourceFileName() << "\n";
844 }
845
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000846 if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
847 [](GlobalValue &, IRMover::ValueAdder) {},
Peter Collingbournee6fd9ff2017-02-03 17:01:14 +0000848 /*IsPerformingImport=*/true))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000849 report_fatal_error("Function Import: link error");
850
Mehdi Amini01e32132016-03-26 05:40:34 +0000851 ImportedCount += GlobalsToImport.size();
Teresa Johnson6c475a72017-01-05 21:34:18 +0000852 NumImportedModules++;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000853 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000854
Teresa Johnson6c475a72017-01-05 21:34:18 +0000855 NumImportedFunctions += ImportedCount;
Teresa Johnsond29478f2016-03-27 15:27:30 +0000856
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000857 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000858 << DestModule.getModuleIdentifier() << "\n");
859 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000860}
861
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000862static bool doImportingForModule(Module &M) {
863 if (SummaryFile.empty())
864 report_fatal_error("error: -function-import requires -summary-file\n");
865 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
866 getModuleSummaryIndexForFile(SummaryFile);
867 if (!IndexPtrOrErr) {
868 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
869 "Error loading file '" + SummaryFile + "': ");
870 return false;
Teresa Johnson21241572016-07-18 21:22:24 +0000871 }
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000872 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
Teresa Johnson21241572016-07-18 21:22:24 +0000873
874 // First step is collecting the import list.
875 FunctionImporter::ImportMapTy ImportList;
Teresa Johnson81bbf742017-12-16 00:18:12 +0000876 // If requested, simply import all functions in the index. This is used
877 // when testing distributed backend handling via the opt tool, when
878 // we have distributed indexes containing exactly the summaries to import.
879 if (ImportAllIndex)
880 ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index,
881 ImportList);
882 else
883 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
884 ImportList);
Teresa Johnson21241572016-07-18 21:22:24 +0000885
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000886 // Conservatively mark all internal values as promoted. This interface is
887 // only used when doing importing via the function importing pass. The pass
888 // is only enabled when testing importing via the 'opt' tool, which does
889 // not do the ThinLink that would normally determine what values to promote.
890 for (auto &I : *Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000891 for (auto &S : I.second.SummaryList) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000892 if (GlobalValue::isLocalLinkage(S->linkage()))
893 S->setLinkage(GlobalValue::ExternalLinkage);
894 }
895 }
896
Teresa Johnson21241572016-07-18 21:22:24 +0000897 // Next we need to promote to global scope and rename any local values that
898 // are potentially exported to other modules.
899 if (renameModuleForThinLTO(M, *Index, nullptr)) {
900 errs() << "Error renaming module\n";
901 return false;
902 }
903
904 // Perform the import now.
905 auto ModuleLoader = [&M](StringRef Identifier) {
906 return loadFile(Identifier, M.getContext());
907 };
908 FunctionImporter Importer(*Index, ModuleLoader);
Peter Collingbourne37e24592017-02-02 18:42:25 +0000909 Expected<bool> Result = Importer.importFunctions(M, ImportList);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000910
911 // FIXME: Probably need to propagate Errors through the pass manager.
912 if (!Result) {
913 logAllUnhandledErrors(Result.takeError(), errs(),
914 "Error importing module: ");
915 return false;
916 }
917
918 return *Result;
Teresa Johnson21241572016-07-18 21:22:24 +0000919}
920
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000921namespace {
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000922
Mehdi Amini42418ab2015-11-24 06:07:49 +0000923/// Pass that performs cross-module function import provided a summary file.
Teresa Johnson21241572016-07-18 21:22:24 +0000924class FunctionImportLegacyPass : public ModulePass {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000925public:
926 /// Pass identification, replacement for typeid
927 static char ID;
928
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000929 explicit FunctionImportLegacyPass() : ModulePass(ID) {}
930
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000931 /// Specify pass name for debug output
Mehdi Amini117296c2016-10-01 02:56:57 +0000932 StringRef getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000933
Mehdi Amini42418ab2015-11-24 06:07:49 +0000934 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000935 if (skipModule(M))
936 return false;
937
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000938 return doImportingForModule(M);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000939 }
940};
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000941
942} // end anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000943
Teresa Johnson21241572016-07-18 21:22:24 +0000944PreservedAnalyses FunctionImportPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000945 ModuleAnalysisManager &AM) {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000946 if (!doImportingForModule(M))
Teresa Johnson21241572016-07-18 21:22:24 +0000947 return PreservedAnalyses::all();
948
949 return PreservedAnalyses::none();
950}
951
952char FunctionImportLegacyPass::ID = 0;
953INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
954 "Summary Based Function Import", false, false)
Mehdi Amini42418ab2015-11-24 06:07:49 +0000955
956namespace llvm {
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000957
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000958Pass *createFunctionImportPass() {
959 return new FunctionImportLegacyPass();
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000960}
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000961
962} // end namespace llvm